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): replay first-run pages on dev/canary, and a restyled workspace menu (#630)
Louis Amaudruzf9a295c1ab62
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex 173412811..53b0047c0 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -100,6 +100,7 @@ import {removeWorkspaceJoinDomain,revokeWorkspaceInvitation,} from './invitations';+import { listServersWithoutMembership } from './reconcile-workspaces';import {withReachableWorkspaceSession,withWorkspaceSession,@@ -231,6 +232,9 @@ export const workspacesController = createRPCController({getActiveId: (): Promise<string | null> => getActiveWorkspaceId(),+ /** Servers where the signed-in account belongs to no workspace yet. */+ serversWithoutMembership: async (): Promise<string[]> => listServersWithoutMembership(),+setActive: (workspaceId: string): Promise<void> => setActiveWorkspaceId(workspaceId),listAgents: (workspaceId: string): Promise<RemoteAgentSummary[]> =>diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.tsindex e897efd62..3edcc3cb9 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts@@ -39,7 +39,7 @@ vi.mock('@main/lib/logger', () => {// store at import, which a test has no key for.vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie, listServers }));-const { reconcileAllWorkspaces, reconcileServerWorkspaces } =+const { listServersWithoutMembership, reconcileAllWorkspaces, reconcileServerWorkspaces } =await import('./reconcile-workspaces');const {createTenantWorkspace,@@ -111,6 +111,22 @@ describe('reconcile-workspaces', () => {expect(found[0]!.role).toBe('owner');});+ it('remembers a server whose account belongs to no workspace, until it joins one', async () => {+ const placeholder = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([]);++ await reconcileServerWorkspaces('srv-1');++ expect(listServersWithoutMembership()).toEqual(['srv-1']);+ // The placeholder is left alone, so the agents and selection naming it stay put.+ expect((await listWorkspacesForServer('srv-1')).map((w) => w.id)).toEqual([placeholder.id]);++ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);+ await reconcileServerWorkspaces('srv-1');++ expect(listServersWithoutMembership()).toEqual([]);+ });+/*** A row is named after its server only until it is matched. After that the* workspace is a tenant, the gateway is the only place it can be named ordiff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.tsindex 4ac6e58de..efe139fd9 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts@@ -146,6 +146,19 @@ export async function reconcileServerWorkspaces(serverId: string): Promise<void>const inFlight = new Map<string, Promise<void>>();+/**+ * Servers whose account, at the last reconcile, belonged to no workspace.+ *+ * Kept in memory rather than on the row: it is a fact about the account at the+ * moment it was asked, the reconcile asks again on every launch and sign-in,+ * and a stale "no workspace" surviving a restart would hide one gained since.+ */+const serversWithoutMembership = new Set<string>();++export function listServersWithoutMembership(): string[] {+ return [...serversWithoutMembership];+}+async function reconcileOneServer(serverId: string): Promise<void> {const server = await requireServer(serverId);const tenants = await fetchTenants(server);@@ -160,8 +173,10 @@ async function reconcileOneServer(serverId: string): Promise<void> {log.warn('workspaces: the gateway reports no workspace membership for this account', {server: serverId,});+ serversWithoutMembership.add(serverId);return;}+ serversWithoutMembership.delete(serverId);const claimed = new Map(localdiff --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 66e9e868c..f1534cffe 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@@ -133,7 +133,12 @@ export const OnboardingFlow = observer(function OnboardingFlow() {* 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) };+ const exit =+ server !== null+ ? { label: 'Finish later', onExit: () => finish(server.id) }+ : onboardingStore.rehearsal+ ? { label: 'Back to the app', onExit: () => finish(null) }+ : null;const cloud = useSwitchCloud();const [cloudAttempt, setCloudAttempt] = useState<{ connecting: boolean; error: string | null }>({@@ -219,6 +224,7 @@ function currentPage(cloud={welcomeCloud}onContinue={() => goTo('whoRuns')}onInvite={() => goTo('invite')}+ onLeave={onboardingStore.rehearsal ? () => finish(null) : null}/>);case 'invite':diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.test.tsnew file mode 100644index 000000000..0924faed6--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';+import { onboardingStore } from './onboarding-store';++describe('replaying the first-run pages', () => {+ it('keeps the flow on screen from its welcome page', () => {+ onboardingStore.reset();+ expect(onboardingStore.inProgress).toBe(false);++ onboardingStore.rehearse();++ expect(onboardingStore.page).toBe('welcome');+ expect(onboardingStore.inProgress).toBe(true);+ });++ it('survives walking back to the welcome page', () => {+ onboardingStore.rehearse();+ onboardingStore.goTo('whoRuns');+ onboardingStore.goTo('welcome');++ expect(onboardingStore.inProgress).toBe(true);+ });++ it('ends when the flow is finished or left', () => {+ onboardingStore.rehearse();+ onboardingStore.reset();++ expect(onboardingStore.rehearsal).toBe(false);+ expect(onboardingStore.inProgress).toBe(false);+ });+});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 c09dbdbd3..c5d4a94f4 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@@ -65,6 +65,13 @@ class OnboardingStore {* account on the server, and the link arrives before there is one.*/invite: InviteLink | null = null;+ /**+ * The flow was opened on purpose from a dev or canary build that already has+ * servers, to walk through the first-run pages again. It keeps the flow on+ * screen from its welcome page, which a launch with servers would otherwise+ * skip, and offers a way back to the app from every page.+ */+ rehearsal = false;constructor() {makeAutoObservable(this);@@ -77,7 +84,13 @@ class OnboardingStore {* been started, so a launch that finds servers should go straight past it.*/get inProgress(): boolean {- return this.page !== 'welcome';+ return this.rehearsal || this.page !== 'welcome';+ }++ /** Open the first-run pages from their start, whatever the install holds. */+ rehearse(): void {+ this.reset();+ this.rehearsal = true;}goTo(page: OnboardingPage): void {@@ -150,6 +163,7 @@ class OnboardingStore {this.joinOfferCount = 0;this.registeredOn = null;this.invite = null;+ this.rehearsal = false;}}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.tsxindex 4a265dd07..00077f386 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@@ -51,15 +51,25 @@ export function WelcomePage({cloud,onContinue,onInvite,+ onLeave,}: {cloud: WelcomeCloud;onContinue: () => void;/** Join a workspace someone else set up, from the link they sent. */onInvite: () => void;+ /** Back to the app, when the pages were opened again rather than on a fresh install. */+ onLeave: (() => void) | null;}) {const cloudOpen = cloud.kind === 'open';return (<div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">+ {onLeave && (+ <div className="flex justify-end px-4 pt-3 [-webkit-app-region:no-drag]">+ <Button variant="ghost" size="sm" onClick={onLeave}>+ Back to the app+ </Button>+ </div>+ )}<div className="flex min-h-0 flex-1 flex-col overflow-auto">{/* Everything the page shows opts out of the drag region: a scrollinside one is swallowed by the window move. What stays draggable isdiff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsxnew file mode 100644index 000000000..68071216f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx@@ -0,0 +1,35 @@+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';+import { showDevTools } from '@renderer/lib/dev-tools';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { Button } from '@renderer/lib/ui/button';+import { SettingRow } from './SettingRow';++/**+ * Walk through the first-run pages again on an install that already has+ * servers, to test them. Dev and canary builds only.+ *+ * It leaves Settings for the home view on the way, because Settings is drawn+ * even when there is no server and so would stay on screen over the flow.+ */+export function ReplayOnboardingRow() {+ const { navigate } = useNavigate();+ if (!showDevTools()) return null;+ return (+ <SettingRow+ title="Replay first-run pages"+ description="Go through the welcome and add-a-server pages as a fresh install would. Your servers and agents stay as they are. Dev and canary builds only."+ control={+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ onboardingStore.rehearse();+ navigate('home');+ }}+ >+ Replay+ </Button>+ }+ />+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsxindex b220dd8f3..7a28ce4d9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx@@ -7,6 +7,7 @@ import { SWITCH_CONSOLE_DOCS_URL } from '@shared/urls';import { AgentsSettingsPage } from '../agents-page/AgentsSettingsPage';import NotificationSettingsCard from './NotificationSettingsCard';import { OnboardingChecklistRow } from './OnboardingSettingsRow';+import { ReplayOnboardingRow } from './ReplayOnboardingRow';import {AutoGenerateSessionNamesRow,AutoTrustWorktreesRow,@@ -44,6 +45,7 @@ function GeneralSettingsPage() {<PreserveSessionNameCapitalizationRow /><NotificationSettingsCard /><OnboardingChecklistRow />+ <ReplayOnboardingRow /><TelemetrySettingsCard /></div>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.tsnew file mode 100644index 000000000..b2521b528--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.ts@@ -0,0 +1,42 @@+import { Cloud, Globe, Laptop, Server } from 'lucide-react';+import { describe, expect, it, vi } from 'vitest';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++vi.mock('./switch-cloud-store', () => ({+ isSwitchCloudServer: (server: SwitchServer) =>+ server.gatewayUrl === 'https://cloud.example.invalid',+}));++const { serverIcon } = await import('./server-icon');++function server(patch: Partial<SwitchServer>): SwitchServer {+ return {+ id: 'srv',+ name: 'srv',+ gatewayUrl: 'https://srv.example.invalid',+ apiUrl: 'https://srv.example.invalid',+ managed: false,+ managementKind: null,+ sshHost: null,+ createdAt: '',+ updatedAt: '',+ ...patch,+ };+}++describe('the icon for a server', () => {+ it('is a cloud for Switch Cloud', () => {+ expect(serverIcon(server({ gatewayUrl: 'https://cloud.example.invalid' }))).toBe(Cloud);+ });++ it('is a globe for any other server reached by URL', () => {+ expect(serverIcon(server({}))).toBe(Globe);+ });++ it('is a laptop or a server for the stacks Console runs', () => {+ expect(serverIcon(server({ managed: true, managementKind: 'local' }))).toBe(Laptop);+ expect(serverIcon(server({ managed: true, managementKind: 'remote', sshHost: 'vm-1' }))).toBe(+ Server+ );+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.tsindex 0663800b7..c2ecd3dde 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.ts@@ -1,15 +1,17 @@-import { Globe, type LucideIcon, Laptop, Server } from 'lucide-react';+import { Cloud, Globe, type LucideIcon, Laptop, Server } from 'lucide-react';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { isSwitchCloudServer } from './switch-cloud-store';/*** Which icon stands for a server, by how it is run: a laptop for the stack on- * this computer, a server for one on a remote host, a globe for one reached by- * URL.+ * this computer, a server for one on a remote host, a cloud for Switch Cloud,+ * and a globe for any other one reached by URL.** Shared so the sidebar and the command palette cannot disagree — they render* the same server in two places, and the picker that creates it is a third.*/export function serverIcon(server: SwitchServer): LucideIcon {if (server.managementKind === 'remote') return Server;- return server.managed ? Laptop : Globe;+ if (server.managed) return Laptop;+ return isSwitchCloudServer(server) ? Cloud : Globe;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsxindex 64fa91558..3ae3b5f4d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx@@ -1,8 +1,10 @@import type { LucideIcon } from 'lucide-react';import { observer } from 'mobx-react-lite';+import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar';+import { workspaceTitle } from '@renderer/features/workspaces/workspace-title';import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';-import { ServerAvatar, ServerStatusPill } from './server-presentation';+import { ServerStatusPill } from './server-presentation';import { switchServersStore } from './switch-servers-store';/**@@ -29,6 +31,7 @@ export const ServerSectionTitlebar = observer(function ServerSectionTitlebar({onSectionClick?: () => void;}) {const server = switchServersStore.servers.find((s) => s.id === serverId);+ const title = server ? workspaceTitle(server) : null;return (<TitlebarleftSlot={@@ -36,8 +39,8 @@ export const ServerSectionTitlebar = observer(function ServerSectionTitlebar({crumbs={[{key: 'server',- icon: server && <ServerAvatar server={server} size="sm" />,- label: server?.name ?? 'Server',+ icon: title && <WorkspaceAvatar name={title} size="sm" active />,+ label: title ?? 'Workspace',maxWidthClassName: 'max-w-40',},{diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.tsnew file mode 100644index 000000000..7389ab5f4--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.ts@@ -0,0 +1,51 @@+import { makeAutoObservable, runInAction } from 'mobx';+import { rpc } from '@renderer/lib/ipc';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++/**+ * Switch Cloud's origin as this build knows it, read once, for the places that+ * mark the Cloud's server apart from any other server reached by URL.+ *+ * Read lazily on first use rather than at import, so a view that never asks+ * never makes the call. A build with no Cloud, or one whose configuration+ * could not be read, has no origin here; `useSwitchCloud` is where the+ * difference between those two is shown.+ */+class SwitchCloudStore {+ private originValue: string | null = null;+ private requested = false;++ constructor() {+ makeAutoObservable<SwitchCloudStore, 'requested'>(this, { requested: false });+ }++ get origin(): string | null {+ if (!this.requested) this.load();+ return this.originValue;+ }++ private load(): void {+ this.requested = true;+ void rpc.switchServers.switchCloud().then(+ (endpoint) => {+ runInAction(() => {+ this.originValue = endpoint ? endpoint.url : null;+ });+ },+ () => {}+ );+ }+}++export const switchCloudStore = new SwitchCloudStore();++/** Whether a server is the one this build treats as Switch Cloud. */+export function isSwitchCloudServer(server: SwitchServer): boolean {+ const origin = switchCloudStore.origin;+ if (origin === null) return false;+ try {+ return new URL(server.gatewayUrl).origin === origin;+ } catch {+ return false;+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsxindex e1568387e..8663360ce 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx@@ -16,6 +16,8 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';+import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar';+import { workspaceTitle } from '@renderer/features/workspaces/workspace-title';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';@@ -40,7 +42,6 @@ import { remoteServerStore } from './remote-server-store';import { RemoteServerControls } from './RemoteServerControls';import { serverIcon } from './server-icon';import {- ServerAvatar,serverDeployedTelemetry,serverDrift,serverPlacementLabel,@@ -53,6 +54,7 @@ import { ServerSignInFields, useServerSignIn } from './server-sign-in';import { ServerStatTiles } from './server-stat-tiles';import { useSharedActionConfirm } from './shared-action-confirm';import { SharedConsolesSection } from './shared-consoles-section';+import { isSwitchCloudServer } from './switch-cloud-store';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';import { TelemetryConsentNotice } from './TelemetryConsentNotice';@@ -200,6 +202,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {const unreachable = store.isUnreachable(serverId);const PlacementIcon = serverIcon(server);const drift = serverDrift(server);+ const title = workspaceTitle(server);const stackTransitioning =server.managementKind === 'remote' && server.sshHost? remoteServerStore.isTransitioning(server.sshHost) ||@@ -211,14 +214,25 @@ const ServerMainPanel = observer(function ServerMainPanel() {<div className="mx-auto w-full max-w-4xl space-y-6 p-6"><header className="flex items-center justify-between gap-3"><div className="flex min-w-0 items-center gap-3">- <ServerAvatar server={server} size="lg" />- <h2 className="truncate text-2xl font-semibold text-foreground">{server.name}</h2>- {/* Where the server lives, as the icon the switcher and the sidebar- already use for it rather than as a second vocabulary in words. */}- <PlacementIcon- aria-label={serverPlacementLabel(server) ?? 'Reached over the network'}- className="size-4 shrink-0 text-foreground-muted"- />+ <WorkspaceAvatar name={title} size="lg" active />+ <div className="min-w-0">+ <h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2>+ {/* The server it is on, said only where the title does not+ already: the placeholder before sign-in is named after it. */}+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">+ {/* Where the server lives, as the icon the switcher and the+ sidebar already use for it rather than as a second vocabulary+ in words. */}+ <PlacementIcon+ aria-label={+ serverPlacementLabel(server) ??+ (isSwitchCloudServer(server) ? 'Switch Cloud' : 'Reached over the network')+ }+ className="size-3.5 shrink-0"+ />+ {title !== server.name && <span className="truncate">{server.name}</span>}+ </div>+ </div></div><div className="flex shrink-0 items-center gap-2">{detailsVisible && (diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsxindex 603c41e39..be6844f6d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx@@ -1,7 +1,7 @@import { useQueryClient } from '@tanstack/react-query';-import { ChevronsUpDown, Plus, Server, UserPlus } from 'lucide-react';+import { Check, ChevronsUpDown, LogIn, Plus, Search, Server, UserPlus } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect } from 'react';+import { useEffect, useState } from 'react';import {InvitedBadge,invitationSummary,@@ -13,6 +13,7 @@ import {useJoinableWorkspaces,usePendingInvitations,} from '@renderer/features/workspaces/pending-invitations';+import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { useToast } from '@renderer/lib/hooks/use-toast';@@ -133,7 +134,11 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {return showsServers(cloud.kind) ? (<ServerMenu activeServer={activeServer} />) : (- <WorkspaceMenu active={active} activeServer={activeServer} />+ <WorkspaceMenu+ active={active}+ activeServer={activeServer}+ cloudOrigin={cloud.kind === 'open' ? cloud.url : null}+ />);});@@ -294,26 +299,43 @@ const ServerMenuItem = observer(function ServerMenuItem({* list. A workspace only means anything on its server — two servers can each* have a "Default" — and the server is also what carries reachability, so the* group heading is where it is said once instead of on every row.+ *+ * A search box at the top narrows the list by workspace or server name, for an+ * account in enough workspaces that scanning them stops being quick.*/const WorkspaceMenu = observer(function WorkspaceMenu({active,activeServer,+ cloudOrigin,}: {active: Workspace;activeServer: SwitchServer;+ /** Switch Cloud's origin when this build knows it, to mark its server as the official one. */+ cloudOrigin: string | null;}) {const store = switchServersStore;const { navigate } = useNavigate();const showAddServerModal = useShowModal('addServerModal');const showCreateWorkspaceModal = useShowModal('createWorkspaceModal');const showInvitePeopleModal = useShowModal('invitePeopleModal');+ const [query, setQuery] = useState('');- const ActiveIcon = serverIcon(activeServer);const drift = serverDrift(activeServer);+ const noWorkspaceYet =+ active.tenantId === null &&+ serverAvailability(activeServer.id) === 'available' &&+ workspacesStore.hasNoMembership(activeServer.id);+ const anyMatch =+ query.trim() === '' ||+ store.servers.some(+ (server) =>+ matchesQuery(server.name, query) ||+ workspacesStore.onServer(server.id).some((w) => matchesQuery(w.name, query))+ );return (<div className="px-2">- <DropdownMenu>+ <DropdownMenu onOpenChange={(open) => !open && setQuery('')}><DropdownMenuTriggerrender={<button@@ -321,14 +343,15 @@ const WorkspaceMenu = observer(function WorkspaceMenu({aria-label="Switch workspace"className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]">- <ServerAvatar server={activeServer} size="md" />+ <WorkspaceAvatar name={active.name} size="md" active /><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-foreground">- {active.name}+ {noWorkspaceYet ? 'No workspace yet' : active.name}</span><span className="flex items-center gap-1.5 text-xs text-foreground-muted">- <ActiveIcon className="size-3 shrink-0" />- <span className="truncate">{switcherSubtitle(active, activeServer)}</span>+ <span className="truncate">+ {noWorkspaceYet ? activeServer.name : switcherSubtitle(active, activeServer)}+ </span><ServerStatusDot server={activeServer} />{drift && <ServerDriftIndicator drift={drift} />}</span>@@ -338,17 +361,28 @@ const WorkspaceMenu = observer(function WorkspaceMenu({</button>}/>- <DropdownMenuContent align="start" className="min-w-72">+ <DropdownMenuContent align="start" className="w-80">+ <WorkspaceSearch value={query} onChange={setQuery} />{store.servers.map((server) => (- <ServerWorkspaceGroup key={server.id} server={server} />+ <ServerWorkspaceGroup+ key={server.id}+ server={server}+ query={query}+ official={cloudOrigin !== null && originOf(server.gatewayUrl) === cloudOrigin}+ />))}+ {!anyMatch && (+ <div className="px-2 py-3 text-center text-xs text-foreground-muted">+ No workspace or server matches “{query.trim()}”.+ </div>+ )}<DropdownMenuSeparator />{/* Offered only where the gateway would take it: it refuses members,and a menu item that always ends in a 403 is a trap. */}{administersWorkspace(active) && (<DropdownMenuItem onClick={() => showInvitePeopleModal({ workspaceId: active.id })}><UserPlus className="size-4" />- Invite people to {active.name}+ Invite people to {active.name}…</DropdownMenuItem>)}{/* Above Add server because it is the commoner errand by far: you add@@ -364,11 +398,11 @@ const WorkspaceMenu = observer(function WorkspaceMenu({}><Plus className="size-4" />- New workspace+ New workspace…</DropdownMenuItem><DropdownMenuItem onClick={() => showAddServerModal({})}><Server className="size-4" />- Add server+ Add server…</DropdownMenuItem><DropdownMenuSeparator />{/* The welcome screen is what the app opens with before any server@@ -383,6 +417,57 @@ const WorkspaceMenu = observer(function WorkspaceMenu({);});+export function matchesQuery(name: string, query: string): boolean {+ const q = query.trim().toLowerCase();+ return q === '' || name.toLowerCase().includes(q);+}++function originOf(url: string): string | null {+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+}++/** Where a server is, as its heading says it: the host and port it answers on. */+function serverAddress(server: SwitchServer): string {+ try {+ return new URL(server.gatewayUrl).host;+ } catch {+ return server.gatewayUrl;+ }+}++/**+ * The search box at the top of the menu.+ *+ * The menu reads typed letters as a jump to the item starting with them, so+ * keys typed here are kept from reaching it — all but the ones that move+ * through or leave the menu.+ */+function WorkspaceSearch({ value, onChange }: { value: string; onChange: (v: string) => void }) {+ return (+ <div className="relative px-1 pt-1 pb-1.5">+ <Search className="pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2 text-foreground-muted" />+ <input+ autoFocus+ type="text"+ aria-label="Find a workspace"+ placeholder="Find a workspace…"+ value={value}+ onChange={(event) => onChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== 'Escape' && event.key !== 'ArrowDown' && event.key !== 'Tab') {+ event.stopPropagation();+ }+ }}+ className="h-8 w-full rounded-md border border-border bg-background-tertiary pr-2 pl-8 text-sm text-foreground outline-none placeholder:text-foreground-muted focus:border-foreground-muted"+ />+ </div>+ );+}+/*** A managed local stack that is starting has no server record yet, so it would* otherwise be invisible until it is healthy — and a failed setup invisible@@ -415,40 +500,180 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {/** One server, as a heading over the workspaces the account has on it. */const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({server,+ query,+ official,+}: {+ server: SwitchServer;+ query: string;+ official: boolean;+}) {+ // A server you are not signed in to cannot be asked about invitations, so+ // the hooks that ask only mount where it can.+ return serverAvailability(server.id) === 'available' ? (+ <AvailableServerWorkspaceGroup server={server} query={query} official={official} />+ ) : (+ <ServerWorkspaceGroupBody+ server={server}+ query={query}+ official={official}+ invitations={NO_OFFERS.invitations}+ joinable={NO_OFFERS.joinable}+ invitationsFailed={false}+ joinableFailed={false}+ />+ );+});++const NO_OFFERS: { invitations: PendingInvitation[]; joinable: JoinableWorkspace[] } = {+ invitations: [],+ joinable: [],+};++function AvailableServerWorkspaceGroup({+ server,+ query,+ official,+}: {+ server: SwitchServer;+ query: string;+ official: boolean;+}) {+ const invitations = usePendingInvitations(server.id);+ const joinable = useJoinableWorkspaces(server.id);+ return (+ <ServerWorkspaceGroupBody+ server={server}+ query={query}+ official={official}+ invitations={listedInvitations(invitations.data)}+ joinable={listedJoinable(joinable.data)}+ invitationsFailed={invitations.isError}+ joinableFailed={joinable.isError}+ />+ );+}++const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({+ server,+ query,+ official,+ invitations,+ joinable,+ invitationsFailed,+ joinableFailed,}: {server: SwitchServer;+ query: string;+ official: boolean;+ invitations: PendingInvitation[];+ joinable: JoinableWorkspace[];+ invitationsFailed: boolean;+ joinableFailed: boolean;}) {+ const { navigate } = useNavigate();+ const { toast } = useToast();+ const showCreateWorkspaceModal = useShowModal('createWorkspaceModal');const Icon = serverIcon(server);- const placement = serverPlacementLabel(server);const drift = serverDrift(server);- const workspaces = workspacesStore.onServer(server.id);+ const searching = query.trim() !== '';+ // A search for the server's own name keeps all of its rows, since that is+ // the quickest way to say "the ones on that server".+ const whole = !searching || matchesQuery(server.name, query);+ const all = workspacesStore.onServer(server.id);+ const availability = serverAvailability(server.id);+ const signedOut = availability === 'signed-out';+ const noMembership = availability === 'available' && workspacesStore.hasNoMembership(server.id);+ // The row a server is registered with names no workspace until sign-in+ // matches it to one. Signed out, or signed in to an account that belongs to+ // none, it would read as a workspace called after the server that does not+ // exist there, so it gives way to what can actually be done.+ const placeholder = all.find((w) => w.tenantId === null) ?? null;+ const hidePlaceholder = signedOut || noMembership;+ const listed = hidePlaceholder ? all.filter((w) => w.tenantId !== null) : all;+ const workspaces = whole ? listed : listed.filter((w) => matchesQuery(w.name, query));+ const signInTarget = placeholder ?? all[0] ?? null;+ const openForSignIn = () => {+ if (!signInTarget) return;+ void workspacesStore+ .setActive(signInTarget.id)+ .then(() => navigate('server', { serverId: server.id }))+ .catch(() => {+ toast({+ title: `Could not open ${server.name}`,+ description: 'The app stayed where it was.',+ variant: 'destructive',+ });+ });+ };+ const shownInvitations = whole+ ? invitations+ : invitations.filter((i) => matchesQuery(i.workspaceName, query));+ const shownJoinable = whole+ ? joinable+ : joinable.filter((j) => matchesQuery(j.workspaceName, query));+ const extraRows = (signedOut && signInTarget) || noMembership;+ if (+ searching &&+ !(whole && extraRows) &&+ workspaces.length + shownInvitations.length + shownJoinable.length === 0+ ) {+ return null;+ }+ const available = availability === 'available';return (<DropdownMenuGroup>- <DropdownMenuLabel className="flex items-center gap-2 py-1.5">- <ServerAvatar server={server} size="sm" />- <span className="min-w-0 flex-1">- <span className="block truncate text-xs font-medium text-foreground">{server.name}</span>- <span className="flex min-w-0 items-center gap-1.5 text-xs font-normal text-foreground-muted">- <Icon className="size-3 shrink-0" />- <span className="truncate">{serverStatusLabel(server)}</span>- {/* Beside the words it qualifies rather than at the row's right edge,- where it read as a property of the row instead of of the status. */}+ <DropdownMenuLabel className="flex items-center gap-1.5 px-2 pt-2.5 pb-1 text-[11px] font-semibold tracking-wide text-foreground-muted uppercase">+ <Icon className="size-3 shrink-0" />+ <span className="min-w-0 truncate">{server.name}</span>+ {/* Said only when something is wrong: a heading for every server that+ is fine would be noise on each of them. */}+ {!available && (+ <><ServerStatusDot server={server} />- {placement && (- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {placement}- </span>- )}- </span>- </span>+ <span className="shrink-0 font-normal tracking-normal normal-case">+ {serverStatusLabel(server)}+ </span>+ </>+ )}{drift && <ServerDriftIndicator drift={drift} />}+ <span className="ml-auto shrink-0 pl-2 font-normal tracking-normal normal-case">+ {official ? (+ <span className="text-green-600 dark:text-green-500">Official</span>+ ) : (+ <span className="text-foreground-passive">{serverAddress(server)}</span>+ )}+ </span></DropdownMenuLabel>- {workspaces.length === 0 ? (+ {signedOut && signInTarget && whole && (+ <DropdownMenuItem onClick={openForSignIn}>+ <LogIn className="size-4" />+ Sign in…+ </DropdownMenuItem>+ )}+ {noMembership && whole && (+ <>+ <div className="px-2 py-1.5 text-xs text-foreground-muted">+ No workspace yet — create one, or accept an invitation below.+ </div>+ <DropdownMenuItem+ onClick={() =>+ showCreateWorkspaceModal({+ serverId: server.id,+ onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),+ })+ }+ >+ <Plus className="size-4" />+ Create a workspace…+ </DropdownMenuItem>+ </>+ )}+ {all.length === 0 ? (// Registering a server is what creates its first workspace, so a server// with none did not finish being registered. Saying so beats an empty// heading, which reads as a rendering fault.- <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">+ <div className="px-2 py-1.5 text-xs text-foreground-muted">No workspace yet — this server has not finished being set up.</div>) : (@@ -457,14 +682,32 @@ const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({key={workspace.id}workspace={workspace}server={server}- onServerCount={workspaces.length}+ onServerCount={all.length}/>)))}- {serverAvailability(server.id) === 'available' && (+ {available && (<>- <PendingInvitationItems server={server} />- <JoinableWorkspaceItems server={server} />+ {invitationsFailed && (+ <div className="px-2 py-1.5 text-xs text-foreground-muted">+ Could not check for invitations to your address.+ </div>+ )}+ {shownInvitations.map((invitation) => (+ <PendingInvitationMenuItem+ key={invitation.id}+ invitation={invitation}+ server={server}+ />+ ))}+ {joinableFailed && (+ <div className="px-2 py-1.5 text-xs text-foreground-muted">+ Could not check for workspaces open to your e-mail domain.+ </div>+ )}+ {shownJoinable.map((offer) => (+ <JoinableWorkspaceMenuItem key={offer.tenantId} offer={offer} server={server} />+ ))}</>)}</DropdownMenuGroup>@@ -512,12 +755,11 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({return (<DropdownMenuItem- // The active workspace is shown by filling its row rather than by a tick- // in the right margin, so the row you are on reads at a glance instead of- // needing the eye to travel to the end of it. `aria-current` carries the- // same fact for anything that cannot see the fill.+ // The active workspace is filled and ticked, so the row you are on reads+ // at a glance. `aria-current` carries the same fact for anything that+ // cannot see either.aria-current={isActive ? 'true' : undefined}- className={cn('pl-9', isActive && 'bg-[var(--sel)]')}+ className={cn(isActive && 'bg-[var(--sel)]')}disabled={unavailable !== null}title={unavailable ? UNAVAILABLE_REASON[unavailable](workspace.name) : undefined}onClick={() => {@@ -536,12 +778,16 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({});}}>- <span className="min-w-0 flex-1 truncate text-sm text-foreground">{workspace.name}</span>- {(unavailable || workspace.role) && (+ <WorkspaceAvatar name={workspace.name} size="sm" active={isActive} />+ <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">+ {workspace.name}+ </span>+ {unavailable && (<span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {unavailable ? UNAVAILABLE_BADGE[unavailable] : workspace.role}+ {UNAVAILABLE_BADGE[unavailable]}</span>)}+ {isActive && <Check className="size-4 shrink-0 text-foreground" />}</DropdownMenuItem>);});@@ -573,28 +819,6 @@ function PendingInvitationCountBadge({ serverId }: { serverId: string }) {);}-/**- * Invitations addressed to you on one server, under its workspaces. Choosing- * one accepts it and opens the workspace it joins.- *- * A server too old to list them shows nothing, since it cannot say whether- * there are any; a server that failed to answer says so, since then there may- * be.- */-function PendingInvitationItems({ server }: { server: SwitchServer }) {- const query = usePendingInvitations(server.id);- if (query.isError) {- return (- <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">- Could not check for invitations to your address.- </div>- );- }- return listedInvitations(query.data).map((invitation) => (- <PendingInvitationMenuItem key={invitation.id} invitation={invitation} server={server} />- ));-}-function PendingInvitationMenuItem({invitation,server,@@ -608,7 +832,6 @@ function PendingInvitationMenuItem({return (<DropdownMenuItem- className="pl-9"title={invitationSummary(invitation)}data-testid="pending-invitation-item"onClick={() => {@@ -628,7 +851,8 @@ function PendingInvitationMenuItem({);}}>- <span className="min-w-0 flex-1 truncate text-sm text-foreground">+ <WorkspaceAvatar name={invitation.workspaceName} size="sm" />+ <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">{invitation.workspaceName}</span><InvitedBadge />@@ -636,24 +860,6 @@ function PendingInvitationMenuItem({);}-/**- * Workspaces open to the domain of your address on one server, after its- * invitations, on the same terms. Choosing one joins it as a member.- */-function JoinableWorkspaceItems({ server }: { server: SwitchServer }) {- const query = useJoinableWorkspaces(server.id);- if (query.isError) {- return (- <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">- Could not check for workspaces open to your e-mail domain.- </div>- );- }- return listedJoinable(query.data).map((offer) => (- <JoinableWorkspaceMenuItem key={offer.tenantId} offer={offer} server={server} />- ));-}-function JoinableWorkspaceMenuItem({offer,server,@@ -667,7 +873,6 @@ function JoinableWorkspaceMenuItem({return (<DropdownMenuItem- className="pl-9"title={joinableSummary(offer)}data-testid="joinable-workspace-item"onClick={() => {@@ -687,7 +892,10 @@ function JoinableWorkspaceMenuItem({);}}>- <span className="min-w-0 flex-1 truncate text-sm text-foreground">{offer.workspaceName}</span>+ <WorkspaceAvatar name={offer.workspaceName} size="sm" />+ <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">+ {offer.workspaceName}+ </span><span className="shrink-0 text-xs font-medium text-foreground-muted">Join</span></DropdownMenuItem>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsxnew file mode 100644index 000000000..10c26c24a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx@@ -0,0 +1,34 @@+import { cn } from '@renderer/utils/utils';++const SIZE = {+ sm: 'size-5 rounded-md text-[10px]',+ md: 'size-[26px] rounded-md text-xs',+ lg: 'size-9 rounded-lg text-lg',+} as const;++/** A workspace's initial in a square, the way a server's avatar shows a server. */+export function WorkspaceAvatar({+ name,+ size,+ active = false,+}: {+ name: string;+ size: keyof typeof SIZE;+ active?: boolean;+}) {+ // Drawn from an attribute rather than as text, so the letter is not read out+ // or counted as part of the row's name.+ return (+ <span+ aria-hidden+ data-initial={name.trim().charAt(0).toUpperCase() || '?'}+ className={cn(+ 'flex shrink-0 items-center justify-center font-semibold before:content-[attr(data-initial)]',+ SIZE[size],+ active+ ? 'bg-[var(--accent-solid)] text-white'+ : 'bg-background-tertiary text-foreground-muted'+ )}+ />+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.tsnew file mode 100644index 000000000..893d46707--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.ts@@ -0,0 +1,55 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';++const state = vi.hoisted(() => ({+ inScope: null as Workspace | null,+ noMembership: false,+}));++vi.mock('./workspaces-store', () => ({+ workspacesStore: {+ onServerInScope: () => state.inScope,+ hasNoMembership: () => state.noMembership,+ },+}));++const { workspaceTitle } = await import('./workspace-title');++const server = { id: 'srv-1', name: 'Switch Cloud' } as SwitchServer;++function workspace(name: string, tenantId: string | null): Workspace {+ return {+ id: 'ws-1',+ serverId: 'srv-1',+ name,+ tenantId,+ slug: null,+ role: null,+ createdAt: '',+ updatedAt: '',+ };+}++beforeEach(() => {+ state.inScope = null;+ state.noMembership = false;+});++describe('what a server page is titled', () => {+ it("is the workspace's name once it is matched", () => {+ state.inScope = workspace('SandboxAQ', 't-1');+ expect(workspaceTitle(server)).toBe('SandboxAQ');+ });++ it("is the server's name for the placeholder before sign-in", () => {+ state.inScope = workspace('Switch Cloud', null);+ expect(workspaceTitle(server)).toBe('Switch Cloud');+ });++ it('says there is no workspace when the account belongs to none', () => {+ state.inScope = workspace('Switch Cloud', null);+ state.noMembership = true;+ expect(workspaceTitle(server)).toBe('No workspace yet');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.tsnew file mode 100644index 000000000..15e20f478--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.ts@@ -0,0 +1,17 @@+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { workspacesStore } from './workspaces-store';++/**+ * What a page about a server's workspace is called: the workspace's own name.+ *+ * Before sign-in has matched the server's first workspace to one on the+ * server, there is no workspace name to give — the row is only a placeholder+ * named after the server — so the server's name stands in. Signed in to an+ * account that belongs to no workspace, it says so instead.+ */+export function workspaceTitle(server: SwitchServer): string {+ const workspace = workspacesStore.onServerInScope(server.id);+ if (!workspace) return server.name;+ if (workspace.tenantId !== null) return workspace.name;+ return workspacesStore.hasNoMembership(server.id) ? 'No workspace yet' : server.name;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.tsindex 59f9e3163..86ca0077c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts@@ -4,6 +4,7 @@ import type { Workspace } from '@shared/core/workspaces/workspaces';const list = vi.hoisted(() => vi.fn());const getActiveId = vi.hoisted(() => vi.fn());const setActive = vi.hoisted(() => vi.fn());+const serversWithoutMembership = vi.hoisted(() => vi.fn(async () => [] as string[]));const subscribers = vi.hoisted(() => new Map<string, (data: unknown) => void>());vi.mock('@renderer/lib/ipc', () => ({@@ -13,7 +14,7 @@ vi.mock('@renderer/lib/ipc', () => ({return () => subscribers.delete(event.name);},},- rpc: { workspaces: { list, getActiveId, setActive } },+ rpc: { workspaces: { list, getActiveId, setActive, serversWithoutMembership } },}));const { WorkspacesStore } = await import('./workspaces-store');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 ff6870192..c0dac6d8b 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@@ -22,6 +22,8 @@ import type { Workspace } from '@shared/core/workspaces/workspaces';export class WorkspacesStore {workspaces: Workspace[] = [];activeId: string | null = null;+ /** Servers where the signed-in account belongs to no workspace yet, as the main process last found. */+ serversWithoutMembership: string[] = [];/** Ordinal of the most recent {@link setActive}; nothing renders it. */lastSwitch = 0;@@ -133,13 +135,15 @@ export class WorkspacesStore {}async refresh(): Promise<void> {- const [workspaces, activeId] = await Promise.all([+ const [workspaces, activeId, serversWithoutMembership] = await Promise.all([rpc.workspaces.list(),rpc.workspaces.getActiveId(),+ rpc.workspaces.serversWithoutMembership(),]);runInAction(() => {this.workspaces = workspaces;this.activeId = activeId;+ this.serversWithoutMembership = serversWithoutMembership;});}@@ -152,6 +156,11 @@ export class WorkspacesStore {return this.byId(workspaceId)?.serverId ?? null;}+ /** Whether this server's signed-in account was found to belong to no workspace. */+ hasNoMembership(serverId: string): boolean {+ return this.serversWithoutMembership.includes(serverId);+ }+onServer(serverId: string): Workspace[] {return this.workspaces.filter((w) => w.serverId === serverId);}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/dev-tools.ts b/console/apps/switch-console-desktop/src/renderer/lib/dev-tools.tsnew file mode 100644index 000000000..956ab0b5b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/dev-tools.ts@@ -0,0 +1,9 @@+import { IS_CANARY } from '@shared/app-identity';++/**+ * Whether this build shows tools meant for the people building Switch: a run+ * from a checkout, or a canary. Never a stable release.+ */+export function showDevTools(): boolean {+ return import.meta.env.DEV || IS_CANARY;+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/replay-onboarding-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/replay-onboarding-row.test.tsxnew file mode 100644index 000000000..9d0dc59b6--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/replay-onboarding-row.test.tsx@@ -0,0 +1,71 @@+/**+ * The settings row that opens the first-run pages again. It exists for the+ * people building Switch, so a stable build must not show it at all.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ devTools: true, navigate: vi.fn() }));++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/dev-tools', () => ({ showDevTools: () => state.devTools }));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate: state.navigate }),+}));++import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';+import { ReplayOnboardingRow } from '@renderer/features/settings/components/ReplayOnboardingRow';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++async function render(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(<ReplayOnboardingRow />));+ return container;+}++beforeEach(() => {+ state.devTools = true;+ state.navigate.mockReset();+ onboardingStore.reset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+ onboardingStore.reset();+});++describe('the replay first-run pages row', () => {+ it('is not there on a stable build', async () => {+ state.devTools = false;+ const el = await render();++ expect(el.textContent).toBe('');+ });++ it('opens the first-run pages from the start and leaves Settings', async () => {+ const el = await render();+ const replay = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Replay');++ await act(async () => replay!.click());++ expect(onboardingStore.rehearsal).toBe(true);+ expect(onboardingStore.page).toBe('welcome');+ expect(state.navigate).toHaveBeenCalledWith('home');+ });+});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.tsxindex d2076ba7d..fbf6ae8ca 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@@ -39,12 +39,17 @@ afterEach(async () => {root = null;});-async function renderPage(cloud: WelcomeCloud = { kind: 'closed' }): Promise<HTMLDivElement> {+async function renderPage(+ cloud: WelcomeCloud = { kind: 'closed' },+ onLeave: (() => void) | null = null+): Promise<HTMLDivElement> {container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);await act(async () =>- root!.render(<WelcomePage cloud={cloud} onContinue={onContinue} onInvite={onInvite} />)+ root!.render(+ <WelcomePage cloud={cloud} onContinue={onContinue} onInvite={onInvite} onLeave={onLeave} />+ ));return container;}@@ -202,3 +207,21 @@ describe('the welcome page when the Cloud setting is broken', () => {).toBe(false);});});++describe('the welcome page opened again from a build with servers', () => {+ it('offers no way back on a fresh install, where there is no app to go back to', async () => {+ const el = await renderPage();++ expect(() => button(el, 'Back to the app')).toThrow();+ });++ it('offers a way back to the app when replayed', async () => {+ const onLeave = vi.fn();+ const el = await renderPage({ kind: 'closed' }, onLeave);++ await act(async () => button(el, 'Back to the app').click());++ expect(onLeave).toHaveBeenCalledOnce();+ expect(onContinue).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsxindex 72a2d723c..9e7d607a1 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx@@ -27,6 +27,7 @@ const state = vi.hoisted(() => ({navigate: vi.fn(),toast: vi.fn(),unavailable: new Set<string>(),+ noMembership: new Set<string>(),listPendingInvitations: vi.fn(),acceptPendingInvitation: vi.fn(),listJoinableWorkspaces: vi.fn(),@@ -78,6 +79,7 @@ vi.mock('@renderer/features/workspaces/workspaces-store', () => ({return state.workspaces.find((w) => w.id === state.activeId) ?? null;},onServer: (serverId: string) => state.workspaces.filter((w) => w.serverId === serverId),+ hasNoMembership: (serverId: string) => state.noMembership.has(serverId),setActive: state.setActive,acceptPendingInvitation: state.acceptPendingInvitation,joinByDomain: state.joinByDomain,@@ -198,7 +200,7 @@ async function settle(): Promise<void> {/** The menu row offering a workspace, by the name shown on it. */function row(name: string): HTMLElement {const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>- item.textContent?.startsWith(name)+ item.querySelector('[data-row-name]')?.textContent?.startsWith(name));expect(found, `no row for ${name}`).toBeDefined();return found!;@@ -210,6 +212,7 @@ beforeEach(() => {state.navigate.mockReset();state.toast.mockReset();state.unavailable.clear();+ state.noMembership.clear();state.listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });state.acceptPendingInvitation.mockReset();state.listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });@@ -239,7 +242,7 @@ describe('the workspaces the switcher offers', () => {// The first span on a row is its name; a second one, where there is one,// is the role or the reason it cannot be opened.[...group.querySelectorAll('[role="menuitem"]')].map(- (item) => item.querySelector('span')?.textContent+ (item) => item.querySelector('[data-row-name]')?.textContent),]);@@ -366,7 +369,7 @@ describe('inviting people from the switcher', () => {'ws-a');- expect(inviteItem()?.textContent).toBe('Invite people to ws-a');+ expect(inviteItem()?.textContent).toBe('Invite people to ws-a…');});it('is not offered to a member, whom the server would refuse', async () => {@@ -628,3 +631,137 @@ describe('the server switcher on a build without Switch Cloud', () => {expect(state.setActive).toHaveBeenCalledWith('ws-a');});});++describe('finding a workspace in the menu', () => {+ async function type(text: string): Promise<void> {+ const input = document.querySelector<HTMLInputElement>('input[aria-label="Find a workspace"]');+ expect(input, 'no search box').not.toBeNull();+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setValue.call(input, text);+ input!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ }++ function names(): (string | null | undefined)[] {+ return [...document.querySelectorAll('[role="menuitem"] [data-row-name]')].map(+ (el) => el.textContent+ );+ }++ it('narrows the list to the workspaces whose name matches', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('platform', 'srv-1'), workspace('docs', 'srv-1'), workspace('scratch', 'srv-2')],+ 'platform'+ );++ await type('doc');++ expect(names()).toEqual(['docs']);+ expect(document.body.textContent).not.toContain('Local dev');+ });++ it("keeps all of a server's workspaces when the server's name matches", async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('platform', 'srv-1'), workspace('docs', 'srv-1'), workspace('scratch', 'srv-2')],+ 'platform'+ );++ await type('acme');++ expect(names()).toEqual(['platform', 'docs']);+ });++ it('says so when nothing matches', async () => {+ await openSwitcher([server('srv-1', 'Acme')], [workspace('platform', 'srv-1')], 'platform');++ await type('zzz');++ expect(names()).toEqual([]);+ expect(document.body.textContent).toContain('No workspace or server matches');+ });+});++describe('the server headings', () => {+ it('marks the Switch Cloud server as official and names where the others are', async () => {+ await openSwitcher(+ [server('cloud', 'Switch Cloud'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'cloud'), workspace('ws-b', 'srv-2')],+ 'ws-a'+ );++ const labels = [...document.querySelectorAll('[data-slot="dropdown-menu-label"]')].map(+ (el) => el.textContent+ );+ expect(labels[0]).toContain('Official');+ expect(labels[1]).toContain('srv-2.example.invalid');+ expect(labels[1]).not.toContain('Official');+ });+});++describe('a server with no workspace to show yet', () => {+ function menuText(): string[] {+ return [...document.querySelectorAll('[role="menuitem"]')].map((el) => el.textContent ?? '');+ }++ it('offers Sign in… instead of a workspace named after a server you are signed out of', async () => {+ state.unavailable.add('cloud');+ await openSwitcher(+ [server('srv-1', 'Acme'), server('cloud', 'Switch Cloud')],+ [workspace('ws-a', 'srv-1'), { ...workspace('Switch Cloud', 'cloud', { tenantId: null }) }],+ 'ws-a'+ );++ expect(menuText()).toContain('Sign in…');+ expect(names()).not.toContain('Switch Cloud');++ const signIn = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (el) => el.textContent === 'Sign in…'+ );+ await act(async () => signIn!.click());+ expect(state.setActive).toHaveBeenCalledWith('Switch Cloud');+ expect(state.navigate).toHaveBeenCalledWith('server', { serverId: 'cloud' });+ });++ it('says there is no workspace yet when the account belongs to none', async () => {+ state.noMembership.add('cloud');+ await openSwitcher(+ [server('srv-1', 'Acme'), server('cloud', 'Switch Cloud')],+ [workspace('ws-a', 'srv-1'), workspace('Switch Cloud', 'cloud', { tenantId: null })],+ 'ws-a'+ );++ expect(document.body.textContent).toContain('No workspace yet');+ expect(menuText()).toContain('Create a workspace…');+ expect(names()).not.toContain('Switch Cloud');+ });++ it('names the button after the missing workspace while the placeholder is open', async () => {+ state.noMembership.add('cloud');+ state.servers = [server('cloud', 'Switch Cloud')];+ state.workspaces = [workspace('Switch Cloud', 'cloud', { tenantId: null })];+ state.activeId = 'Switch Cloud';+ 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}>+ <WorkspaceSwitcher />+ </QueryClientProvider>+ )+ );++ const trigger = container.querySelector('[aria-label="Switch workspace"]');+ expect(trigger?.textContent).toContain('No workspace yet');+ });+});++function names(): (string | null | undefined)[] {+ return [...document.querySelectorAll('[role="menuitem"] [data-row-name]')].map(+ (el) => el.textContent+ );+}