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(console): a welcome page on a fresh install

Petr Bauch00ace97b82a2
diff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts
new file mode 100644
index 000000000..5bef6e6e8
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts
@@ -0,0 +1,6 @@
+import { createRPCController } from '@shared/lib/ipc/rpc';
+import { installIsEmpty } from './install-contents';
+
+export const onboardingController = createRPCController({
+ installIsEmpty,
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts
new file mode 100644
index 000000000..f59a08805
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts
@@ -0,0 +1,27 @@
+import { db } from '@main/db/client';
+import { agents, locations, switchServers } from '@main/db/schema';
+
+/**
+ * Whether this install holds nothing of its own — the fresh-install question the
+ * shell asks before it puts the first-run page over the whole window.
+ *
+ * Deliberately not "has no Switch server". Agents, locations and the sessions
+ * running in them outlive a server on purpose: removing one says in as many
+ * words that its agents are kept and can be re-linked elsewhere. Reading an
+ * empty server list as a fresh install would answer that promise by replacing
+ * the window with a welcome page — permanently, across relaunches, with those
+ * sessions still running behind it.
+ *
+ * Answered here rather than assembled in the renderer because the counts are
+ * three rows the database already has, and the alternative is the shell waiting
+ * on stores that mount agents and open SSH connections to tell it whether to
+ * draw a sidebar at all.
+ */
+export async function installIsEmpty(): Promise<boolean> {
+ const [server] = await db.select({ id: switchServers.id }).from(switchServers).limit(1);
+ if (server) return false;
+ const [location] = await db.select({ id: locations.id }).from(locations).limit(1);
+ if (location) return false;
+ const [agent] = await db.select({ id: agents.id }).from(agents).limit(1);
+ return agent === undefined;
+}
diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.ts
index 404a6e31e..68a133597 100644
--- a/console/apps/switch-console-desktop/src/main/rpc.ts
+++ b/console/apps/switch-console-desktop/src/main/rpc.ts
@@ -7,6 +7,7 @@ import { filesController } from './core/fs/controller';
import { locationsController } from './core/locations/controller';
import { localSwitchServerController } from './core/managed-switch-server/controller';
import { remoteSwitchServerController } from './core/managed-switch-server/remote-controller';
+import { onboardingController } from './core/onboarding/controller';
import { providersController } from './core/providers/controller';
import { remoteHostsController } from './core/remote-hosts/controller';
import { resourceMonitorController } from './core/resource-monitor/controller';
@@ -39,6 +40,7 @@ export const rpcRouter = createRPCRouter({
switchServers: switchServersController,
agentTypes: agentTypesController,
workspaces: workspacesController,
+ onboarding: onboardingController,
localSwitchServer: localSwitchServerController,
remoteSwitchServer: remoteSwitchServerController,
remoteHosts: remoteHostsController,
diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts
new file mode 100644
index 000000000..b5a3d90ad
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+import { shellShape } from './shell-shape';
+
+/**
+ * The window has two shapes and what the install holds picks between them. Both
+ * wrong answers are bad in a way a layout bug is not: onboarding shown to
+ * someone who has an install hides it behind a first-run page, and the
+ * workspace shown on a fresh install is a sidebar listing nothing.
+ */
+
+/**
+ * A loaded, empty, undisturbed install — the fresh-install case. Each test
+ * below names only what it changes about it.
+ */
+function shape(differences: Partial<Parameters<typeof shellShape>[0]>) {
+ return shellShape({
+ loaded: true,
+ listError: null,
+ installIsEmpty: true,
+ viewWorksWithoutServer: false,
+ ...differences,
+ });
+}
+
+describe('what fills the window', () => {
+ it('waits rather than guessing before anything has been read', () => {
+ // The trap: an install with five servers looks exactly like a fresh one
+ // until the read comes back, because neither has answered yet.
+ expect(shape({ loaded: false, installIsEmpty: false })).toBe('loading');
+ });
+
+ it('onboards only once the install is known to be empty', () => {
+ expect(shape({})).toBe('onboarding');
+ });
+
+ /**
+ * "Something to show" is not "a server". Removing one says in as many words
+ * that its agents are kept and can be re-linked elsewhere, so an install left
+ * with agents and no server still has a window's worth of content — and the
+ * sessions in those agents are still running behind it.
+ */
+ it('shows the workspace as soon as there is anything to show', () => {
+ expect(shape({ installIsEmpty: false })).toBe('workspace');
+ });
+
+ it('lets a view that needs no server out of the onboarding page', () => {
+ // Settings and the remote hosts are views, so only the workspace can draw
+ // them, and the onboarding page carries no chrome of its own. Holding the
+ // window on it would leave ⌘, and the Preferences menu item doing nothing.
+ expect(shape({ viewWorksWithoutServer: true })).toBe('workspace');
+ });
+
+ /**
+ * Settings is where the logs and the database are, so a failed first read is
+ * precisely when it has to be reachable — and it needs nothing from the read
+ * to draw. Ordering this after the load gate would leave ⌘, and Preferences
+ * doing nothing in the one state that calls for them.
+ */
+ it('draws such a view even when nothing could be read', () => {
+ expect(shape({ loaded: false, viewWorksWithoutServer: true })).toBe('workspace');
+ expect(
+ shape({ loaded: false, listError: 'Could not load', viewWorksWithoutServer: true })
+ ).toBe('workspace');
+ });
+
+ it('says a first read failed instead of staying blank', () => {
+ // Otherwise the failure is indistinguishable from the blank first frame and
+ // the window just never fills.
+ expect(shape({ loaded: false, listError: 'Could not load' })).toBe('failed');
+ });
+
+ it('keeps the workspace when a later read fails', () => {
+ // The list in hand is still the list; a failed refresh is not a reason to
+ // take the app away from someone using it.
+ expect(shape({ listError: 'Could not load', installIsEmpty: false })).toBe('workspace');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
new file mode 100644
index 000000000..e2e059a33
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
@@ -0,0 +1,62 @@
+/** Which of the window's shapes what this install holds implies. */
+export type ShellShape = 'loading' | 'failed' | 'onboarding' | 'workspace';
+
+/**
+ * Decide what fills the window from what is known about this install.
+ *
+ * Separated from the component because the wrong answer here is not a layout
+ * bug — `onboarding` shown to someone who has an install hides the whole of it
+ * behind a first-run page, and `workspace` shown on a fresh one is a sidebar
+ * listing nothing. The inputs are easy to get the wrong way round, so they are
+ * decided in one place that can be exercised directly.
+ *
+ * `loaded` is what separates an empty install from one that has not been asked
+ * yet; both leave `installIsEmpty` false.
+ */
+export function shellShape({
+ loaded,
+ listError,
+ installIsEmpty,
+ viewWorksWithoutServer,
+}: {
+ loaded: boolean;
+ /**
+ * The list read's own failure, not the store's shared error slot — every
+ * action in that store writes the shared one, and a rename that went wrong
+ * is not a reason to put the whole window into its failure shape.
+ *
+ * It must also outlive a retry rather than being cleared as one starts:
+ * otherwise pressing "Try again" takes the failure page off screen, and the
+ * button with it, for as long as the retry runs.
+ */
+ listError: string | null;
+ /**
+ * Whether this install holds nothing at all — no server, no location, no
+ * agent.
+ *
+ * Not "has no server". Removing a server keeps its agents and says so in the
+ * confirmation, and the sessions running in them carry on; reading that as a
+ * fresh install would hide all of it behind a welcome page, permanently and
+ * across relaunches.
+ */
+ installIsEmpty: boolean;
+ /**
+ * Whether what is on screen can be drawn with no server behind it.
+ *
+ * The way out of the onboarding page for the views that do not describe a
+ * server. Without one, ⌘, and the Preferences menu item do nothing on a
+ * fresh install. Each view says this about itself rather than being named
+ * here, so the next one of the same kind is not missed.
+ */
+ viewWorksWithoutServer: boolean;
+}): ShellShape {
+ // Checked before the read, not after. Such a view needs nothing from this
+ // install to draw, and a first read that failed is exactly when Settings —
+ // its logs, its database — is where the user has to be able to get to.
+ if (viewWorksWithoutServer) return 'workspace';
+ // A failed read that nevertheless loaded once keeps the workspace: the list
+ // in hand is still the list, and a later refresh failing is not a reason to
+ // take the app away.
+ if (!loaded) return listError === null ? 'loading' : 'failed';
+ return installIsEmpty ? 'onboarding' : 'workspace';
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
index fbd991036..e94190add 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
@@ -58,12 +58,28 @@ export type ViewDefinition<TParams extends object = Record<never, never>> = {
* by older builds, so each guard must validate the shape before using it.
*/
canActivate?: (params: unknown) => GuardResult;
+ /**
+ * Set on a view that has something to show with no Switch server registered
+ * at all — Settings, the remote hosts. Everything else describes a server,
+ * or a workspace on one, and has nothing to draw without one.
+ *
+ * The shell reads it to decide whether the first-run page may be stepped out
+ * of. It lives on the view because only the view knows: a list of ids in the
+ * shell is a list someone has to remember to add to.
+ */
+ worksWithoutServer?: boolean;
};
type Views = typeof views;
export type ViewId = keyof Views;
+/** Whether the view on screen can be drawn before any server is registered. */
+export function viewWorksWithoutServer(viewId: ViewId): boolean {
+ const view: Pick<ViewDefinition, 'MainPanel' | 'worksWithoutServer'> = views[viewId];
+ return view.worksWithoutServer === true;
+}
+
/**
* The registry and the shared list of view ids say the same thing.
*
diff --git a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
index 648f23619..aa60be82d 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
@@ -1,36 +1,128 @@
+import { observer } from 'mobx-react-lite';
+import { useEffect, type ReactNode } from 'react';
+import { WelcomePage } from '@renderer/features/onboarding/welcome-page';
import { LeftSidebar } from '@renderer/features/sidebar/left-sidebar';
import { RoomEmbedLayer } from '@renderer/features/switch-rooms/room-embed-layer';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { CommandShortcutBinder } from '@renderer/lib/commands/command-shortcut-binder';
import { AppKeyboardShortcuts } from '@renderer/lib/components/app-keyboard-shortcuts';
import { MonacoKeyboardBridge } from '@renderer/lib/components/monaco-keyboard-bridge';
import { useTheme } from '@renderer/lib/hooks/useTheme';
-import { useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';
+import { useCurrentViewId, useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';
import { WorkspaceContentLayout, WorkspaceLayout } from '@renderer/lib/layout/workspace-layout';
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
+import { Button } from '@renderer/lib/ui/button';
+import { Spinner } from '@renderer/lib/ui/spinner';
import { Toaster } from '@renderer/lib/ui/toaster';
+import { shellShape } from './shell-shape';
+import { viewWorksWithoutServer } from './view-registry';
-export function Workspace() {
+/**
+ * What fills the window.
+ *
+ * Two shapes, not one: the workspace — sidebar, views, the room layer — and the
+ * onboarding flow that takes the whole window before there is any server to
+ * show. The choice is made here rather than inside a view because it is the
+ * chrome itself that differs; an onboarding page rendered into the workspace
+ * would sit beside a sidebar listing nothing.
+ *
+ * The server list is read here for the same reason. It used to be loaded by the
+ * sidebar, which is no longer always mounted, and the shell cannot ask a
+ * component it may not render which shape to take.
+ */
+export const Workspace = observer(function Workspace() {
useTheme();
const { WrapView } = useWorkspaceSlots();
const { wrapParams } = useWorkspaceWrapParams();
+ useEffect(() => {
+ void switchServersStore.init();
+ }, []);
+
return (
<>
<AppKeyboardShortcuts />
<CommandShortcutBinder />
<MonacoKeyboardBridge />
- <WorkspaceLayout
- leftSidebar={<LeftSidebar />}
+ <Shell
mainContent={
<WrapView {...wrapParams}>
<WorkspaceViewContent />
</WrapView>
}
- persistentLayer={<RoomEmbedLayer />}
/>
<Toaster />
</>
);
+});
+
+const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode }) {
+ const currentViewId = useCurrentViewId();
+ const shape = shellShape({
+ loaded: switchServersStore.loaded,
+ listError: switchServersStore.listError,
+ installIsEmpty: switchServersStore.installIsEmpty,
+ viewWorksWithoutServer: viewWorksWithoutServer(currentViewId),
+ });
+
+ switch (shape) {
+ // Nothing on screen rather than a spinner: this is one or two local IPC
+ // round-trips, and a spinner that flashes is worse than a beat of window.
+ case 'loading':
+ return null;
+ case 'failed':
+ return (
+ <ShellFailure
+ message={switchServersStore.listError ?? 'Could not load your Switch servers.'}
+ detail={switchServersStore.listErrorDetail}
+ retrying={switchServersStore.loadingServers}
+ />
+ );
+ case 'onboarding':
+ return <WelcomePage />;
+ case 'workspace':
+ return (
+ <WorkspaceLayout
+ leftSidebar={<LeftSidebar />}
+ mainContent={mainContent}
+ persistentLayer={<RoomEmbedLayer />}
+ />
+ );
+ }
+});
+
+/**
+ * The window when the first read of the server list failed.
+ *
+ * A retry runs on this page rather than replacing it. The read clears nothing
+ * as it starts, so the message, the detail and the button all stay put and the
+ * button says it is working — otherwise pressing it would unmount the only
+ * thing on screen and leave a blank window for as long as the retry took.
+ */
+function ShellFailure({
+ message,
+ detail,
+ retrying,
+}: {
+ message: string;
+ detail: string | null;
+ retrying: boolean;
+}) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 bg-background p-8 text-center [-webkit-app-region:drag]">
+ <p className="text-sm text-foreground">{message}</p>
+ {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}
+ <Button
+ className="[-webkit-app-region:no-drag]"
+ variant="outline"
+ disabled={retrying}
+ onClick={() => void switchServersStore.init()}
+ >
+ {retrying && <Spinner size="sm" className="mr-2" />}
+ {retrying ? 'Trying again…' : 'Try again'}
+ </Button>
+ </div>
+ );
}
function WorkspaceViewContent() {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx
new file mode 100644
index 000000000..3696b25fb
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx
@@ -0,0 +1,113 @@
+import { Cloud, Server } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { SwitchConsoleAppIcon } from '@renderer/lib/switch-console-app-icon';
+import { Button } from '@renderer/lib/ui/button';
+import { StepPager } from '@renderer/lib/ui/step-pager';
+import { cn } from '@renderer/utils/utils';
+
+const TAGLINE = 'Agents that work alongside your team, in the chat apps you already use.';
+
+/**
+ * The first page of a fresh install: what Switch is, and where it should run.
+ *
+ * It takes the whole window. There is no sidebar behind it because there is
+ * nothing for a sidebar to list — no servers, so no rooms, agents or sessions —
+ * and a first impression made of empty containers says less about the app than
+ * one question does.
+ *
+ * The two places are a list, not a choice. Only one of them can be had: Switch
+ * Cloud has no endpoint to sign in to and no account to sign in with. A radio
+ * group would announce itself as something to pick between and then answer
+ * neither arrow key nor click, which is a worse page than an honest list of
+ * two, one of them marked unavailable. Cloud stays on the page rather than
+ * being left off it, because the question is "where should it run" and an
+ * answer that exists but is not ready yet is part of that answer.
+ *
+ * So nothing here is a control except the button, and the button says which of
+ * the two it takes — the emphasis on the card is a repeat of that in colour,
+ * not the only place it is written.
+ */
+export function WelcomePage() {
+ const showAddServerModal = useShowModal('addServerModal');
+ const onContinue = () => showAddServerModal({});
+
+ return (
+ <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">
+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">
+ {/* Everything the page shows opts out of the drag region: a scroll
+ inside one is swallowed by the window move. What stays draggable is
+ the margin around it. */}
+ <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-8 px-8 py-10 [-webkit-app-region:no-drag]">
+ <div className="flex flex-col items-center gap-4">
+ <SwitchConsoleAppIcon size={64} className="rounded-2xl" />
+ <h1 className="text-3xl font-semibold">Welcome to Switch</h1>
+ <p className="text-center text-sm text-foreground-muted">{TAGLINE}</p>
+ </div>
+
+ <div className="flex flex-col gap-3">
+ <h2 className="text-sm font-medium">Where should it run?</h2>
+ <ul className="grid gap-3">
+ <HostingChoice
+ icon={<Cloud className="size-5" />}
+ title="Switch Cloud"
+ badge="Coming soon"
+ description="We would run it for you. Not open yet — there is nothing to sign in to."
+ unavailable
+ />
+ <HostingChoice
+ icon={<Server className="size-5" />}
+ title="Your own server"
+ description="Run the Switch stack on hardware you control. Your data and your accounts stay there."
+ />
+ </ul>
+ <div className="mt-1">
+ <Button onClick={onContinue}>Continue with your own server</Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="[-webkit-app-region:no-drag]">
+ <StepPager pageName="Welcome" onBack={null} onNext={onContinue} />
+ </div>
+ </div>
+ );
+}
+
+function HostingChoice({
+ icon,
+ title,
+ badge,
+ description,
+ unavailable = false,
+}: {
+ icon: ReactNode;
+ title: string;
+ badge?: string;
+ description: string;
+ /** Somewhere Switch cannot run yet. Said in the badge and the description
+ * too, so it does not rest on the greyed-out card alone. */
+ unavailable?: boolean;
+}) {
+ return (
+ <li
+ className={cn(
+ 'flex list-none items-start gap-3 rounded-lg border p-4 text-left',
+ unavailable ? 'border-border opacity-60' : 'border-foreground'
+ )}
+ >
+ <span className="mt-0.5 text-foreground-muted">{icon}</span>
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-foreground">{title}</span>
+ {badge && (
+ <span className="rounded-full bg-background-tertiary-2 px-2 py-0.5 text-[10px] text-foreground-muted">
+ {badge}
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-foreground-muted">{description}</p>
+ </div>
+ </li>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index b731af82f..cfc2ed1a4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -324,6 +324,9 @@ export const remoteHostView = {
// No titlebar slot: the page header already names the host and repeats the
// alias underneath it, so a third copy in the title bar was only noise.
MainPanel: RemoteHostMainPanel,
+ // A host is somewhere agents run, not something a server owns: its page says
+ // the same things with no server registered as with ten.
+ worksWithoutServer: true,
canActivate: (params: unknown): GuardResult => {
// Params can come from a snapshot written by an older build, so validate
// rather than trust: a view with no host to show has nothing to render.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
index 95760bd76..d41c1cc8e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
@@ -342,6 +342,10 @@ function RemoveHostButton({
*/
export const remoteHostsView = {
MainPanel: RemoteHostsSettingsPage,
+ // A host is somewhere agents run, not something a server owns, so the page
+ // stands up with no server registered — as does the Settings tab it forwards
+ // to.
+ worksWithoutServer: true,
canActivate: (): GuardResult => ({
ok: false,
redirect: 'settings',
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx
index ddba564ae..110e01933 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx
@@ -67,4 +67,8 @@ export function SettingsMainPanel() {
export const settingsView = {
WrapView: SettingsViewWrapper,
MainPanel: SettingsMainPanel,
+ // Preferences, themes, remote hosts and connector installs all stand on their
+ // own before any server is registered, and ⌘, has to lead somewhere on a
+ // fresh install.
+ worksWithoutServer: true,
};
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
index f7d5521de..842fb3400 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
@@ -4,6 +4,7 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
const getAuthConfig = vi.hoisted(() => vi.fn());
const getConnectionStatus = vi.hoisted(() => vi.fn());
const listServers = vi.hoisted(() => vi.fn());
+const installIsEmpty = vi.hoisted(() => vi.fn());
const setActiveServer = vi.hoisted(() => vi.fn());
/** The workspace selection as the main process holds it, by the server it is on. */
const selection = vi.hoisted(() => ({ serverId: null as string | null }));
@@ -23,6 +24,7 @@ vi.mock('@renderer/lib/ipc', () => ({
removeServer,
addServer,
},
+ onboarding: { installIsEmpty },
},
}));
/**
@@ -126,6 +128,7 @@ beforeEach(() => {
}));
getAuthConfig.mockResolvedValue(authConfig);
listServers.mockResolvedValue([]);
+ installIsEmpty.mockResolvedValue(true);
selectServer(null);
setActiveServer.mockImplementation(async (serverId: string) => selectServer(serverId));
});
@@ -244,6 +247,129 @@ describe('recovering when connectivity returns', () => {
});
});
+describe('reading the server list', () => {
+ it('serves callers arriving together one read', async () => {
+ // The shell asks on the first frame and so does the sidebar. Two reads of
+ // the same list race each other into the same fields for no gain.
+ listServers.mockResolvedValue([server('srv-a')]);
+ selectServer('srv-a');
+ const store = new SwitchServersStore();
+
+ await Promise.all([store.init(), store.init(), store.init()]);
+
+ expect(revalidate).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads again for a caller arriving after the last read settled', async () => {
+ // Sharing only the read in flight: the paths that change something and then
+ // ask for the list back must not be handed the answer from before it.
+ const store = new SwitchServersStore();
+ await store.init();
+ listServers.mockResolvedValue([server('srv-a')]);
+
+ await store.init();
+
+ expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);
+ });
+
+ it('keeps the failure on screen for as long as the retry runs', async () => {
+ // The window draws its failure page — message, detail and the button that
+ // starts the retry — from `listError`. Clearing it as the retry begins
+ // unmounts the page and the button with it, leaving a blank window until
+ // the retry lands.
+ listServers.mockRejectedValueOnce(new Error('gateway unreachable'));
+ const store = new SwitchServersStore();
+ await store.init();
+ expect(store.listError).not.toBeNull();
+
+ const retryRead = deferred<SwitchServer[]>();
+ listServers.mockReturnValueOnce(retryRead.promise);
+ const retrying = store.init();
+ await flush();
+
+ expect(store.listError).not.toBeNull();
+ expect(store.loadingServers).toBe(true);
+
+ retryRead.resolve([server('srv-a')]);
+ await retrying;
+
+ expect(store.listError).toBeNull();
+ expect(store.listErrorDetail).toBeNull();
+ });
+
+ it('reads what the install holds rather than inferring it from the list', async () => {
+ // An install whose server was removed keeps its agents — the confirmation
+ // says so — and the sessions in them are still running. An empty list is
+ // therefore not the fresh-install answer, and the shell needs that answer
+ // to decide whether to replace the window with a first-run page.
+ listServers.mockResolvedValue([]);
+ installIsEmpty.mockResolvedValue(false);
+ const store = new SwitchServersStore();
+
+ await store.init();
+
+ expect(store.servers).toEqual([]);
+ expect(store.installIsEmpty).toBe(false);
+ });
+
+ it('says a read is not coming back rather than leaving the window blank', async () => {
+ // Nothing is drawn until the first read lands, so a handler that never
+ // settles is a blank, inert window with no message and no way to ask again.
+ vi.useFakeTimers();
+ try {
+ listServers.mockReturnValueOnce(deferred<SwitchServer[]>().promise);
+ const store = new SwitchServersStore();
+ void store.init();
+
+ // Well past any deadline worth having: what is asserted is that one
+ // exists, not the exact number of seconds.
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ expect(store.loaded).toBe(false);
+ expect(store.listError).not.toBeNull();
+ expect(store.loadingServers).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('ignores a given-up read that lands after the retry has answered', async () => {
+ // The read cannot be cancelled, only abandoned — so the stale one is still
+ // out there, and letting it write would replace a good list with the one
+ // the user already gave up on.
+ vi.useFakeTimers();
+ try {
+ const stuck = deferred<SwitchServer[]>();
+ listServers.mockReturnValueOnce(stuck.promise);
+ const store = new SwitchServersStore();
+ void store.init();
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ listServers.mockResolvedValue([server('srv-a')]);
+ await store.init();
+ stuck.resolve([server('srv-stale')]);
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);
+ expect(store.listError).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps a failure from elsewhere out of the slot the window reads', async () => {
+ // `error` is the banner, written by every action here — a rename, a sign-out,
+ // adding a server. None of those is a reason to take the window away.
+ const store = newStore([server('srv-a')]);
+ removeServer.mockRejectedValue(new Error('still in use'));
+
+ await store.removeServer('srv-a');
+
+ expect(store.error).not.toBeNull();
+ expect(store.listError).toBeNull();
+ });
+});
+
describe('a page left on a server that is gone', () => {
it('is revalidated when the server is removed', async () => {
const store = newStore([server('srv-a')]);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index a8e41855e..dd7e4df98 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -1,7 +1,7 @@
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 } from '@renderer/lib/errors/describe-failure';
+import { describeFailure, type FailureDescription } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
import type {
@@ -11,6 +11,13 @@ import type {
UpdateServerResult,
} from '@shared/core/switch-servers/switch-servers';
+/**
+ * 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
@@ -63,9 +70,41 @@ export class SwitchServersStore {
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);
+ makeAutoObservable(this, { initInFlight: false });
}
/** Headline and detail as one string, for the modals that have a single slot. */
@@ -146,20 +185,48 @@ export class SwitchServersStore {
return this.authConfigInFlight.has(serverId);
}
- async init(): Promise<void> {
+ /**
+ * 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] = await Promise.all([
+ 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
@@ -168,14 +235,46 @@ export class SwitchServersStore {
await this.ensureActiveServer();
await this.refreshAllStatuses();
} catch (cause) {
- this.setError(cause, 'Could not load your Switch servers.');
- } finally {
+ if (generation !== this.listReadGeneration) return;
+ const { headline, detail } = this.setError(cause, 'Could not load your Switch servers.');
runInAction(() => {
- this.loadingServers = false;
+ 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
@@ -527,13 +626,17 @@ export class SwitchServersStore {
* 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): void {
+ private setError(cause: unknown, fallback: string): FailureDescription {
const { headline, detail } = describeFailure(cause, fallback);
runInAction(() => {
this.error = headline;
this.errorDetail = detail;
});
+ return { headline, detail };
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx
new file mode 100644
index 000000000..01fcb8ed1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { views, viewWorksWithoutServer, type ViewId } from '@renderer/app/view-registry';
+
+/**
+ * Which views may be drawn with nothing registered, named once.
+ *
+ * The flag lives on each view so the next one of its kind is not missed, and
+ * that is the right place for it — but it also means no single file says what
+ * the set is, and dropping the flag from Settings breaks ⌘, on a fresh install
+ * while every other test stays green. This is the file that notices.
+ *
+ * Deliberately a whole-set comparison rather than a per-view assertion: the
+ * failure worth catching is a flag that quietly appeared or disappeared, and
+ * only the set catches both.
+ *
+ * A browser test because importing the registry pulls in every view, which
+ * wants the preload bridge this project installs before a module evaluates.
+ */
+const CAN_BE_DRAWN_WITHOUT_A_SERVER = ['remoteHost', 'remoteHosts', 'settings'];
+
+describe('the views that need no Switch server', () => {
+ it('are these three and no others', () => {
+ const ids = (Object.keys(views) as ViewId[]).filter(viewWorksWithoutServer).sort();
+
+ expect(ids).toEqual(CAN_BE_DRAWN_WITHOUT_A_SERVER);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx
new file mode 100644
index 000000000..2b0560a76
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx
@@ -0,0 +1,118 @@
+/**
+ * The first page of a fresh install.
+ *
+ * Its whole job is to say where Switch can run and get on with the one place it
+ * can. So what matters is that the place nobody can use yet — Switch Cloud has
+ * no endpoint behind it — says so in words rather than only in grey, that
+ * nothing on the page pretends to be a choice, and that the place that does
+ * work leads somewhere rather than sitting there.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const showModal = vi.hoisted(() => vi.fn());
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/modal/modal-provider', () => ({
+ useShowModal: (id: string) => (props: unknown) => showModal(id, props),
+}));
+
+import { WelcomePage } from '@renderer/features/onboarding/welcome-page';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ showModal.mockReset();
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function renderPage(): Promise<HTMLDivElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(<WelcomePage />));
+ return container;
+}
+
+function choice(el: HTMLElement, title: string): HTMLElement {
+ const found = [...el.querySelectorAll<HTMLElement>('li')].find((c) =>
+ c.textContent?.includes(title)
+ );
+ expect(found, `no option named ${title}`).toBeDefined();
+ return found!;
+}
+
+function button(el: HTMLElement, label: string): HTMLButtonElement {
+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === label
+ );
+ expect(found, `no ${label} button`).toBeDefined();
+ return found!;
+}
+
+describe('the welcome page', () => {
+ it('asks where Switch should run and offers both places', async () => {
+ const el = await renderPage();
+
+ expect(el.textContent).toContain('Welcome to Switch');
+ expect(el.textContent).toContain('Where should it run?');
+ expect(choice(el, 'Switch Cloud')).toBeDefined();
+ expect(choice(el, 'Your own server')).toBeDefined();
+ });
+
+ it('says in words that Switch Cloud is not ready, not only in grey', async () => {
+ // Nothing hosts it yet. Shown anyway, because "where should it run" has two
+ // answers and one of them is not ready — but the reason has to be legible
+ // to someone who cannot see the card is dimmed.
+ const el = await renderPage();
+ const cloud = choice(el, 'Switch Cloud');
+
+ expect(cloud.textContent).toContain('Coming soon');
+ expect(cloud.textContent).toContain('there is nothing to sign in to');
+ });
+
+ it('offers nothing to pick between, since only one answer can be had', async () => {
+ // A radiogroup here was a widget with no working option in it: two
+ // `role="radio"` divs, no click handler, no key handler. Announcing a
+ // choice and then answering neither the keyboard nor the mouse is worse
+ // than a list that never claimed to be one.
+ const el = await renderPage();
+
+ expect(el.querySelectorAll('[role="radiogroup"], [role="radio"]')).toHaveLength(0);
+ // The one control on the page, and it names which of the two it takes.
+ expect(button(el, 'Continue with your own server')).toBeDefined();
+ });
+
+ it('opens the add-server flow from the button', async () => {
+ const el = await renderPage();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(showModal).toHaveBeenCalledWith('addServerModal', {});
+ });
+
+ it('sends the pager forward to the same place as Continue', async () => {
+ // The arrow is unlabelled, so it may only repeat a move the page already
+ // offers — never introduce one of its own.
+ const el = await renderPage();
+
+ await act(async () => el.querySelector<HTMLButtonElement>('[aria-label="Next page"]')!.click());
+
+ expect(showModal).toHaveBeenCalledWith('addServerModal', {});
+ });
+});