Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): pick or create a workspace after signing in
Petr Bauch414be2c86b0e
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.tsindex 1bc7b26c1..106418c65 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts@@ -10,6 +10,8 @@ const trackEvent = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());const passwordLogin = vi.hoisted(() => vi.fn());const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());+const listWorkspacesForServer = vi.hoisted(() => vi.fn());+const createTenant = vi.hoisted(() => vi.fn());// Stubbed rather than reimplemented: what the tests below assert is that the// kind reaches the event, not how a row is read as one.const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));@@ -35,6 +37,7 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({reconcileServerWorkspaces,}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({ listWorkspacesForServer }));// Writes to the app's log file, which a test has no business creating.vi.mock('@main/lib/logger', () => ({log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },@@ -52,6 +55,7 @@ vi.mock('./gateway-client', () => ({fetchAgentRooms: vi.fn(),fetchAgents: vi.fn(),fetchAuthConfig,+ createTenant,fetchRoomRoles: vi.fn(),fetchRooms: vi.fn(),registerKnownAgent: vi.fn(),@@ -252,6 +256,144 @@ describe('reading the account’s workspaces once it is signed in', () => {});});+function workspaceRow(overrides: Record<string, unknown>) {+ return {+ id: 'ws',+ serverId: 'srv',+ name: 'W',+ tenantId: 'tenant-1',+ slug: 'w',+ role: 'member',+ createdAt: '',+ updatedAt: '',+ ...overrides,+ };+}++describe('resolveWorkspaces', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset rather than cleared: an earlier test leaves a rejection standing on+ // it, and `clearAllMocks` forgets the calls but keeps the behaviour.+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('answers with the memberships the server confirmed', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-2', tenantId: 't2' }),+ ]);++ const found = await switchServersController.resolveWorkspaces('srv');++ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');+ expect(found.map((w) => w.id)).toEqual(['ws-1', 'ws-2']);+ });++ // The placeholder a registration creates is not a membership, and offering it+ // would scope the window to a workspace the gateway has never heard of.+ it('leaves out the row that was never matched to a tenant', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: null, slug: null, role: null }),+ ]);++ await expect(switchServersController.resolveWorkspaces('srv')).resolves.toEqual([]);+ });++ /**+ * The row is kept locally so its agents are not silently detached, but every+ * call scoped to it is refused. Offering it puts the refusal after the click;+ * worse, left as the only answer it is the one the caller enters without+ * asking.+ */+ it('leaves out a membership the account has been removed from', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-gone', tenantId: 't2', role: null }),+ ]);++ const found = await switchServersController.resolveWorkspaces('srv');++ expect(found.map((w) => w.id)).toEqual(['ws-1']);+ });++ // "You belong to nothing" and "nobody could be asked" are different answers,+ // and a caller that received the empty list for both would offer to create a+ // second workspace to someone who already has one.+ it('raises rather than answering empty when the server cannot be asked', async () => {+ reconcileServerWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ await expect(switchServersController.resolveWorkspaces('srv')).rejects.toThrow(+ 'gateway unreachable'+ );+ });+});++describe('createWorkspace', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('returns the local row for the workspace the gateway minted', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Acme', role: 'owner' }),+ ]);++ const created = await switchServersController.createWorkspace({+ serverId: 'srv',+ name: 'Acme',+ });++ expect(createTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'Acme');+ expect(created.id).toBe('ws-9');+ });++ /**+ * The reconcile is what records the workspace, name included — so one that+ * failed has recorded nothing. Answering anyway would hand back whichever row+ * happened to be there, under a name the user did not type, and report a+ * success the install has no trace of.+ */+ it('raises when the reconcile that records the workspace fails', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ reconcileServerWorkspaces.mockRejectedValue(new Error('the gateway stopped answering'));++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow('the gateway stopped answering');+ expect(listWorkspacesForServer).not.toHaveBeenCalled();+ });++ // The workspace exists on the server either way. Returning something else, or+ // nothing, would leave the app scoped to a workspace that is not the one just+ // made — so it says so instead.+ it('raises when the new workspace did not land locally', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow('did not record it');+ });++ it('does not ask a server whose host is down to create anything', async () => {+ getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));+ managedServerHostBlocked.mockReturnValue({ sshHost: 'h', status: 'unreachable' });++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow();+ expect(createTenant).not.toHaveBeenCalled();+ });+});+describe('adding a server by URL', () => {const params = { name: 'S', gatewayUrl: 'http://gateway', apiUrl: 'http://api' };diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.tsindex 7b9c8aea5..95ff5cb1f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -5,6 +5,7 @@ import { isManagedServerRunning } from '@main/core/managed-switch-server/managedimport type { TelemetryAuthMethod, TelemetrySignInFailure } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';+import { listWorkspacesForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type {AddServerParams,@@ -17,10 +18,11 @@ import type {UpdateServerParams,UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';+import { isWithdrawnWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';import { bundledChatSignInFor } from './bundled-chat-sign-in';-import { fetchAuthConfig, fetchMe, GatewayError } from './gateway-client';+import { createTenant, fetchAuthConfig, fetchMe, GatewayError } from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';import { hostUnreachable, requireReachableServer, requireServer } from './require-server';import {@@ -125,6 +127,65 @@ export const switchServersController = createRPCController({setActiveServer: (serverId: string): Promise<void> => setActiveServerId(serverId),+ /**+ * Ask a server which workspaces this account belongs to, and return the local+ * rows for them.+ *+ * Local rows rather than the gateway's answer directly, because what a caller+ * does next is scope the window to one, and that is addressed by the row's+ * id. Reconciling first is what guarantees there is a row for each.+ *+ * An empty list means the server answered and the account belongs to nothing+ * — a real answer, and the one the first-run flow turns into "create your+ * workspace". A server that cannot be asked raises instead, because the two+ * are not the same and a caller that treated them alike would offer to create+ * a second workspace to someone who already has one.+ */+ resolveWorkspaces: async (serverId: string): Promise<Workspace[]> => {+ await reconcileServerWorkspaces(serverId);+ const workspaces = await listWorkspacesForServer(serverId);+ // A withdrawn membership is a row this install still holds for a workspace+ // the account has been removed from. It is kept so its agents are not+ // silently detached, but it is not somewhere to work: every call scoped to+ // it is refused, and with exactly one of them the caller would take it+ // without asking.+ return workspaces.filter(+ (workspace) => workspace.tenantId !== null && !isWithdrawnWorkspace(workspace)+ );+ },++ /**+ * Create a workspace on a server, owned by the signed-in user.+ *+ * Addressed by server rather than by workspace — the exception the split+ * allows itself, because the thing being created is the workspace: there is+ * no id to address it by until the gateway has minted one, and on a fresh+ * install there is no other workspace to address it from either.+ *+ * Reconciling afterwards rather than inserting a row here keeps one+ * implementation of "which local row is this membership": the new workspace+ * may claim the tenant-less row a freshly registered server starts with, and+ * deciding that twice is how the two answers come to differ. It is also what+ * carries the typed name onto the row, since a matched workspace takes its+ * name from the gateway — so a reconcile that fails here leaves the name to+ * the next one rather than stranding it on the server forever, which is what+ * a rename issued from this call site would have done.+ */+ createWorkspace: async (params: { serverId: string; name: string }): Promise<Workspace> => {+ const server = await requireReachableServer(params.serverId);+ const tenant = await createTenant(server, params.name);+ await reconcileServerWorkspaces(params.serverId);++ const workspaces = await listWorkspacesForServer(params.serverId);+ const created = workspaces.find((workspace) => workspace.tenantId === tenant.id);+ if (!created) {+ throw new Error(+ `${server.name} created the workspace ${tenant.name}, but this install did not record it.`+ );+ }+ return created;+ },+getAuthConfig: async (serverId: string): Promise<SwitchAuthConfig> =>fetchAuthConfig(await requireReachableServer(serverId)),diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex 4ffb91dbb..9a5c71e2f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -362,6 +362,23 @@ export async function fetchTenants(server: SwitchServer): Promise<RemoteTenant[]return json.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: mapRole(t.role) }));}+/**+ * Create a workspace on this server, owned by the signed-in user.+ *+ * The gateway derives the slug from the name and refuses a name whose slug is+ * already taken, so the caller shows that refusal rather than retrying under a+ * name the user did not choose.+ */+export async function createTenant(server: SwitchServer, name: string): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, '/tenants', {+ authenticated: true,+ method: 'POST',+ body: { name },+ });+ const json = (await res.json()) as { id: string; slug: string; name: string; role: string };+ return { id: json.id, slug: json.slug, name: json.name, role: mapRole(json.role) };+}+/*** Select a tenant for this server's session, persisting the re-minted cookie.*diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsxnew file mode 100644index 000000000..af75cf12f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx@@ -0,0 +1,137 @@+import { useState } from 'react';+import { createWorkspaceFailureText } from '@renderer/features/workspaces/describe-create-failure';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';++/**+ * Make the workspace the account will work in.+ *+ * A name and nothing else. The design's address hint under the field describes+ * a workspace reachable at its own subdomain, which is not how a Switch+ * workspace is addressed — it lives on the server you signed in to, and showing+ * an address that resolves to nothing would be the app inventing an answer. The+ * "let my team join automatically" toggle is gone for the same reason: joining+ * by email domain is a thing no Switch server can do yet, so a switch for it+ * would silently do nothing.+ */+export function CreateWorkspacePage({+ server,+ onBack,+ onCreated,+}: {+ server: SwitchServer;+ /** Null where the account is in no workspace, so there is no list behind this. */+ onBack: (() => void) | null;+ onCreated: () => void;+}) {+ const [name, setName] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ /**+ * The workspace the server has already minted, when entering it is what+ * failed.+ *+ * Asking again would offer a name the server has just taken and come back+ * with a conflict that reads as the name being refused. On the page reached+ * with no memberships there is no Back either, so the only remaining move has+ * to be the one that can still work: entering what exists.+ */+ const [created, setCreated] = useState<Workspace | null>(null);++ const trimmed = name.trim();++ const submit = async () => {+ if (submitting || (created === null && trimmed === '')) return;+ setSubmitting(true);+ setError(null);+ try {+ const workspace = created ?? (await workspacesStore.create(server.id, trimmed));+ setCreated(workspace);+ await workspacesStore.setActive(workspace.id);+ onCreated();+ } catch (cause) {+ // Two different failures wear the same button. Before the workspace+ // exists the likeliest one is the name, and after it exists the name is+ // settled and what failed was the move into it — saying "could not+ // create" then would be describing the wrong step.+ setError(+ created === null+ ? createWorkspaceFailureText(+ cause,+ server.name,+ `${server.name} could not create the workspace.`+ )+ : failureText(cause, `This window could not be moved into ${created.name}.`)+ );+ setSubmitting(false);+ }+ };++ return (+ <WizardFrame+ title="Create your workspace"+ subtitle={+ onBack === null+ ? `You’re not in a workspace on ${server.name} yet, so you’re the first one here. A workspace is where your agents, rooms and teammates live.`+ : 'A workspace is where your agents, rooms and teammates live.'+ }+ pager={{+ pageName: 'Create your workspace',+ onBack: onBack && !submitting && created === null ? onBack : null,+ onNext: null,+ }}+ footer={+ <>+ {onBack && created === null && (+ <Button variant="outline" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ )}+ <ConfirmButton+ onClick={() => void submit()}+ disabled={submitting || (created === null && trimmed === '')}+ >+ {created !== null+ ? submitting+ ? 'Opening…'+ : 'Open workspace'+ : submitting+ ? 'Creating…'+ : 'Create workspace'}+ </ConfirmButton>+ </>+ }+ >+ <FieldGroup>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Acme Robotics"+ autoFocus+ disabled={created !== null}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submit();+ }}+ />+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ {created !== null && (+ <p className="mt-1 text-xs text-foreground-muted">+ {created.name} was created on {server.name}, but this window could not be moved into+ it. Try again — asking for it a second time would only be refused for the name it+ already has.+ </p>+ )}+ </Field>+ </FieldGroup>+ </WizardFrame>+ );+}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.tsxindex 995f5f716..bf25b2ea5 100644--- 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@@ -23,7 +23,9 @@ import type {AddServerStepName,} from '@shared/core/switch-servers/add-server-steps';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { CreateWorkspacePage } from './create-workspace-page';import { onboardingStore, type OnboardingPage } from './onboarding-store';+import { PickWorkspacePage } from './pick-workspace-page';import { WelcomePage } from './welcome-page';/**@@ -35,6 +37,11 @@ import { WelcomePage } from './welcome-page';* 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.+ *+ * The workspace pages are unreported for the opposite reason: they are not+ * steps of the add-server wizard at all — the modal has nothing like them,+ * because by the time you open it you are already in a workspace — so counting+ * them here would put drop-offs from one funnel into the other's numbers.*/const STEP_FOR_PAGE: Record<OnboardingPage, AddServerStepName | null> = {welcome: null,@@ -43,6 +50,8 @@ const STEP_FOR_PAGE: Record<OnboardingPage, AddServerStepName | null> = {remoteHost: 'remoteHost',connect: 'external',signIn: 'signIn',+ pickWorkspace: null,+ createWorkspace: null,linkAccounts: 'linkAccounts',};@@ -59,6 +68,8 @@ const CHOICE_FOR_PAGE: Record<OnboardingPage, AddServerChoiceName> = {remoteHost: 'remoteHost',connect: 'external',signIn: 'external',+ pickWorkspace: 'external',+ createWorkspace: 'external',linkAccounts: 'external',};@@ -191,7 +202,29 @@ function currentPage(server={server}onBack={() => goTo('connect')}onClose={null}- onSignedIn={() => goTo('linkAccounts')}+ onSignedIn={() => goTo('pickWorkspace')}+ />+ );+ case 'pickWorkspace':+ if (server === null) break;+ return (+ <PickWorkspacePage+ server={server}+ onBack={() => goTo('signIn')}+ onPicked={() => goTo('linkAccounts')}+ onCreate={() => goTo('createWorkspace')}+ />+ );+ case 'createWorkspace':+ if (server === null) break;+ return (+ <CreateWorkspacePage+ server={server}+ // Nothing to go back to when the account is in no workspace: the+ // picker sent the user straight here, and returning to it would be a+ // door onto the list it had nothing to show.+ onBack={onboardingStore.serverWorkspaces?.length ? () => goTo('pickWorkspace') : null}+ onCreated={() => goTo('linkAccounts')}/>);case 'linkAccounts':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.tsindex 2cee3d2c1..0ea223da4 100644--- 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@@ -1,5 +1,6 @@import { makeAutoObservable } from 'mobx';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';/** Where a fresh install is in getting its first server. */export type OnboardingPage =@@ -9,6 +10,8 @@ export type OnboardingPage =| 'remoteHost'| 'connect'| 'signIn'+ | 'pickWorkspace'+ | 'createWorkspace'| 'linkAccounts';/**@@ -30,6 +33,8 @@ class OnboardingStore {page: OnboardingPage = 'welcome';/** The server the connect page added, and the subject of the pages after it. */server: SwitchServer | null = null;+ /** The workspaces that server said the account is in, once it has been asked. */+ serverWorkspaces: Workspace[] | null = null;/*** The server a managed path brought up, and the page that brought it up.*@@ -56,12 +61,14 @@ class OnboardingStore {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.+ // server it may already have registered and what that server answered.+ // 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.serverWorkspaces = null;this.registeredOn = null;}this.page = page;@@ -84,9 +91,21 @@ class OnboardingStore {this.page = 'signIn';}+ /**+ * What the server answered when asked which workspaces this account is in.+ *+ * Kept so the create page knows whether there was anything to come back to:+ * an account with no membership is sent straight to the form, and offering it+ * a Back to a list of nothing would be a door onto a blank wall.+ */+ resolved(workspaces: Workspace[]): void {+ this.serverWorkspaces = workspaces;+ }+reset(): void {this.page = 'welcome';this.server = null;+ this.serverWorkspaces = null;this.registeredOn = null;}}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsxnew file mode 100644index 000000000..d3782bad8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx@@ -0,0 +1,195 @@+import { useQuery } from '@tanstack/react-query';+import { Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useEffect, useRef, useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';+import { onboardingStore } from './onboarding-store';++/**+ * Which of the server's workspaces the window should be scoped to.+ *+ * The page asks the server rather than reading the list this app already holds:+ * signing in is the first moment the gateway will say what the account is a+ * member of, and an install that has been sitting on the sign-in form is+ * answering from before that.+ *+ * Only memberships are offered. The design also shows workspaces open to you+ * because your email domain matches, and invitations waiting for your address —+ * both are **absent here rather than empty**, because a Switch server cannot+ * answer for either yet: it records no email domain against a workspace and has+ * no way to list the invitations sent to an address. An empty "nobody has+ * invited you" section would be a claim the server never made, and one that+ * will read as false to the first person who was in fact invited.+ */+export const PickWorkspacePage = observer(function PickWorkspacePage({+ server,+ onBack,+ onPicked,+ onCreate,+}: {+ server: SwitchServer;+ onBack: () => void;+ onPicked: () => void;+ onCreate: () => void;+}) {+ const [opening, setOpening] = useState<string | null>(null);+ const [openError, setOpenError] = useState<string | null>(null);++ const query = useQuery({+ queryKey: ['onboarding-workspaces', server.id],+ queryFn: () => rpc.switchServers.resolveWorkspaces(server.id),+ });+ const workspaces = query.data ?? null;++ const open = useCallback(+ async (workspace: Workspace) => {+ setOpening(workspace.id);+ setOpenError(null);+ try {+ await workspacesStore.setActive(workspace.id);+ onPicked();+ } catch (cause) {+ setOpenError(failureText(cause, `Could not open ${workspace.name}.`));+ setOpening(null);+ }+ },+ [onPicked]+ );++ // Once per answer, not once per render: the callbacks are made fresh by the+ // page above, so without the latch a re-render would re-run the choice that+ // is already under way.+ const settled = useRef(false);+ useEffect(() => {+ if (workspaces === null || settled.current) return;+ settled.current = true;+ onboardingStore.resolved(workspaces);+ // A question with one answer is not a question, and with none there is+ // nothing here to answer it with.+ if (workspaces.length === 0) onCreate();+ else if (workspaces.length === 1) void open(workspaces[0]!);+ }, [workspaces, open, onCreate]);++ return (+ <WizardFrame+ title="Pick a workspace"+ subtitle="You’re a member of these. A workspace is where your agents, rooms and teammates live."+ /* The chevron below repeats this. It is unlabelled, so it cannot be the+ only way back from a page whose rows all lead forward. Both are held+ shut while a workspace is being opened, since leaving now would land+ the user two pages on when it resolves. */+ footer={+ <Button variant="outline" onClick={onBack} disabled={opening !== null}>+ Back+ </Button>+ }+ pager={{+ pageName: 'Pick a workspace',+ onBack: opening === null ? onBack : null,+ onNext: null,+ }}+ >+ {query.isPending ? (+ <p className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner className="size-3.5" />+ Checking which workspaces you’re in…+ </p>+ ) : query.isError ? (+ <div className="flex flex-col items-start gap-3">+ <p className="text-sm text-destructive">+ {failureText(query.error, `Could not ask ${server.name} which workspaces you’re in.`)}+ </p>+ <Button variant="outline" size="sm" onClick={() => void query.refetch()}>+ Retry+ </Button>+ </div>+ ) : (+ <div className="flex w-full flex-col gap-3">+ <ul className="flex flex-col gap-2">+ {(workspaces ?? []).map((workspace) => (+ <WorkspaceRow+ key={workspace.id}+ workspace={workspace}+ opening={opening === workspace.id}+ disabled={opening !== null}+ onOpen={() => void open(workspace)}+ />+ ))}+ </ul>++ {openError && <p className="text-sm text-destructive">{openError}</p>}++ <div className="flex items-center gap-3">+ <span className="h-px flex-1 bg-border" />+ <span className="text-xs text-foreground-muted">or start fresh</span>+ <span className="h-px flex-1 bg-border" />+ </div>++ <button+ type="button"+ onClick={onCreate}+ disabled={opening !== null}+ className="flex items-center justify-center gap-2 rounded-[10px] border border-dashed border-border px-3.5 py-3 text-sm font-medium text-foreground hover:bg-[var(--sel-soft)] disabled:opacity-50"+ >+ <Plus className="size-4" />+ Create a new workspace+ </button>+ </div>+ )}+ </WizardFrame>+ );+});++function WorkspaceRow({+ workspace,+ opening,+ disabled,+ onOpen,+}: {+ workspace: Workspace;+ opening: boolean;+ disabled: boolean;+ onOpen: () => void;+}) {+ return (+ <li>+ <button+ type="button"+ onClick={onOpen}+ disabled={disabled}+ className="flex w-full items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3 text-left hover:bg-[var(--sel-soft)] disabled:opacity-60"+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-sm font-semibold text-foreground">+ {initialOf(workspace.name)}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {workspace.name}+ </span>+ {workspace.role && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {workspace.role}+ </span>+ )}+ {opening ? (+ <Spinner className="size-3.5 shrink-0" />+ ) : (+ <span className="shrink-0 text-sm text-foreground-muted">Open</span>+ )}+ </button>+ </li>+ );+}++const GRAPHEMES = new Intl.Segmenter();++/** By grapheme, so a name starting with an emoji is not cut in half. */+function initialOf(name: string): string {+ return ([...GRAPHEMES.segment(name)][0]?.segment ?? '?').toUpperCase();+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.tsnew file mode 100644index 000000000..d7de0cc47--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { RpcError } from '@shared/lib/ipc/rpc-error';+import { createWorkspaceFailureText } from './describe-create-failure';++function gatewayError(status: number, detail: string): RpcError {+ return new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: `Gateway returned ${status}: ${detail}`,+ data: { kind: 'http', status, detail },+ } as unknown as ConstructorParameters<typeof RpcError>[0]);+}++const FALLBACK = 'Local dev could not create it.';++describe('creating a workspace, when it fails', () => {+ /**+ * The gateway's own words are `Slug already taken: acme-robotics` — no+ * terminal punctuation, so the shared description does not read it as a+ * sentence and shows it as diagnostics instead. What reached the user was a+ * status code and a slug they never typed, for the one refusal that is+ * entirely about what they did type.+ */+ it('blames the name for a name conflict, and says nothing about slugs', () => {+ const text = createWorkspaceFailureText(+ gatewayError(409, 'Slug already taken: acme-robotics'),+ 'Local dev',+ FALLBACK+ );++ expect(text).toContain('already goes by that name');+ expect(text).toContain('Local dev');+ expect(text).not.toContain('acme-robotics');+ expect(text).not.toContain('409');+ });++ // The whole point of the rewrite is that the name is at fault. Saying so over+ // an expired session sends the user to rename a workspace when what they have+ // to do is sign in.+ it('leaves every other gateway refusal to the shared description', () => {+ const expired = new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: 'Gateway returned 401',+ data: { kind: 'unauthorized', status: 401 },+ } as unknown as ConstructorParameters<typeof RpcError>[0]);++ expect(createWorkspaceFailureText(expired, 'Local dev', FALLBACK)).toContain('Sign in again');+ });++ it('keeps the caller’s sentence for a failure it cannot place', () => {+ const text = createWorkspaceFailureText(new Error('socket hang up'), 'Local dev', FALLBACK);++ expect(text).toContain(FALLBACK);+ expect(text).toContain('socket hang up');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.tsnew file mode 100644index 000000000..37d626664--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts@@ -0,0 +1,31 @@+import { failureText } from '@renderer/lib/errors/describe-failure';+import { RpcError } from '@shared/lib/ipc/rpc-error';++/**+ * What to put under the name field when creating a workspace fails.+ *+ * The name being taken is by far the likeliest way this form fails, and it is+ * the only failure the person at the keyboard can fix. The gateway derives a+ * slug from the name and refuses a duplicate with `Slug already taken:+ * acme-robotics` — no terminal punctuation, so the generic description does not+ * read it as a sentence and shows it as diagnostic text instead: a status code+ * and a slug the user never typed, for the one refusal that is about what they+ * did type.+ *+ * Only that route's conflict is rewritten. Everything else keeps the shared+ * description, because a name-specific sentence over an expired session or an+ * unreachable server would blame the name for something it had nothing to do+ * with.+ */+export function createWorkspaceFailureText(+ error: unknown,+ serverName: string,+ fallback: string+): string {+ const conflict =+ error instanceof RpcError &&+ error.code === 'GatewayError' &&+ error.numberField('status') === 409;+ if (!conflict) return failureText(error, fallback);+ return `A workspace on ${serverName} already goes by that name. Capitalisation and punctuation do not make it a different one, so pick a name that stands apart.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.tsindex 8d86acd2d..71e3eebc1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts@@ -75,6 +75,20 @@ export class WorkspacesStore {});}+ /**+ * Create a workspace on a server and return it.+ *+ * Refreshes before returning, so a caller that scopes the window to the new+ * workspace is not doing it against a list that does not contain it yet.+ * Failures propagate: the name may be refused for a slug already in use, and+ * the form has to say so rather than appear to have worked.+ */+ async create(serverId: string, name: string): Promise<Workspace> {+ const workspace = await rpc.switchServers.createWorkspace({ serverId, name });+ await this.refresh();+ return workspace;+ }+async refresh(): Promise<void> {const [workspaces, activeId] = await Promise.all([rpc.workspaces.list(),diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsxnew file mode 100644index 000000000..9fcab9ad5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx@@ -0,0 +1,316 @@+/**+ * Choosing a workspace on a server you have just signed in to.+ *+ * The interesting behaviour is not the list — it is what the pages do with the+ * three answers the server can give. None, one and several each lead somewhere+ * different, being asked and failing is not the same as being asked and told+ * "none", and the sections the server cannot answer for at all are absent+ * rather than drawn empty.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const resolveWorkspaces = vi.hoisted(() => vi.fn());+const createWorkspace = vi.hoisted(() => vi.fn());+const setActiveWorkspace = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: { switchServers: { resolveWorkspaces } },+ events: { on: () => () => {}, emit: () => {} },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ setActive: setActiveWorkspace,+ create: createWorkspace,+ idOnServerInScope: () => 'ws-1',+ },+}));++const SERVER = vi.hoisted(() => ({+ id: 'srv-1',+ name: 'switch.example.com',+ gatewayUrl: 'https://switch.example.com',+ apiUrl: 'https://switch.example.com:8000',+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ setActive: vi.fn(),+ errorText: null,+ serverById: (id: string | null) => (id === SERVER.id ? SERVER : null),+ // Stepping back off the picker draws the sign-in page, which reads these.+ ensureAuthConfig: () => Promise.resolve(),+ authConfigFor: () => ({+ passwordLoginEnabled: true,+ oidcEnabled: false,+ oidcProviderLabel: null,+ }),+ authConfigCheckFailed: () => false,+ authConfigChecking: () => false,+ passwordLogin: () => Promise.resolve(true),+ oidcLogin: () => Promise.resolve(true),+ },+}));++// The last page of the flow, and not what these tests are about — stubbed so+// reaching it is a fact the test can assert without dragging in the bridge+// reads behind it.+vi.mock('@renderer/features/switch-servers/link-accounts-step', () => ({+ LinkAccountsStep: () => <div>Link your messaging accounts</div>,+}));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate: vi.fn() }),+}));++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';++function workspace(id: string, name: string) {+ return {+ id,+ serverId: 'srv-1',+ name,+ tenantId: `tenant-${id}`,+ slug: name.toLowerCase(),+ role: 'member' as const,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ resolveWorkspaces.mockReset();+ createWorkspace.mockReset();+ setActiveWorkspace.mockReset().mockResolvedValue(undefined);+ onboardingStore.reset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++/** The flow, opened at the page that follows a successful sign-in. */+async function renderAtPickWorkspace(): Promise<HTMLDivElement> {+ onboardingStore.connected(SERVER as never);+ onboardingStore.goTo('pickWorkspace');++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <OnboardingFlow />+ </QueryClientProvider>+ )+ );+ await settle();+ return container;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++async function click(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());+ await settle();+}++async function typeName(el: HTMLElement, value: string): Promise<void> {+ const input = el.querySelector('input');+ expect(input, 'no name field').not.toBeNull();+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input!.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('picking a workspace after signing in', () => {+ it('lists the workspaces the account is a member of', async () => {+ resolveWorkspaces.mockResolvedValue([+ workspace('ws-1', 'Acme'),+ workspace('ws-2', 'Skunkworks'),+ ]);++ const el = await renderAtPickWorkspace();++ expect(resolveWorkspaces).toHaveBeenCalledWith('srv-1');+ expect(el.textContent).toContain('Pick a workspace');+ expect(el.textContent).toContain('Acme');+ expect(el.textContent).toContain('Skunkworks');+ expect(el.textContent).toContain('Create a new workspace');+ });++ it('leaves out the join and invite rows the server cannot answer for', async () => {+ // The design offers workspaces open to you by email domain, and invitations+ // waiting for your address. A Switch server records neither, so an empty+ // section would be a claim it never made.+ resolveWorkspaces.mockResolvedValue([+ workspace('ws-1', 'Acme'),+ workspace('ws-2', 'Skunkworks'),+ ]);++ const el = await renderAtPickWorkspace();++ expect(el.textContent).not.toContain('Join');+ expect(el.textContent).not.toContain('Accept');+ expect(el.textContent).not.toContain('invited you');+ expect(el.textContent).not.toContain('domain');+ });++ it('does not ask a question with one answer', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);++ const el = await renderAtPickWorkspace();++ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-1');+ expect(onboardingStore.page).toBe('linkAccounts');+ expect(el.textContent).toContain('Link your messaging accounts');+ });++ it('goes straight to creating one when the account is in none', async () => {+ resolveWorkspaces.mockResolvedValue([]);++ const el = await renderAtPickWorkspace();++ expect(onboardingStore.page).toBe('createWorkspace');+ expect(el.textContent).toContain('Create your workspace');+ // Nothing behind it: the picker had no list to return to. The arrow stays+ // in the tab order and says as much in its own label, so it is matched on+ // the start of one.+ const back = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;+ expect(back.getAttribute('aria-disabled')).toBe('true');+ expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain('Back');+ });++ it('goes back by a button and not only by a chevron', async () => {+ // The chevron is unlabelled, so it may repeat the way back but never be the+ // only one — the same invariant the who-runs page keeps.+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);++ const el = await renderAtPickWorkspace();+ await click(el, 'Back');++ expect(onboardingStore.page).toBe('signIn');+ });++ /**+ * Leaving while a workspace is being entered lands the user two pages on when+ * it resolves — back on the sign-in, and then thrown forward out of it.+ */+ it('holds the way back shut while a workspace is being opened', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);+ const opening = deferred<void>();+ setActiveWorkspace.mockReturnValue(opening.promise);++ const el = await renderAtPickWorkspace();+ await click(el, 'Acme');++ const back = [...el.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent?.trim() === 'Back'+ )!;+ expect(back.disabled).toBe(true);+ const chevron = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;+ expect(chevron.getAttribute('aria-disabled')).toBe('true');++ opening.resolve();+ await settle();+ });++ it('says the server could not be asked, rather than treating it as no workspaces', async () => {+ // Conflating the two would offer to create a second workspace to someone+ // who already has one.+ resolveWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ const el = await renderAtPickWorkspace();++ expect(el.textContent).toContain('switch.example.com');+ expect(el.textContent).toContain('Retry');+ expect(onboardingStore.page).toBe('pickWorkspace');+ expect(el.textContent).not.toContain('Create your workspace');+ });++ it('creates a workspace and carries on into it', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));++ const el = await renderAtPickWorkspace();+ await typeName(el, ' Acme ');+ await click(el, 'Create workspace');++ expect(createWorkspace).toHaveBeenCalledWith('srv-1', 'Acme');+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ /**+ * The workspace exists on the server from the moment Create returns. Asking+ * again would send back a name it has just taken and earn a conflict that+ * reads as the name being refused — and on this page, reached because the+ * account is in no workspace at all, there is no Back either.+ */+ it('offers to open the workspace it already made rather than creating it twice', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));+ setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));++ const el = await renderAtPickWorkspace();+ await typeName(el, 'Acme');+ await click(el, 'Create workspace');++ expect(el.textContent).toContain('could not be moved into it');++ setActiveWorkspace.mockResolvedValue(undefined);+ await click(el, 'Open workspace');++ expect(createWorkspace).toHaveBeenCalledTimes(1);+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ it('keeps the form and says why when the name is refused', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockRejectedValue(new Error('That name is already taken.'));++ const el = await renderAtPickWorkspace();+ await typeName(el, 'Acme');+ await click(el, 'Create workspace');++ expect(el.textContent).toContain('already taken');+ expect(onboardingStore.page).toBe('createWorkspace');+ });+});