Skip to content

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

feat(switchdash): in-app room creation (CHOO-1875) (#103)

Louis Amaudruzcc97346203c4
diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/free-port.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/free-port.ts
index de08eed97..e84ee23b5 100644
--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/free-port.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/free-port.ts
@@ -8,7 +8,7 @@ import { createServer } from 'node:net';
* 5432 / 3000 never hits a "port is already allocated" failure.
*/
export type LocalServerPorts = {
- /** Operator gateway (dashboard) — what "Open web app" and management calls use. */
+ /** Operator gateway (dashboard) — what "Open admin interface" and management calls use. */
gateway: number;
/** switch-core agent bridge API — a connector's `SWITCH_API_ENDPOINT`. */
api: number;
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
index 7329af652..fd3b94dbb 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
@@ -21,8 +21,12 @@ vi.mock('./switch-room-service', () => ({
onSessionRoomChanged: () => () => {},
},
}));
+const noteIntendedRoom = vi.fn();
vi.mock('./switch-notification-poller', () => ({
- switchNotificationPoller: { noteSpawnTrigger: vi.fn() },
+ switchNotificationPoller: {
+ noteSpawnTrigger: vi.fn(),
+ noteIntendedRoom: (...args: unknown[]) => noteIntendedRoom(...args),
+ },
}));
vi.mock('@main/core/agents/getAgentById', () => ({
@@ -204,4 +208,18 @@ describe('AutoSessionWatcher.handleNotification', () => {
await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));
});
});
+
+ it('declares the room for the session it is about to create', async () => {
+ // The session exists because of a message in this room, so its connection
+ // opens already claiming it. Without this it starts room-less and only
+ // joins once the agent gets round to connect_to_room — until then it shows
+ // outside the room it was started for.
+ const watcher = fakeWatcher();
+
+ handle(watcher, 'room-x');
+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));
+
+ const sessionId = (createSession.mock.calls[0][0] as { id: string }).id;
+ expect(noteIntendedRoom).toHaveBeenCalledWith(sessionId, 'room-x', null);
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
index abbbe10ef..eae49f2fe 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
@@ -468,8 +468,15 @@ class AutoSessionWatcher {
for (let attempt = 1; attempt <= SPAWN_MAX_ATTEMPTS; attempt += 1) {
if (watcher.abort.signal.aborted) return;
try {
+ const sessionId = randomUUID();
+ // This session exists *because* of a message in this room, so it has no
+ // reason to start room-less and wait to be told. Declaring it here opens
+ // its connection already claiming the room, which is what puts it under
+ // the room in the sidebar from the moment it appears rather than after
+ // the agent gets round to connect_to_room.
+ switchNotificationPoller.noteIntendedRoom(sessionId, roomId, null);
const result = await sessionService.createSession({
- id: randomUUID(),
+ id: sessionId,
agentId: watcher.localAgentId,
agentName: watcher.agentName,
title: `Switch room ${roomId}`,
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts
index 9923347e4..3426a4abd 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts
@@ -3,11 +3,24 @@ import type { RoomEmbed } from '@shared/core/switch-rooms/room-embed';
import type { SessionRoomConnection } from '@shared/core/switch-rooms/switch-rooms';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { resolveChannelEmbed } from './mattermost-embed';
+import { switchNotificationPoller } from './switch-notification-poller';
import { switchRoomService } from './switch-room-service';
export const switchRoomsController = createRPCController({
getConnections: (): SessionRoomConnection[] => switchRoomService.getConnections(),
+ /**
+ * Declare the room a session is being started for, before it is spawned. The
+ * session's connection then opens already claiming that room, so it appears
+ * under it immediately instead of after the agent's first `connect_to_room`.
+ */
+ noteIntendedRoom: (params: {
+ sessionId: string;
+ roomId: string;
+ roomName: string | null;
+ }): void =>
+ switchNotificationPoller.noteIntendedRoom(params.sessionId, params.roomId, params.roomName),
+
/**
* Decide how a room's conversation should be shown, and prepare whatever
* that needs (a logged-in Mattermost partition, for the inline case). Called
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
index b41178303..eeb7fbce7 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
@@ -937,6 +937,23 @@ describe('the room is set by the server', () => {
conn.stop();
});
+ it('reports the room it declared once the server confirms it', async () => {
+ // A session launched into a room declares it at open, and the server answers
+ // with the same room. That answer is the only signal the rest of the app
+ // gets that the session is in it — deduping it against the declared value
+ // left the session showing as room-less until the agent's own
+ // connect_to_room arrived, which can be a long time and may never come.
+ const { conn, rooms } = connectWithFrames(
+ [`event: connection_state\ndata: ${JSON.stringify({ rooms: ['room-declared'] })}\n\n`],
+ 'room-declared'
+ );
+ await flush(8);
+
+ expect(conn.room).toBe('room-declared');
+ expect(rooms).toEqual(['room-declared']);
+ conn.stop();
+ });
+
it('ignores a control command that arrives before the room is known', async () => {
// `reset` re-types a prompt naming the room; naming the wrong one would
// move the session. Refusing beats guessing.
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
index 8f69e3711..aa238e3cd 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
@@ -251,6 +251,14 @@ export class RoomConnection {
private readonly startCursor: number | undefined;
/** Notified whenever the server tells us which room this session is in. */
private readonly onRoomChanged: ((roomId: string | null) => void) | null;
+ /**
+ * The last room we passed to `onRoomChanged`. Deliberately not seeded from
+ * the declared room: a connection opened declaring one is *told* the same
+ * room back on the `connected` frame, and deduping that against the declared
+ * value would swallow the server's first word — leaving the session's room
+ * known here but never reported to anyone.
+ */
+ private reportedRoom: string | null = null;
/** Unaddressed room messages filtered out since the last event we surfaced. */
private missed = 0;
@@ -346,10 +354,15 @@ export class RoomConnection {
*/
private adoptRoom(rooms: string[]): void {
const next = rooms[0] ?? null;
- if (next === this.roomId) return;
+ // Against what we last *reported*, not what we hold: a session launched
+ // into a room declares it at open and the server confirms the same value,
+ // which is the only signal the rest of the app ever gets that the session
+ // is in that room.
+ if (next === this.reportedRoom) return;
const previous = this.roomId;
this.roomId = next;
+ this.reportedRoom = next;
// The name is not on the wire — the renderer resolves it from the gateway's
// room list, and falls back to a short id when it cannot.
if (next !== previous) this.roomName = null;
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
index 72a8d045d..85ab5705f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
@@ -39,6 +39,8 @@ class SwitchNotificationPoller {
private readonly connections = new Map<string, RoomConnection>();
/** Agent id → buffer position the next session for it should start from. */
private readonly pendingStart = new Map<string, number>();
+ /** Session id → the room it is being started for, before it exists. */
+ private readonly pendingRoom = new Map<string, { roomId: string; roomName: string | null }>();
/**
* Open this session's connection before it launches, and return the id to
@@ -56,7 +58,28 @@ class SwitchNotificationPoller {
async ensureForSession(ctx: SessionRoomContext): Promise<string | null> {
const existing = this.connections.get(ctx.sessionId);
if (existing) return existing.connection;
- return await this.start(ctx, null, null);
+ // Consumed, not just read: the room belongs to this session's launch.
+ const intended = this.pendingRoom.get(ctx.sessionId);
+ this.pendingRoom.delete(ctx.sessionId);
+ return await this.start(ctx, intended?.roomId ?? null, intended?.roomName ?? null);
+ }
+
+ /**
+ * The room a session about to be spawned is meant to be in.
+ *
+ * A session started for a specific room otherwise sits under "Unassigned"
+ * until the agent boots and calls `connect_to_room` — which can take a while,
+ * and never happens if it ignores the prompt. Declaring the room when the
+ * connection opens makes the server claim it there and then, and it comes
+ * back over the same `subscription_changed` signal as any other claim, so the
+ * server stays the one authority on which room a session is in.
+ *
+ * The agent's own `connect_to_room` is still wanted, and still happens — it
+ * is the only thing that returns the room's instructions, and re-claiming a
+ * room already held by the same connection is a no-op.
+ */
+ noteIntendedRoom(sessionId: string, roomId: string, roomName: string | null): void {
+ this.pendingRoom.set(sessionId, { roomId, roomName });
}
/**
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
index b5e4d0f88..c5537f018 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
@@ -19,12 +19,15 @@ import type {
AddServerParams,
AgentDefaults,
AgentVerifyResult,
+ CreateRoomParams,
+ CreateRoomResult,
PasswordLoginParams,
ProvisionAgentParams,
ProvisionAgentResult,
ProvisionRemoteAgentParams,
RemoteAgentRoom,
RemoteAgentSummary,
+ RemoteBridge,
RemoteExternalUser,
RemoteRoomGroup,
RemoteRoomRole,
@@ -38,7 +41,9 @@ import type {
} from '@shared/core/switch-servers/switch-servers';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { type LoginError, oidcLogin, passwordLogin } from './auth';
+import { createRoomOnServer } from './create-room';
import {
+ addRoomAgents,
agentExistsOnServer,
fetchAddressingPolicy,
fetchAgentDetail,
@@ -46,11 +51,14 @@ import {
fetchAgents,
fetchAllExternalUsers,
fetchAuthConfig,
+ fetchBridges,
fetchMe,
+ fetchRoomAgentIds,
fetchRoomGroups,
fetchRoomRoles,
fetchRooms,
GatewayError,
+ removeRoomAgent,
updateAddressingPolicy,
} from './gateway-client';
import { openAuthenticatedGatewayPage } from './gateway-web';
@@ -185,6 +193,25 @@ export const switchServersController = createRPCController({
listRemoteRooms: async (serverId: string): Promise<RemoteRoomSummary[]> =>
fetchRooms(await requireServer(serverId)),
+ listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> =>
+ fetchBridges(await requireReachableServer(serverId)),
+
+ /**
+ * Create a room on the chosen server, owned by the signed-in user. Room
+ * provisioning stays server-side (`POST /gateway/rooms`); this only maps
+ * recoverable failures onto a typed result the modal can act on.
+ */
+ createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {
+ const server = await requireReachableServer(params.serverId);
+ return createRoomOnServer(server, {
+ name: params.name,
+ description: params.description,
+ instructions: params.instructions,
+ bridgeId: params.bridgeId,
+ agentIds: params.agentIds,
+ });
+ },
+
listAgentRooms: async (params: {
serverId: string;
agentId: string;
@@ -194,6 +221,29 @@ export const switchServersController = createRPCController({
listRoomRoles: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomRole[]> =>
fetchRoomRoles(await requireServer(params.serverId), params.roomId),
+ listRoomAgentIds: async (params: { serverId: string; roomId: string }): Promise<string[]> =>
+ fetchRoomAgentIds(await requireServer(params.serverId), params.roomId),
+
+ /**
+ * Add agents to a room. Failures propagate as-is: the caller shows the
+ * gateway's own words (e.g. an agent whose server-side client is not running,
+ * which the gateway rejects) rather than a generic message.
+ */
+ addRoomAgents: async (params: {
+ serverId: string;
+ roomId: string;
+ agentIds: string[];
+ }): Promise<void> =>
+ addRoomAgents(await requireReachableServer(params.serverId), params.roomId, params.agentIds),
+
+ /** Remove one agent from a room. Membership only — the agent is not deleted. */
+ removeRoomAgent: async (params: {
+ serverId: string;
+ roomId: string;
+ agentId: string;
+ }): Promise<void> =>
+ removeRoomAgent(await requireReachableServer(params.serverId), params.roomId, params.agentId),
+
listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>
fetchRoomGroups(await requireServer(serverId)),
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.test.ts
new file mode 100644
index 000000000..ffd351df9
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+
+const { createRoomOnServer } = await import('./create-room');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'https://switch.example.com',
+ managed: false,
+} as never;
+
+const PARAMS = {
+ name: 'design-review',
+ description: 'Where design gets reviewed',
+ bridgeId: 'bridge-1',
+ agentIds: ['agent-1'],
+};
+
+/** A far-from-expiry JWT, so no renewal path is exercised here. */
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ const text = typeof body === 'string' ? body : JSON.stringify(body);
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => (typeof body === 'string' ? {} : body),
+ headers: { getSetCookie: () => [] },
+ text: async () => text,
+ } as unknown as Response;
+}
+
+const CREATED = {
+ id: 'room-1',
+ name: 'design-review',
+ description: 'Where design gets reviewed',
+ channel_type: 'channel_public',
+ agent_count: 1,
+ bridge_display_name: 'Mattermost',
+ archived: false,
+ created_at: '2026-01-01T00:00:00Z',
+};
+
+const fetchMock = vi.fn();
+
+describe('createRoomOnServer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('returns the created room on success', async () => {
+ fetchMock.mockResolvedValue(response(201, CREATED));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toMatchObject({
+ kind: 'created',
+ room: { id: 'room-1', name: 'design-review' },
+ });
+ });
+
+ it('maps a rejected session onto unauthenticated so the caller prompts a sign-in', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toEqual({ kind: 'unauthenticated' });
+ });
+
+ it("calls out a stopped bridge as its own case, in the gateway's words", async () => {
+ fetchMock.mockResolvedValue(response(400, { detail: 'Bridge not running: bridge-1' }));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'bridge-unavailable',
+ message: 'Bridge not running: bridge-1',
+ });
+ });
+
+ it('reports a rejected argument as invalid, using the detail rather than the status line', async () => {
+ fetchMock.mockResolvedValue(response(400, { detail: 'Unknown agent ID: nope' }));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'invalid',
+ message: 'Unknown agent ID: nope',
+ });
+ });
+
+ it('surfaces an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toMatchObject({ kind: 'error' });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).rejects.toMatchObject({ status: 500 });
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.ts
new file mode 100644
index 000000000..6b89714f3
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-room.ts
@@ -0,0 +1,50 @@
+import { createRoom, GatewayError } from '@main/core/switch-servers/gateway-client';
+import type {
+ CreateRoomParams,
+ CreateRoomResult,
+ SwitchServer,
+} from '@shared/core/switch-servers/switch-servers';
+
+/** The gateway reports an unknown bridge id and a configured-but-stopped bridge
+ * with the same 400, differing only in wording. Both mean "you cannot bridge to
+ * that right now", which is the one failure the user can act on directly. */
+function isBridgeFailure(detail: string): boolean {
+ return /bridge/i.test(detail) && /not running|unavailable|not found/i.test(detail);
+}
+
+/**
+ * Create a room on `server` and map recoverable gateway failures onto a typed
+ * {@link CreateRoomResult}, so the modal can name what went wrong instead of
+ * surfacing a raw status line — or worse, appearing to do nothing.
+ *
+ * Unmapped failures still throw: an unexpected 500 is a bug, not a form error,
+ * and should reach the logs rather than be flattened into the same inline
+ * message as a typo in the room name.
+ */
+export async function createRoomOnServer(
+ server: SwitchServer,
+ params: Omit<CreateRoomParams, 'serverId'>
+): Promise<CreateRoomResult> {
+ try {
+ const room = await createRoom(server, {
+ name: params.name,
+ description: params.description,
+ instructions: params.instructions,
+ bridgeId: params.bridgeId,
+ agentIds: params.agentIds,
+ });
+ return { kind: 'created', room };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && (cause.status === 400 || cause.status === 422)) {
+ const message = cause.detail ?? cause.message;
+ return isBridgeFailure(message)
+ ? { kind: 'bridge-unavailable', message }
+ : { kind: 'invalid', message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
index 62aac0bad..103e27857 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -7,7 +7,7 @@ const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
vi.mock('./servers-store', () => ({ getSessionCookie }));
vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
-const { fetchMe } = await import('./gateway-client');
+const { createRoom, fetchBridges, fetchMe } = await import('./gateway-client');
const SERVER = {
id: 'srv-1',
@@ -196,3 +196,141 @@ describe('gatewayFetch managed-server silent re-auth', () => {
expect(fetchMock).toHaveBeenCalledOnce();
});
});
+
+function jsonResponse(body: unknown): Response {
+ return {
+ status: 200,
+ ok: true,
+ json: async () => body,
+ headers: { getSetCookie: () => [] },
+ text: async () => JSON.stringify(body),
+ } as unknown as Response;
+}
+
+function errorResponse(status: number, body: string): Response {
+ return {
+ status,
+ ok: false,
+ json: async () => ({}),
+ headers: { getSetCookie: () => [] },
+ text: async () => body,
+ } as unknown as Response;
+}
+
+function bodyOf(call: unknown[]): Record<string, unknown> {
+ const init = call[1] as { body: string };
+ return JSON.parse(init.body) as Record<string, unknown>;
+}
+
+describe('room creation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('maps the bridge list, defaulting is_default to false when absent', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse([
+ {
+ bridge_id: 'b1',
+ bridge_type: 'mattermost',
+ display_name: 'Mattermost',
+ status: 'active',
+ is_default: true,
+ },
+ { bridge_id: 'b2', bridge_type: 'slack', display_name: 'Slack', status: 'stopped' },
+ ]) as never
+ );
+
+ await expect(fetchBridges(SERVER)).resolves.toEqual([
+ {
+ id: 'b1',
+ type: 'mattermost',
+ displayName: 'Mattermost',
+ status: 'active',
+ isDefault: true,
+ },
+ { id: 'b2', type: 'slack', displayName: 'Slack', status: 'stopped', isDefault: false },
+ ]);
+ });
+
+ it('always names a bridge and a channel type, never the internal-only escape hatch', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ id: 'room-1',
+ name: 'design',
+ description: 'd',
+ channel_type: 'channel_public',
+ agent_count: 1,
+ bridge_display_name: 'Mattermost',
+ owner_id: 'u1',
+ archived: false,
+ created_at: '2026-01-01T00:00:00Z',
+ }) as never
+ );
+
+ const room = await createRoom(SERVER, {
+ name: 'design',
+ description: 'd',
+ bridgeId: 'b1',
+ agentIds: ['a1'],
+ });
+
+ const body = bodyOf(fetchMock.mock.calls[0]);
+ expect(body).toMatchObject({
+ name: 'design',
+ description: 'd',
+ bridge_id: 'b1',
+ channel_type: 'channel_public',
+ agent_ids: ['a1'],
+ });
+ expect(body).not.toHaveProperty('internal_only');
+ expect(room.ownerId).toBe('u1');
+ });
+
+ it('sends blank instructions as null rather than an empty string', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ id: 'room-1',
+ name: 'design',
+ description: 'd',
+ channel_type: 'channel_public',
+ agent_count: 0,
+ bridge_display_name: null,
+ archived: false,
+ created_at: '2026-01-01T00:00:00Z',
+ }) as never
+ );
+
+ await createRoom(SERVER, {
+ name: 'design',
+ description: 'd',
+ instructions: ' ',
+ bridgeId: 'b1',
+ agentIds: [],
+ });
+
+ expect(bodyOf(fetchMock.mock.calls[0]).instructions).toBeNull();
+ });
+
+ it("unwraps the gateway's detail envelope so a failure can be shown in the user's terms", async () => {
+ fetchMock.mockResolvedValue(errorResponse(400, '{"detail":"Bridge not running: b1"}') as never);
+
+ await expect(
+ createRoom(SERVER, { name: 'x', description: 'y', bridgeId: 'b1', agentIds: [] })
+ ).rejects.toMatchObject({ status: 400, detail: 'Bridge not running: b1' });
+ });
+
+ it('leaves detail unset when the error body is not a detail envelope', async () => {
+ fetchMock.mockResolvedValue(errorResponse(502, '<html>bad gateway</html>') as never);
+
+ await expect(
+ createRoom(SERVER, { name: 'x', description: 'y', bridgeId: 'b1', agentIds: [] })
+ ).rejects.toMatchObject({ status: 502, detail: undefined });
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
index 9e77c9315..78bee5e5f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -2,6 +2,7 @@ import type {
AddressingPolicy,
RemoteAgentRoom,
RemoteAgentSummary,
+ RemoteBridge,
RemoteExternalUser,
RemoteRoomGroup,
RemoteRoomRole,
@@ -75,13 +76,34 @@ export class GatewayError extends Error {
constructor(
readonly kind: GatewayErrorKind,
message: string,
- readonly status?: number
+ readonly status?: number,
+ /** The gateway's own explanation, unwrapped from the FastAPI `{"detail":…}`
+ * envelope. Present only when the body carried one. Prefer this over
+ * `message` when showing a failure to the user: `message` is prefixed with
+ * the raw status line, which reads as noise in a form. */
+ readonly detail?: string
) {
super(message);
this.name = 'GatewayError';
}
}
+/**
+ * Unwrap FastAPI's `{"detail": "…"}` error envelope. Returns undefined for any
+ * other body shape (an HTML error page, a 422 validation array, empty), leaving
+ * the caller with the full status-prefixed message rather than a misleading
+ * fragment.
+ */
+function parseErrorDetail(body: string): string | undefined {
+ if (!body) return undefined;
+ try {
+ const parsed = JSON.parse(body) as { detail?: unknown };
+ return typeof parsed.detail === 'string' ? parsed.detail : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
type FetchOptions = {
/** Attach the stored `switch_auth` cookie. Off for unauthenticated calls
* such as `/auth/config`. */
@@ -156,11 +178,12 @@ async function gatewayFetch(
throw new GatewayError('unauthorized', 'Switch session expired — please sign in again.', 401);
}
if (!response.ok) {
- const detail = await response.text().catch(() => '');
+ const body = await response.text().catch(() => '');
throw new GatewayError(
'http',
- `Switch gateway returned ${response.status}${detail ? `: ${detail}` : ''}`,
- response.status
+ `Switch gateway returned ${response.status}${body ? `: ${body}` : ''}`,
+ response.status,
+ parseErrorDetail(body)
);
}
return response;
@@ -436,19 +459,42 @@ export async function fetchRoomGroups(server: SwitchServer): Promise<RemoteRoomG
return json.map((g) => ({ id: g.id, name: g.name }));
}
+/**
+ * List the collaboration bridges configured on a server (`GET /collaborations`).
+ * Returns every bridge regardless of status — callers that need a usable one
+ * (room creation) filter on `status === 'active'` themselves, so they can tell
+ * "no bridges at all" apart from "the bridge is down".
+ */
+export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]> {
+ const res = await gatewayFetch(server, '/collaborations', { authenticated: true });
+ const json = (await res.json()) as Array<{
+ bridge_id: string;
+ bridge_type: string;
+ display_name: string;
+ status: string;
+ is_default?: boolean;
+ }>;
+ return json.map((b) => ({
+ id: b.bridge_id,
+ type: b.bridge_type,
+ displayName: b.display_name,
+ status: b.status,
+ isDefault: b.is_default ?? false,
+ }));
+}
+
/**
* Union of external (bridged human) users across every bridge on the server
* (`GET /collaborations`, then each bridge's `/users`). The addressing policy's
* `users` dimension keys off these ExternalUser ids.
*/
export async function fetchAllExternalUsers(server: SwitchServer): Promise<RemoteExternalUser[]> {
- const bridgesRes = await gatewayFetch(server, '/collaborations', { authenticated: true });
- const bridges = (await bridgesRes.json()) as Array<{ bridge_id: string }>;
+ const bridges = await fetchBridges(server);
const byId = new Map<string, RemoteExternalUser>();
for (const bridge of bridges) {
const res = await gatewayFetch(
server,
- `/collaborations/${encodeURIComponent(bridge.bridge_id)}/users`,
+ `/collaborations/${encodeURIComponent(bridge.id)}/users`,
{ authenticated: true }
);
const users = (await res.json()) as Array<{ id: string; external_username: string }>;
@@ -542,21 +588,24 @@ export async function fetchRoomRoles(
}));
}
-export async function fetchRooms(server: SwitchServer): Promise<RemoteRoomSummary[]> {
- const res = await gatewayFetch(server, '/rooms', { authenticated: true });
- const json = (await res.json()) as Array<{
- id: string;
- name: string;
- description: string;
- channel_type: string | null;
- agent_count: number;
- bridge_display_name: string | null;
- bridge_type?: string | null;
- external_channel_url?: string | null;
- archived: boolean;
- created_at: string;
- }>;
- return json.map((r) => ({
+/** The gateway `RoomSummary` wire shape. `RoomDetail` (returned by create) is a
+ * superset, so the same mapper serves both. */
+type RoomSummaryJson = {
+ id: string;
+ name: string;
+ description: string;
+ channel_type: string | null;
+ agent_count: number;
+ bridge_display_name: string | null;
+ bridge_type?: string | null;
+ external_channel_url?: string | null;
+ owner_id?: string | null;
+ archived: boolean;
+ created_at: string;
+};
+
+function mapRoomSummary(r: RoomSummaryJson): RemoteRoomSummary {
+ return {
id: r.id,
name: r.name,
description: r.description,
@@ -565,7 +614,100 @@ export async function fetchRooms(server: SwitchServer): Promise<RemoteRoomSummar
bridgeDisplayName: r.bridge_display_name,
bridgeType: r.bridge_type ?? null,
externalChannelUrl: r.external_channel_url ?? null,
+ ownerId: r.owner_id ?? null,
archived: r.archived,
createdAt: r.created_at,
- }));
+ };
+}
+
+export async function fetchRooms(server: SwitchServer): Promise<RemoteRoomSummary[]> {
+ const res = await gatewayFetch(server, '/rooms', { authenticated: true });
+ const json = (await res.json()) as RoomSummaryJson[];
+ return json.map(mapRoomSummary);
+}
+
+/**
+ * Switch agent ids that are members of a room (`GET /rooms/{id}`). One call for
+ * the whole room, rather than asking every candidate agent what it belongs to.
+ * Connecting to a room is only meaningful for an agent already in it, so this is
+ * what scopes the agent picker when starting a session from a room.
+ */
+export async function fetchRoomAgentIds(server: SwitchServer, roomId: string): Promise<string[]> {
+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}`, {
+ authenticated: true,
+ });
+ const json = (await res.json()) as { agent_ids?: string[] };
+ return json.agent_ids ?? [];
+}
+
+/**
+ * Add agents to an existing room (`POST /rooms/{id}/agents`). Requires write
+ * access to the room. Agents already in the room are ignored server-side, so
+ * this is safe to call with a set that overlaps the current membership.
+ */
+export async function addRoomAgents(
+ server: SwitchServer,
+ roomId: string,
+ agentIds: string[]
+): Promise<void> {
+ await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/agents`, {
+ authenticated: true,
+ method: 'POST',
+ body: { agent_ids: agentIds },
+ });
+}
+
+/**
+ * Remove one agent from a room (`DELETE /rooms/{id}/agents/{agentId}`). Requires
+ * write access. This is membership only — the agent itself, its credentials and
+ * its sessions are untouched; it simply stops being in this room.
+ */
+export async function removeRoomAgent(
+ server: SwitchServer,
+ roomId: string,
+ agentId: string
+): Promise<void> {
+ await gatewayFetch(
+ server,
+ `/rooms/${encodeURIComponent(roomId)}/agents/${encodeURIComponent(agentId)}`,
+ { authenticated: true, method: 'DELETE' }
+ );
+}
+
+/**
+ * Create a room on `server` (session-authed `POST /gateway/rooms`), owned by the
+ * signed-in user. Provisioning stays entirely server-side — this is the same
+ * endpoint the operator web app posts to.
+ *
+ * `bridgeId` is required by switchdash even though the gateway allows an
+ * unbridged room: a room with no messaging app attached is unreachable for the
+ * humans it is being created for. `channel_type` is always `channel_public` for
+ * now; the gateway demands the field whenever a new channel is provisioned.
+ *
+ * Failures throw `GatewayError` — see `createRoomOnServer` for the mapping onto
+ * a user-facing result.
+ */
+export async function createRoom(
+ server: SwitchServer,
+ params: {
+ name: string;
+ description: string;
+ instructions?: string;
+ bridgeId: string;
+ agentIds: string[];
+ }
+): Promise<RemoteRoomSummary> {
+ const res = await gatewayFetch(server, '/rooms', {
+ authenticated: true,
+ method: 'POST',
+ body: {
+ name: params.name,
+ description: params.description,
+ instructions: params.instructions?.trim() ? params.instructions : null,
+ bridge_id: params.bridgeId,
+ channel_type: 'channel_public',
+ agent_ids: params.agentIds,
+ },
+ });
+ return mapRoomSummary((await res.json()) as RoomSummaryJson);
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
index 9083edb4c..efdd033e1 100644
--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
@@ -5,8 +5,10 @@ import { ResetAgentModal } from '@renderer/features/locations/components/reset-a
import { CreateSessionModal } from '@renderer/features/sessions/create-session-modal/create-session-modal';
import { DeleteSessionModal } from '@renderer/features/sessions/delete-session-modal';
import { RenameSessionModal } from '@renderer/features/sessions/rename-session-modal';
+import { AddAgentsToRoomModal } from '@renderer/features/switch-rooms/AddAgentsToRoomModal';
import { AddServerModal } from '@renderer/features/switch-servers/AddServerModal';
import { AssignServerModal } from '@renderer/features/switch-servers/assign-server-modal';
+import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';
import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';
import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';
import { ConfirmActionDialog } from '@renderer/lib/components/confirm-action-dialog';
@@ -60,5 +62,10 @@ export const modalRegistry = {
dismissOnOutsideClick: false,
}),
deleteServerModal: createModal(DeleteServerModal, { size: 'sm' }),
+ createRoomModal: createModal(CreateRoomModal, { size: 'md', dismissOnOutsideClick: false }),
+ addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {
+ size: 'sm',
+ dismissOnOutsideClick: false,
+ }),
// oxlint-disable-next-line typescript/no-explicit-any
} satisfies Record<string, ModalRegistryEntry<any, any>>;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx
index b9437aa29..ed61ad9ad 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx
@@ -6,6 +6,11 @@ interface LocationViewWrapperProps {
/** When set, the view is scoped to this Claude Code subagent of the location's
* agent: Sessions lists only its sessions and Settings shows its own config. */
agentName?: string;
+ /** The room this agent page was opened from, when it was opened from a room in
+ * the sidebar. The page ignores it — it is navigation context, so the sidebar
+ * can highlight the row that was clicked rather than every row for the same
+ * agent, and so that survives back/forward. */
+ roomId?: string;
}
export function LocationViewWrapper({ children }: LocationViewWrapperProps) {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx
index 3c033bbc1..ce99c7f9c 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx
@@ -19,4 +19,8 @@ export const locationView = {
? { ok: true }
: { ok: false, redirect: 'home' };
},
-} satisfies ViewDefinition<{ locationId: string; agentName?: string }>;
+ // `roomId` records which room the agent was opened *from*, when it was opened
+ // from a room in the sidebar. The page itself ignores it; it is what lets the
+ // sidebar highlight the row that was clicked rather than every row for that
+ // agent, and it travels with history so back/forward stay right.
+} satisfies ViewDefinition<{ locationId: string; agentName?: string; roomId?: string }>;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
index dd33c8180..c8fe87f96 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { ChevronDown } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
@@ -37,6 +38,7 @@ import {
import { Textarea } from '@renderer/lib/ui/textarea';
import { log } from '@renderer/utils/logger';
import { cn } from '@renderer/utils/utils';
+import type { Agent } from '@shared/core/agents/agents';
import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';
import { buildConnectPrompt } from './build-connect-prompt';
@@ -68,25 +70,85 @@ function useDefaultLocationId(propLocationId?: string): string | undefined {
}, []); // computed once on mount
}
+/**
+ * The local agents that could actually take a session in `roomId`: registered on
+ * that room's server, and already a member of the room.
+ *
+ * Connecting is not a join — it is an instruction in the session's opening
+ * prompt — so an agent outside the room would start a session that then fails to
+ * connect. Offering only members keeps that failure off the table, and the empty
+ * case is surfaced rather than presented as a working choice.
+ */
+function useRoomMemberAgents(roomId: string | undefined): {
+ agents: Agent[];
+ serverId: string | null;
+ loading: boolean;
+} {
+ const serverId = roomId ? switchRoomsStore.roomServerId(roomId) : null;
+
+ useEffect(() => {
+ if (roomId) void agentsStore.load();
+ }, [roomId]);
+
+ const membersQuery = useQuery({
+ queryKey: ['roomAgentIds', serverId, roomId],
+ queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId: roomId! }),
+ enabled: !!serverId && !!roomId,
+ });
+
+ const memberIds = useMemo(() => new Set(membersQuery.data ?? []), [membersQuery.data]);
+ const agents = [...agentsStore.byLocation.values()]
+ .flat()
+ .filter((a) => a.serverId === serverId && a.switchAgentId && memberIds.has(a.switchAgentId))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ return { agents, serverId, loading: membersQuery.isLoading || !agentsStore.loaded };
+}
+
export const CreateSessionModal = observer(function CreateSessionModal({
locationId,
agentName,
+ roomId,
onClose,
}: BaseModalProps & {
locationId?: string;
/** When set, start the session as this Claude Code subagent of the agent. */
agentName?: string;
+ /** When set, the session connects to THIS room and the modal asks which agent
+ * should join it — the inverse of the agent-first flow, for starting a session
+ * from a room in the sidebar. */
+ roomId?: string;
// Accepted for source compatibility with switchdash callers; ignored in switchdash v0.
strategy?: string;
initialPR?: unknown;
}) {
- const selectedLocationId = useDefaultLocationId(locationId);
+ const defaultLocationId = useDefaultLocationId(locationId);
const { navigate } = useNavigate();
const [name, setName] = useState('');
const [prompt, setPrompt] = useState('');
const [room, setRoom] = useState<RemoteAgentRoom | null>(null);
const [roleName, setRoleName] = useState<string>(NO_ROLE);
+ const [pickedAgent, setPickedAgent] = useState<Agent | null>(null);
+
+ // Room-first mode: the room is fixed and the agent is the open question —
+ // unless the caller already answered it (a "+" on an agent row listed under
+ // the room), in which case the picker just shows that agent, still switchable.
+ const roomFirst = !!roomId;
+ const roomMembers = useRoomMemberAgents(roomId);
+ const presetAgent =
+ roomMembers.agents.find(
+ (a) => a.name === agentName && (!locationId || a.locationId === locationId)
+ ) ?? null;
+ // Auto-pick when there is only one candidate — the choice would be a
+ // formality, and the user still sees which agent it resolved to.
+ const effectiveAgent =
+ pickedAgent ?? presetAgent ?? (roomMembers.agents.length === 1 ? roomMembers.agents[0] : null);
+ const selectedLocationId = roomFirst ? effectiveAgent?.locationId : defaultLocationId;
+ // Every switchdash agent is its own Switch identity, so a session is always
+ // owned by a named agent row (CHOO-1440) — the picked agent's name plays the
+ // same part here as the `agentName` an agent row passes in.
+ const effectiveAgentName = roomFirst ? effectiveAgent?.name : agentName;
// A session belongs to an agent; resolve the location's agent up front so we
// can offer the rooms it belongs to.
@@ -101,18 +163,20 @@ export const CreateSessionModal = observer(function CreateSessionModal({
// When a specific agent is named, the session joins rooms under that agent's
// own Switch identity — its own agent row — so the room picker uses that
// agent's id/server, matched by name (CHOO-1440).
- const subagent = agentName ? (locationAgents.find((a) => a.name === agentName) ?? null) : null;
+ const subagent = effectiveAgentName
+ ? (locationAgents.find((a) => a.name === effectiveAgentName) ?? null)
+ : null;
- const serverId = agentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);
- const switchAgentId = agentName
+ const serverId = effectiveAgentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);
+ const switchAgentId = effectiveAgentName
? (subagent?.switchAgentId ?? null)
: (agent?.switchAgentId ?? null);
useEffect(() => {
- if (serverId && switchAgentId) {
+ if (!roomFirst && serverId && switchAgentId) {
void switchRoomsStore.fetchAgentRooms(serverId, switchAgentId);
}
- }, [serverId, switchAgentId]);
+ }, [roomFirst, serverId, switchAgentId]);
const rooms =
serverId && switchAgentId
@@ -120,14 +184,30 @@ export const CreateSessionModal = observer(function CreateSessionModal({
: [];
const roomsLoading =
!!serverId && !!switchAgentId && switchRoomsStore.isLoading(serverId, switchAgentId);
- const canConnectRoom = !!serverId && !!switchAgentId;
+ const canConnectRoom = !roomFirst && !!serverId && !!switchAgentId;
+
+ // In room-first mode the room is given, not chosen; everything downstream
+ // (roles, the connect prompt) keys off the same value either way.
+ const activeRoom: RemoteAgentRoom | null = roomFirst
+ ? roomId
+ ? {
+ roomId,
+ roomName: switchRoomsStore.roomNameById(roomId) ?? 'this room',
+ archived: false,
+ status: 'no_session',
+ roomRole: null,
+ }
+ : null
+ : room;
+ const roleServerId = roomFirst ? roomMembers.serverId : serverId;
// Roles are room-scoped, so only fetch once a room is chosen. The set is small
// and changes rarely, so a plain per-room query (no shared cache) is enough.
const rolesQuery = useQuery({
- queryKey: ['roomRoles', serverId, room?.roomId],
- queryFn: () => rpc.switchServers.listRoomRoles({ serverId: serverId!, roomId: room!.roomId }),
- enabled: !!serverId && !!room,
+ queryKey: ['roomRoles', roleServerId, activeRoom?.roomId],
+ queryFn: () =>
+ rpc.switchServers.listRoomRoles({ serverId: roleServerId!, roomId: activeRoom!.roomId }),
+ enabled: !!roleServerId && !!activeRoom,
});
const roles = rolesQuery.data ?? [];
@@ -141,7 +221,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({
const id = crypto.randomUUID();
const trimmedName = name.trim();
const chosenRole = roleName !== NO_ROLE ? roleName : null;
- const initialPrompt = buildConnectPrompt(room?.roomName ?? null, chosenRole, prompt);
+ const initialPrompt = buildConnectPrompt(activeRoom?.roomName ?? null, chosenRole, prompt);
void (async () => {
const freshAgents = await rpc.agents.getAgents(selectedLocationId);
@@ -149,16 +229,26 @@ export const CreateSessionModal = observer(function CreateSessionModal({
// from `session.agent_id → agents.name`, so the session is
// invisible/misidentified if it points at a different agent. Resolve the
// row by name here; error out rather than silently fall back (CHOO-1440).
- const resolvedAgent = agentName
- ? (subagent ?? freshAgents.find((a) => a.name === agentName) ?? null)
+ const resolvedAgent = effectiveAgentName
+ ? (subagent ?? freshAgents.find((a) => a.name === effectiveAgentName) ?? null)
: (agent ?? freshAgents[0]);
if (!resolvedAgent) {
log.error('spawn session failed: no agent for location/subagent', {
locationId: selectedLocationId,
- agentName,
+ agentName: effectiveAgentName,
});
return;
}
+ // Declare the room before the session exists, so its connection opens
+ // already claiming it and the session shows under the right room from the
+ // start rather than after the agent's first connect_to_room.
+ if (activeRoom) {
+ await rpc.switchRooms.noteIntendedRoom({
+ sessionId: id,
+ roomId: activeRoom.roomId,
+ roomName: activeRoom.roomName,
+ });
+ }
// createSession registers the session synchronously (before its first
// await), so it is in the manager by the time this call returns — the
// session-view guard then finds it and navigation lands on the session.
@@ -168,7 +258,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({
title: trimmedName || 'Session',
autoApprove: resolvedAgent.autoApprove,
initialPrompt,
- agentName: agentName || undefined,
+ agentName: effectiveAgentName || undefined,
});
navigate('session', { locationId: selectedLocationId, sessionId: id });
onClose();
@@ -179,10 +269,71 @@ export const CreateSessionModal = observer(function CreateSessionModal({
return (
<>
<DialogHeader className="flex items-center gap-2">
- <DialogTitle>{agentName ? `New Session · @${agentName}` : 'New Session'}</DialogTitle>
+ <DialogTitle>
+ {roomFirst
+ ? `New Session · ${activeRoom?.roomName ?? 'room'}`
+ : agentName
+ ? `New Session · @${agentName}`
+ : 'New Session'}
+ </DialogTitle>
</DialogHeader>
<DialogContentArea>
<div className="flex w-full flex-col gap-5">
+ {roomFirst && (
+ <Field>
+ <FieldLabel>Agent</FieldLabel>
+ <Combobox
+ items={roomMembers.agents}
+ value={effectiveAgent}
+ onValueChange={(next: Agent | null) => setPickedAgent(next)}
+ isItemEqualToValue={(a: Agent, b: Agent) => a.id === b.id}
+ filter={(item: Agent, query) =>
+ item.name.toLowerCase().includes(query.toLowerCase())
+ }
+ autoHighlight
+ >
+ <ComboboxTrigger
+ disabled={roomMembers.loading || roomMembers.agents.length === 0}
+ className={cn(
+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',
+ (roomMembers.loading || roomMembers.agents.length === 0) &&
+ 'cursor-not-allowed opacity-60'
+ )}
+ >
+ <span
+ className={cn(
+ 'flex-1 truncate text-left',
+ !effectiveAgent && 'text-foreground-muted'
+ )}
+ >
+ {effectiveAgent
+ ? effectiveAgent.name
+ : roomMembers.loading
+ ? 'Loading agents…'
+ : 'Choose an agent'}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />
+ </ComboboxTrigger>
+ <ComboboxContent className="min-w-(--anchor-width)">
+ <ComboboxInput showTrigger={false} placeholder="Search agents…" />
+ <ComboboxList>
+ {(item: Agent) => (
+ <ComboboxItem key={item.id} value={item}>
+ <span className="min-w-0 flex-1 truncate">{item.name}</span>
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ <ComboboxEmpty>No agents found</ComboboxEmpty>
+ </ComboboxContent>
+ </Combobox>
+ {!roomMembers.loading && roomMembers.agents.length === 0 && (
+ <p className="mt-1 text-xs text-foreground-muted">
+ None of your agents is a member of this room yet. Add one from the room's page in
+ the gateway, then try again.
+ </p>
+ )}
+ </Field>
+ )}
<Field>
<FieldLabel>Name</FieldLabel>
<Input
@@ -246,7 +397,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({
)}
</Field>
)}
- {room && (
+ {activeRoom && (
<Field>
<FieldLabel>Assume role</FieldLabel>
<Select
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx
new file mode 100644
index 000000000..97f60c3d6
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx
@@ -0,0 +1,112 @@
+import { observer } from 'mobx-react-lite';
+import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { sidebarStore } from '@renderer/lib/stores/app-state';
+import { agentExpandKey, SidebarAgentItem } from './agent-item';
+import { SidebarSessionItem } from './session-item';
+import {
+ groupByRoom,
+ isRoomViewActive,
+ openRoomInGateway,
+ openRoomInMessagingApp,
+ openRoomView,
+ RoomRow,
+ roomLabel,
+} from './sidebar-room-grouping';
+import { agentRoomGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
+import { agentSessions, scopedAgents } from './sidebar-tree-data';
+
+/**
+ * The agent-grouped sidebar: agents at the top level, their sessions beneath,
+ * bucketed by whichever room each session is connected to.
+ *
+ * Here a room is a property of a session — a heading over some of an agent's
+ * work — so rooms with nothing running in them do not appear, and the row
+ * offers only navigation. The room-grouped tree treats rooms as the subject
+ * instead; the two are separate on purpose.
+ */
+
+/** Render an agent's sessions grouped by room, under the agent row. */
+const AgentSessions = observer(function AgentSessions({
+ agentId,
+ locationId,
+ sessions,
+ depth,
+}: {
+ agentId: string;
+ locationId: string;
+ sessions: SessionStore[];
+ depth: number;
+}) {
+ return (
+ <>
+ {groupByRoom(sessions).map(([roomKey, roomSessions]) => {
+ // Sessions with no room sit directly under the agent, no room header.
+ if (roomKey === UNASSIGNED_ROOM_KEY) {
+ return roomSessions.map((session) => (
+ <SidebarSessionItem
+ key={session.data.id}
+ locationId={locationId}
+ sessionId={session.data.id}
+ depth={depth}
+ />
+ ));
+ }
+ const groupKey = agentRoomGroupKey(agentId, roomKey);
+ const roomExpanded = sidebarStore.isGroupExpanded(groupKey);
+ return (
+ <div key={roomKey}>
+ <RoomRow
+ label={roomLabel(roomKey)}
+ count={roomSessions.length}
+ expanded={roomExpanded}
+ depth={depth}
+ bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}
+ onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}
+ onSelect={() => openRoomView(roomKey)}
+ isActive={isRoomViewActive(roomKey)}
+ onOpenGateway={() => openRoomInGateway(roomKey)}
+ onOpenChannel={
+ switchRoomsStore.roomChannelUrl(roomKey)
+ ? () => openRoomInMessagingApp(roomKey)
+ : null
+ }
+ />
+ {roomExpanded &&
+ roomSessions.map((session) => (
+ <SidebarSessionItem
+ key={session.data.id}
+ locationId={locationId}
+ sessionId={session.data.id}
+ depth={depth + 1}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </>
+ );
+});
+
+export const AgentTree = observer(function AgentTree() {
+ return (
+ <>
+ {scopedAgents().map((entry) => {
+ const expanded = sidebarStore.isGroupExpanded(agentExpandKey(entry.agent.id));
+ return (
+ <div key={entry.agent.id}>
+ <SidebarAgentItem agent={entry.agent} depth={0} />
+ {expanded && (
+ <AgentSessions
+ agentId={entry.agent.id}
+ locationId={entry.agent.locationId}
+ sessions={agentSessions(entry)}
+ depth={1}
+ />
+ )}
+ </div>
+ );
+ })}
+ </>
+ );
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsx
index 83ec50166..b21edb3e5 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsx
@@ -1,7 +1,9 @@
import { DoorOpen, Filter, Laptop, ListFilter, Plus, Server, Users } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import type { ComponentType } from 'react';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
import { buttonVariants } from '@renderer/lib/ui/button';
@@ -23,7 +25,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/toolti
import { cn } from '@renderer/utils/utils';
import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';
import { getProvider } from '@shared/core/providers/agent-provider-registry';
-import type { SidebarGrouping } from '@shared/view-state';
+import { type SidebarGrouping, UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
const CONNECTION_LABEL: Record<AgentConnectionKind, string> = {
local: 'Local',
@@ -70,16 +72,131 @@ const ViewGroupingToggle = observer(function ViewGroupingToggle() {
);
});
+/** Human label for a messaging-app filter value. */
+function bridgeLabel(value: string): string {
+ if (value === UNBRIDGED_FILTER_VALUE) return 'No messaging app';
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
/**
- * Optional additive filters for the grouped sidebar — a funnel button that opens
- * checkbox sections for run location, agent type, and live-session presence. Only
- * dimensions with matching agents in the active server are offered; a dot on the
- * icon signals that filters are narrowing the tree.
+ * Filters for the room view: which messaging app a room is bridged to, and
+ * whether anything is running in it.
+ *
+ * The agent dimensions (run location, agent type) are deliberately absent. They
+ * describe an agent, and applying them here would mean "rooms containing an
+ * agent that matches" — a room disappearing because of a property of one of its
+ * members, under a control that looks like it filters rooms.
*/
-const FilterDropdown = observer(function FilterDropdown() {
+const RoomFilterSections = observer(function RoomFilterSections() {
+ const bridgeValues = switchRoomsStore.bridgeFilterValuesInActiveScope;
+
+ return (
+ <>
+ {bridgeValues.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
+ Messaging app
+ </DropdownMenuLabel>
+ {bridgeValues.map((value) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={sidebarStore.filterBridgeTypes.has(value)}
+ onCheckedChange={() => sidebarStore.toggleFilterBridgeType(value)}
+ >
+ {hasBridgeIcon(value) ? (
+ <BridgeIcon bridgeType={value} size={16} className="mr-1.5" />
+ ) : (
+ <DoorOpen className="mr-1.5 h-4 w-4" />
+ )}
+ {bridgeLabel(value)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuGroup>
+ )}
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
+ Activity
+ </DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={sidebarStore.filterRoomHasLiveSession}
+ onCheckedChange={(checked) => sidebarStore.setFilterRoomHasLiveSession(checked)}
+ >
+ Has running session
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </>
+ );
+});
+
+/** Filters for the agent view: run location, agent type, live-session presence.
+ * Only dimensions with matching agents on the active server are offered. */
+const AgentFilterSections = observer(function AgentFilterSections() {
const connections = sidebarStore.availableFilterConnections;
const providerIds = sidebarStore.availableFilterProviderIds;
- const active = sidebarStore.hasActiveFilters;
+
+ return (
+ <>
+ {connections.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
+ Run location
+ </DropdownMenuLabel>
+ {connections.map((kind) => (
+ <DropdownMenuCheckboxItem
+ key={kind}
+ checked={sidebarStore.filterConnections.has(kind)}
+ onCheckedChange={() => sidebarStore.toggleFilterConnection(kind)}
+ >
+ {kind === 'remote' ? (
+ <Server className="mr-1.5 h-4 w-4" />
+ ) : (
+ <Laptop className="mr-1.5 h-4 w-4" />
+ )}
+ {CONNECTION_LABEL[kind]}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuGroup>
+ )}
+ {providerIds.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
+ Agent type
+ </DropdownMenuLabel>
+ {providerIds.map((id) => (
+ <DropdownMenuCheckboxItem
+ key={id}
+ checked={sidebarStore.filterProviderIds.has(id)}
+ onCheckedChange={() => sidebarStore.toggleFilterProviderId(id)}
+ >
+ <AgentIcon id={id} size={16} className="mr-1.5" />
+ {getProvider(id)?.name ?? id}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuGroup>
+ )}
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
+ Session
+ </DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={sidebarStore.filterHasLiveSession}
+ onCheckedChange={(checked) => sidebarStore.setFilterHasLiveSession(checked)}
+ >
+ Has running session
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </>
+ );
+});
+
+/**
+ * Optional additive filters for the grouped sidebar — a funnel button whose
+ * sections belong to the view you are in, since the two views filter different
+ * things. A dot on the icon signals that the view on screen is being narrowed.
+ */
+const FilterDropdown = observer(function FilterDropdown() {
+ const roomMode = sidebarStore.grouping === 'room';
+ const active = sidebarStore.hasActiveFiltersInCurrentView;
return (
<DropdownMenu>
@@ -90,7 +207,7 @@ const FilterDropdown = observer(function FilterDropdown() {
render={
<button
type="button"
- aria-label="Filter agents"
+ aria-label={roomMode ? 'Filter rooms' : 'Filter agents'}
className={buttonVariants({
size: 'icon-xs',
variant: 'ghost',
@@ -113,57 +230,9 @@ const FilterDropdown = observer(function FilterDropdown() {
</Tooltip>
<DropdownMenuContent className="min-w-52" align="end">
<DropdownMenuGroup>
- <DropdownMenuLabel>Filter agents</DropdownMenuLabel>
- </DropdownMenuGroup>
- {connections.length > 0 && (
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
- Run location
- </DropdownMenuLabel>
- {connections.map((kind) => (
- <DropdownMenuCheckboxItem
- key={kind}
- checked={sidebarStore.filterConnections.has(kind)}
- onCheckedChange={() => sidebarStore.toggleFilterConnection(kind)}
- >
- {kind === 'remote' ? (
- <Server className="mr-1.5 h-4 w-4" />
- ) : (
- <Laptop className="mr-1.5 h-4 w-4" />
- )}
- {CONNECTION_LABEL[kind]}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuGroup>
- )}
- {providerIds.length > 0 && (
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
- Agent type
- </DropdownMenuLabel>
- {providerIds.map((id) => (
- <DropdownMenuCheckboxItem
- key={id}
- checked={sidebarStore.filterProviderIds.has(id)}
- onCheckedChange={() => sidebarStore.toggleFilterProviderId(id)}
- >
- <AgentIcon id={id} size={16} className="mr-1.5" />
- {getProvider(id)?.name ?? id}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuGroup>
- )}
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-xs font-normal text-foreground-muted">
- Session
- </DropdownMenuLabel>
- <DropdownMenuCheckboxItem
- checked={sidebarStore.filterHasLiveSession}
- onCheckedChange={(checked) => sidebarStore.setFilterHasLiveSession(checked)}
- >
- Has running session
- </DropdownMenuCheckboxItem>
+ <DropdownMenuLabel>{roomMode ? 'Filter rooms' : 'Filter agents'}</DropdownMenuLabel>
</DropdownMenuGroup>
+ {roomMode ? <RoomFilterSections /> : <AgentFilterSections />}
<DropdownMenuSeparator />
<DropdownMenuItem disabled={!active} onClick={() => sidebarStore.clearFilters()}>
Clear filters
@@ -175,6 +244,12 @@ const FilterDropdown = observer(function FilterDropdown() {
export const LocationsGroupLabel = observer(function LocationsGroupLabel() {
const showAddLocationModal = useShowModal('addAgentModal');
+ const showCreateRoomModal = useShowModal('createRoomModal');
+ // The add button acts on whatever the section is currently listing: adding an
+ // agent while looking at a list of rooms is not what the button appears to
+ // offer (CHOO-1875).
+ const roomMode = sidebarStore.grouping === 'room';
+ const addLabel = roomMode ? 'New Room' : 'Add Agent';
return (
<div className="flex h-[40px] items-center justify-between pr-2.5 pl-2.5">
@@ -188,7 +263,7 @@ export const LocationsGroupLabel = observer(function LocationsGroupLabel() {
render={
<button
type="button"
- aria-label="Sort agents"
+ aria-label={roomMode ? 'Sort rooms' : 'Sort agents'}
className={buttonVariants({
size: 'icon-xs',
variant: 'ghost',
@@ -207,20 +282,46 @@ export const LocationsGroupLabel = observer(function LocationsGroupLabel() {
<DropdownMenuContent className="min-w-48">
<DropdownMenuGroup>
<DropdownMenuLabel>Sort by</DropdownMenuLabel>
- <DropdownMenuRadioGroup value={sidebarStore.sessionSortBy}>
- <DropdownMenuRadioItem
- value="created-at"
- onClick={() => sidebarStore.applySort('created-at')}
- >
- Created at
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem
- value="updated-at"
- onClick={() => sidebarStore.applySort('updated-at')}
- >
- Last used
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
+ {roomMode ? (
+ // Rooms are places, so they order by their own properties, and
+ // separately from the session sort — switching view must not
+ // silently re-order the other one.
+ <DropdownMenuRadioGroup value={sidebarStore.roomSortBy}>
+ <DropdownMenuRadioItem
+ value="name"
+ onClick={() => sidebarStore.setRoomSortBy('name')}
+ >
+ Name
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="created-at"
+ onClick={() => sidebarStore.setRoomSortBy('created-at')}
+ >
+ Created
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="updated-at"
+ onClick={() => sidebarStore.setRoomSortBy('updated-at')}
+ >
+ Last active
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ ) : (
+ <DropdownMenuRadioGroup value={sidebarStore.sessionSortBy}>
+ <DropdownMenuRadioItem
+ value="created-at"
+ onClick={() => sidebarStore.applySort('created-at')}
+ >
+ Created at
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="updated-at"
+ onClick={() => sidebarStore.applySort('updated-at')}
+ >
+ Last used
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ )}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
@@ -230,8 +331,8 @@ export const LocationsGroupLabel = observer(function LocationsGroupLabel() {
render={
<button
type="button"
- onClick={() => showAddLocationModal({})}
- aria-label="Add Agent"
+ onClick={() => (roomMode ? showCreateRoomModal({}) : showAddLocationModal({}))}
+ aria-label={addLabel}
className={buttonVariants({
size: 'icon-xs',
variant: 'ghost',
@@ -243,8 +344,8 @@ export const LocationsGroupLabel = observer(function LocationsGroupLabel() {
}
/>
<TooltipContent>
- Add Agent
- <BoundShortcut settingsKey="newLocation" variant="badge" />
+ {addLabel}
+ {!roomMode && <BoundShortcut settingsKey="newLocation" variant="badge" />}
</TooltipContent>
</Tooltip>
</div>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx
new file mode 100644
index 000000000..578c6c707
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -0,0 +1,175 @@
+import { useQuery } from '@tanstack/react-query';
+import { Bot, ChevronRight, DoorOpen, Plus } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { getLocationStore } from '@renderer/features/locations/stores/location-selectors';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { useToast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from '@renderer/lib/ui/context-menu';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import { cn } from '@renderer/utils/utils';
+import type { Agent } from '@shared/core/agents/agents';
+import { SidebarItemMiniButton, SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';
+import { depthIndent, roomAgentGroupKey } from './sidebar-store';
+
+/**
+ * A member agent, as listed under a room.
+ *
+ * Deliberately not `SidebarAgentItem` with a room bolted on. The identity of
+ * this row is the *pair* (room, agent): the same agent is listed under every
+ * room it belongs to, and those are different places in the tree that expand
+ * and highlight independently. Sharing one row keyed by agent id made every
+ * copy expand and select together.
+ *
+ * Its actions are the room's, too — start a session here, or drop the agent's
+ * membership — rather than the whole-agent operations (reset, delete) that
+ * would read like room operations in this context and are not.
+ */
+export const RoomAgentRow = observer(function RoomAgentRow({
+ agent,
+ roomId,
+ depth,
+}: {
+ agent: Agent;
+ roomId: string;
+ depth: number;
+}) {
+ const { navigate } = useNavigate();
+ const showCreateSessionModal = useShowModal('sessionModal');
+ const { toastPromise } = useToast();
+
+ const location = getLocationStore(agent.locationId);
+
+ // Labelled by the agent's registered Switch name — this is a Switch room's
+ // member list, so the Switch identity is the one that matters here.
+ const remoteAgentQuery = useQuery({
+ queryKey: ['remoteAgentName', agent.serverId, agent.switchAgentId],
+ queryFn: () =>
+ rpc.switchServers.getRemoteAgent({
+ serverId: agent.serverId!,
+ agentId: agent.switchAgentId!,
+ }),
+ enabled: !!agent.serverId && !!agent.switchAgentId,
+ });
+ const label = remoteAgentQuery.data?.name?.trim() || agent.name || 'Unnamed agent';
+
+ const expandKey = roomAgentGroupKey(roomId, agent.id);
+ const expanded = sidebarStore.isGroupExpanded(expandKey);
+
+ // Active only when the agent page was opened from *this* room. The room
+ // travels on the route, so opening the same agent from the agent tree (no
+ // room) correctly lights up nothing here instead of an arbitrary row.
+ const params = appState.navigation.viewParamsStore.location as
+ | { locationId?: string; agentName?: string; roomId?: string }
+ | undefined;
+ const isActive =
+ appState.navigation.currentViewId === 'location' &&
+ params?.locationId === agent.locationId &&
+ params?.agentName === agent.name &&
+ params?.roomId === roomId;
+
+ if (!location) return null;
+
+ const iconClass =
+ 'absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0';
+
+ const removeFromRoom = () => {
+ const serverId = switchRoomsStore.roomServerId(roomId);
+ if (!serverId || !agent.switchAgentId) return;
+ const roomLabel = switchRoomsStore.roomNameById(roomId) ?? 'the room';
+ void toastPromise(
+ rpc.switchServers
+ .removeRoomAgent({ serverId, roomId, agentId: agent.switchAgentId })
+ .then(() => switchRoomsStore.refreshAll()),
+ {
+ loading: `Removing ${label} from ${roomLabel}…`,
+ success: `${label} was removed from ${roomLabel}`,
+ error: (error) =>
+ `Failed to remove from room: ${error instanceof Error ? error.message : String(error)}`,
+ }
+ );
+ };
+
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger>
+ <SidebarMenuRow
+ className="group/row flex h-8 justify-between px-1"
+ style={depthIndent(depth)}
+ data-active={isActive || undefined}
+ isActive={isActive}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => {
+ sidebarStore.ensureGroupExpanded(expandKey);
+ navigate('location', { locationId: agent.locationId, agentName: agent.name, roomId });
+ }}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ <SidebarItemMiniButton
+ type="button"
+ aria-label={`${expanded ? 'Collapse' : 'Expand'} ${label}`}
+ className="relative"
+ onClick={(e) => {
+ e.stopPropagation();
+ sidebarStore.toggleGroupExpanded(expandKey);
+ }}
+ >
+ {agent.providerId ? (
+ <AgentIcon id={agent.providerId} size={16} className={iconClass} />
+ ) : (
+ <Bot className={iconClass} />
+ )}
+ <ChevronRight
+ className={cn(
+ 'absolute h-4 w-4 opacity-0 transition-all duration-150 group-hover/row:opacity-100',
+ expanded && 'rotate-90'
+ )}
+ />
+ </SidebarItemMiniButton>
+ <SidebarMenuAction aria-label={`Open agent ${label}`} className="truncate select-none">
+ <span className="truncate">{label}</span>
+ </SidebarMenuAction>
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ className="h-6"
+ render={
+ <SidebarItemMiniButton
+ type="button"
+ aria-label={`New session for ${label} in this room`}
+ className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ showCreateSessionModal({
+ locationId: agent.locationId,
+ agentName: agent.name,
+ roomId,
+ });
+ }}
+ >
+ <Plus className="h-4 w-4" />
+ </SidebarItemMiniButton>
+ }
+ />
+ <TooltipContent>New session in this room</TooltipContent>
+ </Tooltip>
+ </SidebarMenuRow>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem variant="destructive" onClick={removeFromRoom}>
+ <DoorOpen className="size-4" />
+ Remove from this room
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.test.ts
new file mode 100644
index 000000000..26ac21ba1
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from 'vitest';
+import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
+
+const isProvisioned = vi.hoisted(() => vi.fn());
+const getSortInstant = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/features/sessions/stores/session-store', () => ({ isProvisioned }));
+vi.mock('./sidebar-store', () => ({ getSortInstant }));
+
+const { bridgeFilterValue, filterRoomGroups, sortRoomGroups } = await import('./room-tree-data');
+
+type TestSession = { id: string; running?: boolean; usedAt?: string };
+
+/** A session stand-in; the rules only ever ask whether it is running and when
+ * it was last used, both of which are mocked per test. */
+function session(id: string, opts: { running?: boolean; usedAt?: string } = {}) {
+ return { id, ...opts } as unknown as never;
+}
+
+function group(
+ roomKey: string,
+ opts: {
+ label?: string;
+ bridgeType?: string | null;
+ createdAt?: string | null;
+ sessions?: TestSession[];
+ } = {}
+) {
+ return {
+ roomKey,
+ label: opts.label ?? roomKey,
+ bridgeType: opts.bridgeType ?? null,
+ createdAt: opts.createdAt ?? null,
+ sessions: (opts.sessions ?? []).map((s) => session(s.id, s)),
+ };
+}
+
+isProvisioned.mockImplementation((s: TestSession) => s.running === true);
+getSortInstant.mockImplementation((s: TestSession) => s.usedAt);
+
+const NO_FILTERS = { bridgeTypes: new Set<string>(), hasLiveSession: false };
+
+describe('bridgeFilterValue', () => {
+ it('gives unbridged rooms a value of their own so they stay filterable', () => {
+ expect(bridgeFilterValue('slack')).toBe('slack');
+ expect(bridgeFilterValue(null)).toBe(UNBRIDGED_FILTER_VALUE);
+ });
+});
+
+describe('filterRoomGroups', () => {
+ it('keeps everything when nothing is filtered', () => {
+ const groups = [group('a'), group('b')];
+ expect(filterRoomGroups(groups, NO_FILTERS)).toBe(groups);
+ });
+
+ it('keeps only rooms on the chosen messaging apps', () => {
+ const groups = [
+ group('slack-room', { bridgeType: 'slack' }),
+ group('mm-room', { bridgeType: 'mattermost' }),
+ group('bare-room', { bridgeType: null }),
+ ];
+
+ const kept = filterRoomGroups(groups, {
+ bridgeTypes: new Set(['slack']),
+ hasLiveSession: false,
+ });
+
+ expect(kept.map((g) => g.roomKey)).toEqual(['slack-room']);
+ });
+
+ it('can filter for rooms with no messaging app at all', () => {
+ const groups = [group('slack-room', { bridgeType: 'slack' }), group('bare-room')];
+
+ const kept = filterRoomGroups(groups, {
+ bridgeTypes: new Set([UNBRIDGED_FILTER_VALUE]),
+ hasLiveSession: false,
+ });
+
+ expect(kept.map((g) => g.roomKey)).toEqual(['bare-room']);
+ });
+
+ it('keeps only rooms with something actually running', () => {
+ const groups = [
+ group('running', { sessions: [{ id: 's1', running: true }] }),
+ // A session that exists but has not started is not a room in use.
+ group('starting', { sessions: [{ id: 's2', running: false }] }),
+ group('idle'),
+ ];
+
+ const kept = filterRoomGroups(groups, {
+ bridgeTypes: new Set<string>(),
+ hasLiveSession: true,
+ });
+
+ expect(kept.map((g) => g.roomKey)).toEqual(['running']);
+ });
+
+ it('ANDs the dimensions together', () => {
+ const groups = [
+ group('slack-live', { bridgeType: 'slack', sessions: [{ id: 's1', running: true }] }),
+ group('slack-idle', { bridgeType: 'slack' }),
+ group('mm-live', { bridgeType: 'mattermost', sessions: [{ id: 's2', running: true }] }),
+ ];
+
+ const kept = filterRoomGroups(groups, {
+ bridgeTypes: new Set(['slack']),
+ hasLiveSession: true,
+ });
+
+ expect(kept.map((g) => g.roomKey)).toEqual(['slack-live']);
+ });
+});
+
+describe('sortRoomGroups', () => {
+ it('sorts by name by default', () => {
+ const groups = [group('b', { label: 'Beta' }), group('a', { label: 'Alpha' })];
+ expect(sortRoomGroups(groups, 'name').map((g) => g.label)).toEqual(['Alpha', 'Beta']);
+ });
+
+ it('sorts newest first by creation', () => {
+ const groups = [
+ group('old', { createdAt: '2026-01-01T00:00:00Z' }),
+ group('new', { createdAt: '2026-06-01T00:00:00Z' }),
+ ];
+ expect(sortRoomGroups(groups, 'created-at').map((g) => g.roomKey)).toEqual(['new', 'old']);
+ });
+
+ it('sorts by the most recent session activity in each room', () => {
+ const groups = [
+ group('quiet', { sessions: [{ id: 's1', usedAt: '2026-01-01T00:00:00Z' }] }),
+ group('busy', {
+ sessions: [
+ { id: 's2', usedAt: '2026-01-02T00:00:00Z' },
+ { id: 's3', usedAt: '2026-09-01T00:00:00Z' },
+ ],
+ }),
+ ];
+ expect(sortRoomGroups(groups, 'updated-at').map((g) => g.roomKey)).toEqual(['busy', 'quiet']);
+ });
+
+ it('puts rooms with no value for the sort key last, then orders them by name', () => {
+ // Most rooms have nothing running in them; that has to be an ordinary case
+ // rather than one that scatters them through the list.
+ const groups = [
+ group('never-used-z', { label: 'Zeta' }),
+ group('used', { label: 'Used', sessions: [{ id: 's1', usedAt: '2026-01-01T00:00:00Z' }] }),
+ group('never-used-a', { label: 'Alpha' }),
+ ];
+ expect(sortRoomGroups(groups, 'updated-at').map((g) => g.label)).toEqual([
+ 'Used',
+ 'Alpha',
+ 'Zeta',
+ ]);
+ });
+
+ it('does not reorder the array it was given', () => {
+ const groups = [group('b', { label: 'Beta' }), group('a', { label: 'Alpha' })];
+ sortRoomGroups(groups, 'name');
+ expect(groups.map((g) => g.label)).toEqual(['Beta', 'Alpha']);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.ts
new file mode 100644
index 000000000..5c9c9b2f5
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree-data.ts
@@ -0,0 +1,94 @@
+import { isProvisioned, type SessionStore } from '@renderer/features/sessions/stores/session-store';
+import type { SidebarRoomSortBy } from '@shared/view-state';
+import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
+import { getSortInstant } from './sidebar-store';
+
+/**
+ * What the room view needs to know about a room to order and filter it, without
+ * reaching into stores. Kept as plain data so the rules below are testable on
+ * their own — they are the part that decides what you can and cannot see.
+ */
+export type RoomGroup = {
+ roomKey: string;
+ label: string;
+ /** Bridge platform (`slack`, `mattermost`, …), or null when not bridged. */
+ bridgeType: string | null;
+ /** When the room was created, if its server's room list has been read. */
+ createdAt: string | null;
+ sessions: SessionStore[];
+};
+
+/** The value a room is filtered by in the messaging-app dimension. Unbridged
+ * rooms get a sentinel rather than being unfilterable. */
+export function bridgeFilterValue(bridgeType: string | null): string {
+ return bridgeType ?? UNBRIDGED_FILTER_VALUE;
+}
+
+export type RoomFilters = {
+ /** Bridge types (and {@link UNBRIDGED_FILTER_VALUE}) to keep. Empty = keep all. */
+ bridgeTypes: ReadonlySet<string>;
+ /** Keep only rooms with a running session in them. */
+ hasLiveSession: boolean;
+};
+
+/** Whether any room filter is set. */
+export function hasRoomFilters(filters: RoomFilters): boolean {
+ return filters.bridgeTypes.size > 0 || filters.hasLiveSession;
+}
+
+/**
+ * Apply the room filters. Dimensions are ANDed, values within one ORed — the
+ * same rule the agent filters follow.
+ */
+export function filterRoomGroups(groups: RoomGroup[], filters: RoomFilters): RoomGroup[] {
+ if (!hasRoomFilters(filters)) return groups;
+ return groups.filter((group) => {
+ if (
+ filters.bridgeTypes.size > 0 &&
+ !filters.bridgeTypes.has(bridgeFilterValue(group.bridgeType))
+ ) {
+ return false;
+ }
+ if (filters.hasLiveSession && !group.sessions.some(isProvisioned)) return false;
+ return true;
+ });
+}
+
+/** The most recent session activity in a room, or null when nothing has run in
+ * it. Rooms are places: plenty of them have no activity at all, and that is the
+ * case ordering has to handle rather than treat as a missing value. */
+function lastActivity(group: RoomGroup): string | null {
+ let latest: string | null = null;
+ for (const session of group.sessions) {
+ const instant = getSortInstant(session, 'updated');
+ if (instant && (latest === null || instant > latest)) latest = instant;
+ }
+ return latest;
+}
+
+/**
+ * Order rooms for the room view.
+ *
+ * `created-at` and `updated-at` put the most recent first, matching the session
+ * sort. A room the sort key is unknown for (never loaded, or never used) sorts
+ * below every room that has one, then by name, so the ordering stays stable
+ * instead of shuffling as data arrives.
+ */
+export function sortRoomGroups(groups: RoomGroup[], sortBy: SidebarRoomSortBy): RoomGroup[] {
+ const key =
+ sortBy === 'created-at'
+ ? (group: RoomGroup) => group.createdAt
+ : sortBy === 'updated-at'
+ ? lastActivity
+ : () => null;
+ return [...groups].sort((a, b) => {
+ const ak = key(a);
+ const bk = key(b);
+ if (ak !== bk) {
+ if (ak === null) return 1;
+ if (bk === null) return -1;
+ return bk.localeCompare(ak);
+ }
+ return a.label.localeCompare(b.label);
+ });
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx
new file mode 100644
index 000000000..0325b2076
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx
@@ -0,0 +1,156 @@
+import { observer } from 'mobx-react-lite';
+import { Fragment } from 'react';
+import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { sidebarStore } from '@renderer/lib/stores/app-state';
+import { RoomAgentRow } from './room-agent-row';
+import { filterRoomGroups, sortRoomGroups } from './room-tree-data';
+import { SidebarSessionItem } from './session-item';
+import {
+ groupByRoom,
+ isRoomViewActive,
+ openRoomInGateway,
+ openRoomInMessagingApp,
+ openRoomView,
+ RoomRow,
+ roomLabel,
+} from './sidebar-room-grouping';
+import { roomAgentGroupKey, roomViewGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
+import { type AgentEntry, agentSessions, scopedAgents } from './sidebar-tree-data';
+
+/**
+ * The room-grouped sidebar: rooms at the top level, their member agents
+ * beneath, and each agent's sessions in that room below that.
+ *
+ * A room here is a place, not a property of a session — it is listed because it
+ * exists and concerns you, and its rows act on the room itself (add a member,
+ * remove one, open the channel). That is why this is a separate tree from the
+ * agent-grouped one rather than the same tree with the nesting inverted, down
+ * to its own agent row.
+ */
+
+/** Which of this app's agents belong to which room. Membership, not sessions:
+ * an agent is in a room whether or not it is running there — and, just as
+ * importantly, is *out* of it the moment membership is dropped, without waiting
+ * for a session that is still pointed at the room to end. */
+function membersByRoom(): Map<string, AgentEntry[]> {
+ const byRoom = new Map<string, AgentEntry[]>();
+ for (const entry of scopedAgents()) {
+ const { serverId, switchAgentId } = entry.agent;
+ if (!serverId || !switchAgentId) continue;
+ for (const membership of switchRoomsStore.roomsFor(serverId, switchAgentId) ?? []) {
+ if (membership.archived) continue;
+ const list = byRoom.get(membership.roomId);
+ if (list) list.push(entry);
+ else byRoom.set(membership.roomId, [entry]);
+ }
+ }
+ return byRoom;
+}
+
+export const RoomTree = observer(function RoomTree() {
+ const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');
+
+ // Tag every visible session with the agent it belongs to, then group by room.
+ const bySession = new Map<string, AgentEntry>();
+ const allSessions: SessionStore[] = [];
+ for (const entry of scopedAgents()) {
+ for (const session of agentSessions(entry)) {
+ bySession.set(session.data.id, entry);
+ allSessions.push(session);
+ }
+ }
+
+ const members = membersByRoom();
+ // A room is listed when one of this app's agents is a member of it, when it
+ // has a session, or when it is listed on its own account — every room on a
+ // server this install manages, and rooms you created elsewhere. None of that
+ // waits on a session, so a room you just made is there immediately.
+ const alwaysShow = [
+ ...new Set([
+ ...switchRoomsStore.listedRoomsInActiveScope.map((room) => room.id),
+ ...members.keys(),
+ ]),
+ ];
+
+ const groups = sortRoomGroups(
+ filterRoomGroups(
+ groupByRoom(allSessions, alwaysShow)
+ // This view lists rooms. A session connected to none of them is not in
+ // a room, and a bucket standing in for that is not one either — the
+ // agent view is where a session with no room belongs.
+ .filter(([roomKey]) => roomKey !== UNASSIGNED_ROOM_KEY)
+ .map(([roomKey, sessions]) => ({
+ roomKey,
+ label: roomLabel(roomKey),
+ bridgeType: switchRoomsStore.roomBridgeTypeById(roomKey),
+ createdAt: switchRoomsStore.roomSummaryById(roomKey)?.createdAt ?? null,
+ sessions,
+ })),
+ {
+ bridgeTypes: sidebarStore.filterBridgeTypes,
+ hasLiveSession: sidebarStore.filterRoomHasLiveSession,
+ }
+ ),
+ sidebarStore.roomSortBy
+ );
+
+ if (groups.length === 0 && sidebarStore.hasActiveRoomFilters) {
+ return <p className="px-2 py-3 text-xs text-foreground-muted">No rooms match filters</p>;
+ }
+
+ return (
+ <>
+ {groups.map(({ roomKey, sessions: roomSessions }) => {
+ const roomViewKey = roomViewGroupKey(roomKey);
+ const expanded = sidebarStore.isGroupExpanded(roomViewKey);
+ const agentsInRoom = members.get(roomKey) ?? [];
+ return (
+ <div key={roomKey}>
+ <RoomRow
+ label={roomLabel(roomKey)}
+ count={roomSessions.length}
+ expanded={expanded}
+ depth={0}
+ bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}
+ onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}
+ onSelect={() => openRoomView(roomKey)}
+ isActive={isRoomViewActive(roomKey)}
+ onOpenGateway={() => openRoomInGateway(roomKey)}
+ onOpenChannel={
+ switchRoomsStore.roomChannelUrl(roomKey)
+ ? () => openRoomInMessagingApp(roomKey)
+ : null
+ }
+ onAddAgent={() => showAddAgentsToRoomModal({ roomId: roomKey })}
+ />
+ {expanded &&
+ agentsInRoom.map((entry) => {
+ const sessionsHere = roomSessions.filter(
+ (session) => bySession.get(session.data.id)?.agent.id === entry.agent.id
+ );
+ const agentExpanded = sidebarStore.isGroupExpanded(
+ roomAgentGroupKey(roomKey, entry.agent.id)
+ );
+ return (
+ <Fragment key={entry.agent.id}>
+ <RoomAgentRow agent={entry.agent} roomId={roomKey} depth={1} />
+ {agentExpanded &&
+ sessionsHere.map((session) => (
+ <SidebarSessionItem
+ key={session.data.id}
+ locationId={entry.agent.locationId}
+ sessionId={session.data.id}
+ depth={2}
+ />
+ ))}
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+ })}
+ </>
+ );
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
index 8822ac0b6..bf7b30166 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
@@ -1,245 +1,62 @@
import { observer } from 'mobx-react-lite';
-import { Fragment, useEffect } from 'react';
+import { useEffect } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import type { LocationStore } from '@renderer/features/locations/stores/location';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
-import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { sidebarStore } from '@renderer/lib/stores/app-state';
-import type { Agent } from '@shared/core/agents/agents';
-import { SidebarAgentItem, agentExpandKey } from './agent-item';
-import { SidebarSessionItem } from './session-item';
-import {
- groupByRoom,
- openRoomInGateway,
- openRoomView,
- openRoomInMessagingApp,
- isRoomViewActive,
- RoomRow,
- roomLabel,
-} from './sidebar-room-grouping';
-import { agentRoomGroupKey, roomViewGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
-
-/** An agent paired with its (mounted) location, for the flat sidebar list. */
-type AgentEntry = { agent: Agent; location: LocationStore };
-
-/**
- * The flat list of agents in the active-server scope, newest first. switchdash
- * shows agents as a flat list — not grouped by directory (CHOO-1440).
- */
-function scopedAgents(): AgentEntry[] {
- const entries: AgentEntry[] = [];
- for (const location of sidebarStore.filteredLocations) {
- for (const agent of agentsStore.byLocation.get(location.id) ?? []) {
- entries.push({ agent, location });
- }
- }
- return entries.sort(
- (a, b) =>
- b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.name.localeCompare(b.agent.name)
- );
-}
+import { AgentTree } from './agent-tree';
+import { RoomTree } from './room-tree';
+import { switchIdentities } from './sidebar-tree-data';
/**
- * An agent's visible sessions: the location's sessions it owns. Sessions are
- * paired to their agent by `agent_id` — the authoritative link — not by matching
- * a name frozen into the session's config against the agent's definition. A
- * session whose owning agent no longer matches by name is still shown under its
- * agent instead of silently vanishing (CHOO-1440).
+ * The sidebar body: loads what both trees read, then hands over to whichever
+ * one the current grouping calls for.
+ *
+ * Agents-first and rooms-first are genuinely different views — different
+ * subjects, different nesting, different row actions — so they are separate
+ * components rather than one tree with the levels swapped.
*/
-function agentSessions(entry: AgentEntry): SessionStore[] {
- const all = sidebarStore.visibleSessionsForLocation(entry.location.id);
- return all.filter(
- (session) => 'agentId' in session.data && session.data.agentId === entry.agent.id
- );
-}
-
export const SidebarGroupedList = observer(function SidebarGroupedList() {
- // Live session→room connections + room names live on the server; pull them
- // once on mount and refresh names on focus so headers show names not ids.
+ // Live session→room connections, room names and room membership all live on
+ // the server; pull them once on mount and refresh on focus.
useEffect(() => {
roomConnectionsStore.ensureLoaded();
- void agentsStore.load();
void hostReachabilityStore.hydrate();
+ // Room membership is what puts an agent under a room, so it is loaded for
+ // every agent up front rather than lazily per row.
+ const loadRooms = async (force: boolean) => {
+ await agentsStore.load();
+ await switchRoomsStore.ensureMembershipsFor(switchIdentities(), { force });
+ };
+ void loadRooms(false);
void switchServersStore.init().then(() => switchRoomsStore.loadRoomNames());
const onFocus = () => {
- void agentsStore.load();
+ void loadRooms(true);
void switchRoomsStore.loadRoomNames();
};
window.addEventListener('focus', onFocus);
return () => window.removeEventListener('focus', onFocus);
}, []);
+ // Agent filters narrowing everything away is only an empty *agent* list. The
+ // room view lists rooms, which are still there, and reports its own filters
+ // being too narrow itself.
const showFilterEmptyState =
- sidebarStore.hasActiveFilters && sidebarStore.filteredLocations.length === 0;
+ sidebarStore.grouping !== 'room' &&
+ sidebarStore.hasActiveFilters &&
+ sidebarStore.filteredLocations.length === 0;
return (
<div className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">
{showFilterEmptyState ? (
<p className="px-2 py-3 text-xs text-foreground-muted">No agents match filters</p>
) : sidebarStore.grouping === 'room' ? (
- <RoomFocusedTree />
+ <RoomTree />
) : (
- <AgentFocusedTree />
+ <AgentTree />
)}
</div>
);
});
-
-/** Render an agent's sessions grouped by room, under the agent row. */
-const AgentSessions = observer(function AgentSessions({
- agentId,
- locationId,
- sessions,
- depth,
-}: {
- agentId: string;
- locationId: string;
- sessions: SessionStore[];
- depth: number;
-}) {
- return (
- <>
- {groupByRoom(sessions).map(([roomKey, roomSessions]) => {
- // Sessions with no room sit directly under the agent, no room header.
- if (roomKey === UNASSIGNED_ROOM_KEY) {
- return roomSessions.map((session) => (
- <SidebarSessionItem
- key={session.data.id}
- locationId={locationId}
- sessionId={session.data.id}
- depth={depth}
- />
- ));
- }
- const groupKey = agentRoomGroupKey(agentId, roomKey);
- const roomExpanded = sidebarStore.isGroupExpanded(groupKey);
- return (
- <div key={roomKey}>
- <RoomRow
- label={roomLabel(roomKey)}
- count={roomSessions.length}
- expanded={roomExpanded}
- depth={depth}
- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}
- onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}
- onSelect={roomKey === UNASSIGNED_ROOM_KEY ? null : () => openRoomView(roomKey)}
- isActive={isRoomViewActive(roomKey)}
- onOpenGateway={() => openRoomInGateway(roomKey)}
- onOpenChannel={
- switchRoomsStore.roomChannelUrl(roomKey)
- ? () => openRoomInMessagingApp(roomKey)
- : null
- }
- />
- {roomExpanded &&
- roomSessions.map((session) => (
- <SidebarSessionItem
- key={session.data.id}
- locationId={locationId}
- sessionId={session.data.id}
- depth={depth + 1}
- />
- ))}
- </div>
- );
- })}
- </>
- );
-});
-
-const AgentFocusedTree = observer(function AgentFocusedTree() {
- const agents = scopedAgents();
- return (
- <>
- {agents.map((entry) => {
- const expanded = sidebarStore.isGroupExpanded(agentExpandKey(entry.agent.id));
- return (
- <div key={entry.agent.id}>
- <SidebarAgentItem agent={entry.agent} depth={0} />
- {expanded && (
- <AgentSessions
- agentId={entry.agent.id}
- locationId={entry.agent.locationId}
- sessions={agentSessions(entry)}
- depth={1}
- />
- )}
- </div>
- );
- })}
- </>
- );
-});
-
-const RoomFocusedTree = observer(function RoomFocusedTree() {
- // Tag every visible session with the agent it belongs to, then group by room.
- const bySession = new Map<string, AgentEntry>();
- const allSessions: SessionStore[] = [];
- for (const entry of scopedAgents()) {
- for (const session of agentSessions(entry)) {
- bySession.set(session.data.id, entry);
- allSessions.push(session);
- }
- }
-
- return (
- <>
- {groupByRoom(allSessions).map(([roomKey, roomSessions]) => {
- const roomViewKey = roomViewGroupKey(roomKey);
- const expanded = sidebarStore.isGroupExpanded(roomViewKey);
- // Agents that have a session in this room, in first-seen order.
- const seen = new Set<string>();
- const agentsInRoom: AgentEntry[] = [];
- for (const session of roomSessions) {
- const entry = bySession.get(session.data.id);
- if (entry && !seen.has(entry.agent.id)) {
- seen.add(entry.agent.id);
- agentsInRoom.push(entry);
- }
- }
- return (
- <div key={roomKey}>
- <RoomRow
- label={roomLabel(roomKey)}
- count={roomSessions.length}
- expanded={expanded}
- depth={0}
- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}
- onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}
- onSelect={roomKey === UNASSIGNED_ROOM_KEY ? null : () => openRoomView(roomKey)}
- isActive={isRoomViewActive(roomKey)}
- onOpenGateway={() => openRoomInGateway(roomKey)}
- onOpenChannel={
- switchRoomsStore.roomChannelUrl(roomKey)
- ? () => openRoomInMessagingApp(roomKey)
- : null
- }
- />
- {expanded &&
- agentsInRoom.map((entry) => {
- const agentSessionsHere = roomSessions.filter(
- (session) => bySession.get(session.data.id)?.agent.id === entry.agent.id
- );
- return (
- <Fragment key={entry.agent.id}>
- <SidebarAgentItem agent={entry.agent} depth={1} />
- {agentSessionsHere.map((session) => (
- <SidebarSessionItem
- key={session.data.id}
- locationId={entry.agent.locationId}
- sessionId={session.data.id}
- depth={2}
- />
- ))}
- </Fragment>
- );
- })}
- </div>
- );
- })}
- </>
- );
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.test.ts
new file mode 100644
index 000000000..feab55a91
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+
+const roomForSession = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));
+vi.mock('@renderer/features/switch-rooms/switch-rooms-store', () => ({
+ switchRoomsStore: { roomForSession },
+}));
+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
+ switchRoomsStore: { roomNameById: (id: string) => id },
+}));
+
+const { groupByRoom } = await import('./sidebar-room-grouping');
+
+function session(id: string): SessionStore {
+ return { data: { id } } as SessionStore;
+}
+
+describe('groupByRoom', () => {
+ it('groups sessions under the room each is connected to', () => {
+ roomForSession.mockImplementation((id: string) => (id === 's1' ? 'room-a' : 'room-b'));
+
+ expect(groupByRoom([session('s1'), session('s2')]).map(([key, s]) => [key, s.length])).toEqual([
+ ['room-a', 1],
+ ['room-b', 1],
+ ]);
+ });
+
+ it('sinks sessions with no room into the Unassigned bucket, listed last', () => {
+ roomForSession.mockImplementation((id: string) => (id === 's1' ? 'room-a' : null));
+
+ const keys = groupByRoom([session('s2'), session('s1')]).map(([key]) => key);
+ expect(keys[0]).toBe('room-a');
+ expect(keys.at(-1)).not.toBe('room-a');
+ expect(keys).toHaveLength(2);
+ });
+
+ it('lists an alwaysShow room with no sessions, so a new room is visible before anything joins it', () => {
+ roomForSession.mockReturnValue(null);
+
+ expect(groupByRoom([], ['room-new'])).toEqual([['room-new', []]]);
+ });
+
+ it('does not duplicate an alwaysShow room that already has sessions', () => {
+ roomForSession.mockReturnValue('room-a');
+
+ expect(groupByRoom([session('s1')], ['room-a']).map(([key, s]) => [key, s.length])).toEqual([
+ ['room-a', 1],
+ ]);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
index 8a8c2f911..951975352 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
@@ -1,9 +1,9 @@
-import { ChevronRight, DoorOpen, ExternalLink } from 'lucide-react';
+import { ChevronRight, DoorOpen, ExternalLink, Plus } from 'lucide-react';
import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+import { openRoomChannel, openRoomGatewayPage } from '@renderer/features/switch-rooms/room-links';
import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
-import { rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { cn } from '@renderer/utils/utils';
@@ -23,8 +23,7 @@ export function roomLabel(roomKey: string): string {
/** Open a room's detail page in the gateway web app (no-op for Unassigned). */
export function openRoomInGateway(roomKey: string): void {
if (roomKey === UNASSIGNED_ROOM_KEY) return;
- const url = switchRoomsStore.gatewayRoomUrl(roomKey);
- if (url) void rpc.app.openExternal(url);
+ openRoomGatewayPage(roomKey);
}
/** Show a room's conversation in the main panel (no-op for Unassigned, which
@@ -56,13 +55,22 @@ export function isRoomViewActive(roomKey: string): boolean {
*/
export function openRoomInMessagingApp(roomKey: string): void {
if (roomKey === UNASSIGNED_ROOM_KEY) return;
- const url = switchRoomsStore.roomChannelUrl(roomKey);
- if (url) void rpc.app.openExternal(url);
+ openRoomChannel(roomKey);
}
-/** Group sessions by their current room key, named rooms first then Unassigned. */
-export function groupByRoom(sessions: SessionStore[]): [string, SessionStore[]][] {
+/**
+ * Group sessions by their current room key, named rooms first then Unassigned.
+ *
+ * `alwaysShow` room keys are included even with no sessions, so a room can be
+ * listed before anything has connected to it — otherwise a room you just
+ * created would be invisible until an agent joined it.
+ */
+export function groupByRoom(
+ sessions: SessionStore[],
+ alwaysShow: string[] = []
+): [string, SessionStore[]][] {
const groups = new Map<string, SessionStore[]>();
+ for (const key of alwaysShow) groups.set(key, []);
for (const session of sessions) {
const key = sessionRoomId(session) ?? UNASSIGNED_ROOM_KEY;
const list = groups.get(key);
@@ -91,6 +99,7 @@ export function RoomRow({
onOpenGateway,
onOpenChannel = null,
onSelect = null,
+ onAddAgent = null,
isActive = false,
depth = 0,
bridgeType = null,
@@ -108,11 +117,13 @@ export function RoomRow({
/** Open the room's channel in the messaging app, or null when there is no
* native deeplink (room not bridged / link unknown). */
onOpenChannel?: (() => void) | null;
+ /** Add an agent to this room. Null for rows with no room behind them
+ * (Unassigned), or where membership is not editable from here. */
+ onAddAgent?: (() => void) | null;
depth?: number;
/** Bridge platform type (`slack`, `mattermost`, …) when the room is bridged. */
bridgeType?: string | null;
}) {
- const linkable = label !== 'Unassigned';
const channelLinkable = onOpenChannel !== null && hasBridgeIcon(bridgeType);
return (
<SidebarMenuRow
@@ -168,26 +179,44 @@ export function RoomRow({
<TooltipContent>Open in {bridgeType}</TooltipContent>
</Tooltip>
)}
- {linkable && (
+ {onAddAgent && (
<Tooltip>
<TooltipTrigger
render={
<SidebarItemMiniButton
type="button"
- aria-label={`Open ${label} in gateway`}
+ aria-label={`Add an agent to ${label}`}
className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100"
onClick={(e) => {
e.stopPropagation();
- onOpenGateway();
+ onAddAgent();
}}
>
- <ExternalLink className="h-3.5 w-3.5" />
+ <Plus className="h-3.5 w-3.5" />
</SidebarItemMiniButton>
}
/>
- <TooltipContent>Open in gateway</TooltipContent>
+ <TooltipContent>Add an agent to this room</TooltipContent>
</Tooltip>
)}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <SidebarItemMiniButton
+ type="button"
+ aria-label={`Open ${label} in gateway`}
+ className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenGateway();
+ }}
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ </SidebarItemMiniButton>
+ }
+ />
+ <TooltipContent>Open in gateway</TooltipContent>
+ </Tooltip>
<span className="shrink-0 text-xs text-foreground-tertiary-passive">{count}</span>
</SidebarMenuRow>
);
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
index d46e9a73d..37dc36a38 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
@@ -6,6 +6,7 @@ import type { Agent } from '@shared/core/agents/agents';
import {
agentRoomGroupKey,
applyManualOrder,
+ roomAgentGroupKey,
roomViewGroupKey,
SidebarStore,
} from './sidebar-store';
@@ -161,6 +162,16 @@ describe('SidebarStore grouping', () => {
expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(true);
});
+ it('collapses one agent-under-room without collapsing the same agent elsewhere', () => {
+ // An agent in two rooms is two rows in two places, not one row drawn twice.
+ // Keyed by agent alone they collapsed and highlighted together.
+ const store = new SidebarStore(locationManager([]));
+ store.toggleGroupExpanded(roomAgentGroupKey('room-1', 'agent-1'));
+
+ expect(store.isGroupExpanded(roomAgentGroupKey('room-1', 'agent-1'))).toBe(false);
+ expect(store.isGroupExpanded(roomAgentGroupKey('room-2', 'agent-1'))).toBe(true);
+ });
+
it('tracks and clears a pending scroll-to-session request', () => {
const store = new SidebarStore(locationManager([]));
expect(store.pendingScrollSessionId).toBeNull();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
index e8dc31d34..23619f9f2 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
@@ -16,7 +16,12 @@ import {
isValidProviderId,
type AgentProviderId,
} from '@shared/core/providers/agent-provider-registry';
-import type { SidebarGrouping, SidebarSnapshot, SidebarSessionSortBy } from '@shared/view-state';
+import type {
+ SidebarGrouping,
+ SidebarRoomSortBy,
+ SidebarSnapshot,
+ SidebarSessionSortBy,
+} from '@shared/view-state';
const AGENT_CONNECTION_KINDS: readonly AgentConnectionKind[] = ['local', 'remote'];
@@ -50,6 +55,18 @@ export function roomViewGroupKey(roomKey: string): string {
return `rv:${roomKey}`;
}
+/**
+ * `collapsedGroupKeys` key for an agent listed under a room (room-focused view).
+ *
+ * Keyed by the pair, not by the agent: the same agent appears under every room
+ * it belongs to, and those rows are separate places in the tree. Keying on the
+ * agent alone made them one row rendered many times — collapse one and they all
+ * collapsed.
+ */
+export function roomAgentGroupKey(roomKey: string, agentId: string): string {
+ return `ra:${roomKey}|${agentId}`;
+}
+
function parseSidebarGrouping(value: unknown): SidebarGrouping | undefined {
return value === 'agent' || value === 'room' ? value : undefined;
}
@@ -58,6 +75,10 @@ function parseSidebarSessionSortBy(value: unknown): SidebarSessionSortBy | undef
return value === 'created-at' || value === 'updated-at' ? value : undefined;
}
+function parseSidebarRoomSortBy(value: unknown): SidebarRoomSortBy | undefined {
+ return value === 'name' || value === 'created-at' || value === 'updated-at' ? value : undefined;
+}
+
export type SessionSortKind = 'created' | 'updated';
export function sortKindFor(sortBy: SidebarSessionSortBy): SessionSortKind {
@@ -131,6 +152,16 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
filterConnections = observable.set<AgentConnectionKind>();
filterProviderIds = observable.set<AgentProviderId>();
filterHasLiveSession = false;
+ /**
+ * Room-focused sort and filters. Separate from the agent ones because the two
+ * views filter and order different things: a room is a place, an agent is a
+ * worker, and a dimension that narrows one has no honest meaning in the other.
+ * Rooms default to name order, which is what they had before they were
+ * sortable at all.
+ */
+ roomSortBy: SidebarRoomSortBy = 'name';
+ filterBridgeTypes = observable.set<string>();
+ filterRoomHasLiveSession = false;
/**
* Session whose row should scroll itself into view once it mounts. Set by the
* deeplink handler (after revealing/expanding the tree) so the landed session
@@ -145,6 +176,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
collapsedGroupKeys: false,
filterConnections: false,
filterProviderIds: false,
+ filterBridgeTypes: false,
sidebarRows: computed,
pinnedSidebarEntries: computed,
filteredLocations: computed,
@@ -234,7 +266,8 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
return false;
}
- /** Whether any filter dimension is currently narrowing the sidebar. */
+ /** Whether any agent filter is currently narrowing the agent list. Scopes the
+ * locations both trees read, so it applies whatever the grouping. */
get hasActiveFilters(): boolean {
return (
this.filterConnections.size > 0 ||
@@ -243,6 +276,17 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
);
}
+ /** Whether any room filter is currently narrowing the room list. */
+ get hasActiveRoomFilters(): boolean {
+ return this.filterBridgeTypes.size > 0 || this.filterRoomHasLiveSession;
+ }
+
+ /** Whether the view on screen is being narrowed — what the filter button's
+ * "on" dot reflects, so it reports the filters you can actually see. */
+ get hasActiveFiltersInCurrentView(): boolean {
+ return this.grouping === 'room' ? this.hasActiveRoomFilters : this.hasActiveFilters;
+ }
+
/** A location passes when it satisfies every active filter dimension. */
private locationMatchesFilters(locationId: string): boolean {
if (this.filterConnections.size > 0) {
@@ -394,6 +438,9 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
filterConnections: [...this.filterConnections],
filterProviderIds: [...this.filterProviderIds],
filterHasLiveSession: this.filterHasLiveSession,
+ roomSortBy: this.roomSortBy,
+ filterBridgeTypes: [...this.filterBridgeTypes],
+ filterRoomHasLiveSession: this.filterRoomHasLiveSession,
};
}
@@ -434,6 +481,14 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
if (snapshot.filterHasLiveSession !== undefined) {
this.filterHasLiveSession = snapshot.filterHasLiveSession;
}
+ const roomSortBy = parseSidebarRoomSortBy(snapshot.roomSortBy);
+ if (roomSortBy !== undefined) this.roomSortBy = roomSortBy;
+ if (snapshot.filterBridgeTypes !== undefined) {
+ this.filterBridgeTypes.replace(snapshot.filterBridgeTypes);
+ }
+ if (snapshot.filterRoomHasLiveSession !== undefined) {
+ this.filterRoomHasLiveSession = snapshot.filterRoomHasLiveSession;
+ }
}
/** Called on first load when no snapshot exists — expand all known locations. */
@@ -477,7 +532,27 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
this.filterHasLiveSession = value;
}
+ toggleFilterBridgeType(bridgeType: string): void {
+ if (this.filterBridgeTypes.has(bridgeType)) this.filterBridgeTypes.delete(bridgeType);
+ else this.filterBridgeTypes.add(bridgeType);
+ }
+
+ setFilterRoomHasLiveSession(value: boolean): void {
+ this.filterRoomHasLiveSession = value;
+ }
+
+ setRoomSortBy(sortBy: SidebarRoomSortBy): void {
+ this.roomSortBy = sortBy;
+ }
+
+ /** Clear the filters of the view on screen. The other view's stay put — they
+ * are not visible from here, so clearing them would be an unseen change. */
clearFilters(): void {
+ if (this.grouping === 'room') {
+ this.filterBridgeTypes.clear();
+ this.filterRoomHasLiveSession = false;
+ return;
+ }
this.filterConnections.clear();
this.filterProviderIds.clear();
this.filterHasLiveSession = false;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
new file mode 100644
index 000000000..38017ab7b
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -0,0 +1,56 @@
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import type { LocationStore } from '@renderer/features/locations/stores/location';
+import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+import { sidebarStore } from '@renderer/lib/stores/app-state';
+import type { Agent } from '@shared/core/agents/agents';
+
+/**
+ * What the two sidebar trees agree on: which agents are in scope and which
+ * sessions belong to them. Everything past that — how they are nested, what a
+ * row does — is the trees' own business and deliberately not shared.
+ */
+
+/** An agent paired with its (mounted) location, for the flat sidebar list. */
+export type AgentEntry = { agent: Agent; location: LocationStore };
+
+/**
+ * The flat list of agents in the active-server scope, newest first. switchdash
+ * shows agents as a flat list — not grouped by directory (CHOO-1440).
+ */
+export function scopedAgents(): AgentEntry[] {
+ const entries: AgentEntry[] = [];
+ for (const location of sidebarStore.filteredLocations) {
+ for (const agent of agentsStore.byLocation.get(location.id) ?? []) {
+ entries.push({ agent, location });
+ }
+ }
+ return entries.sort(
+ (a, b) =>
+ b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.name.localeCompare(b.agent.name)
+ );
+}
+
+/**
+ * An agent's visible sessions: the location's sessions it owns. Sessions are
+ * paired to their agent by `agent_id` — the authoritative link — not by matching
+ * a name frozen into the session's config against the agent's definition. A
+ * session whose owning agent no longer matches by name is still shown under its
+ * agent instead of silently vanishing (CHOO-1440).
+ */
+export function agentSessions(entry: AgentEntry): SessionStore[] {
+ const all = sidebarStore.visibleSessionsForLocation(entry.location.id);
+ return all.filter(
+ (session) => 'agentId' in session.data && session.data.agentId === entry.agent.id
+ );
+}
+
+/** Every scoped agent that has a Switch identity, as membership-lookup keys. */
+export function switchIdentities(): { serverId: string; switchAgentId: string }[] {
+ const identities: { serverId: string; switchAgentId: string }[] = [];
+ for (const { agent } of scopedAgents()) {
+ if (agent.serverId && agent.switchAgentId) {
+ identities.push({ serverId: agent.serverId, switchAgentId: agent.switchAgentId });
+ }
+ }
+ return identities;
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
new file mode 100644
index 000000000..eae619d78
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -0,0 +1,186 @@
+import { useQuery } from '@tanstack/react-query';
+import { ChevronDown, X } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useState } from 'react';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { rpc } from '@renderer/lib/ipc';
+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+} from '@renderer/lib/ui/combobox';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Field, FieldLabel } from '@renderer/lib/ui/field';
+import { cn } from '@renderer/utils/utils';
+import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
+
+type Props = BaseModalProps<void> & { roomId: string };
+
+export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
+ roomId,
+ onSuccess,
+ onClose,
+}: Props) {
+ const { setCloseGuard } = useModalContext();
+ const serverId = switchRoomsStore.roomServerId(roomId);
+ const roomName = switchRoomsStore.roomNameById(roomId);
+
+ const [selected, setSelected] = useState<RemoteAgentSummary[]>([]);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const agentsQuery = useQuery({
+ queryKey: ['remote-agents', serverId],
+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId!),
+ enabled: !!serverId,
+ });
+ const membersQuery = useQuery({
+ queryKey: ['roomAgentIds', serverId, roomId],
+ queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId }),
+ enabled: !!serverId,
+ });
+
+ // Agents already in the room are dropped rather than shown as no-ops: the
+ // server ignores them, so offering them would suggest an effect there isn't.
+ const members = new Set(membersQuery.data ?? []);
+ const candidates = (agentsQuery.data ?? []).filter(
+ (a) => !members.has(a.id) && !selected.some((s) => s.id === a.id)
+ );
+ const loading = agentsQuery.isLoading || membersQuery.isLoading;
+ const nothingToAdd = !loading && candidates.length === 0 && selected.length === 0;
+
+ const handleSubmit = useCallback(async () => {
+ if (!serverId || selected.length === 0) return;
+ setIsSubmitting(true);
+ setCloseGuard(true);
+ setError(null);
+ try {
+ await rpc.switchServers.addRoomAgents({
+ serverId,
+ roomId,
+ agentIds: selected.map((a) => a.id),
+ });
+ // The sidebar lists agents under a room by membership, so the caches that
+ // answer "which rooms is this agent in" have to be re-read, not just the
+ // room list.
+ await switchRoomsStore.refreshAll();
+ await switchRoomsStore.loadRoomNames();
+ onSuccess();
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setIsSubmitting(false);
+ setCloseGuard(false);
+ }
+ }, [serverId, roomId, selected, onSuccess, setCloseGuard]);
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Add agents to {roomName ?? 'room'}</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ <div className="flex w-full flex-col gap-4">
+ {!serverId && (
+ <p className="text-destructive text-xs">
+ This room&apos;s server is not known yet, so its members cannot be changed.
+ </p>
+ )}
+
+ <Field>
+ <FieldLabel>Agents</FieldLabel>
+ <Combobox
+ items={candidates}
+ value={null}
+ onValueChange={(next: RemoteAgentSummary | null) => {
+ if (next) setSelected((current) => [...current, next]);
+ setError(null);
+ }}
+ isItemEqualToValue={(a: RemoteAgentSummary, b: RemoteAgentSummary) => a.id === b.id}
+ filter={(item: RemoteAgentSummary, query) =>
+ item.name.toLowerCase().includes(query.toLowerCase())
+ }
+ autoHighlight
+ >
+ <ComboboxTrigger
+ disabled={loading || nothingToAdd}
+ className={cn(
+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',
+ (loading || nothingToAdd) && 'cursor-not-allowed opacity-60'
+ )}
+ >
+ <span className="flex-1 truncate text-left text-foreground-muted">
+ {loading ? 'Loading agents…' : 'Add an agent'}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />
+ </ComboboxTrigger>
+ <ComboboxContent className="min-w-(--anchor-width)">
+ <ComboboxInput showTrigger={false} placeholder="Search agents…" />
+ <ComboboxList>
+ {(item: RemoteAgentSummary) => (
+ <ComboboxItem key={item.id} value={item}>
+ <span className="min-w-0 flex-1 truncate">{item.name}</span>
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ <ComboboxEmpty>No agents found</ComboboxEmpty>
+ </ComboboxContent>
+ </Combobox>
+ {selected.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {selected.map((agent) => (
+ <span
+ key={agent.id}
+ className="flex items-center gap-1 rounded-md border border-border px-2 py-0.5 text-xs"
+ >
+ {agent.name}
+ <button
+ type="button"
+ aria-label={`Remove ${agent.name}`}
+ className="text-foreground-muted hover:text-foreground"
+ onClick={() =>
+ setSelected((current) => current.filter((a) => a.id !== agent.id))
+ }
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ {nothingToAdd && (
+ <p className="mt-1 text-xs text-foreground-muted">
+ Every agent on this server is already in the room.
+ </p>
+ )}
+ </Field>
+
+ {error && <p className="text-destructive text-xs">{error}</p>}
+ </div>
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <ConfirmButton
+ onClick={() => void handleSubmit()}
+ disabled={!serverId || selected.length === 0 || isSubmitting}
+ >
+ {isSubmitting ? 'Adding…' : 'Add to room'}
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-links.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-links.ts
new file mode 100644
index 000000000..0e5f5211e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-links.ts
@@ -0,0 +1,19 @@
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { rpc } from '@renderer/lib/ipc';
+
+/**
+ * Open a room's bridged channel in the messaging app's desktop client, via the
+ * native deeplink the gateway built. No-op when the room has no such link —
+ * callers should check {@link switchRoomsStore.roomChannelUrl} first and not
+ * offer the action at all rather than present a control that does nothing.
+ */
+export function openRoomChannel(roomId: string): void {
+ const url = switchRoomsStore.roomChannelUrl(roomId);
+ if (url) void rpc.app.openExternal(url);
+}
+
+/** Open a room's detail page in the gateway web app. */
+export function openRoomGatewayPage(roomId: string): void {
+ const url = switchRoomsStore.gatewayRoomUrl(roomId);
+ if (url) void rpc.app.openExternal(url);
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx
index f75acea92..8d49a4817 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx
@@ -1,8 +1,51 @@
+import { ExternalLink } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';
import { useParams } from '@renderer/lib/layout/navigation-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import { openRoomChannel } from './room-links';
+
+/**
+ * Opens the room's channel in the messaging app it is bridged to. The embedded
+ * view is a convenience, not a replacement — threads, search and notifications
+ * live in the real client, so there is always a way out to it.
+ *
+ * Rendered only when the gateway supplied a deeplink; an unbridged room has no
+ * messaging app to open, and a button that quietly does nothing is worse than
+ * no button.
+ */
+const OpenInMessagingApp = observer(function OpenInMessagingApp({ roomId }: { roomId: string }) {
+ const bridgeType = switchRoomsStore.roomBridgeTypeById(roomId);
+ if (!switchRoomsStore.roomChannelUrl(roomId)) return null;
+
+ const platform = bridgeType ?? 'messaging app';
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="size-7 p-0"
+ aria-label={`Open in ${platform}`}
+ onClick={() => openRoomChannel(roomId)}
+ >
+ {hasBridgeIcon(bridgeType) ? (
+ <BridgeIcon bridgeType={bridgeType} size={16} className="size-4" />
+ ) : (
+ <ExternalLink className="size-4" />
+ )}
+ </Button>
+ }
+ />
+ <TooltipContent side="bottom">Open in {platform}</TooltipContent>
+ </Tooltip>
+ );
+});
const RoomTitlebar = observer(function RoomTitlebar() {
const { params } = useParams('room');
@@ -24,6 +67,11 @@ const RoomTitlebar = observer(function RoomTitlebar() {
<span className="max-w-56 truncate">{name ?? 'Room'}</span>
</div>
}
+ rightSlot={
+ <div className="mr-2 flex items-center gap-1">
+ <OpenInMessagingApp roomId={params.roomId} />
+ </div>
+ }
/>
);
});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
new file mode 100644
index 000000000..a0edb8863
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -0,0 +1,329 @@
+import { useQuery } from '@tanstack/react-query';
+import { ChevronDown, X } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useState } from 'react';
+import { rpc } from '@renderer/lib/ipc';
+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+} from '@renderer/lib/ui/combobox';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Field, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/lib/ui/select';
+import { Textarea } from '@renderer/lib/ui/textarea';
+import { cn } from '@renderer/utils/utils';
+import type { RemoteAgentSummary, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import { switchRoomsStore } from './switch-rooms-store';
+import { switchServersStore } from './switch-servers-store';
+
+type CreateRoomModalArgs = {
+ /** Create on this server instead of the active one — for callers that are not
+ * driven by the sidebar's server scope, such as onboarding. */
+ serverId?: string;
+};
+
+type Props = BaseModalProps<{ roomId: string }> & CreateRoomModalArgs;
+
+export const CreateRoomModal = observer(function CreateRoomModal({
+ serverId: overrideServerId,
+ onSuccess,
+ onClose,
+}: Props) {
+ const { setCloseGuard } = useModalContext();
+
+ // The sidebar shows one server at a time, so the room belongs to that server;
+ // asking again would let the user create a room somewhere they are not
+ // looking, and then wonder where it went.
+ const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
+ const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
+
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [instructions, setInstructions] = useState('');
+ const [bridgeId, setBridgeId] = useState<string | null>(null);
+ const [agents, setAgents] = useState<RemoteAgentSummary[]>([]);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const bridgesQuery = useQuery({
+ queryKey: ['remote-bridges', serverId],
+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ enabled: !!serverId,
+ });
+ const agentsQuery = useQuery({
+ queryKey: ['remote-agents', serverId],
+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId),
+ enabled: !!serverId,
+ });
+
+ // Only a running bridge can back a new room. Keeping the inactive ones out of
+ // the picker (rather than letting the create call fail) means the one thing
+ // shown is the one thing that works — and "no bridges" is stated outright.
+ const bridges = (bridgesQuery.data ?? []).filter((b) => b.status === 'active');
+ const selectedBridge =
+ bridges.find((b) => b.id === bridgeId) ??
+ bridges.find((b) => b.isDefault) ??
+ bridges[0] ??
+ null;
+ const noBridges = !bridgesQuery.isLoading && bridges.length === 0;
+
+ const trimmedName = name.trim();
+ const trimmedDescription = description.trim();
+ const canSubmit =
+ !!serverId && !!trimmedName && !!trimmedDescription && !!selectedBridge && !isSubmitting;
+
+ const handleSubmit = useCallback(async () => {
+ if (!canSubmit || !selectedBridge) return;
+ setIsSubmitting(true);
+ setCloseGuard(true);
+ setError(null);
+
+ try {
+ const result = await rpc.switchServers.createRoom({
+ serverId,
+ name: trimmedName,
+ description: trimmedDescription,
+ instructions: instructions.trim() || undefined,
+ bridgeId: selectedBridge.id,
+ agentIds: agents.map((a) => a.id),
+ });
+
+ if (result.kind !== 'created') {
+ setError(messageFor(result));
+ return;
+ }
+
+ // Refresh the room caches so the sidebar shows the room straight away
+ // rather than at the next window focus.
+ await switchRoomsStore.loadRoomNames();
+ void switchRoomsStore.refreshAll();
+ onSuccess({ roomId: result.room.id });
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setIsSubmitting(false);
+ setCloseGuard(false);
+ }
+ }, [
+ canSubmit,
+ selectedBridge,
+ serverId,
+ trimmedName,
+ trimmedDescription,
+ instructions,
+ agents,
+ onSuccess,
+ setCloseGuard,
+ ]);
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>New room{server ? ` on ${server.name}` : ''}</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ <div className="flex w-full flex-col gap-5">
+ {!server && (
+ <p className="text-destructive text-xs">
+ No Switch server is selected, so there is nowhere to create a room. Choose a server in
+ the sidebar first.
+ </p>
+ )}
+
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <Input
+ autoFocus
+ placeholder="e.g. design-review"
+ value={name}
+ onChange={(e) => {
+ setName(e.target.value);
+ setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && canSubmit) void handleSubmit();
+ }}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <Input
+ placeholder="What this room is for"
+ value={description}
+ onChange={(e) => {
+ setDescription(e.target.value);
+ setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && canSubmit) void handleSubmit();
+ }}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel>Messaging app</FieldLabel>
+ <Select
+ value={selectedBridge?.id ?? ''}
+ onValueChange={(next) => setBridgeId(next ?? null)}
+ disabled={bridgesQuery.isLoading || noBridges}
+ >
+ <SelectTrigger>
+ {/* Resolve the label ourselves: the trigger shows the raw value
+ otherwise, which for a bridge is an opaque uuid. */}
+ <SelectValue
+ placeholder={bridgesQuery.isLoading ? 'Loading…' : 'No messaging app available'}
+ >
+ {selectedBridge ? bridgeLabel(selectedBridge) : undefined}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {bridges.map((bridge) => (
+ <SelectItem key={bridge.id} value={bridge.id}>
+ {bridgeLabel(bridge)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {noBridges && (
+ <p className="text-destructive mt-1 text-xs">
+ This server has no messaging app connected, so a room created here would be
+ unreachable. Connect one first.
+ </p>
+ )}
+ {bridgesQuery.isError && (
+ <p className="text-destructive mt-1 text-xs">
+ Could not load messaging apps: {errorText(bridgesQuery.error)}
+ </p>
+ )}
+ </Field>
+
+ <Field>
+ <FieldLabel>Agents</FieldLabel>
+ <Combobox
+ items={(agentsQuery.data ?? []).filter((a) => !agents.some((s) => s.id === a.id))}
+ value={null}
+ onValueChange={(next: RemoteAgentSummary | null) => {
+ if (next) setAgents((current) => [...current, next]);
+ }}
+ isItemEqualToValue={(a: RemoteAgentSummary, b: RemoteAgentSummary) => a.id === b.id}
+ filter={(item: RemoteAgentSummary, query) =>
+ item.name.toLowerCase().includes(query.toLowerCase())
+ }
+ autoHighlight
+ >
+ <ComboboxTrigger
+ disabled={agentsQuery.isLoading}
+ className={cn(
+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',
+ agentsQuery.isLoading && 'cursor-not-allowed opacity-60'
+ )}
+ >
+ <span className="flex-1 truncate text-left text-foreground-muted">
+ {agentsQuery.isLoading ? 'Loading agents…' : 'Add an agent'}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />
+ </ComboboxTrigger>
+ <ComboboxContent className="min-w-(--anchor-width)">
+ <ComboboxInput showTrigger={false} placeholder="Search agents…" />
+ <ComboboxList>
+ {(item: RemoteAgentSummary) => (
+ <ComboboxItem key={item.id} value={item}>
+ <span className="min-w-0 flex-1 truncate">{item.name}</span>
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ <ComboboxEmpty>No agents found</ComboboxEmpty>
+ </ComboboxContent>
+ </Combobox>
+ {agents.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {agents.map((agent) => (
+ <span
+ key={agent.id}
+ className="flex items-center gap-1 rounded-md border border-border px-2 py-0.5 text-xs"
+ >
+ {agent.name}
+ <button
+ type="button"
+ aria-label={`Remove ${agent.name}`}
+ className="text-foreground-muted hover:text-foreground"
+ onClick={() =>
+ setAgents((current) => current.filter((a) => a.id !== agent.id))
+ }
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ <p className="mt-1 text-xs text-foreground-muted">
+ Optional — agents can be added to the room later.
+ </p>
+ </Field>
+
+ <Field>
+ <FieldLabel>Instructions</FieldLabel>
+ <Textarea
+ placeholder="Optional guidance shown to agents when they connect"
+ value={instructions}
+ onChange={(e) => setInstructions(e.target.value)}
+ rows={3}
+ />
+ </Field>
+
+ {error && <p className="text-destructive text-xs">{error}</p>}
+ </div>
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>
+ {isSubmitting ? 'Creating…' : 'Create room'}
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+});
+
+function bridgeLabel(bridge: RemoteBridge): string {
+ return bridge.isDefault ? `${bridge.displayName} (default)` : bridge.displayName;
+}
+
+function errorText(cause: unknown): string {
+ return cause instanceof Error ? cause.message : String(cause);
+}
+
+/** Turn a failed create into something the user can act on. */
+function messageFor(result: { kind: string; message?: string }): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session for this server expired. Sign in again, then retry.';
+ case 'bridge-unavailable':
+ return `The messaging app is not available: ${result.message ?? 'unknown reason'}`;
+ default:
+ return result.message ?? 'Could not create the room.';
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
new file mode 100644
index 000000000..a6f41f8d2
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
+
+const listRemoteRooms = vi.hoisted(() => vi.fn());
+const listAgentRooms = vi.hoisted(() => vi.fn());
+const serversStore = vi.hoisted(() => ({
+ servers: [] as { id: string; managed?: boolean }[],
+ activeServerId: null as string | null,
+ isConnected: () => true,
+ statusFor: (serverId: string) => ({ user: { id: `user-of-${serverId}` } }),
+}));
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: { switchServers: { listRemoteRooms, listAgentRooms } },
+}));
+vi.mock('./switch-servers-store', () => ({ switchServersStore: serversStore }));
+
+const { SwitchRoomsStore } = await import('./switch-rooms-store');
+
+function room(id: string, ownerId: string | null, overrides: Partial<RemoteRoomSummary> = {}) {
+ return {
+ id,
+ name: id,
+ description: '',
+ channelType: 'channel_public',
+ agentCount: 0,
+ bridgeDisplayName: null,
+ bridgeType: null,
+ externalChannelUrl: null,
+ ownerId,
+ archived: false,
+ createdAt: '2026-01-01T00:00:00Z',
+ ...overrides,
+ } satisfies RemoteRoomSummary;
+}
+
+describe('listed rooms', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ serversStore.servers = [{ id: 'srv-a' }, { id: 'srv-b' }];
+ serversStore.activeServerId = null;
+ });
+
+ it('lists every room on a server this install manages', async () => {
+ // You run that deployment. Nothing on it should need a second app to see.
+ serversStore.servers = [{ id: 'srv-a', managed: true }, { id: 'srv-b' }];
+ serversStore.activeServerId = 'srv-a';
+ listRemoteRooms.mockImplementation(async (serverId: string) =>
+ serverId === 'srv-a'
+ ? [
+ room('mine', 'user-of-srv-a'),
+ room('someone-elses', 'user-of-someone-else'),
+ room('gone', 'user-of-srv-a', { archived: true }),
+ ]
+ : []
+ );
+
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+
+ expect(store.listedRoomsInActiveScope.map((r) => r.id)).toEqual(['mine', 'someone-elses']);
+ });
+
+ it('lists only rooms owned by that server’s signed-in user, excluding archived ones', async () => {
+ listRemoteRooms.mockImplementation(async (serverId: string) =>
+ serverId === 'srv-a'
+ ? [
+ room('mine', 'user-of-srv-a'),
+ room('someone-elses', 'user-of-someone-else'),
+ room('mine-but-archived', 'user-of-srv-a', { archived: true }),
+ room('ownerless', null),
+ ]
+ : []
+ );
+
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['mine']);
+ });
+
+ it('shows only the active server’s rooms, not every connected server’s', async () => {
+ listRemoteRooms.mockImplementation(async (serverId: string) => [
+ room(`${serverId}-room`, `user-of-${serverId}`),
+ ]);
+
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+ serversStore.activeServerId = 'srv-b';
+
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);
+ });
+
+ it('hides nothing when no server is active, matching how locations are scoped', async () => {
+ listRemoteRooms.mockImplementation(async (serverId: string) => [
+ room(`${serverId}-room`, `user-of-${serverId}`),
+ ]);
+
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([
+ 'srv-a-room',
+ 'srv-b-room',
+ ]);
+ });
+
+ it('keeps a server that failed to respond from dropping the others', async () => {
+ listRemoteRooms.mockImplementation(async (serverId: string) => {
+ if (serverId === 'srv-a') throw new Error('unreachable');
+ return [room('srv-b-room', 'user-of-srv-b')];
+ });
+
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);
+ });
+});
+
+describe('agent memberships', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => [
+ {
+ roomId: `room-of-${agentId}`,
+ roomName: 'r',
+ archived: false,
+ status: 'live',
+ roomRole: null,
+ },
+ ]);
+ });
+
+ it('loads every agent’s rooms so the sidebar can list agents under a room', async () => {
+ const store = new SwitchRoomsStore();
+
+ await store.ensureMembershipsFor([
+ { serverId: 'srv-a', switchAgentId: 'agent-1' },
+ { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ ]);
+
+ expect(store.roomsFor('srv-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');
+ expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');
+ });
+
+ it('serves cached memberships without refetching, unless forced', async () => {
+ const store = new SwitchRoomsStore();
+ const agents = [{ serverId: 'srv-a', switchAgentId: 'agent-1' }];
+
+ await store.ensureMembershipsFor(agents);
+ await store.ensureMembershipsFor(agents);
+ expect(listAgentRooms).toHaveBeenCalledOnce();
+
+ await store.ensureMembershipsFor(agents, { force: true });
+ expect(listAgentRooms).toHaveBeenCalledTimes(2);
+ });
+
+ it('lets one agent’s failed lookup stand without losing the others', async () => {
+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => {
+ if (agentId === 'agent-1') throw new Error('nope');
+ return [{ roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null }];
+ });
+ const store = new SwitchRoomsStore();
+
+ await store.ensureMembershipsFor([
+ { serverId: 'srv-a', switchAgentId: 'agent-1' },
+ { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ ]);
+
+ expect(store.roomsFor('srv-a', 'agent-1')).toBeUndefined();
+ expect(store.errorFor('srv-a', 'agent-1')).toBe('nope');
+ expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
index 7b89000db..7bb15e490 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
@@ -1,6 +1,10 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { rpc } from '@renderer/lib/ipc';
-import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';
+import type {
+ RemoteAgentRoom,
+ RemoteRoomSummary,
+} from '@shared/core/switch-servers/switch-servers';
+import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
import { switchServersStore } from './switch-servers-store';
/** Cache key for an agent's room membership: server + Switch agent id. */
@@ -29,6 +33,14 @@ export class SwitchRoomsStore {
/** Room id → native deeplink that opens its channel in the messaging app's
* desktop client, when the room is bridged and the link could be built. */
private readonly channelUrlByRoom = new Map<string, string>();
+ /** Server id → the active rooms on that server owned by the signed-in user.
+ * The sidebar lists these even when no session is connected to them, so a
+ * room you create in switchdash is visible the moment it exists rather than
+ * only once an agent joins it. */
+ private readonly ownedRoomsByServer = new Map<string, RemoteRoomSummary[]>();
+ /** Server id → every active room on it. Listed in full for a server this
+ * install manages; elsewhere it backs lookups rather than the room list. */
+ private readonly allRoomsByServer = new Map<string, RemoteRoomSummary[]>();
/** Keys with an in-flight fetch. */
readonly loading = new Set<string>();
/** Last error per key, if the most recent fetch failed. */
@@ -94,6 +106,60 @@ export class SwitchRoomsStore {
return `${base}/agents/${switchAgentId}`;
}
+ /**
+ * The rooms the sidebar lists on their own account, before membership is
+ * considered — the ones that are there because of what they are, not because
+ * one of this install's agents is in them.
+ *
+ * On a server this install manages, that is **every** room: you run the
+ * deployment, so there is nothing on it you should have to go elsewhere to
+ * see. On any other server it is the rooms you created, which would otherwise
+ * disappear the moment you made one and put no agent in it.
+ *
+ * The sidebar tree shows one server at a time, so these follow the same scope
+ * rule as locations do — including that no active server hides nothing.
+ */
+ get listedRoomsInActiveScope(): RemoteRoomSummary[] {
+ const activeServerId = switchServersStore.activeServerId;
+ const serverIds = activeServerId
+ ? [activeServerId]
+ : [...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()])];
+ const listed = serverIds.flatMap((serverId) => {
+ const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;
+ return (
+ (managed ? this.allRoomsByServer.get(serverId) : this.ownedRoomsByServer.get(serverId)) ??
+ []
+ );
+ });
+ return listed.sort((a, b) => a.name.localeCompare(b.name));
+ }
+
+ /**
+ * The messaging-app values worth offering as a room filter on the active
+ * server: the bridge types actually in use, plus the unbridged sentinel when
+ * some room has no messaging app. Offering a platform with no rooms behind it
+ * would be a filter that can only ever empty the list.
+ */
+ get bridgeFilterValuesInActiveScope(): string[] {
+ const present = new Set<string>();
+ for (const room of this.listedRoomsInActiveScope) {
+ present.add(room.bridgeType ?? UNBRIDGED_FILTER_VALUE);
+ }
+ // The sentinel sorts last so the real platforms lead the menu.
+ return [...present].sort((a, b) => {
+ if (a === UNBRIDGED_FILTER_VALUE) return 1;
+ if (b === UNBRIDGED_FILTER_VALUE) return -1;
+ return a.localeCompare(b);
+ });
+ }
+
+ /** Full detail for a room, when its server's room list has been loaded. */
+ roomSummaryById(roomId: string): RemoteRoomSummary | null {
+ const serverId = this.roomServerById.get(roomId);
+ if (!serverId) return null;
+ return this.allRoomsByServer.get(serverId)?.find((room) => room.id === roomId) ?? null;
+ }
+
/**
* Refresh the room id → name map from every connected server's room list.
* Best-effort: a server that fails to respond is skipped (its rooms keep
@@ -107,6 +173,9 @@ export class SwitchRoomsStore {
connected.map(async (server) => {
try {
const rooms = await rpc.switchServers.listRemoteRooms(server.id);
+ // Ownership is per server: the same person is a different user row on
+ // each gateway, so match against that server's signed-in identity.
+ const signedInUserId = switchServersStore.statusFor(server.id)?.user?.id ?? null;
runInAction(() => {
for (const room of rooms) {
this.roomNames.set(room.id, room.name);
@@ -117,6 +186,12 @@ export class SwitchRoomsStore {
this.channelUrlByRoom.set(room.id, room.externalChannelUrl);
else this.channelUrlByRoom.delete(room.id);
}
+ const active = rooms.filter((r) => !r.archived);
+ this.allRoomsByServer.set(server.id, active);
+ this.ownedRoomsByServer.set(
+ server.id,
+ signedInUserId ? active.filter((r) => r.ownerId === signedInUserId) : []
+ );
});
} catch {
// skip this server; names stay best-effort
@@ -130,6 +205,21 @@ export class SwitchRoomsStore {
return this.roomsByAgent.get(key(serverId, switchAgentId));
}
+ /**
+ * Load membership for several agents at once. The room-grouped sidebar lists
+ * an agent under every room it belongs to, not only the rooms it happens to
+ * have a session in, so it needs the whole set up front rather than one
+ * agent's at a time.
+ */
+ async ensureMembershipsFor(
+ agents: { serverId: string; switchAgentId: string }[],
+ options: { force?: boolean } = {}
+ ): Promise<void> {
+ await Promise.all(
+ agents.map((a) => this.fetchAgentRooms(a.serverId, a.switchAgentId, options))
+ );
+ }
+
isLoading(serverId: string, switchAgentId: string): boolean {
return this.loading.has(key(serverId, switchAgentId));
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
index 145aa2d75..65a002681 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
@@ -232,7 +232,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
<div className={`${card} space-y-3`}>
<p className="text-sm text-foreground-muted">
- Managing this server's agents and rooms is done in the web app for now.
+ Configure resources, messaging apps, API keys and users in the full admin interface.
</p>
<Button
variant="outline"
@@ -245,7 +245,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
}
>
<ExternalLink className="size-4" />
- Open web app
+ Open admin interface
</Button>
</div>
</>
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
index c3a0d8d10..721f88a47 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -149,6 +149,11 @@ export type RemoteRoomSummary = {
* desktop client (slack://…, mattermost://…), or null when not bridged / the
* bridge is down / the platform has no scheme. Built server-side. */
externalChannelUrl: string | null;
+ /** Switch user who owns the room — whoever created it. Null for rooms created
+ * before ownership was tracked, or auto-created by an inbound bridge channel.
+ * Rooms the signed-in user owns stay listed in the sidebar even with no live
+ * session, so a room you just made never vanishes on you. */
+ ownerId: string | null;
archived: boolean;
createdAt: string;
};
@@ -175,6 +180,22 @@ export type RemoteRoomGroup = {
name: string;
};
+/**
+ * A collaboration bridge configured on a server (mirrors the gateway
+ * `BridgeDetail`). Every room switchdash creates is bridged to one of these, so
+ * the humans it is being created for can actually reach it.
+ */
+export type RemoteBridge = {
+ id: string;
+ /** Platform key (`slack`, `mattermost`, …) — drives the bridge icon. */
+ type: string;
+ displayName: string;
+ /** Only `active` bridges can back a new room. */
+ status: string;
+ /** The bridge used when a room is created without naming one. */
+ isDefault: boolean;
+};
+
/** A bridged (external) human identity on a server. The `users` dimension of an
* addressing policy keys off these ids. */
export type RemoteExternalUser = {
@@ -280,6 +301,43 @@ export type ProvisionAgentResult =
| { kind: 'invalid-name'; message: string }
| { kind: 'error'; message: string };
+/**
+ * Parameters for creating a room on a server from inside switchdash
+ * (CHOO-1875) — the minimal set that gets a user to a working room. The wider
+ * gateway surface (roles, groups, visibility, references, existing-channel
+ * binding) stays in the operator web app.
+ *
+ * A bridge is mandatory: a room nobody can reach from a messaging app is not a
+ * useful room, so there is no internal-only path here.
+ */
+export type CreateRoomParams = {
+ serverId: string;
+ name: string;
+ description: string;
+ /** Room-specific system prompt shown to agents on connect. Optional. */
+ instructions?: string;
+ bridgeId: string;
+ /** Switch agent ids to add as members. May be empty — a bridged room is
+ * valid with no agents, and members can be invited later. */
+ agentIds: string[];
+};
+
+/**
+ * Outcome of creating a room. `created` carries the new room; every other
+ * variant maps a recoverable gateway failure onto something the modal can say
+ * out loud, rather than a raw throw or a silent no-op.
+ *
+ * `bridge-unavailable` is its own case because it is the one failure a user can
+ * act on directly (start the bridge, or pick another) — the gateway reports an
+ * unknown bridge id and a stopped bridge identically, as a 400.
+ */
+export type CreateRoomResult =
+ | { kind: 'created'; room: RemoteRoomSummary }
+ | { kind: 'unauthenticated' }
+ | { kind: 'bridge-unavailable'; message: string }
+ | { kind: 'invalid'; message: string }
+ | { kind: 'error'; message: string };
+
/**
* A role defined in a room — an assumable instruction bundle (mirrors the
* gateway `RoomRoleDetail`). Offered when starting a session connected to a
diff --git a/dash/apps/switchdash-desktop/src/shared/view-state.ts b/dash/apps/switchdash-desktop/src/shared/view-state.ts
index 1980bf7b5..c86f839e3 100644
--- a/dash/apps/switchdash-desktop/src/shared/view-state.ts
+++ b/dash/apps/switchdash-desktop/src/shared/view-state.ts
@@ -13,6 +13,11 @@ export type NavigationSnapshot = {
export type SidebarSessionSortBy = 'created-at' | 'updated-at';
+/** How the room-focused sidebar orders rooms. Rooms are places rather than
+ * work, so they sort by name by default; `updated-at` means the most recent
+ * session activity in the room. */
+export type SidebarRoomSortBy = 'name' | 'created-at' | 'updated-at';
+
/** How the sidebar groups sessions: by agent (agent → room → sessions) or by
* room (room → agents → sessions). */
export type SidebarGrouping = 'agent' | 'room';
@@ -48,4 +53,17 @@ export type SidebarSnapshot = {
filterConnections?: AgentConnectionKind[];
filterProviderIds?: AgentProviderId[];
filterHasLiveSession?: boolean;
+ /**
+ * Room-focused filters, kept apart from the agent ones above: the two views
+ * filter different things, so a dimension set in one must not silently narrow
+ * the other. `filterBridgeTypes` holds bridge types (`slack`, …) plus the
+ * sentinel {@link UNBRIDGED_FILTER_VALUE} for rooms with no messaging app.
+ */
+ roomSortBy?: SidebarRoomSortBy;
+ filterBridgeTypes?: string[];
+ filterRoomHasLiveSession?: boolean;
};
+
+/** `filterBridgeTypes` entry standing for "no messaging app", which has no
+ * bridge type of its own but is a thing you want to filter for. */
+export const UNBRIDGED_FILTER_VALUE = '__unbridged__';
diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.ts
index 5b64fb8d9..5105fdad0 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts
@@ -273,8 +273,8 @@ async function main(): Promise<void> {
hookToken: server.getToken(),
endpointFile,
runtime,
- openConnectionFor: (sessionId, providerId, startCursor) =>
- runtime.ensureForSession(sessionId, providerId, startCursor),
+ openConnectionFor: (sessionId, providerId, roomId, startCursor) =>
+ runtime.ensureForSession(sessionId, providerId, roomId, startCursor),
switchEnv: {
SWITCH_API_ENDPOINT: creds.apiEndpoint,
SWITCH_API_TOKEN: creds.token,
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
index 801b184ab..39a324d60 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
@@ -35,6 +35,7 @@ export interface InProcessSessionSpawnerDeps {
openConnectionFor?: (
sessionId: string,
providerId: string,
+ roomId: string,
startCursor?: number
) => string | null;
/** The agent's Switch identity as `SWITCH_*` env, injected into every
@@ -153,9 +154,11 @@ export class InProcessSessionSpawner implements SessionSpawner {
// Open the session's connection before launching it: its first
// connect_to_room arrives tagged with this id, and the server refuses a
- // call naming a connection that is not open.
+ // call naming a connection that is not open. The room goes with it — this
+ // session is being launched to answer a message in that room, so there is
+ // nothing to wait to be told.
const connectionId =
- this.deps.openConnectionFor?.(sessionId, spec.providerId, startCursor) ?? null;
+ this.deps.openConnectionFor?.(sessionId, spec.providerId, roomId, startCursor) ?? null;
const hookEnv = {
...this.deps.switchEnv,
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
index 3d82a68bd..5b6bdb012 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -95,16 +95,27 @@ describe('SidecarRuntime (multi-session)', () => {
it('opens a spawned session at the cursor the watcher handed over', () => {
const { runtime, created } = makeRuntime();
- runtime.ensureForSession('session-a', 'codex', 41);
+ runtime.ensureForSession('session-a', 'codex', 'room-1', 41);
expect(created).toHaveLength(1);
expect(created[0].deps.startCursor).toBe(41);
});
+ // A session is auto-started to answer a message in a room, so it opens
+ // already claiming it. Waiting for the agent's own connect_to_room left it
+ // room-less — sitting outside the room it was started for.
+ it('opens a spawned session already claiming the room it was launched for', () => {
+ const { runtime, created } = makeRuntime();
+
+ runtime.ensureForSession('session-a', 'codex', 'room-1', 41);
+
+ expect(created[0].deps.roomId).toBe('room-1');
+ });
+
it('opens a session at head when no cursor was handed over', () => {
const { runtime, created } = makeRuntime();
- runtime.ensureForSession('session-a', 'codex');
+ runtime.ensureForSession('session-a', 'codex', 'room-1');
expect(created[0].deps.startCursor).toBeUndefined();
});
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index c6e16d37a..a80f78604 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -172,11 +172,22 @@ export class SidecarRuntime {
* which arrives tagged with this id. It also makes the room server-driven
* here too: the claim lands on this connection and comes back as
* `subscription_changed`, so the sidecar stops depending on parsing the hook.
+ *
+ * `roomId` is the room the session is being launched for, when it is being
+ * launched for one — an auto-started session always is. Declaring it opens
+ * the connection already claiming that room, so the session belongs to it
+ * from the start instead of from whenever the agent calls connect_to_room.
+ * Null for a session opened without a room in mind.
*/
- ensureForSession(sessionId: string, providerId: string, startCursor?: number): string {
+ ensureForSession(
+ sessionId: string,
+ providerId: string,
+ roomId: string | null,
+ startCursor?: number
+ ): string {
const existing = this.sessions.get(sessionId);
if (existing) return existing.connection.connection;
- return this.openConnection(sessionId, providerId, null, null, startCursor);
+ return this.openConnection(sessionId, providerId, roomId, null, startCursor);
}
private connectRoom(