Skip to content

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

26.5 KB
Raw Blame
import { makeAutoObservable, runInAction } from 'mobx';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import {
  dashboardOrigin,
  type RemoteAgentRoom,
  type RemoteRoomSummary,
  type RetireOutcome,
  type RoomVisibility,
} from '@shared/core/switch-servers/switch-servers';
import { administersWorkspace } from '@shared/core/workspaces/workspaces';
import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
import { type RoomPermissions, roomPermissionsFor } from './room-permissions';
import { serverAvailability } from './server-availability';
import { servesWebGateway } from './server-gateway';
import { switchServersStore } from './switch-servers-store';

/** Cache key for an agent's room membership: workspace + Switch agent id. */
function key(workspaceId: string, switchAgentId: string): string {
  return `${workspaceId}:${switchAgentId}`;
}

/**
 * The messaging-app values worth offering as a room filter for these rooms:
 * 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.
 */
export function bridgeFilterValues(rooms: readonly RemoteRoomSummary[]): string[] {
  const present = new Set<string>();
  for (const room of rooms) {
    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);
  });
}

/**
 * Renderer cache of per-agent room membership, queried live from the gateway
 * (the server is the source of truth — we do not mirror rooms into SQLite).
 * Entries are cached in memory and re-fetched on demand or on window focus, so
 * the "connect to room" picker and the room-focused sidebar grouping render the
 * last-known set instantly while a refresh runs.
 *
 * Everything here is keyed by workspace, because that is what a room belongs
 * to: one server can host several, and the same server answers with a different
 * set of rooms in each. Where a fact is about the gateway rather than about the
 * rooms — whether it is reachable, who is signed in, what its web app's URL is
 * — the server is resolved from the workspace and asked for that alone.
 */
export class SwitchRoomsStore {
  /** Membership per `${workspaceId}:${switchAgentId}`. */
  private readonly roomsByAgent = new Map<string, RemoteAgentRoom[]>();
  private readonly membershipRequests = new Map<string, number>();
  /** Room id → display name, aggregated across workspaces (room ids are
   * globally unique UUIDs, so a flat map is safe). Drives sidebar room headers. */
  private readonly roomNames = new Map<string, string>();
  /** Room id → owning workspace id, so a room can be addressed and linked. */
  private readonly roomWorkspaceById = new Map<string, string>();
  /** Room id → bridge type (`slack`, `mattermost`, …) when the room is bridged
   * to an external platform, so the sidebar can show that platform's icon. */
  private readonly bridgeTypeByRoom = new Map<string, string>();
  /** 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>();
  /** Workspace id → the active rooms in it owned by the signed-in user.
   * The sidebar lists these even when no session is connected to them, so a
   * room you create in Switch Console is visible the moment it exists rather than
   * only once an agent joins it. */
  private readonly ownedRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();
  /** Workspace id → every active room in it. Listed in full for a workspace on a
   * server this install manages; elsewhere it backs lookups rather than the
   * room list. */
  private readonly allRoomsByWorkspace = 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. */
  readonly errors = new Map<string, string>();
  /** Workspace id → why its room list could not be read, if the last try failed. */
  private readonly roomListErrors = new Map<string, string>();
  /** Workspaces whose server was not connected when the room list was last
   * refreshed, so their rooms were never asked for at all. */
  private unreachableWorkspaceIds: string[] = [];
  /** The agents whose membership this store is responsible for keeping current.
   * Recorded on {@link ensureMembershipsFor} so a refresh re-reads the current
   * set rather than only the keys that happen to be cached — an agent created
   * after the sidebar mounted is otherwise never fetched. */
  private trackedIdentities: { workspaceId: string; switchAgentId: string }[] = [];
  /** Agents whose membership is on screen outside the sidebar's own list, such
   * as a managed agent's page, with how many views show each. The tracked list
   * holds only this install's local agents, so without these a page's rooms are
   * read once and a room the agent joins later never appears. */
  private readonly watchedIdentities = new Map<
    string,
    { workspaceId: string; switchAgentId: string; views: number }
  >();

  constructor() {
    makeAutoObservable(this);
  }

  /** Display name for a room id, or null if not yet known. */
  roomNameById(roomId: string): string | null {
    return this.roomNames.get(roomId) ?? null;
  }

  /** Bridge type (`slack`, `mattermost`, …) for a room, or null if it isn't
   * bridged to an external platform (or its rooms haven't loaded yet). */
  roomBridgeTypeById(roomId: string): string | null {
    return this.bridgeTypeByRoom.get(roomId) ?? null;
  }

  /** Native deeplink that opens the room's channel in the messaging app's
   * desktop client, or null if the room isn't bridged / the link is unknown. */
  roomChannelUrl(roomId: string): string | null {
    return this.channelUrlByRoom.get(roomId) ?? null;
  }

  /**
   * Remember rooms read outside the room list — archived ones, which the list
   * leaves out — so a room page opened on one can still say where it lives and
   * address calls about it. They are not added to any list.
   */
  noteRooms(workspaceId: string, rooms: RemoteRoomSummary[]): void {
    for (const room of rooms) {
      this.roomNames.set(room.id, room.name);
      this.roomWorkspaceById.set(room.id, workspaceId);
      if (room.bridgeType) this.bridgeTypeByRoom.set(room.id, room.bridgeType);
      if (room.externalChannelUrl) this.channelUrlByRoom.set(room.id, room.externalChannelUrl);
    }
  }

  /** Id of the workspace a room belongs to, or null if not yet loaded. This is
   * what a call about the room is addressed with. */
  roomWorkspaceId(roomId: string): string | null {
    return this.roomWorkspaceById.get(roomId) ?? null;
  }

  /** Id of the server hosting a room's workspace, for the things that are about
   * the gateway rather than the room — its web app, its Mattermost session. */
  roomServerId(roomId: string): string | null {
    const workspaceId = this.roomWorkspaceById.get(roomId);
    if (!workspaceId) return null;
    return workspacesStore.serverIdFor(workspaceId);
  }

  /**
   * URL of a room's detail page in the gateway web app, or null if the room's
   * owning server isn't known yet (names/workspaces are loaded by loadRoomNames)
   * or serves no web gateway (a native local server started without its pages).
   */
  gatewayRoomUrl(roomId: string): string | null {
    const serverId = this.roomServerId(roomId);
    if (!serverId) return null;
    const server = switchServersStore.servers.find((s) => s.id === serverId);
    if (!server || !servesWebGateway(server)) return null;
    const base = dashboardOrigin(server).replace(/\/+$/, '');
    return `${base}/rooms/${roomId}`;
  }

  /**
   * URL of an agent's detail page in the gateway web app, or null if the server
   * isn't known or serves no web gateway. Unlike rooms, the caller supplies
   * the server id directly (an agent carries its owning server on its config).
   */
  gatewayAgentUrl(serverId: string, switchAgentId: string): string | null {
    const server = switchServersStore.servers.find((s) => s.id === serverId);
    if (!server || !servesWebGateway(server)) return null;
    const base = dashboardOrigin(server).replace(/\/+$/, '');
    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.
   *
   * In a workspace 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. Anywhere else it is the rooms you created (which would
   * otherwise disappear the moment you made one and put no agent in it), the
   * rooms you are a member of, and the rooms your agents are in.
   *
   * The sidebar tree shows one workspace at a time, so these follow the same
   * scope rule as locations do — including that no active workspace hides
   * nothing.
   */
  get listedRoomsInActiveScope(): RemoteRoomSummary[] {
    const listed = this.workspaceIdsInScope.flatMap((id) => this.listedRoomsInWorkspace(id));
    return listed.sort((a, b) => a.name.localeCompare(b.name));
  }

  /**
   * The rooms one workspace contributes to the lists above, under the same scope
   * rule. Named separately so a page about a single workspace asks for that
   * workspace rather than for whichever one happens to be active.
   */
  listedRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {
    const serverId = workspacesStore.serverIdFor(workspaceId);
    const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;
    if (managed) return this.allRoomsByWorkspace.get(workspaceId) ?? [];
    const own = this.ownedRoomsByWorkspace.get(workspaceId) ?? [];
    const ownIds = new Set(own.map((room) => room.id));
    // And the rooms the user's agents are in, managed ones included, by their membership.
    const ofAgents = (this.allRoomsByWorkspace.get(workspaceId) ?? []).filter(
      (room) => !ownIds.has(room.id) && this.localMemberIdsByRoom.has(room.id)
    );
    return [...own, ...ofAgents];
  }

  /**
   * Every active room the signed-in user can see in a workspace — what the
   * gateway returned, which is already scoped to rooms they may read.
   *
   * Wider than {@link listedRoomsInWorkspace} on purpose. A standing list has to
   * earn its place on screen, so the sidebar shows only rooms with a claim on
   * you; a picker is a list you went looking for, and one that hides rooms you
   * have every right to join cannot be searched into showing them.
   */
  readableRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {
    return this.allRoomsByWorkspace.get(workspaceId) ?? [];
  }

  /**
   * The same listed rooms as {@link listedRoomsInActiveScope}, but across every
   * workspace rather than the active one.
   *
   * Search is deliberately not scoped to the active workspace: you search
   * precisely because you do not know where a thing is, and a result set
   * silently limited to the one you happen to be looking at cannot answer that.
   * Navigating to one of these switches the active workspace (see
   * `scopeToRoomWorkspace`), so the sidebar follows you there rather than
   * filtering the room back out.
   */
  get listedRoomsInAllWorkspaces(): RemoteRoomSummary[] {
    const listed = workspacesStore.workspaces.flatMap((w) => this.listedRoomsInWorkspace(w.id));
    return listed.sort((a, b) => a.name.localeCompare(b.name));
  }

  /** Full detail for a room, when its workspace's room list has been loaded. */
  roomSummaryById(roomId: string): RemoteRoomSummary | null {
    const workspaceId = this.roomWorkspaceById.get(roomId);
    if (!workspaceId) return null;
    return this.allRoomsByWorkspace.get(workspaceId)?.find((room) => room.id === roomId) ?? null;
  }

  /**
   * What the signed-in user may do with a room, by the gateway's own rules:
   * its owner and the workspace's admins manage it — delete it, change who may
   * see it, name it after its channel — and anyone may also write to a room
   * whose write access is public.
   *
   * This mirrors the server so actions are not offered where they would only be
   * refused. It is not the check that protects anything — the server's is — and
   * where the viewer is unknown the answer is no, since showing an action that
   * fails is worse than not showing one.
   */
  roomPermissions(
    workspaceId: string,
    room: {
      ownerId: string | null;
      writeVisibility?: RoomVisibility;
      serverPermissions?: RoomPermissions;
    }
  ): RoomPermissions {
    const serverId = workspacesStore.serverIdFor(workspaceId);
    const user = serverId ? (switchServersStore.statusFor(serverId)?.user ?? null) : null;
    const workspace = workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;
    return roomPermissionsFor(room, {
      userId: user?.id ?? null,
      isAdmin: user?.role === 'admin' || (workspace !== null && administersWorkspace(workspace)),
    });
  }

  /** Whether the signed-in user may delete a room (see `roomPermissions`). */
  canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {
    return this.roomPermissions(workspaceId, room).canManage;
  }

  /**
   * Delete a room in its workspace, then re-read what is left. Resolves to
   * what became of its platform channel: null when it had none or it was kept,
   * which it is unless `retireChannel` asks for it to be archived, deleted or
   * left as its platform allows.
   *
   * Throws on refusal rather than reporting a boolean: the caller is a
   * confirmation dialog, and a delete that quietly did nothing would leave the
   * room on screen with no account of why.
   */
  async deleteRoom(
    workspaceId: string,
    roomId: string,
    options: { retireChannel: boolean }
  ): Promise<RetireOutcome | null> {
    const channel = await rpc.workspaces.deleteRoom({
      workspaceId,
      roomId,
      retireChannel: options.retireChannel,
    });
    await this.refreshRoomState();
    return channel;
  }

  /**
   * The workspaces whose state is on screen: the active one, or all of them
   * when none is active (the same scope rule the room and location lists
   * follow).
   *
   * Each workspace is its own world — its own rooms, its own agents. Reading or
   * reporting on one you are not looking at is both wasted work and, worse,
   * someone else's problem presented as yours.
   */
  private get workspaceIdsInScope(): string[] {
    const activeId = workspacesStore.activeId;
    if (activeId) return [activeId];
    return workspacesStore.workspaces.map((w) => w.id);
  }

  /**
   * Refresh the room catalogue for the workspaces on screen.
   *
   * A workspace that cannot be read keeps its last-known rooms rather than
   * losing them, but the failure is recorded in {@link roomListErrors} instead
   * of being swallowed: last-known data rendered as if it were current is the
   * one outcome worse than showing nothing.
   */
  async loadRoomNames(): Promise<void> {
    await this.loadRoomsFrom(this.workspaceIdsInScope);
  }

  /**
   * Refresh the room catalogue for **every** workspace.
   *
   * Only for cross-workspace search, which is deliberately not scoped — you
   * search because you do not know where a thing is. Everything else loads the
   * workspaces it is actually showing.
   */
  async loadRoomsInAllWorkspaces(): Promise<void> {
    await this.loadRoomsFrom(workspacesStore.workspaces.map((w) => w.id));
  }

  private async loadRoomsFrom(workspaceIds: string[]): Promise<void> {
    const asked = workspacesStore.workspaces.filter((w) => workspaceIds.includes(w.id));
    const connected = asked.filter((w) => switchServersStore.isConnected(w.serverId));
    runInAction(() => {
      // Not being connected is not a failure — there is simply nothing to ask
      // right now — but the rooms in that workspace are equally unknown, and the
      // sidebar has to be able to say so.
      const askedIds = new Set(workspaceIds);
      this.unreachableWorkspaceIds = [
        ...this.unreachableWorkspaceIds.filter((id) => !askedIds.has(id)),
        ...asked.filter((w) => !switchServersStore.isConnected(w.serverId)).map((w) => w.id),
      ];
      // A load that failed because the session had ended is the same fact as
      // being signed out, which is said on its own; a retry cannot fix it.
      for (const workspace of asked) {
        if (serverAvailability(workspace.serverId) === 'signed-out') {
          this.roomListErrors.delete(workspace.id);
        }
      }
    });
    await Promise.all(
      connected.map(async (workspace) => {
        try {
          const rooms = await rpc.workspaces.listRooms(workspace.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(workspace.serverId)?.user?.id ?? null;
          runInAction(() => {
            this.roomListErrors.delete(workspace.id);
            for (const room of rooms) {
              this.roomNames.set(room.id, room.name);
              this.roomWorkspaceById.set(room.id, workspace.id);
              if (room.bridgeType) this.bridgeTypeByRoom.set(room.id, room.bridgeType);
              else this.bridgeTypeByRoom.delete(room.id);
              if (room.externalChannelUrl)
                this.channelUrlByRoom.set(room.id, room.externalChannelUrl);
              else this.channelUrlByRoom.delete(room.id);
            }
            const active = rooms.filter((r) => !r.archived);
            this.allRoomsByWorkspace.set(workspace.id, active);
            this.ownedRoomsByWorkspace.set(
              workspace.id,
              signedInUserId
                ? active.filter((r) => r.ownerId === signedInUserId || r.viewerIsMember)
                : []
            );
          });
        } catch (cause) {
          runInAction(() => {
            this.roomListErrors.set(
              workspace.id,
              failureText(cause, `Could not load the rooms in ${workspace.name}.`)
            );
          });
        }
      })
    );
  }

  /**
   * Whether a room's name is missing because Switch Console is not signed in to its
   * server, rather than because the load has not finished.
   *
   * The room itself is known — an agent's membership put it there — so the row
   * has to say something. Which of the two it is decides whether the user is
   * being asked to wait or to act.
   */
  roomNameBlockedBySignIn(roomId: string): boolean {
    const workspaceId = this.roomWorkspaceById.get(roomId) ?? workspacesStore.activeId;
    if (!workspaceId) return false;
    const serverId = workspacesStore.serverIdFor(workspaceId);
    if (!serverId) return false;
    return serverAvailability(serverId) === 'signed-out';
  }

  /**
   * Workspaces on screen whose room list was asked for and failed.
   *
   * Distinct from {@link workspacesNotSignedIn}: this is a fault, it may be
   * transient, and retrying is a sensible thing to offer.
   */
  get workspacesThatFailedToLoad(): { id: string; name: string }[] {
    return this.namedWorkspacesInScope([...this.roomListErrors.keys()]);
  }

  /**
   * Workspaces on screen that were never asked because Switch Console is not
   * signed in to their server.
   *
   * Not a fault and not retryable — the user has to sign in. Reporting it as a
   * failure with a retry button offers an action that cannot work.
   */
  get workspacesNotSignedIn(): { id: string; name: string; serverId: string }[] {
    return this.namedWorkspacesInScope(this.unreachableWorkspaceIds).flatMap((workspace) => {
      const serverId = workspacesStore.serverIdFor(workspace.id);
      return serverId !== null && serverAvailability(serverId) === 'signed-out'
        ? [{ ...workspace, serverId }]
        : [];
    });
  }

  private namedWorkspacesInScope(workspaceIds: string[]): { id: string; name: string }[] {
    const inScope = new Set(this.workspaceIdsInScope);
    return [...new Set(workspaceIds)]
      .filter((id) => inScope.has(id))
      .map((id) => ({ id, name: workspacesStore.byId(id)?.name ?? id }))
      .sort((a, b) => a.name.localeCompare(b.name));
  }

  /**
   * Agents whose room membership is not known: the fetch failed, or has not run.
   *
   * Their rooms cannot list them, so a room can look emptier than it is. That is
   * indistinguishable from a genuinely empty room unless it is said out loud.
   */
  get agentsWithUnknownMembership(): number {
    return this.trackedIdentities.filter(
      ({ workspaceId, switchAgentId }) =>
        this.roomsByAgent.get(key(workspaceId, switchAgentId)) === undefined &&
        !this.isLoading(workspaceId, switchAgentId)
    ).length;
  }

  /** Cached membership, or undefined if never fetched. */
  roomsFor(workspaceId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {
    return this.roomsByAgent.get(key(workspaceId, switchAgentId));
  }

  /**
   * Room id → the Switch agent ids of this install's agents that belong to it.
   *
   * The gateway answers membership per agent, so the room-keyed view has to be
   * derived. Deriving it **here, once** rather than in each tree at render time
   * is what makes a room's member list and its member count the same read: any
   * view that wants either reads this, so the two cannot disagree.
   *
   * Scope is deliberate. This install can only act on its own agents, so those
   * are the only members the sidebar can draw. A room's full membership, agents
   * on other installs included, is the server's own count and is listed on the
   * Your Rooms page.
   */
  get localMemberIdsByRoom(): Map<string, string[]> {
    const byRoom = new Map<string, string[]>();
    // Only agents tracked or on screen now: a deleted agent's, or another
    // account's, memberships stay in the cache but claim no room.
    const current = new Set([
      ...this.trackedIdentities.map((a) => key(a.workspaceId, a.switchAgentId)),
      ...this.watchedIdentities.keys(),
    ]);
    for (const [cacheKey, memberships] of this.roomsByAgent) {
      if (!current.has(cacheKey)) continue;
      const switchAgentId = cacheKey.slice(cacheKey.indexOf(':') + 1);
      for (const membership of memberships) {
        if (membership.archived) continue;
        const members = byRoom.get(membership.roomId);
        if (members) members.push(switchAgentId);
        else byRoom.set(membership.roomId, [switchAgentId]);
      }
    }
    return byRoom;
  }

  /** The Switch agent ids of this install's agents in a room. */
  localMemberIds(roomId: string): string[] {
    return this.localMemberIdsByRoom.get(roomId) ?? [];
  }

  /**
   * Re-read every fact the sidebar's room state is built from: the room lists
   * and the membership of every tracked agent.
   *
   * The single door for "something changed, the view must catch up". Mutations
   * call this instead of picking their own subset of refreshes, which is how a
   * write ends up landing in one cache and missing another.
   */
  async refreshRoomState(): Promise<void> {
    await Promise.all([
      this.loadRoomNames(),
      this.ensureMembershipsFor(this.trackedIdentities, { force: true }),
    ]);
  }

  /**
   * 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: { workspaceId: string; switchAgentId: string }[],
    options: { force?: boolean } = {}
  ): Promise<void> {
    runInAction(() => {
      this.trackedIdentities = agents;
    });
    const identities = new Map(agents.map((a) => [key(a.workspaceId, a.switchAgentId), a]));
    for (const [k, watched] of this.watchedIdentities)
      if (!identities.has(k)) identities.set(k, watched);
    await Promise.all(
      [...identities.values()].map((a) =>
        this.fetchAgentRooms(a.workspaceId, a.switchAgentId, options)
      )
    );
  }

  /**
   * Keep an agent's membership current while a view shows it: read it now, and
   * again on every refresh until the returned function is called.
   */
  watchMembership(workspaceId: string, switchAgentId: string): () => void {
    const k = key(workspaceId, switchAgentId);
    const watched = this.watchedIdentities.get(k);
    if (watched) watched.views += 1;
    else this.watchedIdentities.set(k, { workspaceId, switchAgentId, views: 1 });
    void this.fetchAgentRooms(workspaceId, switchAgentId, { force: true });
    return () =>
      runInAction(() => {
        const current = this.watchedIdentities.get(k);
        if (!current) return;
        if (current.views > 1) current.views -= 1;
        else this.watchedIdentities.delete(k);
      });
  }

  isLoading(workspaceId: string, switchAgentId: string): boolean {
    return this.loading.has(key(workspaceId, switchAgentId));
  }

  errorFor(workspaceId: string, switchAgentId: string): string | null {
    return this.errors.get(key(workspaceId, switchAgentId)) ?? null;
  }

  /**
   * Fetch (or return cached) membership for an agent. Pass `force` to bypass the
   * cache. Returns the membership, or null if the fetch failed.
   */
  async fetchAgentRooms(
    workspaceId: string,
    switchAgentId: string,
    options: { force?: boolean } = {}
  ): Promise<RemoteAgentRoom[] | null> {
    const k = key(workspaceId, switchAgentId);
    const cached = this.roomsByAgent.get(k);
    if (cached && !options.force) return cached;
    const request = (this.membershipRequests.get(k) ?? 0) + 1;
    this.membershipRequests.set(k, request);

    runInAction(() => {
      this.loading.add(k);
      this.errors.delete(k);
    });
    try {
      const rooms = await rpc.workspaces.listAgentRooms({ workspaceId, agentId: switchAgentId });
      runInAction(() => {
        if (this.membershipRequests.get(k) === request) this.roomsByAgent.set(k, rooms);
      });
      return rooms;
    } catch (cause) {
      runInAction(() => {
        if (this.membershipRequests.get(k) === request)
          this.errors.set(k, failureText(cause, 'Could not load the rooms this agent belongs to.'));
      });
      return null;
    } finally {
      runInAction(() => {
        if (this.membershipRequests.get(k) === request) this.loading.delete(k);
      });
    }
  }
}

export const switchRoomsStore = new SwitchRoomsStore();