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): the own-server path through first run (CHOO-2702)

Petr Bauch9f8c618b1298
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts
index 9fd7600dd..ac0975a66 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts
@@ -46,7 +46,8 @@ function sampleFor(property: string): string | number | boolean {
property === 'connected_to_room' ||
property === 'delete_in_switch' ||
property === 'resolved' ||
- property === 'cold_start'
+ property === 'cold_start' ||
+ property === 'first_run'
) {
return true;
}
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
index a8b03b05f..23bcadd3c 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
@@ -651,7 +651,7 @@ export const TELEMETRY_EVENT_PROPERTIES = {
onboarding_step_started: ['step_id'],
onboarding_checklist_dismissed: [],
onboarding_completed: [],
- add_server_step: ['step', 'choice'],
+ add_server_step: ['step', 'choice', 'first_run'],
renderer_crashed: [],
telemetry_consent_changed: ['source'],
session_attached: ['agent_type', 'outcome'],
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts
index 844be6f70..abfb66ec2 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts
@@ -53,6 +53,7 @@ const RENDERER_TELEMETRY_SCHEMAS = {
add_server_step: z.object({
step: z.enum(ADD_SERVER_STEPS),
choice: z.enum(ADD_SERVER_CHOICES),
+ first_run: z.boolean(),
}),
renderer_crashed: z.object({}),
} as const satisfies {
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
index b5a3d90ad..204e09326 100644
--- 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
@@ -18,6 +18,7 @@ function shape(differences: Partial<Parameters<typeof shellShape>[0]>) {
listError: null,
installIsEmpty: true,
viewWorksWithoutServer: false,
+ onboardingInProgress: false,
...differences,
});
}
@@ -63,6 +64,17 @@ describe('what fills the window', () => {
).toBe('workspace');
});
+ it('stays on the first-run pages once the flow has added the server', () => {
+ // The flow adds the server pages before it is done with it — signing in and
+ // linking accounts both come after. Going by the contents alone would throw
+ // the user out of the flow at the moment it half-succeeded.
+ expect(shape({ installIsEmpty: false, onboardingInProgress: true })).toBe('onboarding');
+ });
+
+ it('still lets such a view out of a flow in progress', () => {
+ expect(shape({ onboardingInProgress: true, 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.
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
index e2e059a33..5f9d0aec8 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
@@ -18,6 +18,7 @@ export function shellShape({
listError,
installIsEmpty,
viewWorksWithoutServer,
+ onboardingInProgress,
}: {
loaded: boolean;
/**
@@ -49,6 +50,8 @@ export function shellShape({
* here, so the next one of the same kind is not missed.
*/
viewWorksWithoutServer: boolean;
+ /** Whether the first-run flow has been started and not yet finished. */
+ onboardingInProgress: 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 —
@@ -58,5 +61,10 @@ export function shellShape({
// 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';
+ // A flow in progress outranks what the install holds, because the flow is
+ // what changes it: the server is added several pages before the user has
+ // signed in to it, and going by the contents alone would throw them out of
+ // the flow at the moment it half-succeeded.
+ if (onboardingInProgress) return 'onboarding';
return installIsEmpty ? 'onboarding' : 'workspace';
}
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 aa60be82d..cb2f395c4 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
@@ -1,6 +1,7 @@
import { observer } from 'mobx-react-lite';
import { useEffect, type ReactNode } from 'react';
-import { WelcomePage } from '@renderer/features/onboarding/welcome-page';
+import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';
+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';
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';
@@ -63,6 +64,7 @@ const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode
listError: switchServersStore.listError,
installIsEmpty: switchServersStore.installIsEmpty,
viewWorksWithoutServer: viewWorksWithoutServer(currentViewId),
+ onboardingInProgress: onboardingStore.inProgress,
});
switch (shape) {
@@ -79,7 +81,7 @@ const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode
/>
);
case 'onboarding':
- return <WelcomePage />;
+ return <OnboardingFlow />;
case 'workspace':
return (
<WorkspaceLayout
diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx
new file mode 100644
index 000000000..995f5f716
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx
@@ -0,0 +1,334 @@
+import { Link2, Server, TriangleAlert, Wrench } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useEffect, useState } from 'react';
+import {
+ ChoiceCard,
+ ExternalServerStep,
+ LocalSetupStep,
+ RemoteHostSetupStep,
+ SignInStep,
+} from '@renderer/features/switch-servers/AddServerModal';
+import { LinkAccountsStep } from '@renderer/features/switch-servers/link-accounts-step';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { report } from '@renderer/lib/telemetry/report';
+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { WizardChromeProvider, WizardFrame } from '@renderer/lib/ui/wizard-frame';
+import type {
+ AddServerChoiceName,
+ AddServerStepName,
+} from '@shared/core/switch-servers/add-server-steps';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { onboardingStore, type OnboardingPage } from './onboarding-store';
+import { WelcomePage } from './welcome-page';
+
+/**
+ * The first-run pages and the add-server wizard's steps, named against each
+ * other so both funnels answer the same question.
+ *
+ * They are the same steps — the first-run pages are the wizard drawn full
+ * window — so reporting them under new names would split "how far did people
+ * get" in two. `firstRun` on the event is what keeps them apart where it
+ * matters. The welcome page belongs to neither: nothing has been chosen on it
+ * and there is no server being added yet.
+ */
+const STEP_FOR_PAGE: Record<OnboardingPage, AddServerStepName | null> = {
+ welcome: null,
+ whoRuns: 'choose',
+ local: 'local',
+ remoteHost: 'remoteHost',
+ connect: 'external',
+ signIn: 'signIn',
+ linkAccounts: 'linkAccounts',
+};
+
+/**
+ * Which path each page belongs to.
+ *
+ * Unlike the modal's, none of these inherit: the only way to reach sign-in on a
+ * fresh install is by connecting to a server someone else runs.
+ */
+const CHOICE_FOR_PAGE: Record<OnboardingPage, AddServerChoiceName> = {
+ welcome: 'none',
+ whoRuns: 'none',
+ local: 'local',
+ remoteHost: 'remoteHost',
+ connect: 'external',
+ signIn: 'external',
+ linkAccounts: 'external',
+};
+
+/**
+ * Everything the window shows before there is a server to show.
+ *
+ * The pages after the first are the add-server wizard's own steps, drawn full
+ * window instead of in a dialog. Setting up a server is the same three
+ * questions whether you have none or nine, and a first-run copy of them would
+ * be a second place for the Docker check, the connection form and the sign-in
+ * to drift from what the rest of the app does.
+ *
+ * Running a managed stack on a remote host is offered only when there is a host
+ * to run it on. It needs one onboarded over SSH, which a fresh install has none
+ * of — but onboarding a host needs no server, so someone who deleted their last
+ * one may well arrive here with hosts already set up, and hiding the path from
+ * them would leave it unreachable.
+ */
+export const OnboardingFlow = observer(function OnboardingFlow() {
+ const { navigate } = useNavigate();
+
+ const goTo = (page: OnboardingPage) => {
+ onboardingStore.goTo(page);
+ reportPage(page);
+ };
+
+ /**
+ * Leave the first-run pages for the app they were setting up.
+ *
+ * Landing on the new server's page rather than wherever the window would
+ * otherwise open: the flow was about that server, and dropping the user into
+ * an empty home view would make the last ten minutes look like they did
+ * nothing.
+ */
+ const finish = (serverId: string | null) => {
+ onboardingStore.reset();
+ if (serverId === null) return;
+ void switchServersStore.setActive(serverId);
+ navigate('server', { serverId });
+ };
+
+ // The server as the list has it, not as the flow remembers it. Once one
+ // exists the window is the workspace again for any view that does not need a
+ // server, so it can be deleted from under the flow — and a form aimed at a
+ // row that is gone fails on submit with no way back to a working one.
+ const server = switchServersStore.serverById(pageServerId());
+
+ /**
+ * Leave the flow for the app, with the server set up but the rest not done.
+ *
+ * Offered only once the page on screen has a server of its own, which is both
+ * when there is something to come back to and when the flow stops being the
+ * only thing the window can draw. Before that, stepping back off the welcome
+ * page is the way out.
+ */
+ const exit = server === null ? null : { label: 'Finish later', onExit: () => finish(server.id) };
+
+ return (
+ <WizardChromeProvider chrome="page" exit={exit}>
+ {currentPage(server, goTo, finish)}
+ </WizardChromeProvider>
+ );
+});
+
+/**
+ * The server the page on screen is the setup of, if it has one yet.
+ *
+ * Asked per page rather than kept as one field, because the paths reach a
+ * server by different means and none of them owns another's: the connect page
+ * hands one over and every page after it works on that same one, while each
+ * managed page brings its own up. Reading a single field instead offered a way
+ * out to a server the current page had nothing to do with — connect to one,
+ * walk back, choose the local path, and the exit still pointed at the first.
+ */
+function pageServerId(): string | null {
+ const page = onboardingStore.page;
+ if (onboardingStore.registeredOn?.page === page) return onboardingStore.registeredOn.serverId;
+ if (CHOICE_FOR_PAGE[page] !== 'external') return null;
+ return onboardingStore.server?.id ?? null;
+}
+
+function reportPage(page: OnboardingPage): void {
+ const step = STEP_FOR_PAGE[page];
+ if (step === null) return;
+ report('add_server_step', { step, choice: CHOICE_FOR_PAGE[page], first_run: true });
+}
+
+function currentPage(
+ server: SwitchServer | null,
+ goTo: (page: OnboardingPage) => void,
+ finish: (serverId: string | null) => void
+) {
+ switch (onboardingStore.page) {
+ case 'welcome':
+ return <WelcomePage onContinue={() => goTo('whoRuns')} />;
+ case 'whoRuns':
+ return (
+ <WhoRunsPage
+ onBack={() => goTo('welcome')}
+ onLocal={() => goTo('local')}
+ onRemoteHost={() => goTo('remoteHost')}
+ onExternal={() => goTo('connect')}
+ />
+ );
+ case 'local':
+ return (
+ <LocalSetupStep
+ onBack={() => goTo('whoRuns')}
+ onDone={finish}
+ onClose={null}
+ onRegistered={(serverId) => onboardingStore.registered('local', serverId)}
+ />
+ );
+ case 'remoteHost':
+ return (
+ <RemoteHostSetupStep
+ onBack={() => goTo('whoRuns')}
+ onDone={finish}
+ onClose={() => goTo('whoRuns')}
+ onRegistered={(serverId) => onboardingStore.registered('remoteHost', serverId)}
+ />
+ );
+ case 'signIn':
+ // Both of these need the server the connect page added. Without one there
+ // is nothing to sign in to, so the flow goes back to the page that makes
+ // it rather than drawing a form against nothing.
+ if (server === null) break;
+ return (
+ <SignInStep
+ server={server}
+ onBack={() => goTo('connect')}
+ onClose={null}
+ onSignedIn={() => goTo('linkAccounts')}
+ />
+ );
+ case 'linkAccounts':
+ if (server === null) break;
+ return (
+ <LinkAccountsStep
+ serverId={server.id}
+ serverName={server.name}
+ onDone={() => finish(server.id)}
+ />
+ );
+ case 'connect':
+ break;
+ }
+
+ return (
+ <ExternalServerStep
+ initialGatewayUrl={null}
+ initialApiUrl={null}
+ initialName={null}
+ serverId={null}
+ isEdit={false}
+ firstRun
+ existing={server}
+ onBack={() => goTo('whoRuns')}
+ onClose={() => goTo('whoRuns')}
+ onSuccess={() => finish(server?.id ?? null)}
+ onConnected={(added) => {
+ onboardingStore.connected(added);
+ reportPage('signIn');
+ }}
+ />
+ );
+}
+
+/**
+ * Whether there are onboarded hosts to offer the managed path on.
+ *
+ * Three states, not two. A failed read is not an empty list — saying "no hosts"
+ * because the question could not be asked hides a path the user has already set
+ * up and leaves them no way to tell why.
+ */
+type HostsRead =
+ | { kind: 'reading' }
+ | { kind: 'read'; hosts: { sshHost: string }[] }
+ | { kind: 'failed'; headline: string; detail: string | null };
+
+function WhoRunsPage({
+ onBack,
+ onLocal,
+ onRemoteHost,
+ onExternal,
+}: {
+ onBack: () => void;
+ onLocal: () => void;
+ onRemoteHost: () => void;
+ onExternal: () => void;
+}) {
+ const [hosts, setHosts] = useState<HostsRead>({ kind: 'reading' });
+
+ const readHosts = useCallback(() => {
+ setHosts({ kind: 'reading' });
+ void rpc.remoteHosts.listHosts().then(
+ (list) => setHosts({ kind: 'read', hosts: list }),
+ (cause) =>
+ setHosts({
+ kind: 'failed',
+ ...describeFailure(cause, 'Could not check for onboarded hosts.'),
+ })
+ );
+ }, []);
+
+ useEffect(readHosts, [readHosts]);
+
+ return (
+ <WizardFrame
+ title="Who runs the server?"
+ subtitle="Either Switch Console installs and looks after the stack for you, or you point it at one that already exists."
+ /* The chevron below repeats this. It is unlabelled, so it cannot be the
+ only way back from a page whose cards all lead forward. */
+ footer={
+ <Button variant="outline" onClick={onBack}>
+ Back
+ </Button>
+ }
+ pager={{ pageName: 'Who runs the server', onBack, onNext: null }}
+ >
+ {/* The whole set waits on the read, not just the card it decides. Painting
+ two and inserting a third between them a round trip later moves the
+ answer under a cursor already on its way to one. */}
+ {hosts.kind === 'reading' ? (
+ <div className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ <span>Looking for onboarded hosts…</span>
+ </div>
+ ) : (
+ <div className="grid gap-3">
+ {hosts.kind === 'failed' && (
+ // The two certain paths are still offered: not knowing about hosts
+ // is no reason to hold the whole question hostage. Retrying may add
+ // a third card, but only because it was asked for.
+ <Alert variant="destructive">
+ <TriangleAlert className="size-4" />
+ <AlertTitle>{hosts.headline}</AlertTitle>
+ <AlertDescription>
+ {hosts.detail ? `${hosts.detail} ` : ''}
+ Running a server on one of your own hosts is not offered until this succeeds.
+ </AlertDescription>
+ <AlertAction>
+ <Button variant="outline" size="sm" onClick={readHosts}>
+ Try again
+ </Button>
+ </AlertAction>
+ </Alert>
+ )}
+ <ChoiceCard
+ icon={<Wrench className="size-5" />}
+ title="Set it up for me"
+ description="Switch Console installs the full stack on this computer with Docker and keeps it updated."
+ onClick={onLocal}
+ />
+ {hosts.kind === 'read' && hosts.hosts.length > 0 && (
+ <ChoiceCard
+ icon={<Server className="size-5" />}
+ title="Set it up on one of my hosts"
+ description="Switch Console installs the stack over SSH on a host you've onboarded. Stays running when Switch Console is closed."
+ onClick={onRemoteHost}
+ />
+ )}
+ <ChoiceCard
+ icon={<Link2 className="size-5" />}
+ title="It's already running"
+ description="Connect by URL to a Switch gateway your team or someone else operates. You'll need its gateway and API addresses."
+ onClick={onExternal}
+ />
+ </div>
+ )}
+ </WizardFrame>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts
new file mode 100644
index 000000000..2cee3d2c1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts
@@ -0,0 +1,94 @@
+import { makeAutoObservable } from 'mobx';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+
+/** Where a fresh install is in getting its first server. */
+export type OnboardingPage =
+ | 'welcome'
+ | 'whoRuns'
+ | 'local'
+ | 'remoteHost'
+ | 'connect'
+ | 'signIn'
+ | 'linkAccounts';
+
+/**
+ * The first-run flow's place in itself.
+ *
+ * Held in a store rather than in the page that draws it, because the flow
+ * outlives its own component. The shell takes the window away from it whenever
+ * Settings is opened, and it decides between the first-run pages and the
+ * workspace from the server list — which stops being empty halfway through the
+ * flow, the moment the server is added but several pages before the user has
+ * signed in to it. Without somewhere to say "still going", adding the server
+ * would throw the user out of the flow that added it.
+ *
+ * Only the page and the server survive being unmounted. What is half typed into
+ * a form does not: the fields belong to the page drawing them, so a stray ⌘,
+ * on the connect page costs the two addresses.
+ */
+class OnboardingStore {
+ page: OnboardingPage = 'welcome';
+ /** The server the connect page added, and the subject of the pages after it. */
+ server: SwitchServer | null = null;
+ /**
+ * The server a managed path brought up, and the page that brought it up.
+ *
+ * The page is kept with it because the two managed paths do not share one:
+ * starting a stack on a host and then walking back to pick the local one
+ * leaves a server that the page now on screen did not make, and an exit
+ * offered to it would take the user somewhere they did not set up.
+ */
+ registeredOn: { page: OnboardingPage; serverId: string } | null = null;
+
+ constructor() {
+ makeAutoObservable(this);
+ }
+
+ /**
+ * Whether the user has committed to setting a server up.
+ *
+ * The welcome page is not in progress: it asks a question and nothing has
+ * been started, so a launch that finds servers should go straight past it.
+ */
+ get inProgress(): boolean {
+ return this.page !== 'welcome';
+ }
+
+ goTo(page: OnboardingPage): void {
+ // Walking back to the welcome page gives up on the attempt, including the
+ // server it may already have registered. Holding on to that reference would
+ // point the next attempt's save at a row the user is free to delete in the
+ // meantime — the window is the workspace again the moment one exists — and
+ // nothing short of a restart would clear it.
+ if (page === 'welcome') {
+ this.server = null;
+ this.registeredOn = null;
+ }
+ this.page = page;
+ }
+
+ /**
+ * A managed path has registered its server.
+ *
+ * Reported from an effect that fires on every render of a page whose stack is
+ * up, so writing the same pair again has to be a no-op — a fresh object each
+ * time would notify, re-render and report again without end.
+ */
+ registered(page: OnboardingPage, serverId: string): void {
+ if (this.registeredOn?.page === page && this.registeredOn.serverId === serverId) return;
+ this.registeredOn = { page, serverId };
+ }
+
+ connected(server: SwitchServer): void {
+ this.server = server;
+ this.page = 'signIn';
+ }
+
+ reset(): void {
+ this.page = 'welcome';
+ this.server = null;
+ this.registeredOn = null;
+ }
+}
+
+export const onboardingStore = new OnboardingStore();
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
index 3696b25fb..3cd6d121a 100644
--- 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
@@ -1,6 +1,5 @@
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';
@@ -28,10 +27,7 @@ const TAGLINE = 'Agents that work alongside your team, in the chat apps you alre
* 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({});
-
+export function WelcomePage({ onContinue }: { onContinue: () => void }) {
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">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
index cb01771a8..723b4623a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
@@ -1,4 +1,4 @@
-import { CircleCheck, Globe, Laptop, Server, TriangleAlert } from 'lucide-react';
+import { CircleCheck, Globe, Info, Laptop, Server, TriangleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useEffect, useRef, useState } from 'react';
import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';
@@ -10,16 +10,10 @@ import { report } from '@renderer/lib/telemetry/report';
import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
-import {
- DialogContentArea,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/lib/ui/dialog';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
import { Input } from '@renderer/lib/ui/input';
import { Spinner } from '@renderer/lib/ui/spinner';
-import { StepPager } from '@renderer/lib/ui/step-pager';
+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';
import type {
AddServerChoiceName,
AddServerStepName,
@@ -148,7 +142,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
useEffect(() => {
if (isEdit || reportedOpening.current) return;
reportedOpening.current = true;
- report('add_server_step', { step: openedAt, choice: openedWith });
+ report('add_server_step', { step: openedAt, choice: openedWith, first_run: false });
}, [isEdit, openedAt, openedWith]);
/**
@@ -163,7 +157,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
const nextChoice = CHOICE_FOR_STEP[next] ?? choice;
setChoice(nextChoice);
setStep(next);
- report('add_server_step', { step: next, choice: nextChoice });
+ report('add_server_step', { step: next, choice: nextChoice, first_run: false });
};
// The server the wizard just created, and the subject of every step after
// it. Null in edit mode and on the two managed paths, which is what
@@ -202,6 +196,9 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
onBack={isEdit ? undefined : () => goToStep('choose')}
onDone={finish}
onClose={props.onClose}
+ // The dialog is closed, not left part-way: Cancel is the way out and it
+ // has no server to name.
+ onRegistered={null}
/>
);
}
@@ -211,6 +208,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
onBack={() => goToStep('choose')}
onDone={finish}
onClose={props.onClose}
+ onRegistered={null}
/>
);
}
@@ -235,10 +233,16 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
}
return (
<ExternalServerStep
- {...props}
+ onSuccess={props.onSuccess}
+ onClose={props.onClose}
+ initialGatewayUrl={props.initialGatewayUrl ?? null}
+ initialApiUrl={props.initialApiUrl ?? null}
+ initialName={props.initialName ?? null}
+ serverId={props.serverId ?? null}
isEdit={isEdit}
+ firstRun={false}
existing={connected}
- onBack={isEdit ? undefined : () => goToStep('choose')}
+ onBack={isEdit ? null : () => goToStep('choose')}
onConnected={(server) => {
setConnected(server);
goToStep('signIn');
@@ -263,43 +267,41 @@ function ChooseStep({
onClose: () => void;
}) {
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Add a Switch server</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="pt-0">
- <div className="grid gap-3">
- <ChoiceCard
- icon={<Laptop className="size-5" />}
- title="Run a server on this computer"
- description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."
- onClick={onLocal}
- />
- <ChoiceCard
- icon={<Server className="size-5" />}
- title="Run a server on a remote host"
- description="Switch Console sets it up over SSH on a host you've onboarded. Stays running when Switch Console is closed."
- onClick={onRemoteHost}
- />
- <ChoiceCard
- icon={<Globe className="size-5" />}
- title="Connect to an existing server"
- description="Point Switch Console at a Switch gateway someone else runs, by URL."
- onClick={onExternal}
- />
- </div>
- </DialogContentArea>
- <DialogFooter>
+ <WizardFrame
+ title="Add a Switch server"
+ subtitle={null}
+ pager={{ pageName: 'Add a server', onBack: null, onNext: null }}
+ footer={
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
- </DialogFooter>
- <StepPager pageName="Add a server" onBack={null} onNext={null} />
- </>
+ }
+ >
+ <div className="grid gap-3">
+ <ChoiceCard
+ icon={<Laptop className="size-5" />}
+ title="Run a server on this computer"
+ description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."
+ onClick={onLocal}
+ />
+ <ChoiceCard
+ icon={<Server className="size-5" />}
+ title="Run a server on a remote host"
+ description="Switch Console sets it up over SSH on a host you've onboarded. Stays running when Switch Console is closed."
+ onClick={onRemoteHost}
+ />
+ <ChoiceCard
+ icon={<Globe className="size-5" />}
+ title="Connect to an existing server"
+ description="Point Switch Console at a Switch gateway someone else runs, by URL."
+ onClick={onExternal}
+ />
+ </div>
+ </WizardFrame>
);
}
-function ChoiceCard({
+export function ChoiceCard({
icon,
title,
description,
@@ -338,15 +340,24 @@ function SetupStepItem({ children }: { children: React.ReactNode }) {
// Step 2a — local server setup (preflight → progress → done)
// ---------------------------------------------------------------------------
-const LocalSetupStep = observer(function LocalSetupStep({
+export const LocalSetupStep = observer(function LocalSetupStep({
onBack,
onDone,
onClose,
+ onRegistered,
}: {
onBack?: () => void;
/** Reports the server the stack registered, so the flow can end on it. */
onDone: (serverId: string | null) => void;
- onClose: () => void;
+ /** Null where the flow has no way out but forwards — the first-run pages. */
+ onClose: (() => void) | null;
+ /**
+ * Reports the server the moment it is registered rather than when Done is
+ * pressed, so a flow that offers a way out can aim it at the right row.
+ * Null for a chrome with no such offer — the dialog, which is closed instead
+ * of left.
+ */
+ onRegistered: ((serverId: string) => void) | null;
}) {
const store = localServerStore;
@@ -355,6 +366,11 @@ const LocalSetupStep = observer(function LocalSetupStep({
void store.checkDocker();
}, [store]);
+ const registeredId = store.status?.serverId ?? null;
+ useEffect(() => {
+ if (registeredId !== null) onRegistered?.(registeredId);
+ }, [registeredId, onRegistered]);
+
const running = store.isRunning;
const starting = store.isTransitioning;
const docker = store.docker;
@@ -363,9 +379,12 @@ const LocalSetupStep = observer(function LocalSetupStep({
const idle = !running && !starting;
// The pager's back arrow only ever repeats the footer's Back, so the two read
- // one const. Held shut while the stack comes up: leaving mid-install abandons
- // a Docker start with nothing watching it.
- const goBack = onBack && !starting ? onBack : null;
+ // one const. Open during the install too: the store is a singleton the main
+ // process streams into, so leaving loses only what is on screen, and holding
+ // the page shut left the full-window flow with no live control at all through
+ // a multi-gigabyte pull — while the same page in the dialog could still be
+ // dismissed with Escape.
+ const goBack = onBack ?? null;
const primaryLabel = running ? 'Done' : store.phase === 'error' ? 'Retry' : 'Start';
const onPrimary = () => {
@@ -374,11 +393,25 @@ const LocalSetupStep = observer(function LocalSetupStep({
};
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Set up a server on this computer</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="space-y-4 pt-0">
+ <WizardFrame
+ title="Set up a server on this computer"
+ subtitle="Switch Console installs the full stack with Docker and keeps it updated."
+ pager={{ pageName: 'Set up a server', onBack: goBack, onNext: null }}
+ footer={
+ <>
+ <BackOrClose
+ onBack={goBack}
+ onClose={onClose}
+ closeDisabled={starting}
+ closeLabel={running ? 'Close' : 'Cancel'}
+ />
+ <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>
+ {starting ? 'Starting…' : primaryLabel}
+ </ConfirmButton>
+ </>
+ }
+ >
+ <div className="space-y-4">
<div className="flex items-center gap-3">
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-foreground-muted">
<Laptop className="size-5" />
@@ -430,9 +463,16 @@ const LocalSetupStep = observer(function LocalSetupStep({
{(starting || store.logs.length > 0) && !running && (
<div className="space-y-1.5">
{store.message && starting && (
- <div className="flex items-center gap-2 text-sm text-foreground">
- <Spinner className="size-3.5" />
- <span>{store.message}</span>
+ <div className="space-y-1">
+ <div className="flex items-center gap-2 text-sm text-foreground">
+ <Spinner className="size-3.5" />
+ <span>{store.message}</span>
+ </div>
+ {/* Said out loud, because Back being live during a download
+ that takes minutes otherwise looks like it cancels one. */}
+ <p className="text-xs text-foreground-muted">
+ This keeps running if you leave the page — come back here to watch it.
+ </p>
</div>
)}
<LogTail
@@ -441,26 +481,51 @@ const LocalSetupStep = observer(function LocalSetupStep({
/>
</div>
)}
- </DialogContentArea>
- <DialogFooter>
- {goBack ? (
- <Button variant="outline" onClick={goBack}>
- Back
- </Button>
- ) : (
- <Button variant="outline" onClick={onClose} disabled={starting}>
- {running ? 'Close' : 'Cancel'}
- </Button>
- )}
- <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>
- {starting ? 'Starting…' : primaryLabel}
- </ConfirmButton>
- </DialogFooter>
- <StepPager pageName="Set up a server" onBack={goBack} onNext={null} />
- </>
+ </div>
+ </WizardFrame>
);
});
+/**
+ * The button on the left of a wizard's footer.
+ *
+ * A page that can be left offers Cancel; one that can only be stepped back
+ * through offers Back; the first-run pages can do neither while a stack is
+ * installing, and get a Back that is visibly held rather than no button and a
+ * footer that changes shape under the eye.
+ */
+function BackOrClose({
+ onBack,
+ onClose,
+ closeDisabled,
+ closeLabel,
+}: {
+ onBack: (() => void) | null;
+ onClose: (() => void) | null;
+ closeDisabled: boolean;
+ closeLabel: string;
+}) {
+ if (onBack) {
+ return (
+ <Button variant="outline" onClick={onBack}>
+ Back
+ </Button>
+ );
+ }
+ if (onClose) {
+ return (
+ <Button variant="outline" onClick={onClose} disabled={closeDisabled}>
+ {closeLabel}
+ </Button>
+ );
+ }
+ return (
+ <Button variant="outline" disabled>
+ Back
+ </Button>
+ );
+}
+
function DockerStatus({
ready,
unavailable,
@@ -506,15 +571,18 @@ function DockerStatus({
// Step 2b — remote-host managed setup (pick an onboarded SSH host → start)
// ---------------------------------------------------------------------------
-const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
+export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
onBack,
onDone,
onClose,
+ onRegistered,
}: {
onBack: () => void;
/** Reports the server the stack registered, so the flow can end on it. */
onDone: (serverId: string | null) => void;
onClose: () => void;
+ /** As on the local page: the registration, not the Done press. */
+ onRegistered: ((serverId: string) => void) | null;
}) {
const store = remoteServerStore;
const [hosts, setHosts] = useState<{ sshHost: string; name: string }[] | null>(null);
@@ -544,12 +612,17 @@ const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
const status = sshHost ? store.statusFor(sshHost) : null;
const logs = sshHost ? store.logsFor(sshHost) : [];
+ const registeredId = sshHost ? (status?.serverId ?? null) : null;
+ useEffect(() => {
+ if (registeredId !== null) onRegistered?.(registeredId);
+ }, [registeredId, onRegistered]);
+
const hostBlocked = sshHost ? store.isHostBlocked(sshHost) : false;
const canStart = !!sshHost && name.trim().length > 0 && dockerReady && !starting && !hostBlocked;
// One const for the footer's Back and the pager's back arrow, which only
- // repeats it. Shut while the stack comes up, for the same reason as the
- // local page: an abandoned Docker start has nothing watching it.
- const goBack = starting ? null : onBack;
+ // repeats it. Open during the install, for the same reason as the local page:
+ // the store outlives the page, so nothing is abandoned by leaving it.
+ const goBack = onBack;
const primaryLabel = running ? 'Done' : status?.phase === 'error' ? 'Retry' : 'Start';
const onPrimary = () => {
if (running) onDone(sshHost ? (store.statusFor(sshHost).serverId ?? null) : null);
@@ -557,11 +630,24 @@ const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
};
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Set up a server on a remote host</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="space-y-4 pt-0">
+ <WizardFrame
+ title="Set up a server on a remote host"
+ subtitle={null}
+ pager={{
+ pageName: 'Set up on a remote host',
+ onBack: goBack,
+ onNext: null,
+ }}
+ footer={
+ <>
+ <BackOrClose onBack={goBack} onClose={onClose} closeDisabled closeLabel="Cancel" />
+ <ConfirmButton onClick={onPrimary} disabled={!running && !canStart}>
+ {starting ? 'Starting…' : primaryLabel}
+ </ConfirmButton>
+ </>
+ }
+ >
+ <div className="space-y-4">
{hosts === null ? (
<div className="flex items-center gap-2 text-sm text-foreground-muted">
<Spinner className="size-3.5" />
@@ -681,23 +767,8 @@ const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
)}
</>
)}
- </DialogContentArea>
- <DialogFooter>
- {goBack ? (
- <Button variant="outline" onClick={goBack}>
- Back
- </Button>
- ) : (
- <Button variant="outline" onClick={onClose} disabled>
- Cancel
- </Button>
- )}
- <ConfirmButton onClick={onPrimary} disabled={!running && !canStart}>
- {starting ? 'Starting…' : primaryLabel}
- </ConfirmButton>
- </DialogFooter>
- <StepPager pageName="Set up on a remote host" onBack={goBack} onNext={null} />
- </>
+ </div>
+ </WizardFrame>
);
});
@@ -714,7 +785,24 @@ function looksLikeUrl(value: string): boolean {
}
}
-const ExternalServerStep = observer(function ExternalServerStep({
+/**
+ * A name for a server the user was never asked to name.
+ *
+ * The first-run form leaves the field out — someone connecting their only
+ * server has nothing to tell it apart from, and a required text box between
+ * them and a working app is a question asked for the list's benefit rather than
+ * theirs. The hostname is what they would have typed anyway, and renaming is a
+ * click away once there is a sidebar to see it in.
+ */
+function nameFromGatewayUrl(gatewayUrl: string): string {
+ // The host rather than the hostname: two servers on one machine differ only
+ // by port, and a sidebar with two rows both called `localhost` names neither
+ // of them. An IPv6 address keeps its brackets, which is how an address with
+ // a port beside it is written.
+ return new URL(gatewayUrl).host;
+}
+
+export const ExternalServerStep = observer(function ExternalServerStep({
onSuccess,
onClose,
onBack,
@@ -723,11 +811,21 @@ const ExternalServerStep = observer(function ExternalServerStep({
initialName,
serverId,
isEdit,
+ firstRun,
existing,
onConnected,
-}: Props & {
+}: {
+ initialGatewayUrl: string | null;
+ initialApiUrl: string | null;
+ initialName: string | null;
+ serverId: string | null;
isEdit: boolean;
- onBack?: () => void;
+ /** The first-run wording of the same form: no name to ask for, and the
+ * server's own accounts worth saying out loud before the sign-in step. */
+ firstRun: boolean;
+ onSuccess: () => void;
+ onClose: () => void;
+ onBack: (() => void) | null;
/** Set when the wizard has already created the server and the user came back
* to fix what they typed — the same form, saving instead of adding. */
existing: SwitchServer | null;
@@ -744,9 +842,11 @@ const ExternalServerStep = observer(function ExternalServerStep({
const trimmedApi = apiUrl.trim();
const gatewayValid = looksLikeUrl(trimmedGateway);
const apiValid = looksLikeUrl(trimmedApi);
- // In edit mode the name is owned by the separate Rename action, so this form
- // only edits the URLs — the name field isn't shown and isn't required.
- const isValid = (isEdit || trimmedName.length > 0) && gatewayValid && apiValid;
+ // In edit mode the name is owned by the separate Rename action, and on first
+ // run it comes from the gateway, so neither shows the field or requires it.
+ const asksForName = !isEdit && !firstRun;
+ const isValid = (!asksForName || trimmedName.length > 0) && gatewayValid && apiValid;
+ const submittedName = firstRun && gatewayValid ? nameFromGatewayUrl(trimmedGateway) : trimmedName;
const gatewayMessage =
trimmedGateway.length > 0 && !gatewayValid
@@ -768,7 +868,7 @@ const ExternalServerStep = observer(function ExternalServerStep({
if (savedId) {
const result = await switchServersStore.updateServer(
savedId,
- trimmedName,
+ submittedName,
trimmedGateway,
trimmedApi
);
@@ -783,7 +883,7 @@ const ExternalServerStep = observer(function ExternalServerStep({
return;
}
} else {
- const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);
+ const saved = await switchServersStore.addServer(submittedName, trimmedGateway, trimmedApi);
if (!saved) {
setError(switchServersStore.errorText ?? 'Could not add the server.');
setSubmitting(false);
@@ -793,7 +893,20 @@ const ExternalServerStep = observer(function ExternalServerStep({
return;
}
onSuccess();
- }, [isValid, isEdit, savedId, trimmedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);
+ }, [isValid, isEdit, savedId, submittedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);
+
+ // First run is asked before the saved row, because a page that goes on to the
+ // sign-in must not offer "Save changes" — the user stepped back to fix an
+ // address, and the button still takes them forward rather than closing.
+ const submitLabel = submitting
+ ? savedId
+ ? 'Saving…'
+ : 'Adding…'
+ : firstRun
+ ? 'Sign in to this server'
+ : savedId
+ ? 'Save changes'
+ : 'Add server';
// The footer's Back and the pager's back arrow are the same move, so they
// read one const. Shut while the form is submitting: the write registers a
@@ -801,64 +914,96 @@ const ExternalServerStep = observer(function ExternalServerStep({
const goBack = onBack && !submitting ? onBack : null;
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>{isEdit ? 'Edit connection' : 'Connect to an existing server'}</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="pt-0">
- <FieldGroup>
- {!isEdit && (
- <Field>
- <FieldLabel>Name</FieldLabel>
- <Input
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="Pilot"
- autoFocus
- />
- </Field>
- )}
- <Field>
- <FieldLabel>Gateway URL</FieldLabel>
- <Input
- value={gatewayUrl}
- onChange={(e) => setGatewayUrl(e.target.value)}
- placeholder="https://switch-gateway.example.com"
- autoFocus={isEdit}
- />
- {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}
- </Field>
+ <WizardFrame
+ title={
+ isEdit
+ ? 'Edit connection'
+ : firstRun
+ ? 'Connect to your server'
+ : 'Connect to an existing server'
+ }
+ subtitle={firstRun ? 'Whoever set it up can give you these addresses.' : null}
+ /* Editing a connection is one dialog rather than a flow, and a pager on
+ it would invent pages either side that do not exist. */
+ pager={
+ isEdit
+ ? null
+ : {
+ pageName: 'Connect to a server',
+ onBack: goBack,
+ onNext: null,
+ }
+ }
+ footer={
+ <>
+ <Button
+ variant="outline"
+ onClick={goBack ?? onClose}
+ disabled={!!onBack && goBack === null}
+ >
+ {onBack ? 'Back' : 'Cancel'}
+ </Button>
+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>
+ {submitLabel}
+ </ConfirmButton>
+ </>
+ }
+ >
+ <FieldGroup>
+ {asksForName && (
<Field>
- <FieldLabel>API URL</FieldLabel>
+ <FieldLabel>Name</FieldLabel>
<Input
- value={apiUrl}
- onChange={(e) => setApiUrl(e.target.value)}
- placeholder="https://switch-api.example.com"
- onKeyDown={(e) => {
- if (e.key === 'Enter') void handleSubmit();
- }}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Pilot"
+ autoFocus
/>
- {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}
- {error && <p className="mt-1 text-xs text-destructive">{error}</p>}
</Field>
- </FieldGroup>
- </DialogContentArea>
- <DialogFooter>
- <Button
- variant="outline"
- onClick={goBack ?? onClose}
- disabled={onBack !== undefined && goBack === null}
- >
- {onBack ? 'Back' : 'Cancel'}
- </Button>
- <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>
- {submitting ? (savedId ? 'Saving…' : 'Adding…') : savedId ? 'Save changes' : 'Add server'}
- </ConfirmButton>
- </DialogFooter>
- {/* Editing a connection is one dialog rather than a flow, and a pager on
- it would invent pages either side that do not exist. */}
- {!isEdit && <StepPager pageName="Connect to a server" onBack={goBack} onNext={null} />}
- </>
+ )}
+ <Field>
+ <FieldLabel>Gateway URL</FieldLabel>
+ <Input
+ value={gatewayUrl}
+ onChange={(e) => setGatewayUrl(e.target.value)}
+ placeholder="https://switch-gateway.example.com"
+ autoFocus={isEdit || firstRun}
+ />
+ {firstRun && (
+ <p className="mt-1 text-xs text-foreground-muted">Where the app and its chat live.</p>
+ )}
+ {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}
+ </Field>
+ <Field>
+ <FieldLabel>API URL</FieldLabel>
+ <Input
+ value={apiUrl}
+ onChange={(e) => setApiUrl(e.target.value)}
+ placeholder="https://switch-api.example.com"
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void handleSubmit();
+ }}
+ />
+ {firstRun && (
+ <p className="mt-1 text-xs text-foreground-muted">
+ Where agents connect. Often the same host on a different port — whoever set the server
+ up knows which.
+ </p>
+ )}
+ {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}
+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}
+ </Field>
+ {firstRun && (
+ <Alert>
+ <Info className="size-4" />
+ <AlertDescription>
+ This server keeps its own accounts. Signing in here signs you in to it, not to
+ anything else.
+ </AlertDescription>
+ </Alert>
+ )}
+ </FieldGroup>
+ </WizardFrame>
);
});
@@ -872,7 +1017,7 @@ const ExternalServerStep = observer(function ExternalServerStep({
* signed-out server lists no rooms, no agents and no messaging apps, and looks
* broken rather than unauthenticated.
*/
-const SignInStep = observer(function SignInStep({
+export const SignInStep = observer(function SignInStep({
server,
onBack,
onClose,
@@ -880,7 +1025,8 @@ const SignInStep = observer(function SignInStep({
}: {
server: SwitchServer;
onBack: () => void;
- onClose: () => void;
+ /** Null where there is nothing to close onto — the first-run pages. */
+ onClose: (() => void) | null;
onSignedIn: () => void;
}) {
const signIn = useServerSignIn(server.id);
@@ -895,42 +1041,43 @@ const SignInStep = observer(function SignInStep({
const goBack = signIn.submitting ? null : onBack;
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Sign in to {server.name}</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="pt-0">
- <ServerSignInFields
- signIn={signIn}
- idPrefix="connect-server-sign-in"
- gatewayUrl={server.gatewayUrl}
- onSignedIn={onSignedIn}
- />
- </DialogContentArea>
- <DialogFooter>
- <Button variant="outline" onClick={onBack} disabled={goBack === null}>
- Back
- </Button>
- {canUsePassword ? (
- <ConfirmButton
- onClick={() => void submit()}
- disabled={!signIn.canSubmitPassword || signIn.submitting}
- >
- {signIn.submitting ? 'Signing in…' : 'Sign in'}
- </ConfirmButton>
- ) : (
- // Nothing for a primary button to do: either the only method is the
- // provider button in the body, or the server offers none at all and
- // the body says so. Leaving a dead "Sign in" there would imply the
- // form was incomplete rather than absent.
- !canUseOidc && (
- <Button variant="outline" onClick={onClose}>
- Close
- </Button>
- )
- )}
- </DialogFooter>
- <StepPager pageName="Sign in" onBack={goBack} onNext={null} />
- </>
+ <WizardFrame
+ title={`Sign in to ${server.name}`}
+ subtitle={null}
+ pager={{ pageName: 'Sign in', onBack: goBack, onNext: null }}
+ footer={
+ <>
+ <Button variant="outline" onClick={onBack} disabled={goBack === null}>
+ Back
+ </Button>
+ {canUsePassword ? (
+ <ConfirmButton
+ onClick={() => void submit()}
+ disabled={!signIn.canSubmitPassword || signIn.submitting}
+ >
+ {signIn.submitting ? 'Signing in…' : 'Sign in'}
+ </ConfirmButton>
+ ) : (
+ // Nothing for a primary button to do: either the only method is the
+ // provider button in the body, or the server offers none at all and
+ // the body says so. Leaving a dead "Sign in" there would imply the
+ // form was incomplete rather than absent.
+ !canUseOidc &&
+ onClose && (
+ <Button variant="outline" onClick={onClose}>
+ Close
+ </Button>
+ )
+ )}
+ </>
+ }
+ >
+ <ServerSignInFields
+ signIn={signIn}
+ idPrefix="connect-server-sign-in"
+ gatewayUrl={server.gatewayUrl}
+ onSignedIn={onSignedIn}
+ />
+ </WizardFrame>
);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
index cbf165cf7..495a98e58 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
@@ -9,14 +9,8 @@ import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
-import {
- DialogContentArea,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/lib/ui/dialog';
import { Spinner } from '@renderer/lib/ui/spinner';
-import { StepPager } from '@renderer/lib/ui/step-pager';
+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';
import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
import { BridgeIdentitySearch } from './bridge-identity-search';
import { connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';
@@ -51,6 +45,14 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
enabled: workspaceId !== null,
});
+ // A disabled query never leaves its pending state, so without this the page
+ // would spin on "reading the apps" forever and never say that it is not
+ // reading anything. Messaging apps hang off a workspace; with none in scope
+ // there is nothing to list and nothing to link an account to.
+ const noWorkspace =
+ workspaceId === null
+ ? new Error(`Your account has no workspace on ${serverName} to link accounts in.`)
+ : null;
const { identities } = useMyIdentities(workspaceId);
// The footer's Back and the pager's back arrow are the same move, so they
@@ -59,63 +61,59 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
if (linking && workspaceId !== null) {
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Link your {bridgePlatformLabel(linking.type)} account</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="pt-0">
- <div className="flex w-full flex-col gap-4">
- <p className="text-sm text-foreground-muted">
- Find yourself in {linking.displayName} and tell Switch that account is you.
- </p>
- <BridgeIdentitySearch
- workspaceId={workspaceId}
- bridgeId={linking.id}
- bridgeDisplayName={linking.displayName}
- platform={bridgePlatformLabel(linking.type)}
- directorySearchSupported={linking.directorySearchSupported}
- autoFocus
- onClaimed={() => setLinking(null)}
- />
- </div>
- </DialogContentArea>
- <DialogFooter>
+ <WizardFrame
+ title={`Link your ${bridgePlatformLabel(linking.type)} account`}
+ subtitle={null}
+ pager={{
+ pageName: `Link ${bridgePlatformLabel(linking.type)}`,
+ onBack: goBack,
+ onNext: null,
+ }}
+ footer={
<Button variant="outline" onClick={goBack}>
Back
</Button>
- </DialogFooter>
- <StepPager
- pageName={`Link ${bridgePlatformLabel(linking.type)}`}
- onBack={goBack}
- onNext={null}
- />
- </>
+ }
+ >
+ <div className="flex w-full flex-col gap-4">
+ <p className="text-sm text-foreground-muted">
+ Find yourself in {linking.displayName} and tell Switch that account is you.
+ </p>
+ <BridgeIdentitySearch
+ workspaceId={workspaceId}
+ bridgeId={linking.id}
+ bridgeDisplayName={linking.displayName}
+ platform={bridgePlatformLabel(linking.type)}
+ directorySearchSupported={linking.directorySearchSupported}
+ autoFocus
+ onClaimed={() => setLinking(null)}
+ />
+ </div>
+ </WizardFrame>
);
}
return (
- <>
- <DialogHeader showCloseButton={false}>
- <DialogTitle>Link your messaging accounts</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="pt-0">
- <BridgeList
- serverName={serverName}
- bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}
- identities={identities}
- isPending={bridgesQuery.isPending}
- error={bridgesQuery.isError ? bridgesQuery.error : null}
- onRetry={() => void bridgesQuery.refetch()}
- onLink={setLinking}
- />
- </DialogContentArea>
- <DialogFooter>
- <ConfirmButton onClick={onDone}>Done</ConfirmButton>
- </DialogFooter>
- {/* The last page of the flow, and signing in cannot be undone by walking
- backwards, so there is nowhere for either arrow to go. */}
- <StepPager pageName="Link accounts" onBack={null} onNext={null} />
- </>
+ <WizardFrame
+ title="Link your messaging accounts"
+ subtitle={null}
+ /* The last page of the flow, and signing in cannot be undone by walking
+ backwards, so there is nowhere for either arrow to go. */
+ pager={{ pageName: 'Link accounts', onBack: null, onNext: null }}
+ footer={<ConfirmButton onClick={onDone}>Done</ConfirmButton>}
+ >
+ <BridgeList
+ serverName={serverName}
+ bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}
+ identities={identities}
+ isPending={noWorkspace === null && bridgesQuery.isPending}
+ error={noWorkspace ?? (bridgesQuery.isError ? bridgesQuery.error : null)}
+ onRetry={() =>
+ void (noWorkspace === null ? bridgesQuery.refetch() : workspacesStore.refresh())
+ }
+ onLink={setLinking}
+ />
+ </WizardFrame>
);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx
new file mode 100644
index 000000000..52cf103c5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx
@@ -0,0 +1,124 @@
+import { createContext, useContext, type ReactNode } from 'react';
+import { Button } from './button';
+import { DialogContentArea, DialogFooter, DialogHeader, DialogTitle } from './dialog';
+import { StepPager } from './step-pager';
+
+/**
+ * Where a wizard page is being drawn: inside a dialog, or filling the window.
+ *
+ * The same pages serve both. Setting up a server is a dialog once you already
+ * have one and the whole window on a fresh install, where there is no app
+ * behind the dialog for it to sit on top of — but it is the same three
+ * questions either way, and a second copy of them would be a second place for
+ * the Docker check, the log tail and the sign-in form to drift.
+ */
+export type WizardChrome = 'dialog' | 'page';
+
+const WizardChromeContext = createContext<WizardChrome>('dialog');
+
+/**
+ * The way out of a wizard that fills the window.
+ *
+ * A dialog has its own — Escape, the backdrop, a Cancel button — and something
+ * behind it to return to. A full-window wizard has neither, so a flow that can
+ * be left part-way has to say so in words on every page rather than relying on
+ * the user pressing Back until the window changes shape under them.
+ */
+export type WizardExit = { label: string; onExit: () => void };
+
+const WizardExitContext = createContext<WizardExit | null>(null);
+
+export function WizardChromeProvider({
+ chrome,
+ exit,
+ children,
+}: {
+ chrome: WizardChrome;
+ /** Null until there is something to leave behind — a flow that has registered
+ * nothing yet is left by finishing it or by stepping back off its first page. */
+ exit: WizardExit | null;
+ children: ReactNode;
+}) {
+ return (
+ <WizardChromeContext.Provider value={chrome}>
+ <WizardExitContext.Provider value={exit}>{children}</WizardExitContext.Provider>
+ </WizardChromeContext.Provider>
+ );
+}
+
+/** The pager under a page, or null where the page is not part of a sequence. */
+export type WizardPager = {
+ pageName: string;
+ onBack: (() => void) | null;
+ onNext: (() => void) | null;
+};
+
+/**
+ * One page of a wizard: its question, its body, what it offers at the foot.
+ *
+ * The page supplies no chrome of its own. A dialog's title bar and a full
+ * window's centred heading are the same title, and which one gets rendered is
+ * the frame's business rather than the page's.
+ */
+export function WizardFrame({
+ title,
+ subtitle,
+ footer,
+ pager,
+ children,
+}: {
+ title: string;
+ /** The line under the title, or null where the title says enough. */
+ subtitle: string | null;
+ /** Buttons for the foot of the page, in reading order, or null for a page
+ * whose only way on is the choice made in its body. */
+ footer: ReactNode | null;
+ pager: WizardPager | null;
+ children: ReactNode;
+}) {
+ const chrome = useContext(WizardChromeContext);
+ const exit = useContext(WizardExitContext);
+
+ if (chrome === 'dialog') {
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>{title}</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ {subtitle && <p className="pb-2 text-sm text-foreground-muted">{subtitle}</p>}
+ {children}
+ </DialogContentArea>
+ {footer && <DialogFooter>{footer}</DialogFooter>}
+ {pager && <StepPager {...pager} />}
+ </>
+ );
+ }
+
+ return (
+ <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">
+ {exit && (
+ <div className="flex justify-end px-3 pt-3 [-webkit-app-region:no-drag]">
+ <Button variant="ghost" size="sm" onClick={exit.onExit}>
+ {exit.label}
+ </Button>
+ </div>
+ )}
+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">
+ <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-6 px-8 py-10 [-webkit-app-region:no-drag]">
+ <div className="flex flex-col items-center gap-2 text-center">
+ <h1 className="text-2xl font-semibold">{title}</h1>
+ {subtitle && <p className="text-sm text-foreground-muted">{subtitle}</p>}
+ </div>
+ {children}
+ {footer && <div className="flex gap-2">{footer}</div>}
+ </div>
+ </div>
+ {pager && (
+ <div className="[-webkit-app-region:no-drag]">
+ <StepPager {...pager} />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx
new file mode 100644
index 000000000..9995ef23b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx
@@ -0,0 +1,395 @@
+/**
+ * The path a fresh install takes to its first server.
+ *
+ * The flow is the add-server wizard drawn full window, so what is worth testing
+ * is not the wizard again but the joins: that the welcome page leads into the
+ * question rather than a dialog, that each page can be backed out of, and that
+ * the one thing the first-run form does differently — not asking for a name —
+ * still produces a server with a name on it.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const addServer = vi.hoisted(() => vi.fn());
+const setActive = vi.hoisted(() => vi.fn());
+const navigate = vi.hoisted(() => vi.fn());
+const listHosts = vi.hoisted(() => vi.fn());
+const servers = vi.hoisted(() => [] as { id: string; name: string }[]);
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: { remoteHosts: { listHosts } },
+}));
+
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: {
+ addServer,
+ setActive,
+ serverById: (id: string | null) => servers.find((s) => s.id === id) ?? null,
+ errorText: null,
+ ensureAuthConfig: () => Promise.resolve(),
+ authConfigFor: () => ({
+ passwordLoginEnabled: true,
+ oidcEnabled: false,
+ oidcProviderLabel: null,
+ }),
+ authConfigCheckFailed: () => false,
+ authConfigChecking: () => false,
+ passwordLogin: () => Promise.resolve(true),
+ oidcLogin: () => Promise.resolve(true),
+ },
+}));
+
+vi.mock('@renderer/lib/layout/navigation-provider', () => ({
+ useNavigate: () => ({ navigate }),
+}));
+
+/**
+ * The local-server supervisor as the page sees it. Stands in for the real
+ * singleton so a test can put the page in the middle of an install without a
+ * Docker daemon anywhere near it.
+ */
+const localServer = vi.hoisted(() => ({
+ status: null as { serverId: string | null; version: string } | null,
+ docker: { available: true } as { available: boolean } | null,
+ isRunning: false,
+ isTransitioning: false,
+ phase: 'stopped',
+ message: null as string | null,
+ error: null as string | null,
+ errorDetail: null as string | null,
+ logs: [] as string[],
+ init: vi.fn(() => Promise.resolve()),
+ checkDocker: vi.fn(() => Promise.resolve()),
+ start: vi.fn(),
+}));
+
+vi.mock('@renderer/features/switch-servers/local-server-store', () => ({
+ localServerStore: localServer,
+}));
+
+vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));
+
+import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';
+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ addServer.mockReset();
+ setActive.mockReset();
+ navigate.mockReset();
+ listHosts.mockReset();
+ listHosts.mockResolvedValue([]);
+ servers.length = 0;
+ onboardingStore.reset();
+ Object.assign(localServer, {
+ status: null,
+ docker: { available: true },
+ isRunning: false,
+ isTransitioning: false,
+ phase: 'stopped',
+ message: null,
+ error: null,
+ errorDetail: null,
+ logs: [],
+ });
+});
+
+/** Register a server the way the connect page does, list and all. */
+function serverAdded(id: string) {
+ const server = {
+ id,
+ name: 'switch.example.com',
+ gatewayUrl: 'https://switch.example.com',
+ apiUrl: 'https://switch.example.com:8000',
+ };
+ servers.push(server);
+ addServer.mockResolvedValue(server);
+ return server;
+}
+
+/** Walk the connect page to the point where the server exists. */
+async function addFromConnectPage(el: HTMLElement) {
+ await act(async () => button(el, 'Continue with your own server').click());
+ await choose(el, "It's already running");
+ await type(field(el, 'Gateway URL')!, 'https://switch.example.com');
+ await type(field(el, 'API URL')!, 'https://switch.example.com:8000');
+ await choose(el, 'Sign in to this server');
+}
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function renderFlow(): Promise<HTMLDivElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(<OnboardingFlow />));
+ return container;
+}
+
+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!;
+}
+
+/** Every button's label, for asserting that one is not among them. */
+function labels(el: HTMLElement): (string | null)[] {
+ return [...el.querySelectorAll('button')].map((b) => b.textContent);
+}
+
+/** A card or button whose text contains this, wherever it sits in the page. */
+async function choose(el: HTMLElement, text: string): Promise<void> {
+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
+ b.textContent?.includes(text)
+ );
+ expect(found, `nothing to click named ${text}`).toBeDefined();
+ await act(async () => found!.click());
+}
+
+function field(el: HTMLElement, label: string): HTMLInputElement | null {
+ const labels = [...el.querySelectorAll<HTMLElement>('label')];
+ const match = labels.find((l) => l.textContent?.trim() === label);
+ if (!match) return null;
+ const input = match.parentElement?.querySelector('input');
+ expect(input, `no input under ${label}`).not.toBeNull();
+ return input as HTMLInputElement;
+}
+
+async function type(input: HTMLInputElement, value: string): Promise<void> {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+describe('the first-run flow', () => {
+ it('asks who runs the server once you continue past the welcome', async () => {
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(el.textContent).toContain('Who runs the server?');
+ expect(el.textContent).toContain('Set it up for me');
+ expect(el.textContent).toContain("It's already running");
+ });
+
+ it('leaves the managed host path out when there is no host to offer', async () => {
+ // A fresh install has onboarded none, and the card would lead to an empty
+ // list every time it was taken.
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(el.textContent).not.toContain('one of my hosts');
+ });
+
+ it('offers the managed host path once a host exists', async () => {
+ // Onboarding a host needs no server, so someone who deleted their last
+ // server arrives here with hosts already set up — and this is the only
+ // place the managed path can be reached from.
+ listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(el.textContent).toContain('one of my hosts');
+ });
+
+ it('paints no cards until it knows whether there are hosts to offer', async () => {
+ // The set waits as a whole. Painting two and inserting a third between them
+ // a round trip later moves the answer out from under a cursor already on
+ // its way to one.
+ let answer!: (list: { sshHost: string }[]) => void;
+ listHosts.mockReturnValue(
+ new Promise<{ sshHost: string }[]>((resolve) => {
+ answer = resolve;
+ })
+ );
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(el.textContent).toContain('Looking for onboarded hosts');
+ expect(el.textContent).not.toContain('Set it up for me');
+
+ await act(async () => answer([{ sshHost: 'build-box' }]));
+
+ expect(el.textContent).toContain('Set it up for me');
+ expect(el.textContent).toContain('one of my hosts');
+ });
+
+ it('says the host check failed instead of reporting no hosts', async () => {
+ // A read that never answered is not an empty list. Reading it as one hides
+ // a path the user has already set up, and says nothing about why.
+ listHosts.mockRejectedValue(new Error('could not read the ssh config'));
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect(el.textContent).toContain('Could not check for onboarded hosts');
+ expect(el.textContent).not.toContain('one of my hosts');
+ // The two paths that need no such check are still offered: not knowing
+ // about hosts is no reason to hold the whole question hostage.
+ expect(el.textContent).toContain('Set it up for me');
+ expect(el.textContent).toContain("It's already running");
+ });
+
+ it('offers the host path when a retry of the check answers', async () => {
+ listHosts.mockRejectedValueOnce(new Error('could not read the ssh config'));
+ const el = await renderFlow();
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);
+ await act(async () => button(el, 'Try again').click());
+
+ expect(el.textContent).toContain('one of my hosts');
+ });
+
+ it('can be left while the local stack is installing, and says so', async () => {
+ // A first run pulls a few gigabytes. Full window, with Back shut and the
+ // primary disabled, that was minutes of a page with no live control at all
+ // — while the same page in the dialog could still be dismissed.
+ localServer.isTransitioning = true;
+ localServer.phase = 'starting';
+ localServer.message = 'Pulling images…';
+ const el = await renderFlow();
+ await act(async () => button(el, 'Continue with your own server').click());
+ await choose(el, 'Set it up for me');
+
+ expect(button(el, 'Back').disabled).toBe(false);
+ expect(el.textContent).toContain('keeps running if you leave the page');
+
+ await act(async () => button(el, 'Back').click());
+
+ expect(el.textContent).toContain('Who runs the server?');
+ });
+
+ it('goes back from the question to the welcome, by a button and not only a chevron', async () => {
+ // The chevron is unlabelled, so it may repeat the way back but never be the
+ // only one.
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+ await act(async () => button(el, 'Back').click());
+
+ expect(el.textContent).toContain('Welcome to Switch');
+ });
+
+ it('asks for the addresses, and not for a name, on the connect page', async () => {
+ // Someone connecting their only server has nothing to tell it apart from,
+ // so the field is a question asked for the list's benefit rather than
+ // theirs.
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+ await choose(el, "It's already running");
+
+ expect(el.textContent).toContain('Connect to your server');
+ expect(field(el, 'Gateway URL')).not.toBeNull();
+ expect(field(el, 'API URL')).not.toBeNull();
+ expect(field(el, 'Name')).toBeNull();
+ });
+
+ it('names the server after its gateway, having never asked', async () => {
+ // The page that skips the question still has to produce a name: an
+ // unnamed row in the sidebar would be the cost of the shortcut.
+ serverAdded('srv-1');
+ const el = await renderFlow();
+
+ await addFromConnectPage(el);
+
+ expect(addServer).toHaveBeenCalledWith(
+ 'switch.example.com',
+ 'https://switch.example.com',
+ 'https://switch.example.com:8000'
+ );
+ });
+
+ it('keeps the flow on screen after the server is added, for the sign-in still to come', async () => {
+ // The server exists from here on, which is exactly when the window would
+ // otherwise decide onboarding is over and take the remaining pages away.
+ serverAdded('srv-1');
+ const el = await renderFlow();
+
+ await addFromConnectPage(el);
+
+ expect(onboardingStore.inProgress).toBe(true);
+ expect(onboardingStore.page).toBe('signIn');
+ });
+
+ it('offers a way out by name once the server exists', async () => {
+ // Sign-in can fail for good — a server that is down, a password that is
+ // refused — and pressing Back until the window changes shape is not an
+ // exit anyone finds.
+ serverAdded('srv-1');
+ const el = await renderFlow();
+
+ await addFromConnectPage(el);
+ await act(async () => button(el, 'Finish later').click());
+
+ expect(onboardingStore.inProgress).toBe(false);
+ expect(navigate).toHaveBeenCalledWith('server', { serverId: 'srv-1' });
+ });
+
+ it('offers nothing to finish later before a server has been registered', async () => {
+ const el = await renderFlow();
+
+ await act(async () => button(el, 'Continue with your own server').click());
+
+ expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain(
+ 'Finish later'
+ );
+ });
+
+ it('offers no way out to a server the page on screen did not set up', async () => {
+ // Connect to one, walk back, take the local path instead: the exit read a
+ // single remembered server, so it still pointed at the abandoned attempt —
+ // and pressing it left for a server this page had nothing to do with.
+ serverAdded('srv-1');
+ const el = await renderFlow();
+ await addFromConnectPage(el);
+ expect(labels(el)).toContain('Finish later');
+
+ await act(async () => button(el, 'Back').click());
+ await act(async () => button(el, 'Back').click());
+ await choose(el, 'Set it up for me');
+
+ expect(el.textContent).toContain('Set up a server on this computer');
+ expect(labels(el)).not.toContain('Finish later');
+ });
+
+ it('forgets a server it registered when the user walks back to the start', async () => {
+ // Everything after the connect page edits that row, and the user is free to
+ // delete it the moment it exists — the window is the workspace again for
+ // anything that does not need a server. A remembered id would aim the next
+ // attempt's save at a row that is gone.
+ serverAdded('srv-1');
+ const el = await renderFlow();
+
+ await addFromConnectPage(el);
+ onboardingStore.goTo('welcome');
+
+ expect(onboardingStore.server).toBeNull();
+ expect(el).toBeDefined();
+ });
+});
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
index 2b0560a76..dc6b9bf44 100644
--- 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
@@ -11,7 +11,7 @@ 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());
+const onContinue = vi.hoisted(() => vi.fn());
vi.hoisted(() => {
window.electronAPI ??= {
@@ -21,17 +21,13 @@ vi.hoisted(() => {
} 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();
+ onContinue.mockReset();
});
afterEach(async () => {
@@ -45,7 +41,7 @@ async function renderPage(): Promise<HTMLDivElement> {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
- await act(async () => root!.render(<WelcomePage />));
+ await act(async () => root!.render(<WelcomePage onContinue={onContinue} />));
return container;
}
@@ -98,12 +94,12 @@ describe('the welcome page', () => {
expect(button(el, 'Continue with your own server')).toBeDefined();
});
- it('opens the add-server flow from the button', async () => {
+ it('moves the flow on from Continue', async () => {
const el = await renderPage();
await act(async () => button(el, 'Continue with your own server').click());
- expect(showModal).toHaveBeenCalledWith('addServerModal', {});
+ expect(onContinue).toHaveBeenCalled();
});
it('sends the pager forward to the same place as Continue', async () => {
@@ -113,6 +109,6 @@ describe('the welcome page', () => {
await act(async () => el.querySelector<HTMLButtonElement>('[aria-label="Next page"]')!.click());
- expect(showModal).toHaveBeenCalledWith('addServerModal', {});
+ expect(onContinue).toHaveBeenCalled();
});
});
diff --git a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts
index c4302d099..6aa013d4b 100644
--- a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts
@@ -46,8 +46,15 @@ export type RendererTelemetryEvents = {
onboarding_checklist_dismissed: Record<never, never>;
/** Every step of the checklist is done. */
onboarding_completed: Record<never, never>;
- /** The add-server wizard reached a step. Where people stop is the question. */
- add_server_step: { step: AddServerStepName; choice: AddServerChoiceName };
+ /**
+ * The add-server wizard reached a step. Where people stop is the question.
+ *
+ * `first_run` separates the two places the same steps are drawn: the wizard
+ * in a dialog, and the full-window pages a fresh install opens on. Giving up
+ * before you have any server at all is a different answer from giving up
+ * adding your second, and one funnel covering both could not tell them apart.
+ */
+ add_server_step: { step: AddServerStepName; choice: AddServerChoiceName; first_run: boolean };
/** A screen failed and the error boundary caught it. */
renderer_crashed: Record<never, never>;
};
diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md
index 56a8f2f61..dca2677a7 100644
--- a/docs/TELEMETRY.md
+++ b/docs/TELEMETRY.md
@@ -118,7 +118,7 @@ id, no IP field, no Switch identity.
| `onboarding_step_started` | `step_id`, one of exactly 4: `addServer`, `agentProviders`, `onboardAgents`, `createRoom` |
| `onboarding_checklist_dismissed` | *(no fields)* |
| `onboarding_completed` | *(no fields)* |
-| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` |
+| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` · `first_run`: `true` / `false` — whether the same step was reached on a fresh install rather than from the Add server dialog |
**Agents and sessions**