Skip to content

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

31.0 KB
Raw Blame
import { makeAutoObservable, runInAction } from 'mobx';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { describeFailure, type FailureDescription } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
import type { InviteServer } from '@shared/core/switch-servers/switch-cloud';
import type {
  ServerConnectionStatus,
  SignupMachine,
  SignupParams,
  SwitchAuthConfig,
  SwitchServer,
  UpdateServerResult,
} from '@shared/core/switch-servers/switch-servers';
import { gatewaySessionEndedChannel } from '@shared/events/switchServerEvents';

/**
 * How long the first read of the server list may take before the window says so
 * instead of staying blank. Generous: this is local IPC, so anything near it is
 * already a handler that is not coming back.
 */
const LIST_READ_DEADLINE_MS = 10_000;

/**
 * Renderer store for the Switch-server integration. Holds the registered
 * gateways, the per-server connection status (so the sidebar can show a dot per
 * entry), the per-server auth config (which login methods to offer), and which
 * server is active. Managing a server's agents/rooms happens in the gateway web
 * app for now, so this store deliberately does not fetch those — only what the
 * sidebar + the minimal server view need. Modeled on the singleton-store +
 * observable-state pattern used across the renderer stores.
 */
export class SwitchServersStore {
  servers: SwitchServer[] = [];

  /** Connection status per server id, refreshed on focus / select / manually. */
  readonly statuses = new Map<string, ServerConnectionStatus>();
  /** Auth config per server id, fetched lazily when a login panel needs it. */
  readonly authConfigs = new Map<string, SwitchAuthConfig>();
  /** Server ids a login panel has asked about. A failed or host-blocked fetch
   * caches nothing, so this is what the recovery paths re-drive. */
  private readonly authConfigWanted = new Set<string>();
  /** Server ids with an auth-config fetch in flight, so several recovery
   * signals arriving at once collapse into a single request. */
  private readonly authConfigInFlight = new Set<string>();
  /** Server ids whose last connection-status read failed. Authoritative for
   * page-level reachability whenever a status read has ever run for that
   * server: {@link isUnreachable} defers to this over
   * {@link authConfigUnreachable} so a hiccup on the sign-in-options endpoint
   * cannot evict a server whose status just came back fine. */
  readonly statusUnreachable = new Set<string>();
  /**
   * Server ids whose last auth-config read failed. Decisive for page-level
   * reachability only before any status read has ever run for that server —
   * once one has, {@link isUnreachable} never looks at this again, since a
   * server can be perfectly reachable while only its sign-in-options endpoint
   * stays broken. It does not stop mattering there: {@link
   * authConfigCheckFailed} exposes it separately so the sign-in panel can
   * disclose a persistently failing check instead of silently reusing a
   * cached answer forever.
   */
  readonly authConfigUnreachable = new Set<string>();

  loadingServers = false;
  /** Whether the list has been read at least once. Until it has, an empty
   * `servers` means "not asked yet", not "no such server" — the difference
   * matters to the server view's guard, which runs at startup before anything
   * has mounted to call {@link init}. */
  loaded = false;
  /** Server ids with an in-flight status refresh. */
  readonly refreshing = new Set<string>();
  /**
   * The latest status check started for each server. Checks overlap (a
   * session-ended hint, the account page after a password change, a manual
   * refresh), and only the latest may write: one that set out with a cookie
   * since replaced must not land after it and undo its answer. Nothing renders it.
   */
  private readonly statusGeneration = new Map<string, number>();
  /** The sentence the page leads with. Never raw exception text. */
  error: string | null = null;
  /** Diagnostics for the same failure, rendered under `error` rather than in it. */
  errorDetail: string | null = null;
  /**
   * The list read's own failure, as opposed to {@link error}, which every
   * action in this store writes — adding a server, renaming one, signing out.
   *
   * The shell decides what fills the window from this. Reading `error` there
   * would put the whole window into its failure shape because a rename went
   * wrong. Set only when a read fails and cleared only when one succeeds:
   * clearing it as a retry starts would take the failure page off screen — and
   * the retry button with it — for as long as the retry ran.
   */
  listError: string | null = null;
  /** Diagnostics for the failure in {@link listError}. */
  listErrorDetail: string | null = null;
  /**
   * Whether this install holds nothing at all — no server, no location, no
   * agent. Read alongside the list, because the shell decides between the
   * first-run page and the workspace from it and an empty server list is not
   * the same question: removing a server keeps its agents and says so, and
   * those agents plus the sessions running in them are still something to show.
   *
   * False until the first read lands; `loaded` is what separates that from an
   * install that really is empty.
   */
  installIsEmpty = false;
  /** The read in flight, so callers arriving together share one. Nothing renders it. */
  initInFlight: Promise<void> | null = null;
  /**
   * Which read is allowed to write. Bumped by each new read and by the deadline
   * below, so a read that has been given up on cannot land later and overwrite
   * the answer of the one that replaced it. Nothing renders it.
   */
  private listReadGeneration = 0;

  constructor() {
    makeAutoObservable(this, { initInFlight: false });
  }

  /** Headline and detail as one string, for the modals that have a single slot. */
  get errorText(): string | null {
    if (!this.error) return null;
    return this.errorDetail ? `${this.error} (${this.errorDetail})` : this.error;
  }

  /** Whether this server is managed on a host the reachability manager has
   * marked unreachable — nothing it serves can be fetched until that clears. */
  isHostBlocked(serverId: string): boolean {
    const server = this.servers.find((s) => s.id === serverId);
    if (!server?.managed || server.managementKind !== 'remote' || !server.sshHost) return false;
    return hostReachabilityStore.isBlocked(server.sshHost);
  }

  /**
   * The server the window is scoped to.
   *
   * Read off the active workspace rather than held here, so the two cannot
   * disagree. What the user selects is a workspace; the server is whichever one
   * hosts it, and the main process resolves it the same way.
   */
  get activeServerId(): string | null {
    return workspacesStore.activeServerId;
  }

  get activeServer(): SwitchServer | null {
    return this.serverById(this.activeServerId);
  }

  serverById(serverId: string | null): SwitchServer | null {
    if (!serverId) return null;
    return this.servers.find((s) => s.id === serverId) ?? null;
  }

  statusFor(serverId: string): ServerConnectionStatus | null {
    return this.statuses.get(serverId) ?? null;
  }

  authConfigFor(serverId: string): SwitchAuthConfig | null {
    return this.authConfigs.get(serverId) ?? null;
  }

  isConnected(serverId: string): boolean {
    return this.statuses.get(serverId)?.connected ?? false;
  }

  /**
   * Whether this server counts as unreachable for the page. Once a status
   * read has ever run for it, status is the sole authority — a signed-in
   * server whose sign-in-options endpoint hiccups must not lose its signed-in
   * view over that. Before status has ever answered, an auth-config failure
   * is the only signal available, so it decides instead.
   */
  isUnreachable(serverId: string): boolean {
    if (this.statuses.has(serverId)) return this.statusUnreachable.has(serverId);
    return this.authConfigUnreachable.has(serverId);
  }

  /**
   * Whether the last sign-in-options read failed, regardless of what
   * {@link isUnreachable} says. A server can be fully reachable — status
   * fine, maybe even signed in — while its sign-in-options endpoint stays
   * persistently broken; that failure never gates the page, so this is the
   * only place it is visible. The sign-in panel reads it to disclose that the
   * options on screen might be out of date rather than silently offering a
   * cached answer forever.
   */
  authConfigCheckFailed(serverId: string): boolean {
    return this.authConfigUnreachable.has(serverId);
  }

  /** Whether a sign-in-options read is in flight right now. The sign-in panel
   * reads this alongside {@link authConfigCheckFailed} so a fresh retry does
   * not get reported as a failure while it is still running. */
  authConfigChecking(serverId: string): boolean {
    return this.authConfigInFlight.has(serverId);
  }

  /**
   * Read the server list, once however many callers ask for it.
   *
   * The shell and the sidebar both ask on the first frame, and so does every
   * panel that needs a server list to draw. They share the read in flight
   * rather than making the same round-trip several times over; a caller
   * arriving after it settles starts a fresh one, so this never hands back a
   * stale answer to someone refreshing after a change of their own.
   */
  init(): Promise<void> {
    if (this.initInFlight) return this.initInFlight;
    // Only if it is still ours: a read given up on below is unhooked while it
    // is still running, and its eventual settling must not unhook the read that
    // replaced it.
    const read = this.readServers().finally(() => {
      if (this.initInFlight === read) this.initInFlight = null;
    });
    this.initInFlight = read;
    return read;
  }

  private async readServers(): Promise<void> {
    const generation = ++this.listReadGeneration;
    runInAction(() => {
      this.loadingServers = true;
      this.error = null;
      this.errorDetail = null;
    });
    const deadline = setTimeout(() => this.giveUpOnListRead(generation), LIST_READ_DEADLINE_MS);
    try {
      const [servers, installIsEmpty] = await Promise.all([
        rpc.switchServers.listServers(),
        rpc.onboarding.installIsEmpty(),
        workspacesStore.refresh(),
      ]);
      if (generation !== this.listReadGeneration) return;
      runInAction(() => {
        this.servers = servers;
        this.installIsEmpty = installIsEmpty;
        this.loaded = true;
        this.listError = null;
        this.listErrorDetail = null;
      });
      // A page restored onto a server that has since been deleted can only be
      // judged once the list is known, and startup restores navigation before
      // anything asks for it.
      appState.navigation.revalidate();
      await this.ensureActiveServer();
      await this.refreshAllStatuses();
    } catch (cause) {
      if (generation !== this.listReadGeneration) return;
      const { headline, detail } = this.setError(cause, 'Could not load your Switch servers.');
      runInAction(() => {
        this.listError = headline;
        this.listErrorDetail = detail;
      });
    } finally {
      clearTimeout(deadline);
      if (generation === this.listReadGeneration) {
        runInAction(() => {
          this.loadingServers = false;
        });
      }
    }
  }

  /**
   * Stop waiting on a read that has not answered.
   *
   * Before the first one lands the shell has nothing to draw, so a handler that
   * never settles leaves a blank, inert window with no way to say anything went
   * wrong and no way to ask again. Saying so is the whole point: the read is
   * abandoned rather than cancelled — it cannot be cancelled — and the
   * generation bump is what stops it landing later on top of the retry's
   * answer.
   *
   * Only before the first success. Once there is a list in hand, a slow refresh
   * is not a reason to take the app away from someone using it.
   */
  private giveUpOnListRead(generation: number): void {
    if (generation !== this.listReadGeneration || this.loaded) return;
    this.listReadGeneration += 1;
    this.initInFlight = null;
    runInAction(() => {
      this.loadingServers = false;
      this.listError = 'Could not load your Switch servers.';
      this.listErrorDetail = `Nothing came back after ${LIST_READ_DEADLINE_MS / 1000} seconds.`;
    });
  }

  /**
   * The switcher, the sidebar and the sessions under it all read the active
   * workspace, so one must be selected whenever any exists. Nothing on the main
   * side picks it — adding the first server leaves the selection empty — so
   * every path that changes the list ends here.
   *
   * A stored selection that no longer names a workspace counts as none. It is
   * not hypothetical: removing the active server and adding another leaves the
   * id pointing at the removed one, and treating that as a selection left the
   * app with no workspace at all — no switcher, no sidebar tree, no way back.
   *
   * Which one it lands on is expressed over servers rather than workspaces,
   * because a server is what the user just added or removed, and its own
   * workspaces are then the main process's to choose between.
   */
  private async ensureActiveServer(): Promise<void> {
    if (workspacesStore.active) return;
    const first = this.servers[0];
    if (first) await this.setActive(first.id);
  }

  async refreshAllStatuses(): Promise<void> {
    await Promise.all(this.servers.map((s) => this.refreshStatus(s.id)));
  }

  /**
   * Re-drive everything that recovers when connectivity does: the connection
   * status of every server, plus any auth config a login panel is still waiting
   * on. Auth config only recovers if something asks again, so it has to ride
   * the same signals as status rather than being a once-per-mount read.
   *
   * Only servers a login panel actually asked about are re-fetched, so this
   * stays as cheap as the status sweep it accompanies.
   */
  async recoverStale(): Promise<void> {
    const pending = [...this.authConfigWanted].filter((id) => !this.authConfigs.has(id));
    await Promise.all([
      this.refreshAllStatuses(),
      ...pending.map((id) => this.ensureAuthConfig(id)),
    ]);
  }

  /**
   * A manual, explicit re-check: the server page's header button and the
   * unreachable card's own Retry click. Covers both what the status card
   * reads and what the sign-in panel needs — refreshing only the status
   * leaves a page that never got its auth config stuck on "Checking sign-in
   * options…", and a click is a single bounded request, so it can afford the
   * full check even where the automatic probe below cannot.
   */
  async refreshServer(serverId: string): Promise<void> {
    await Promise.all([this.refreshStatus(serverId), this.refreshAuthConfig(serverId)]);
  }

  /**
   * The unreachable card's automatic 10-second timer. Only connectivity is
   * worth re-checking on a fixed interval; sign-in options keep the
   * once-cached behavior of {@link ensureAuthConfig} so a genuine outage does
   * not turn into two doomed round trips on every tick, forever — the panel's
   * own {@link authConfigCheckFailed} disclosure, plus the card's manual
   * Retry button, are what re-drive a persistently broken sign-in-options
   * endpoint instead.
   */
  async retryConnection(serverId: string): Promise<void> {
    await Promise.all([this.refreshStatus(serverId), this.ensureAuthConfig(serverId)]);
  }

  /**
   * A signed-in call to this server was refused with 401. Re-read its status
   * rather than signing out on the spot: `/auth/me` is what decides, so a
   * session that has really gone reads as signed out — the sidebar asks for a
   * sign-in instead of calling its rooms out of date and its chats offline —
   * and a stray 401 costs one request and changes nothing.
   *
   * Only a server that reads as signed in is re-checked, and not while a check
   * is already running. The re-check of a dead session is itself refused with
   * 401 and says so again; once it has landed, the server no longer reads as
   * signed in, so that echo ends here.
   */
  async noteSessionEnded(serverId: string): Promise<void> {
    if (!this.isConnected(serverId) || this.refreshing.has(serverId)) return;
    await this.refreshStatus(serverId);
  }

  async refreshStatus(serverId: string): Promise<void> {
    const generation = (this.statusGeneration.get(serverId) ?? 0) + 1;
    this.statusGeneration.set(serverId, generation);
    const latest = () => this.statusGeneration.get(serverId) === generation;
    runInAction(() => {
      this.refreshing.add(serverId);
    });
    try {
      const status = await rpc.switchServers.getConnectionStatus(serverId);
      if (!latest()) return;
      runInAction(() => {
        this.statuses.set(serverId, status);
        this.statusUnreachable.delete(serverId);
      });
    } catch (cause) {
      // An unreachable server is a real, displayable state — record it as
      // disconnected (the per-server status dot shows it) and flag the server
      // so its page can say so in one line. A background poll failure must NOT
      // raise the page-level `error` banner: that field is global, so one
      // unreachable server would paint an error over every server's view.
      console.warn(`[switch-servers] could not read status for ${serverId}`, cause);
      if (!latest()) return;
      runInAction(() => {
        this.statuses.set(serverId, { serverId, connected: false, user: null });
        this.statusUnreachable.add(serverId);
      });
    } finally {
      // An overtaken check leaves the flag to the one still running.
      if (latest()) {
        runInAction(() => {
          this.refreshing.delete(serverId);
        });
      }
    }
  }

  /**
   * Fetch which login methods a server offers, unless that is already known.
   *
   * Safe to call from every recovery path: a cached config short-circuits, and
   * concurrent callers collapse into the one in-flight request. A failure
   * caches nothing, so the next caller retries — which is the point, since the
   * usual failure is a connectivity blip that later heals (CHOO-2042).
   */
  async ensureAuthConfig(serverId: string): Promise<void> {
    runInAction(() => {
      this.authConfigWanted.add(serverId);
    });
    if (this.authConfigs.has(serverId)) return;
    await this.fetchAuthConfig(serverId);
  }

  /**
   * Re-fetch a server's login methods even though one is already cached — for
   * the manual refresh path, where the cached answer is exactly what might be
   * wrong (an operator turning on OIDC after Console cached password-only). A
   * failed refresh leaves the stale config in place rather than clearing it,
   * and {@link isUnreachable} does not let this failure alone evict a server
   * whose connection status is fine — but the staleness itself is not
   * silent: {@link authConfigCheckFailed} discloses it to the sign-in panel,
   * which is the one place still showing what this fetch returned.
   */
  async refreshAuthConfig(serverId: string): Promise<void> {
    runInAction(() => {
      this.authConfigWanted.add(serverId);
    });
    await this.fetchAuthConfig(serverId);
  }

  private async fetchAuthConfig(serverId: string): Promise<void> {
    if (this.authConfigInFlight.has(serverId)) return;
    // The gateway of a server on an unreachable host cannot answer, and the
    // host-unreachable surface already states why — don't paint the global
    // error banner with a doomed fetch (CHOO-1780). The host un-blocking is
    // itself a recovery signal, so this is a skip, not a giving up — and a
    // failure recorded before the host went down does not belong to this
    // skip, so it does not survive it either.
    if (this.isHostBlocked(serverId)) {
      runInAction(() => {
        this.authConfigUnreachable.delete(serverId);
      });
      return;
    }
    runInAction(() => {
      this.authConfigInFlight.add(serverId);
    });
    try {
      const config = await rpc.switchServers.getAuthConfig(serverId);
      runInAction(() => {
        this.authConfigs.set(serverId, config);
        this.authConfigUnreachable.delete(serverId);
      });
    } catch (cause) {
      // Not the error banner: the raw text is our own IPC method name wrapped
      // around a fetch failure, which tells the user nothing they can act on.
      // The page states the one thing that matters, that the server cannot be
      // reached, and the detail stays in the console for us.
      console.warn(`[switch-servers] could not read auth config for ${serverId}`, cause);
      runInAction(() => {
        this.authConfigUnreachable.add(serverId);
      });
    } finally {
      runInAction(() => {
        this.authConfigInFlight.delete(serverId);
      });
    }
  }

  async addServer(name: string, url: string): Promise<SwitchServer | null> {
    this.clearError();
    try {
      const created = await rpc.switchServers.addServer({ name, url });
      const [servers, installIsEmpty] = await Promise.all([
        rpc.switchServers.listServers(),
        rpc.onboarding.installIsEmpty(),
        workspacesStore.refresh(),
      ]);
      runInAction(() => {
        this.servers = servers;
        this.installIsEmpty = installIsEmpty;
      });
      await this.ensureActiveServer();
      await this.refreshStatus(created.id);
      return created;
    } catch (cause) {
      this.setError(cause, 'Could not add the server.');
      return null;
    }
  }

  /**
   * Register Switch Cloud, or take the row already registered for it.
   *
   * Raises rather than recording a store error like `addServer`: the Cloud is
   * chosen from a card with no form under it, so the card is where the failure
   * has to be shown.
   */
  async connectToSwitchCloud(): Promise<SwitchServer> {
    const server = await rpc.switchServers.connectToSwitchCloud();
    const [servers, installIsEmpty] = await Promise.all([
      rpc.switchServers.listServers(),
      rpc.onboarding.installIsEmpty(),
      workspacesStore.refresh(),
    ]);
    runInAction(() => {
      this.servers = servers;
      this.installIsEmpty = installIsEmpty;
    });
    await this.ensureActiveServer();
    await this.refreshStatus(server.id);
    return server;
  }

  /**
   * The server an invite link names, registering Switch Cloud when that is it.
   *
   * Refreshes like {@link connectToSwitchCloud} when a row was added, so the
   * sign-in page that follows finds the server in the list it reads.
   */
  async serverForInvite(origin: string): Promise<InviteServer> {
    const found = await rpc.switchServers.serverForInvite(origin);
    if (found.kind === 'unknown') return found;
    const [servers, installIsEmpty] = await Promise.all([
      rpc.switchServers.listServers(),
      rpc.onboarding.installIsEmpty(),
      workspacesStore.refresh(),
    ]);
    runInAction(() => {
      this.servers = servers;
      this.installIsEmpty = installIsEmpty;
    });
    await this.ensureActiveServer();
    await this.refreshStatus(found.server.id);
    return found;
  }

  async updateServer(id: string, name: string, url: string): Promise<UpdateServerResult | null> {
    this.clearError();
    try {
      const result = await rpc.switchServers.updateServer({ id, name, url });
      const servers = await rpc.switchServers.listServers();
      runInAction(() => {
        this.servers = servers;
      });
      return result;
    } catch (cause) {
      this.setError(cause, 'Could not save the server.');
      return null;
    }
  }

  async renameServer(id: string, name: string): Promise<boolean> {
    this.clearError();
    try {
      await rpc.switchServers.renameServer({ id, name });
      const servers = await rpc.switchServers.listServers();
      runInAction(() => {
        this.servers = servers;
      });
      return true;
    } catch (cause) {
      this.setError(cause, 'Could not rename the server.');
      return false;
    }
  }

  /**
   * Delete a server. For a managed server this first tears down its stack (the
   * Docker/SSH reset — stops containers and destroys the stack's data), since
   * removing the record while the stack keeps running would strand it. That
   * teardown also deletes the stack's agents, whose identity it destroys.
   *
   * External servers have no stack: de-registering one destroys nothing, so its
   * agents keep working and are merely unlinked (see {@link removeServer}).
   * Returns false if the teardown or de-register failed.
   */
  async deleteServer(serverId: string): Promise<boolean> {
    this.clearError();
    const server = this.servers.find((s) => s.id === serverId);
    try {
      if (server?.managed) {
        if (server.managementKind === 'remote' && server.sshHost) {
          await rpc.remoteSwitchServer.reset(server.sshHost);
        } else {
          await rpc.localSwitchServer.reset();
        }
      }
    } catch (cause) {
      this.setError(cause, 'Could not shut down the server’s stack, so it was not deleted.');
      return false;
    }
    await this.removeServer(serverId);
    return this.error === null;
  }

  async removeServer(serverId: string): Promise<void> {
    this.clearError();
    try {
      await rpc.switchServers.removeServer(serverId);
      await this.forgetRemovedServer(serverId);
    } catch (cause) {
      this.setError(cause, 'Could not remove the server.');
    }
  }

  /**
   * Re-read what a server's removal leaves behind in this store. Public for the
   * remote store, which disconnects from a shared remote server itself.
   */
  async forgetRemovedServer(serverId: string): Promise<void> {
    const [servers] = await Promise.all([
      rpc.switchServers.listServers(),
      workspacesStore.refresh(),
    ]);
    runInAction(() => {
      this.servers = servers;
      this.statuses.delete(serverId);
      this.authConfigs.delete(serverId);
      this.authConfigWanted.delete(serverId);
      this.statusUnreachable.delete(serverId);
      this.authConfigUnreachable.delete(serverId);
    });
    // The removed id also sits in the server view's saved params, where it
    // outlives the record and would be read back — as a page for a server
    // that is gone, and as gateway calls for an id nothing can resolve.
    appState.navigation.revalidate();
    await this.ensureActiveServer();
  }

  /**
   * Scope the window to a server, for the callers that know only one — adding
   * a server, and following a navigation onto another server's room or agent.
   *
   * Which of its workspaces that lands on is the main process's to decide: it
   * keeps the current selection if it is already on this server, and otherwise
   * picks one. Picking here instead would make this store the second place that
   * answers the same question.
   */
  async setActive(serverId: string): Promise<void> {
    this.clearError();
    try {
      await rpc.switchServers.setActiveServer(serverId);
      await workspacesStore.refresh();
    } catch (cause) {
      this.setError(cause, 'Could not switch to that server.');
    }
  }

  async passwordLogin(serverId: string, email: string, password: string): Promise<boolean> {
    this.clearError();
    const result = await rpc.switchServers.passwordLogin({ serverId, email, password });
    if (!result.success) {
      runInAction(() => {
        this.error = result.error.message;
        this.errorDetail = null;
      });
      return false;
    }
    // Signing in is when the server first says which workspaces the account
    // belongs to, so the list this app holds is stale the moment it returns.
    await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);
    return true;
  }

  /** Resolves the new account's machine status once signed in, or null when
   * the account was not created (the reason is in `error`). */
  async signup(params: SignupParams): Promise<SignupMachine | null> {
    this.clearError();
    let result: Awaited<ReturnType<typeof rpc.switchServers.signup>>;
    try {
      result = await rpc.switchServers.signup(params);
    } catch (cause) {
      this.setError(cause, 'Could not create the account.');
      return null;
    }
    if (!result.success) {
      runInAction(() => {
        this.error = result.error.message;
        this.errorDetail = null;
      });
      return null;
    }
    // Signed in now, and as with a sign-in the account's workspaces are known.
    await Promise.all([this.refreshStatus(params.serverId), workspacesStore.refresh()]);
    return result.data.machine;
  }

  /** `provider`: one of the server's sign-in options, or null for its one SSO button. */
  async oidcLogin(serverId: string, provider: string | null): Promise<boolean> {
    this.clearError();
    const result = await rpc.switchServers.oidcLogin(serverId, provider);
    if (!result.success) {
      // A user-cancelled window is not an error worth shouting about.
      if (result.error.kind !== 'cancelled') {
        runInAction(() => {
          this.error = result.error.message;
          this.errorDetail = null;
        });
      }
      return false;
    }
    // Signing in may also have taught Console where an older server keeps its
    // dashboard, which the links built here read from the list.
    const [servers] = await Promise.all([
      rpc.switchServers.listServers(),
      this.refreshStatus(serverId),
      workspacesStore.refresh(),
    ]);
    runInAction(() => {
      this.servers = servers;
    });
    return true;
  }

  /** Gives up a sign-in waiting on the system browser; its `oidcLogin` resolves as cancelled. */
  cancelOidcLogin(serverId: string): void {
    void rpc.switchServers.cancelOidcLogin(serverId);
  }

  async logout(serverId: string): Promise<void> {
    this.clearError();
    try {
      await rpc.switchServers.logout(serverId);
      await this.refreshStatus(serverId);
    } catch (cause) {
      this.setError(cause, 'Could not sign out of the server.');
    }
  }

  /**
   * Delete the signed-in account on `serverId`, confirmed by its email. Throws
   * with the server's reason when it refuses, for the dialog that asked to say.
   */
  async deleteAccount(serverId: string, email: string): Promise<void> {
    await rpc.switchServers.deleteAccount({ serverId, email });
    await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);
  }

  private clearError(): void {
    runInAction(() => {
      this.error = null;
      this.errorDetail = null;
    });
  }

  /**
   * `error` is rendered directly in banners and modals, so it goes through the
   * shared boundary rather than carrying whatever was thrown. The fallback is
   * per-action: the store knows which request failed, and the failure itself
   * usually does not.
   *
   * Returns what it wrote, for the one caller that also keeps the failure in a
   * slot of its own.
   */
  private setError(cause: unknown, fallback: string): FailureDescription {
    const { headline, detail } = describeFailure(cause, fallback);
    runInAction(() => {
      this.error = headline;
      this.errorDetail = detail;
    });
    return { headline, detail };
  }
}

export const switchServersStore = new SwitchServersStore();

events.on(gatewaySessionEndedChannel, ({ serverId }) => {
  void switchServersStore.noteSessionEnded(serverId);
});