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
Visual design pass on Switch Console (CHOO-2164) (#232)
Louis Amaudruz333f0b33d9c6
diff --git a/console/apps/switch-console-desktop/src/main/app/window.ts b/console/apps/switch-console-desktop/src/main/app/window.tsindex 57fdcc5ff..7bb44e84a 100644--- a/console/apps/switch-console-desktop/src/main/app/window.ts+++ b/console/apps/switch-console-desktop/src/main/app/window.ts@@ -1,9 +1,11 @@import { join } from 'node:path';import { BrowserWindow } from 'electron';import appIcon from '@/assets/images/switch-console/icon-dock.png?asset';+import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { registerExternalLinkHandlers, registerGuestLinkHandlers } from '@main/utils/externalLinks';import { PRODUCT_NAME } from '@shared/app-identity';+import { appCommandNavigateChannel } from '@shared/events/appEvents';import { APP_ORIGIN } from './protocol';let mainWindow: BrowserWindow | null = null;@@ -34,6 +36,19 @@ export function createMainWindow(): BrowserWindow {titleBarStyle: 'hiddenInset',trafficLightPosition: { x: 10, y: 10 },acceptFirstMouse: true,+ // The sidebar is meant to read as a vibrancy material rather than a+ // painted panel, which means the desktop behind the window has to+ // show through it. Only the compositor can blur what is behind a+ // window — CSS `backdrop-filter` reaches no further than the page —+ // so the effect is the OS's and the renderer only tints it.+ //+ // A transparent `backgroundColor` is what stops Electron painting an+ // opaque sheet over the effect. The renderer must not repaint one+ // either: `index.html` keys its translucent material on the same+ // platform test this branch does.+ vibrancy: 'under-window',+ visualEffectState: 'active',+ backgroundColor: '#00000000',}: {}),show: false,@@ -55,6 +70,17 @@ export function createMainWindow(): BrowserWindow {mainWindow?.show();});+ // Windows delivers the mouse's back/forward buttons here rather than to the+ // page, so they have to be handed across; macOS and Linux give them to the+ // renderer as ordinary mouse events and never reach this.+ mainWindow.on('app-command', (_event, command) => {+ if (command === 'browser-backward') {+ events.emit(appCommandNavigateChannel, { direction: 'back' });+ } else if (command === 'browser-forward') {+ events.emit(appCommandNavigateChannel, { direction: 'forward' });+ }+ });+mainWindow.on('focus', () => {if (typeof mainWindow?.setWindowButtonVisibility === 'function') {mainWindow.setWindowButtonVisibility(true);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 5d10751af..626811743 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@@ -45,6 +45,7 @@ import type {RemoteBridge,RemoteBridgeType,RemoteExternalUser,+ RemoteRoomDetail,RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,@@ -54,6 +55,7 @@ import type {SwitchServer,UpdateBridgeParams,UpdateBridgeResult,+ UpdateRoomParams,UpdateServerParams,UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';@@ -67,6 +69,7 @@ import {addRoomAgents,agentExistsOnServer,deleteBridge,+ deleteRoom,fetchAddressingPolicy,fetchAgentDetail,fetchAgentRooms,@@ -78,6 +81,7 @@ import {fetchMe,fetchMyIdentities,fetchRoomAgentIds,+ fetchRoomDetail,fetchRoomGroups,fetchRoomRoles,fetchRooms,@@ -86,6 +90,7 @@ import {releaseBridgeIdentity,removeRoomAgent,updateAddressingPolicy,+ updateRoom,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';import { claimIdentityOnServer, searchDirectoryOnServer } from './identities';@@ -308,6 +313,21 @@ export const switchServersController = createRPCController({listRoomAgentIds: async (params: { serverId: string; roomId: string }): Promise<string[]> =>fetchRoomAgentIds(await requireServer(params.serverId), params.roomId),+ /** One room in full, for its configuration page. */+ getRoomDetail: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomDetail> =>+ fetchRoomDetail(await requireServer(params.serverId), params.roomId),++ /**+ * Change a room's own settings. Failures propagate as-is — a user without+ * write access to the room needs the gateway's refusal, not a saved-looking+ * field holding a value the server never took.+ */+ updateRoom: async (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>+ updateRoom(await requireReachableServer(params.serverId), params.roomId, {+ description: params.description,+ instructions: params.instructions,+ }),+/*** Add agents to a room. Failures propagate as-is: the caller shows the* gateway's own words (e.g. an agent whose server-side client is not running,@@ -328,6 +348,10 @@ export const switchServersController = createRPCController({}): Promise<void> =>removeRoomAgent(await requireReachableServer(params.serverId), params.roomId, params.agentId),+ /** Delete a room and everything in it. The gateway enforces who may. */+ deleteRoom: async (params: { serverId: string; roomId: string }): Promise<void> =>+ deleteRoom(await requireReachableServer(params.serverId), params.roomId),+listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>fetchRoomGroups(await requireServer(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 7ecd52ecf..c5c0d61f2 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@@ -17,6 +17,7 @@ import type {RemoteBridge,RemoteBridgeType,RemoteExternalUser,+ RemoteRoomDetail,RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,@@ -1046,18 +1047,63 @@ export async function fetchRooms(server: SwitchServer): Promise<RemoteRoomSummarreturn json.map(mapRoomSummary);}+/** The gateway `RoomDetail` wire shape — `RoomSummary` plus the fields only a+ * single-room read carries. */+type RoomDetailJson = RoomSummaryJson & {+ instructions?: string | null;+ agent_ids?: string[];+ connected_user_names?: string[];+};++function mapRoomDetail(r: RoomDetailJson): RemoteRoomDetail {+ return {+ ...mapRoomSummary(r),+ instructions: r.instructions ?? null,+ agentIds: r.agent_ids ?? [],+ connectedUserNames: r.connected_user_names ?? [],+ };+}++/** One room in full (`GET /rooms/{id}`) — what its configuration page reads. */+export async function fetchRoomDetail(+ server: SwitchServer,+ roomId: string+): Promise<RemoteRoomDetail> {+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}`, {+ authenticated: true,+ });+ return mapRoomDetail((await res.json()) as RoomDetailJson);+}+/**- * Switch agent ids that are members of a room (`GET /rooms/{id}`). One call for- * the whole room, rather than asking every candidate agent what it belongs to.- * Connecting to a room is only meaningful for an agent already in it, so this is- * what scopes the agent picker when starting a session from a room.+ * Switch agent ids that are members of a room. One call for the whole room,+ * rather than asking every candidate agent what it belongs to. Connecting to a+ * room is only meaningful for an agent already in it, so this is what scopes the+ * agent picker when starting a session from a room.*/export async function fetchRoomAgentIds(server: SwitchServer, roomId: string): Promise<string[]> {+ return (await fetchRoomDetail(server, roomId)).agentIds;+}++/**+ * Change a room's own settings (`PATCH /rooms/{id}`). Requires write access to+ * the room; the gateway returns the room as it now stands, so the caller reads+ * back what was actually stored rather than assuming its own input landed.+ *+ * A field left out is left alone. An empty string is a real value and clears the+ * field — that is how a description or a set of instructions is removed.+ */+export async function updateRoom(+ server: SwitchServer,+ roomId: string,+ changes: { description?: string; instructions?: string }+): Promise<RemoteRoomDetail> {const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}`, {authenticated: true,+ method: 'PATCH',+ body: changes,});- const json = (await res.json()) as { agent_ids?: string[] };- return json.agent_ids ?? [];+ return mapRoomDetail((await res.json()) as RoomDetailJson);}/**@@ -1094,6 +1140,21 @@ export async function removeRoomAgent();}+/**+ * Delete a room outright (`DELETE /rooms/{id}`), taking its history and its+ * bridged channel with it.+ *+ * The gateway decides who may: its owner, or an admin. Switch Console hides the+ * action from anyone else, but that is a courtesy — a refusal here is the+ * authoritative answer and is surfaced rather than swallowed.+ */+export async function deleteRoom(server: SwitchServer, roomId: string): Promise<void> {+ await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}`, {+ authenticated: true,+ method: 'DELETE',+ });+}+/*** Create a room on `server` (session-authed `POST /gateway/rooms`), owned by the* signed-in user. Provisioning stays entirely server-side — this is the samediff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex 8f90a698b..907badd86 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -7,6 +7,8 @@ import { CreateSessionModal } from '@renderer/features/sessions/create-session-mimport { DeleteSessionModal } from '@renderer/features/sessions/delete-session-modal';import { RenameSessionModal } from '@renderer/features/sessions/rename-session-modal';import { AddAgentsToRoomModal } from '@renderer/features/switch-rooms/AddAgentsToRoomModal';+import { AddAgentToRoomsModal } from '@renderer/features/switch-rooms/AddAgentToRoomsModal';+import { DeleteRoomModal } from '@renderer/features/switch-rooms/DeleteRoomModal';import { AddServerModal } from '@renderer/features/switch-servers/AddServerModal';import { AssignServerModal } from '@renderer/features/switch-servers/assign-server-modal';import { ClaimIdentityModal } from '@renderer/features/switch-servers/ClaimIdentityModal';@@ -46,7 +48,7 @@ export function createModal<TProps, TResult>(export const modalRegistry = {commandPaletteModal: createModal(CommandPaletteModal, { size: 'md' }),sessionModal: createModal(CreateSessionModal, { dismissOnOutsideClick: false }),- addAgentModal: createModal(AddAgentModal, { dismissOnOutsideClick: false }),+ addAgentModal: createModal(AddAgentModal, { size: 'lg', dismissOnOutsideClick: false }),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),resetAgentModal: createModal(ResetAgentModal, { size: 'sm' }),@@ -65,7 +67,7 @@ export const modalRegistry = {dismissOnOutsideClick: false,}),deleteServerModal: createModal(DeleteServerModal, { size: 'sm' }),- createRoomModal: createModal(CreateRoomModal, { size: 'md', dismissOnOutsideClick: false }),+ createRoomModal: createModal(CreateRoomModal, { size: 'lg', dismissOnOutsideClick: false }),connectMessagingAppModal: createModal(ConnectMessagingAppModal, {size: 'md',dismissOnOutsideClick: false,@@ -79,8 +81,17 @@ export const modalRegistry = {dismissOnOutsideClick: false,}),addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {- size: 'sm',+ // The room-side twin of `addAgentToRoomModal`, and sized to match: the two+ // do the same job from opposite ends and should not feel like two dialogs.+ size: 'lg',+ dismissOnOutsideClick: false,+ }),+ addAgentToRoomModal: createModal(AddAgentToRoomsModal, {+ // Wide enough for a searchable list and a grid of what you have picked —+ // this dialog browses a whole server's rooms, not just confirms one.+ size: 'lg',dismissOnOutsideClick: false,}),+ deleteRoomModal: createModal(DeleteRoomModal, { size: 'sm', dismissOnOutsideClick: false }),// oxlint-disable-next-line typescript/no-explicit-any} satisfies Record<string, ModalRegistryEntry<any, any>>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsxindex 272f013eb..b07f8c820 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx@@ -15,6 +15,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { REMOTE_HOSTS_QUERY_KEY } from '@renderer/features/remote-hosts/views/remote-hosts-view';import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';import { agentExpandKey } from '@renderer/features/sidebar/sidebar-store';+import { openRoom } from '@renderer/features/switch-rooms/open-room';import { serverIcon } from '@renderer/features/switch-servers/server-icon';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';@@ -25,7 +26,7 @@ import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';-import { scopeToLocationServer, scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';+import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';import { Shortcut } from '@renderer/lib/ui/shortcut';@@ -362,7 +363,7 @@ export function CommandPaletteModal({const handleNavigateToRoom = (item: SearchItem) => {handleClose();- void scopeToRoomServer(item.id).then(() => navigate('room', { roomId: item.id }));+ void openRoom(item.id);};const handleNavigateToServer = (item: SearchItem) => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex f72c13a40..840151020 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -1,12 +1,8 @@import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';import { useQuery } from '@tanstack/react-query';-import { CheckCircle2, CircleAlert } from 'lucide-react';+import { Monitor, Server } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import type {- AgentOnboardingError,- ModeData as AgentOnboardingModeData,-} from '@renderer/features/locations/stores/agent-onboarding-types';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';@@ -16,7 +12,6 @@ import {useRemoteHostReadiness,} from '@renderer/features/remote-hosts/host-readiness-notice';import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';-import type { ServerVerifyState } from '@renderer/features/switch-servers/agent-server-picker';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -46,23 +41,13 @@ import {} from '@renderer/lib/ui/select';import { log } from '@renderer/utils/logger';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';-import { getProvider } from '@shared/core/providers/agent-provider-registry';-import {- sameApiEndpoint,- type ProvisionAgentResult,-} from '@shared/core/switch-servers/switch-servers';-import { basenameFromAnyPath } from '@shared/path-name';+import { type ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';import { AgentAdvancedConfig } from './agent-advanced-config';import { AgentTypePicker } from './agent-type-picker';-import { ConfigureAgentPanel } from './configure-agent-panel';-import { PickExistingPanel } from './content';+import { AgentIdentityFields, AgentSettingsSection } from './configure-agent-panel';import { LaunchProfileConfig } from './launch-profile-config';+import { LocalDirectorySelector } from './local-directory-selector';import { useConfigureAgentForm, usePickMode } from './modes';-import {- type AdoptKind,- OnboardExistingPanel,- type OnboardableAgent,-} from './onboard-existing-panel';// Switch Console adds a Switch *agent* by pointing at a local directory that the// switch-connector `configure` skill has set up (its `.claude/settings.local.json`@@ -84,38 +69,30 @@ function canonicalDir(dir: string): string {export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocationModalProps) {const [submitState, setSubmitState] = useState<'idle' | 'creating'>('idle');- const [verifyState, setVerifyState] = useState<ServerVerifyState>('idle');const { navigate } = useNavigate();const { setCloseGuard } = useModalContext();const showAddServerModal = useShowModal('addServerModal');const pickState = usePickMode();- const configureForm = useConfigureAgentForm(pickState.path, false, pickState.providerId);+ const form = useConfigureAgentForm();// Run location: 'local' (default) or an onboarded remote host's SSH alias. A// remote agent runs its sessions on the host and needs a remote working dir.const [runHost, setRunHost] = useState<string>(LOCAL_RUN_LOCATION);- // `remoteRepoDir` is the *committed* remote working dir that drives discovery- // (SSH agent-detect, agent defaults, subagent scan). `remoteRepoDirDraft` is- // the raw text field. They are split so typing does not refire those queries- // on every keystroke — discovery runs only when the user commits the dir- // (the "Set location" button or Enter). See CHOO-1440.+ // Typed directly, with no commit step: it used to need one because committing+ // fired the directory scans, and there are none left to fire.const [remoteRepoDir, setRemoteRepoDir] = useState('');- const [remoteRepoDirDraft, setRemoteRepoDirDraft] = useState('');- // Configure form for onboarding a brand-new agent in the remote dir. Defaults- // (name/description) are derived from the remote dir just like a local agent.- const remoteConfigureForm = useConfigureAgentForm(- remoteRepoDir.trim(),- true,- pickState.providerId- );const { data: remoteHosts } = useQuery({queryKey: ['remote-hosts'],queryFn: () => rpc.remoteHosts.listHosts(),});const onboardedHosts = useMemo(() => remoteHosts ?? [], [remoteHosts]);const isRemoteRun = runHost !== LOCAL_RUN_LOCATION;- const remoteRunValid = !isRemoteRun || remoteRepoDir.trim().length > 0;+ // The trigger has to say the host's name, not the value behind it: the value+ // for this machine is the sentinel "local", which is not what it is called.+ const runLocationLabel = isRemoteRun+ ? (onboardedHosts.find((h) => h.sshHost === runHost)?.name ?? runHost)+ : 'This computer';// An agent always binds to the active (scoped) server — the user does not pick// one here. Ensure the server list + active id are loaded when the modal opens@@ -174,13 +151,21 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc// Codex left Codex selected, and the form went on looking valid for a choice// the new machine cannot honour. Clearing it sends the picker back through// its own availability check for the host now selected.+ //+ // The name and description are not among them: they describe the agent, not+ // the machine, and clearing them threw away typed text on the way to a+ // second thought about where to run it.const { setProviderId } = pickState;useEffect(() => {setRemoteRepoDir('');- setRemoteRepoDirDraft('');setProviderId(null);}, [runHost, setProviderId]);+ const { suggestAutoApprove } = form;+ useEffect(() => {+ suggestAutoApprove(isRemoteRun);+ }, [isRemoteRun, suggestAutoApprove]);+// Advanced definition attributes (model, effort, tools, system prompt, …) the// user set in the collapsed Advanced section. Held in a ref (not state) so the// section can report changes without re-rendering the modal.@@ -197,215 +182,9 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoclaunchProfileConfigRef.current = config;}, []);- const shouldCheckPathStatus = !isRemoteRun && pickState.path.trim().length > 0;- const pathStatusQuery = useQuery({- queryKey: ['locationPathStatus', 'local', pickState.path],- queryFn: () => rpc.locations.inspectLocationPath({ path: pickState.path }),- enabled: shouldCheckPathStatus,- });-- // Remote agents have no local directory — detect + verify the Switch agent in- // the remote working dir over SSH instead of inspecting a local path.- const trimmedRemoteDir = remoteRepoDir.trim();- const shouldDetectRemote = isRemoteRun && trimmedRemoteDir.length > 0;- const remoteAgentQuery = useQuery({- queryKey: ['remoteAgentDetect', runHost, trimmedRemoteDir],- queryFn: () =>- rpc.remoteHosts.detectRemoteAgent({ sshHost: runHost, remoteRepoDir: trimmedRemoteDir }),- enabled: shouldDetectRemote,- });-- // Provider agents defined in the picked dir (`.claude/agents/*.md`) — both those- // already set up for Switch and plain provider subagents a user created directly.- // The modal suggests onboarding them alongside the create flow; a directory is a- // flat container of agents (CHOO-1440). Works for local and remote dirs.- const discoverDir = isRemoteRun ? trimmedRemoteDir : pickState.path;- const discoverSshHost = isRemoteRun ? runHost : null;- const discoverQuery = useQuery({- queryKey: [- 'discoverLocationAgents',- discoverSshHost ?? 'local',- discoverDir,- pickState.providerId,- pickState.serverId,- ],- queryFn: () =>- rpc.agents.discoverLocationAgents({- sshHost: discoverSshHost,- dir: discoverDir,- providerId: pickState.providerId!,- serverId: pickState.serverId!,- }),- enabled: !!pickState.providerId && !!pickState.serverId && discoverDir.trim().length > 0,- });- // Agents already configured in the directory, found by their provider-neutral- // Switch credentials rather than by any provider's definition format. This is- // what an agent someone else set up on a shared host looks like, and the only- // way a provider with no definition concept (Codex) is visible at all- // (CHOO-1937). The scan itself is provider-agnostic; it still waits on the type- // picker because nothing below the directory is shown until a type is chosen, so- // scanning earlier would be work (an SSH round trip, for a remote dir) whose- // result cannot be displayed.- const configuredQuery = useQuery({- queryKey: [- 'discoverConfiguredAgents',- discoverSshHost ?? 'local',- discoverDir,- pickState.serverId,- ],- queryFn: () =>- rpc.agents.discoverConfiguredAgents({- sshHost: discoverSshHost,- dir: discoverDir,- serverId: pickState.serverId!,- }),- enabled: !!pickState.providerId && !!pickState.serverId && discoverDir.trim().length > 0,- });-- // Definitions that can join Switch and Switch Console hasn't already onboarded — the- // ones worth offering. Already-onboarded ones (on THIS client) are excluded so- // the modal never offers to re-add a row it already has; ones registered on the- // gateway by another client are still offered (imported, not re-minted). CHOO-1440.- const definitionAgents = (discoverQuery.data ?? []).filter((a) => a.eligible && !a.alreadyAgent);- const definitionNames = new Set(definitionAgents.map((a) => a.name));- // Credentials-only agents: those the definition scan does not already cover.- // A definition WITH credentials is left to the onboard path, which reuses its- // identity too — listing it twice would offer one agent as two rows.- const attachableAgents = (configuredQuery.data ?? []).filter(- (a) => !a.alreadyAgent && !definitionNames.has(a.name)- );- // An identity belongs to the server that issued it, so importing one into a- // different server is not a thing that can happen: the onboard path would find- // the id absent here, mint a replacement, and write it over the credentials the- // other server's agent runs on. Say who it belongs to and leave it alone — the- // way in is to create a new agent (CHOO-2044).- const foreignCredentialReason = (endpoint: string | null): string | null => {- if (endpoint === null || !targetServer) return null;- if (sameApiEndpoint(endpoint, targetServer.apiUrl)) return null;- // Name the server when this switchdash has it registered. The raw endpoint is- // an implementation detail to the person reading the row, and for a server- // they have registered it is one they already know by name.- const owner = switchServersStore.servers.find((s) => sameApiEndpoint(s.apiUrl, endpoint));- return `Already registered with ${owner ? owner.name : 'another Switch server'}, so it cannot be imported into ${targetServer.name}. Create a new agent instead.`;- };-- const onboardableAgents: OnboardableAgent[] = [- ...definitionAgents.map((a) => ({- name: a.name,- description: a.description,- kind: (a.registered ? 'import' : 'adopt') as AdoptKind,- providerLabel: null,- blockedReason: foreignCredentialReason(a.credentialEndpoint),- })),- ...attachableAgents.map((a) => {- const providerId = a.providerId ?? pickState.providerId ?? null;- const providerLabel = providerId ? (getProvider(providerId)?.name ?? providerId) : null;- return {- name: a.name,- description: null,- kind: 'attach' as AdoptKind,- providerLabel,- blockedReason:- providerLabel === null- ? 'Pick an agent type above to attach this one — the directory does not say which runs it.'- : null,- };- }),- ];- // Onboarding needs both halves of the question answered: which directory, and- // which agent type the agents brought in will run under. With no type picked- // there is nothing to offer — every row would be unactionable — so the list and- // its button stay away and the modal asks for the type instead. Derived in one- // place so the footer button and the list it submits cannot disagree.- const hasOnboardable = !!pickState.providerId && onboardableAgents.length > 0;- /** Rows that cannot be brought in — listed with their reason, never selectable. */- const blockedNames = new Set(- onboardableAgents.filter((a) => a.blockedReason !== null).map((a) => a.name)- );- /** Attachable rows keyed by name, with the provider resolved for submission. */- const attachByName = new Map(- attachableAgents.flatMap((a) => {- const providerId = a.providerId ?? pickState.providerId ?? null;- return providerId ? [[a.name, providerId] as const] : [];- })- );+ const trimmedRemoteDir = canonicalDir(remoteRepoDir);+ const dir = isRemoteRun ? trimmedRemoteDir : pickState.path;- // Branch the flow when a directory has onboardable definitions: `createMode`- // false shows the multi-select adopt list; true reveals the create form. When- // there is nothing to onboard, the create form always shows. `selectedNames`- // are the checked definitions to onboard (default: all).- const [createMode, setCreateMode] = useState(false);- const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());- // Default-select only what can actually be submitted: a blocked row (unknown- // provider, or an identity belonging to another server) is disabled, and- // pre-checking it would just block the button with no visible cause. Resolving- // the block changes this key and folds the row into the selection.- const onboardableKey = onboardableAgents- .filter((a) => a.blockedReason === null)- .map((a) => a.name)- .join('|');- useEffect(() => {- setSelectedNames(new Set(onboardableKey ? onboardableKey.split('|') : []));- setCreateMode(false);- }, [onboardableKey]);- const showCreate = !hasOnboardable || createMode;- const toggleSelected = useCallback((name: string, checked: boolean) => {- setSelectedNames((prev) => {- const next = new Set(prev);- if (checked) next.add(name);- else next.delete(name);- return next;- });- }, []);-- const inspection = pathStatusQuery.data;- // Discovery (`.claude/agents` scan) is a separate query from agent-detection;- // fold its pending state into `isChecking` so the modal decides "onboard- // existing vs create new" only once BOTH have settled — otherwise the create- // form flashes up first and then flips to the onboard list when discovery lands- // (CHOO-1440).- const scanTargetChosen = !!pickState.serverId && discoverDir.trim().length > 0;- const isDiscovering =- (!!pickState.providerId && scanTargetChosen && discoverQuery.isPending) ||- (scanTargetChosen && configuredQuery.isPending);- const isChecking =- (isRemoteRun- ? shouldDetectRemote && remoteAgentQuery.isPending- : shouldCheckPathStatus && pathStatusQuery.isPending) || isDiscovering;- const switchAgent = isRemoteRun- ? (remoteAgentQuery.data ?? null)- : (inspection?.switchAgent ?? null);- // A local directory with no legacy Switch agent config offers the create flow.- // This is available even when the directory already contains other agents — a- // directory is a flat container, so you can always add another (CHOO-1440);- // onboarding pre-existing definitions is offered alongside it (see below).- const isMissingSwitchAgent = !isRemoteRun && !isChecking && shouldCheckPathStatus && !switchAgent;- // A remote dir with no Switch agent offers the remote configure flow: register- // the agent on the server and write its creds into the remote dir over SSH.- const isMissingRemoteAgent = isRemoteRun && !isChecking && shouldDetectRemote && !switchAgent;-- // An agent always binds to the active Switch server, so there is no server- // picker. Silently verify the detected agent exists on that server to gate- // submission (this replaces the former inline "Switch server" picker).- const verifyQuery = useQuery({- queryKey: ['verifyAgent', pickState.serverId, switchAgent?.agentId],- queryFn: async (): Promise<ServerVerifyState> => {- const serverId = pickState.serverId;- if (!serverId || !switchAgent) return 'idle';- return rpc.switchServers.verifyAgent({ serverId, agentId: switchAgent.agentId });- },- enabled: !!pickState.serverId && !!switchAgent,- });- useEffect(() => {- setVerifyState(verifyQuery.data ?? 'idle');- }, [verifyQuery.data]);-- // Detected flow: the agent already exists; we can add it once the chosen- // server confirms it owns the agent. Configure flow: no agent yet — gate on a- // valid form + a chosen server, then register before adding.- // Remote submit gate: a provider, a remote dir, a detected agent, and a- // verified server. Name defaults from the remote dir basename (see below), so- // it is not separately gated. Local submit keeps the existing pick validity.// Never create an agent on a host we know we cannot reach — it would be born// into the failing state this ticket exists to surface (CHOO-1676).const runHostReachable = !isRemoteRun || !hostReachabilityStore.isBlocked(runHost);@@ -421,83 +200,21 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst runHostReady = !isRemoteRun || (!hostReadiness.blocked && !hostReadiness.checking);// Where the block stops the flow. A host missing its own prerequisites cannot- // run anything, so nothing below the location picker is worth filling in —- // the same rule reachability already follows. A host that is fine but lacks- // one agent CLI blocks only the parts that commit to that type, so the type- // picker stays live and you can pick one the host already has.+ // run anything, so nothing below the location picker is worth filling in.const hostLevelBlocked = isRemoteRun && hostReadiness.blocked && hostReadiness.scope === 'host';const canChooseAgentType = runHostReachable && !hostLevelBlocked;const canConfigureAgent = canChooseAgentType && runHostReady;- // The agent type is the next gate after the host, and it gates everything below- // the directory: which agents in the directory can be brought in, and how a new- // one is created, both depend on it. Filling in a name, a description and a- // config for an agent that has no type yet is answering questions out of order —- // the form cannot be submitted from there anyway (CHOO-2044).- const canDetailAgent = canConfigureAgent && !!pickState.providerId;- const canSubmitDetected = isRemoteRun- ? !!pickState.providerId &&- trimmedRemoteDir.length > 0 &&- !isChecking &&- !!switchAgent &&- verifyState === 'found' &&- runHostReachable &&- runHostReady &&- submitState === 'idle'- : pickState.isValid &&- !isChecking &&- !!switchAgent &&- verifyState === 'found' &&- submitState === 'idle';- const canSubmitConfigure =- isMissingSwitchAgent &&- !isChecking &&- configureForm.isValid &&- !policyHasDeadRule(configureForm.addressingPolicy) &&+ const canSubmit =+ form.isValid &&+ !policyHasDeadRule(form.addressingPolicy) &&!!pickState.serverId &&!!pickState.providerId &&- remoteRunValid &&+ dir.trim().length > 0 &&runHostReachable &&runHostReady &&submitState === 'idle';- // Remote configure gate: no agent in the remote dir yet — a valid remote- // configure form + a chosen server + a provider. The server is not verified- // here (the agent does not exist yet); it is verified after registration by- // the create path (createRemoteLocation).- const canSubmitConfigureRemote =- isMissingRemoteAgent &&- !isChecking &&- remoteConfigureForm.isValid &&- !policyHasDeadRule(remoteConfigureForm.addressingPolicy) &&- !!pickState.serverId &&- !!pickState.providerId &&- trimmedRemoteDir.length > 0 &&- runHostReachable &&- runHostReady &&- submitState === 'idle';-- const reportCreationError = (error: AgentOnboardingError) => {- if (error.type === 'switch-server-unauthenticated') {- toast({- title: `Sign in to ${error.serverName}`,- description: 'This agent belongs to a server you are not signed in to yet.',- variant: 'destructive',- });- navigate('server', { serverId: error.serverId });- return;- }- if (error.type === 'switch-agent-not-on-server') {- toast({- title: `Agent not on ${error.serverName}`,- description: 'This agent isn’t registered on the selected server. Pick another server.',- variant: 'destructive',- });- return;- }- log.error(error);- };-const finishWith = (locationId: string) => {setCloseGuard(false);setSubmitState('idle');@@ -505,72 +222,6 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocnavigate('location', { locationId });};- /** Run the shared create-location path with the current pick state. Returns the- * new/existing location id, or null when there is no chosen server. */- const startCreate = async (): Promise<string | null> => {- if (!pickState.serverId || !pickState.providerId) return null;- const id = crypto.randomUUID();- const data: AgentOnboardingModeData = isRemoteRun- ? {- mode: 'pick',- name: remoteConfigureForm.agentName.trim() || basenameFromAnyPath(trimmedRemoteDir),- path: undefined,- serverId: pickState.serverId,- providerId: pickState.providerId,- remote: { sshHost: runHost, dir: trimmedRemoteDir },- autoApprove: remoteConfigureForm.autoApprove,- }- : {- mode: 'pick',- name: pickState.name,- path: pickState.path,- serverId: pickState.serverId,- providerId: pickState.providerId,- remote: undefined,- autoApprove: configureForm.autoApprove,- };- // The new location mounts (leaving the always-shown "unregistered" state)- // before agentsStore re-fetches its agent, which would drop it out of the- // server-scoped sidebar. Seed the location→server mapping now so it stays- // visible, and refresh the agent list once creation succeeds.- agentsStore.noteLocationServer(id, pickState.serverId);- const result = await getLocationManagerStore().startAgentOnboarding(data, { id });- if (result.kind === 'existing') return result.locationId;- void result.completion- .then((completion) => {- if (completion.success) void agentsStore.load();- else reportCreationError(completion.error);- })- .catch((error) => {- log.error(error);- });- return result.locationId;- };-- const handleSubmit = async () => {- if (!canSubmitDetected) return;- setSubmitState('creating');- setCloseGuard(true);- try {- const locationId = await startCreate();- if (locationId) {- finishWith(locationId);- } else {- setCloseGuard(false);- setSubmitState('idle');- }- } catch (error) {- log.error(error);- setCloseGuard(false);- setSubmitState('idle');- toast({- title: 'Failed to add agent',- description: String(error),- variant: 'destructive',- });- }- };-const reportProvisionError = (result: ProvisionAgentResult) => {if (result.kind === 'unauthenticated' && pickState.serverId) {toast({@@ -606,7 +257,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc/** Create a brand-new flat agent in the chosen directory (local or remote):* mint its identity, write its `.claude/agents/<name>.md` definition + its* per-agent credentials, and create the row — all via `addAgent`. */- const createNewAgent = async (form: ReturnType<typeof useConfigureAgentForm>) => {+ const createNewAgent = async () => {if (!pickState.serverId || !pickState.providerId) return;setSubmitState('creating');setCloseGuard(true);@@ -650,173 +301,69 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}};- const handleConfigure = () => createNewAgent(configureForm);- const handleConfigureRemote = () => createNewAgent(remoteConfigureForm);-- /**- * Bring in the selected agents. Definitions go through the onboard path- * (importing a registered identity, minting one for a plain definition);- * credentials-only agents go through the attach path, which adopts the- * identity already on disk and writes nothing to the directory (CHOO-1937).- */- const handleOnboard = async () => {- // `canOnboard` already requires a server; repeated so the calls below narrow.- if (!canOnboard || !pickState.serverId) return;- // Blocked rows are disabled in the list, so a selected one means the list went- // stale under the user. Dropping them here keeps a stale tick from reaching a- // path that would refuse it — or worse, act on it.- const submittable = [...selectedNames].filter((name) => !blockedNames.has(name));- const attachSelected = submittable.flatMap((name) => {- const providerId = attachByName.get(name);- return providerId ? [{ name, providerId }] : [];- });- const onboardSelected = submittable.filter((name) => !attachByName.has(name));- if (onboardSelected.length > 0 && !pickState.providerId) return;- setSubmitState('creating');- setCloseGuard(true);- try {- const locationIds: string[] = [];- if (attachSelected.length > 0) {- const attached = await rpc.agents.attachConfiguredAgents({- sshHost: discoverSshHost,- dir: discoverDir,- serverId: pickState.serverId,- agents: attachSelected,- });- if (!attached.success) {- reportCreationError(attached.error);- setCloseGuard(false);- setSubmitState('idle');- return;- }- locationIds.push(...attached.data.map((a) => a.locationId));- }- if (onboardSelected.length === 0) {- await agentsStore.load();- await getLocationManagerStore().reload();- finishWith(locationIds[0]!);- return;- }- const result = await rpc.agents.onboardLocationAgents({- sshHost: discoverSshHost,- dir: discoverDir,- providerId: pickState.providerId!,- serverId: pickState.serverId,- names: onboardSelected,- });- if (!result.success) {- reportCreationError(result.error);- setCloseGuard(false);- setSubmitState('idle');- return;- }- // reload (not load) — the initial load is memoized, so a plain load() would- // no-op and the onboarded location wouldn't mount until a restart (CHOO-1440).- await agentsStore.load();- await getLocationManagerStore().reload();- finishWith(result.data[0].locationId);- } catch (error) {- log.error(error);- setCloseGuard(false);- setSubmitState('idle');- toast({- title: 'Failed to onboard agents',- description: String(error),- variant: 'destructive',- });- }- };-- const submittableNames = [...selectedNames].filter((name) => !blockedNames.has(name));- // A definition still needs the picked agent type to run under; an attach row- // carries its own (inferred from disk, or the picked one as a fallback).- const selectionNeedsProviderPick = submittableNames.some((name) => !attachByName.has(name));- // Adopting agents that already exist in the directory still puts them on this- // host, so it answers to the same gates as creating one. Omitting them here- // let you onboard onto a host that was unreachable or missing prerequisites.- const canOnboard =- hasOnboardable &&- submittableNames.length > 0 &&- !!pickState.serverId &&- (!selectionNeedsProviderPick || !!pickState.providerId) &&- runHostReachable &&- runHostReady &&- submitState === 'idle';- const submitLabel = submitState === 'creating' ? 'Adding...' : 'Add Agent';+ const handleCreate = () => createNewAgent();return (<ModalLayoutheader={<DialogHeader showCloseButton={submitState === 'idle'}>- <DialogTitle>Add Switch Agent</DialogTitle>+ <DialogTitle>New agent</DialogTitle></DialogHeader>}footer={<DialogFooter>- {/* The onboard list comes first, and deliberately outranks a detected- legacy agent. The body renders the list whenever there is something- to onboard, so a footer that branched on detection first put the- wrong button under it: a directory carrying another server's- `.claude/settings.local.json` showed the detected-agent button, which- then verified that foreign agent against this server, failed, and- stayed disabled forever — with the onboardable list visible above it- and no way to submit it (CHOO-2044). */}- {hasOnboardable && !createMode ? (- <ConfirmButton- type="button"- onClick={() => void handleOnboard()}- disabled={!canOnboard}- >- {submitState === 'creating' ? 'Adding...' : `Add ${submittableNames.length} selected`}- </ConfirmButton>- ) : switchAgent ? (- <ConfirmButton- type="button"- onClick={() => void handleSubmit()}- disabled={!canSubmitDetected}- >- {submitLabel}- </ConfirmButton>- ) : isMissingRemoteAgent ? (- <ConfirmButton- type="button"- onClick={() => void handleConfigureRemote()}- disabled={!canSubmitConfigureRemote}- >- {submitState === 'creating' ? 'Registering...' : 'Configure & Add Agent'}- </ConfirmButton>- ) : isMissingSwitchAgent ? (- <ConfirmButton- type="button"- onClick={() => void handleConfigure()}- disabled={!canSubmitConfigure}- >- {submitState === 'creating' ? 'Registering...' : 'Configure & Add Agent'}- </ConfirmButton>- ) : (- <ConfirmButton- type="button"- onClick={() => void handleSubmit()}- disabled={!canSubmitDetected}- >- {submitLabel}- </ConfirmButton>+ {/* Why Add agent is greyed out, said where the greyed-out button is.+ Left alone, a disabled primary with no explanation beside it is+ indistinguishable from a broken one. */}+ {isRemoteRun && hostReadiness.checking && (+ <span className="mr-auto self-center text-xs text-foreground-muted">+ Waiting for {runLocationLabel}…+ </span>)}+ <Button+ type="button"+ variant="outline"+ onClick={onClose}+ disabled={submitState !== 'idle'}+ >+ Cancel+ </Button>+ <ConfirmButton type="button" onClick={() => void handleCreate()} disabled={!canSubmit}>+ {submitState === 'creating' ? 'Adding…' : 'Add agent'}+ </ConfirmButton></DialogFooter>}><DialogContentArea data-autofocus tabIndex={-1} className="max-h-[calc(100dvh-13rem)] gap-4">+ <AgentIdentityFields form={form} />+<Field><FieldLabel>Run location</FieldLabel>+ {/* Icons and the right-hand kind, because the list mixes two sorts of+ thing: this machine, and hosts reached over SSH. The names alone+ do not say which is which. */}<Select value={runHost} onValueChange={(v) => setRunHost(v ?? LOCAL_RUN_LOCATION)}>- <SelectTrigger>- <SelectValue />+ <SelectTrigger className="w-full">+ <SelectValue>+ {isRemoteRun ? (+ <Server className="size-4 text-foreground-muted" />+ ) : (+ <Monitor className="size-4 text-foreground-muted" />+ )}+ <span className="truncate">{runLocationLabel}</span>+ </SelectValue></SelectTrigger><SelectContent>- <SelectItem value={LOCAL_RUN_LOCATION}>Local (this machine)</SelectItem>+ <SelectItem value={LOCAL_RUN_LOCATION}>+ <Monitor className="size-4 text-foreground-muted" />+ <span className="flex-1">This computer</span>+ <span className="text-xs text-foreground-muted">local</span>+ </SelectItem>{allowedHosts.map((host) => (<SelectItem key={host.sshHost} value={host.sshHost}>- {host.name} ({host.sshHost})+ <Server className="size-4 text-foreground-muted" />+ <span className="flex-1 truncate">{host.name}</span>+ <span className="text-xs text-foreground-muted">ssh</span></SelectItem>))}</SelectContent>@@ -829,182 +376,80 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc</p>)}{isRemoteRun && <HostReachabilityNotice sshHost={runHost} />}- {isRemoteRun && runHostReachable && (+ {/* Not while it is still checking: the provider picker below is+ already saying so, and two spinners for one question read as two+ questions. Its verdict — the part only it can report — still+ lands here. */}+ {isRemoteRun && runHostReachable && !hostReadiness.checking && (<HostReadinessNoticesshHost={runHost}readiness={hostReadiness}onNavigateAway={onClose}/>)}- {/* Not while we are still finding out what the host has: asking for a- working directory under a "checking…" spinner invites the user to- fill in a form we may be about to refuse. */}- {isRemoteRun && canChooseAgentType && !hostReadiness.checking && (- <div className="flex items-center gap-2">+ </Field>++ {/* The host still gates what comes below it: with it unreachable, or+ missing its own prerequisites, we cannot know which providers it+ has, so offering the tiles would be guessing. What no longer gates+ anything is the directory — nothing is scanned in it, so it can be+ filled in while the host is still being surveyed. */}+ {canChooseAgentType && (+ <Field>+ <FieldLabel>Directory</FieldLabel>+ {isRemoteRun ? (+ // No file picker for a host: the directory is on the other end of+ // an SSH connection, so it is typed rather than browsed.<Input- value={remoteRepoDirDraft}- placeholder="Remote working directory, e.g. /home/agent/repo"- onChange={(e) => setRemoteRepoDirDraft(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault();- setRemoteRepoDir(canonicalDir(remoteRepoDirDraft));- }- }}+ value={remoteRepoDir}+ placeholder="/home/agent/repo"+ onChange={(e) => setRemoteRepoDir(e.target.value)}/>- <Button- type="button"- variant="outline"- onClick={() => setRemoteRepoDir(canonicalDir(remoteRepoDirDraft))}- disabled={canonicalDir(remoteRepoDirDraft) === remoteRepoDir}- >- Set location- </Button>- </div>- )}- </Field>- {/* The host is the first gate: with it unreachable, or missing its own- prerequisites, we cannot know which agent types it has, so offering a- type picker (or a directory to scan) would be guessing. Everything- below waits for a usable host — and everything past the picker waits- for a type that host can actually run, rather than letting you fill- in a name and a config only to be refused at the last button. */}+ ) : (+ <LocalDirectorySelector+ title="Choose the agent's working directory"+ message="The agent runs its sessions here."+ path={pickState.path}+ onPathChange={pickState.handlePathChange}+ />+ )}+ </Field>+ )}+{canChooseAgentType && (<AgentTypePickervalue={pickState.providerId}onChange={pickState.setProviderId}sshHost={isRemoteRun ? runHost : undefined}+ onNavigateAway={onClose}/>)}- {canConfigureAgent && !isRemoteRun && (- <PickExistingPanel state={pickState} showName={canDetailAgent && !isMissingSwitchAgent} />- )}- {canDetailAgent && isChecking && (- <p className="text-sm text-foreground-muted">Scanning directory for agents…</p>- )}- {/* A directory chosen with no agent type is a half-answered question, and- nothing below can be acted on from there: the agents that could be- brought in need a type to run under, and so does a new one. Ask for the- type rather than showing a form and a list that cannot be submitted- (CHOO-2044). */}- {canConfigureAgent && !pickState.providerId && discoverDir.trim().length > 0 && (- <p className="text-sm text-foreground-muted">Pick an agent type above to continue.</p>- )}- {canDetailAgent && hasOnboardable && !createMode && (- <>- <OnboardExistingPanel- agents={onboardableAgents}- selected={selectedNames}- onToggle={toggleSelected}- />- <Button- type="button"- variant="outline"- className="self-start"- onClick={() => setCreateMode(true)}- >- Create a new agent instead- </Button>- </>- )}- {hasOnboardable && createMode && (- <Button- type="button"- variant="ghost"- size="sm"- className="self-start"- onClick={() => setCreateMode(false)}- >- ← Back to existing agents- </Button>- )}- {canDetailAgent && isMissingRemoteAgent && showCreate && (++ {canConfigureAgent && !!pickState.providerId && (<>- <ConfigureAgentPanel- form={remoteConfigureForm}- serverId={pickState.serverId}- onAddServer={() => showAddServerModal({})}- /><AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} /><LaunchProfileConfigproviderId={pickState.providerId}- sshHost={discoverSshHost}- dir={discoverDir}+ sshHost={isRemoteRun ? runHost : null}+ dir={dir}onChange={onLaunchProfileConfigChange}/></>)}- {canDetailAgent && switchAgent && (- <>- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">- <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-green-500" />- <span>- Switch agent detected- <span className="ml-1 font-mono text-foreground-tertiary-passive">- {switchAgent.agentId.slice(0, 8)}- </span>- </span>- </div>- {/* The detected agent belongs to whichever server its on-disk config- was written for, which need not be the one being added to. Saying- so is the difference between an explained dead end and a button- that is simply disabled for no stated reason (CHOO-2044). */}- {verifyState === 'not-found' && (- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <span>- The agent configured in this directory is not registered on- {targetServer ? ` ${targetServer.name}` : ' the active server'} — it belongs to a- different Switch server. Onboard one of this directory's agents instead, or- switch to the server it belongs to.- </span>- </div>- )}- {verifyState === 'unauthenticated' && (- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <span>- You are not signed in to- {targetServer ? ` ${targetServer.name}` : ' the active server'}, so this agent- cannot be verified.- </span>- </div>- )}- {switchServersStore.servers.length === 0 && (- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <div className="flex min-w-0 flex-1 flex-col gap-1.5">- <span>- No Switch servers are registered yet. Add the server this agent belongs to.- </span>- <Button- variant="outline"- size="sm"- className="self-start"- onClick={() => showAddServerModal({})}- >- Add a server- </Button>- </div>- </div>- )}- </>- )}- {canDetailAgent && isMissingSwitchAgent && showCreate && (- <>- <ConfigureAgentPanel- form={configureForm}- serverId={pickState.serverId}- onAddServer={() => showAddServerModal({})}- />- <AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} />- <LaunchProfileConfig- providerId={pickState.providerId}- sshHost={discoverSshHost}- dir={discoverDir}- onChange={onLaunchProfileConfigChange}- />- </>++ {/* Last, below Advanced configuration. Everything above it is a choice+ the agent cannot exist without; these have working defaults and are+ changeable afterwards from the agent's own settings. */}+ {canConfigureAgent && (+ <AgentSettingsSection+ form={form}+ serverId={pickState.serverId}+ onAddServer={() => showAddServerModal({})}+ onOpenMessagingApps={() => {+ onClose();+ if (pickState.serverId) navigate('server', { serverId: pickState.serverId });+ }}+ />)}</DialogContentArea></ModalLayout>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsxindex d749afa3f..a65f66967 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx@@ -1,10 +1,10 @@import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';import { useQuery } from '@tanstack/react-query';-import { ChevronRight } from 'lucide-react';import { useEffect, useMemo, useState } from 'react';import { rpc } from '@renderer/lib/ipc';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';-import { cn } from '@renderer/utils/utils';+import { getProvider } from '@shared/core/providers/agent-provider-registry';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import {advancedFields,@@ -37,6 +37,7 @@ export function AgentAdvancedConfig({});const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);+ const providerLabel = providerId ? (getProvider(providerId)?.name ?? providerId) : null;const [state, setState] = useState<FormState>({});// Reset the form (and reported attributes) whenever the provider's field set@@ -59,17 +60,19 @@ export function AgentAdvancedConfig({};return (- <div className="rounded-md border border-border">- <button- type="button"- className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"- onClick={() => setOpen((v) => !v)}- >- <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />- Advanced configuration- </button>+ <div>+ <DisclosureRow+ open={open}+ title="Advanced configuration"+ meta={+ providerLabel+ ? `${providerLabel} · ${fields.length} ${fields.length === 1 ? 'field' : 'fields'}`+ : undefined+ }+ onToggle={() => setOpen((v) => !v)}+ />{open && (- <div className="flex flex-col gap-4 border-t border-border px-3 py-3">+ <div className="flex flex-col gap-4 pt-3">{fields.map((field) => (<Field key={field.key}><FieldLabel htmlFor={`agent-advanced-${field.key}`}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsxindex 6aaa10f00..9331cd388 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx@@ -2,17 +2,12 @@ import { CircleAlert } from 'lucide-react';import { useEffect, useMemo } from 'react';import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useAgents } from '@renderer/lib/stores/use-agents';import { useAgentTypeAvailability } from '@renderer/lib/stores/use-switch-setup';import { Field, FieldLabel } from '@renderer/lib/ui/field';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';import { Spinner } from '@renderer/lib/ui/spinner';+import { cn } from '@renderer/utils/utils';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { autoSelectedAgentType } from './agent-type-auto-selection';@@ -31,11 +26,16 @@ export function AgentTypePicker({value,onChange,sshHost,+ onNavigateAway,}: {value: AgentProviderId | null;onChange: (providerId: AgentProviderId) => void;sshHost?: string;+ /** Called before leaving for the page that installs providers, so the modal+ * can close itself rather than being navigated out from under. */+ onNavigateAway: () => void;}) {+ const { navigate } = useNavigate();const { data: availability, isPending } = useAgentTypeAvailability(sshHost);const { data: agents } = useAgents();const { value: defaultAgent } = useAppSettingsKey('defaultAgent');@@ -93,57 +93,74 @@ export function AgentTypePicker({// Asking the host what it has costs SSH round trips, and an empty dropdown// during that reads as "this host offers nothing" rather than "still asking".+ // The placeholder tiles say the answer is a set of these, so the section does+ // not resize under the user when it arrives.if (isPending) {return (<Field>- <FieldLabel>Agent type</FieldLabel>- <div className="flex items-center gap-2 text-xs text-foreground-muted">+ <FieldLabel>Agent provider</FieldLabel>+ <div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner />{sshHost ? `Checking what ${sshHost} has installed…` : 'Checking what is installed…'}</div>+ <div aria-hidden className="grid grid-cols-3 gap-2">+ {[0, 1, 2].map((i) => (+ <div key={i} className="h-[86px] animate-pulse rounded-[11px] bg-[var(--fill)]" />+ ))}+ </div></Field>);}- const selected = options.find((o) => o.agent.id === value);-return (<Field>{emptyNotice}- <FieldLabel>Agent type</FieldLabel>- <Select value={value ?? undefined} onValueChange={(v) => v && onChange(v as AgentProviderId)}>- <SelectTrigger>- <SelectValue placeholder="Select an agent type">- {selected ? (- <span className="flex items-center gap-2">- <AgentIcon id={selected.agent.id} size={16} />- {selected.agent.name}- </span>- ) : undefined}- </SelectValue>- </SelectTrigger>- <SelectContent>- {/*- Types that cannot be used here are listed and disabled rather than- omitted. A missing row says nothing; a greyed one with its reason- says what to go and fix. Availability is per-machine, so a type the- user has locally can legitimately be absent on the host they picked.- */}- {options.map(({ agent, available, blockedReason }) => (- <SelectItem key={agent.id} value={agent.id} disabled={!available}>- <span className="flex items-center gap-2">- <AgentIcon id={agent.id} size={16} />- {agent.name}- {!available && (- <span className="text-xs text-foreground-muted">- — {blockedReason ?? 'Not available here.'}- </span>- )}- </span>- </SelectItem>- ))}- </SelectContent>- </Select>+ <FieldLabel>Agent provider</FieldLabel>+ {/*+ Types that cannot be used here are listed and disabled rather than+ omitted. A missing tile says nothing; a dimmed one with its reason+ says what to go and fix. Availability is per-machine, so a type the+ user has locally can legitimately be absent on the host they picked.+ */}+ <div className="grid grid-cols-3 gap-2">+ {options.map(({ agent, available, blockedReason }) => (+ <button+ key={agent.id}+ type="button"+ disabled={!available}+ aria-pressed={value === agent.id}+ title={!available ? (blockedReason ?? 'Not available here.') : undefined}+ onClick={() => onChange(agent.id as AgentProviderId)}+ className={cn(+ 'flex cursor-pointer flex-col items-start gap-2 rounded-[11px] border p-3 text-left transition-colors',+ value === agent.id+ ? 'border-foreground bg-[var(--sel-soft)]'+ : 'border-border hover:bg-[var(--sel-soft)]',+ !available && 'cursor-not-allowed opacity-45 hover:bg-transparent'+ )}+ >+ <AgentIcon id={agent.id} size={22} />+ <span className="w-full truncate text-sm text-foreground">{agent.name}</span>+ </button>+ ))}+ </div>+ {/* The list is a report on one machine, so the way to change it is on+ that machine's own page — Agent providers for this computer, the+ host's page for a host. */}+ <p className="text-xs text-foreground-muted">+ Only providers installed {sshHost ? `on ${sshHost}` : 'on this machine'} are listed.{' '}+ <button+ type="button"+ className="-mx-1 cursor-pointer rounded px-1 text-foreground underline underline-offset-2 transition-colors hover:bg-[var(--sel-soft)]"+ onClick={() => {+ onNavigateAway();+ if (sshHost) navigate('remoteHost', { sshHost });+ else navigate('settings', { tab: 'clis-models' });+ }}+ >+ {sshHost ? `Set up ${sshHost}` : 'Set up agent providers'}+ </button>+ </p></Field>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 97fb7bd14..6c3d5120a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -1,7 +1,7 @@import { useQuery } from '@tanstack/react-query';import { CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useId } from 'react';+import { useEffect, useId, useState } from 'react';import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';import { AddressingPolicyControl } from '@renderer/features/switch-servers/addressing-policy-control';import type { OptionItem } from '@renderer/features/switch-servers/addressing-policy-editor';@@ -9,6 +9,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-serimport { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Switch } from '@renderer/lib/ui/switch';@@ -22,17 +23,20 @@ import type { ConfigureAgentFormState } from './modes';* run-mode or notify-handle choice (CHOO-1440); advanced definition attributes* live in the collapsed Advanced section.*/-export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({+export const AgentSettingsSection = observer(function AgentSettingsSection({form,serverId,onAddServer,+ onOpenMessagingApps,}: {form: ConfigureAgentFormState;serverId: string | null;onAddServer: () => void;+ onOpenMessagingApps: () => void;}) {- const nameId = useId();- const descriptionId = useId();+ // Sessions, permissions and addressing are set once and rarely revisited, so+ // they start folded — the identity fields above are what the dialog is for.+ const [settingsOpen, setSettingsOpen] = useState(false);useEffect(() => {if (switchServersStore.servers.length === 0) void switchServersStore.init();@@ -81,6 +85,17 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({// Read here rather than inside the editor so the owner-only default can be// questioned before the agent exists, not after it has gone quiet.const { identities } = useMyIdentities(serverId);+ const bridgesQuery = useQuery({+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId as string),+ enabled: serverId !== null,+ });+ const unlinkedApps =+ identities === null || bridgesQuery.data === undefined+ ? null+ : bridgesQuery.data+ .filter((bridge) => !identities.some((identity) => identity.bridgeId === bridge.id))+ .map((bridge) => bridge.displayName);if (servers.length === 0) {return (@@ -100,20 +115,109 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({return (<FieldGroup>- <Field>- <FieldLabel>Switch server</FieldLabel>- <div className="rounded-md border border-border bg-background-1 px-3 py-1.5 text-sm">- {serverId- ? (servers.find((s) => s.id === serverId)?.name ?? serverId)- : 'No server selected'}- </div>- </Field>+ {/* No box around the disclosure: it is a heading for the fields it+ reveals, and framing it made it read as a control of the same weight+ as the inputs above and below it. */}+ <div>+ <DisclosureRow+ open={settingsOpen}+ title="Settings"+ meta="Sessions, permissions, who can address it"+ onToggle={() => setSettingsOpen((v) => !v)}+ />+ {settingsOpen && (+ <FieldGroup className="pt-3">+ <Field>+ <label className="-mx-2 flex cursor-pointer items-start justify-between gap-3 rounded-md px-2 py-1.5 transition-colors hover:bg-[var(--sel-soft)]">+ <span className="flex flex-col gap-0.5">+ <span className="flex items-center gap-1.5 text-sm">+ Auto-create a session on notify+ <InfoTooltip+ label="More info about auto-creating a session"+ content="Switch Console watches this agent's Switch rooms and starts a session — connected to the room and ready to reply — whenever it's addressed with no session running."+ />+ </span>+ <span className="text-xs text-foreground-muted">+ Start a session when this agent is addressed.+ </span>+ </span>+ <Switch+ className="mt-0.5"+ checked={form.autoSession}+ onCheckedChange={(checked) => form.setAutoSession(checked)}+ />+ </label>+ </Field>++ <Field>+ <label className="-mx-2 flex cursor-pointer items-start justify-between gap-3 rounded-md px-2 py-1.5 transition-colors hover:bg-[var(--sel-soft)]">+ <span className="flex flex-col gap-0.5">+ <span className="flex items-center gap-1.5 text-sm">+ Bypass permissions+ <InfoTooltip+ label="More info about bypassing permissions"+ content="Sessions start with the provider's auto-approve flag, including ones started automatically. Turn it on only for agents you trust to run unattended."+ />+ </span>+ <span className="text-xs text-foreground-muted">+ Run this agent's sessions without permission prompts.+ </span>+ </span>+ <Switch+ className="mt-0.5"+ checked={form.autoApprove}+ onCheckedChange={(checked) => form.setAutoApprove(checked)}+ />+ </label>+ </Field>++ <Field>+ <FieldLabel>+ <span className="flex items-center gap-1.5">+ Who can send instructions+ <InfoTooltip+ label="More info about addressing"+ content="Sending instructions means an @mention, a targeted message, or a delegated task. A new agent answers only you; grant other agents to let them delegate to it. You can change this later from the agent's settings."+ />+ </span>+ </FieldLabel>+ <AddressingPolicyControl+ value={form.addressingPolicy}+ onChange={form.setAddressingPolicy}+ rooms={roomOptions}+ roomGroups={groupOptions}+ users={userOptions}+ agents={agentOptions}+ unlinkedApps={unlinkedApps}+ onOpenMessagingApps={onOpenMessagingApps}+ inlineLabel={null}+ />+ </Field>+ </FieldGroup>+ )}+ </div>+ </FieldGroup>+ );+});+/**+ * Name and description, which are what the dialog is really asking for.+ *+ * Separate from the settings below because they need nothing but the form,+ * while the addressing control needs the server's rooms, groups, users and+ * agents — so the two halves can sit in different places in the dialog without+ * the identity fields waiting on four queries they do not use.+ */+export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState }) {+ const nameId = useId();+ const descriptionId = useId();+ return (+ <FieldGroup><Field>- <FieldLabel htmlFor={nameId}>Agent name</FieldLabel>+ <FieldLabel htmlFor={nameId}>Name</FieldLabel><Inputid={nameId}- placeholder="claude-code.my-repo.me"+ placeholder="Name this agent"value={form.agentName}onChange={(e) => form.setAgentName(e.target.value)}aria-invalid={form.agentName.length > 0 && !form.nameIsValid}@@ -123,10 +227,18 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({Use lowercase letters, digits, <span className="font-mono">. - _</span>, starting with aletter or digit. No spaces or uppercase.</span>+ ) : form.agentName.length > 0 ? (+ // Once there is a name, show the handle it produces rather than+ // repeating the advice: the advice is about choosing a name, and it+ // has been taken.+ <span className="text-xs text-foreground-muted">+ In rooms this agent is addressed as{' '}+ <span className="text-foreground">@{form.agentName}</span>.+ </span>) : (<span className="text-xs text-foreground-muted">- Visible to everyone in the agent's rooms — include your name so it's clear- which person's Claude Code this is.+ In rooms this agent is addressed by its name — include your own so it's clear whose+ agent it is.</span>)}</Field>@@ -135,80 +247,14 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({<FieldLabel htmlFor={descriptionId}>Description</FieldLabel><Inputid={descriptionId}- placeholder="Claude Code running in my-repo"+ placeholder="What is this agent for?"value={form.description}onChange={(e) => form.setDescription(e.target.value)}/>- </Field>-- <Field>- <label className="flex cursor-pointer items-start justify-between gap-3 rounded-md border border-border px-2 py-1.5">- <span className="flex flex-col gap-0.5">- <span className="flex items-center gap-1.5 text-sm">- Auto-create a session on notify- <InfoTooltip- label="More info about auto-creating a session"- content="Switch Console watches this agent's Switch rooms and starts a session — connected to the room and ready to reply — whenever it's addressed with no session running."- />- </span>- <span className="text-xs text-foreground-muted">- Start a session when this agent is addressed.- </span>- </span>- <Switch- className="mt-0.5"- checked={form.autoSession}- onCheckedChange={(checked) => form.setAutoSession(checked)}- />- </label>- </Field>-- <Field>- <label className="flex cursor-pointer items-start justify-between gap-3 rounded-md border border-border px-2 py-1.5">- <span className="flex flex-col gap-0.5">- <span className="flex items-center gap-1.5 text-sm">- Bypass permissions- <InfoTooltip- label="More info about bypassing permissions"- content="Sessions start with the provider's auto-approve flag, including ones started automatically. Turn it on only for agents you trust to run unattended."- />- </span>- <span className="text-xs text-foreground-muted">- Run this agent's sessions without permission prompts.- </span>- </span>- <Switch- className="mt-0.5"- checked={form.autoApprove}- onCheckedChange={(checked) => form.setAutoApprove(checked)}- />- </label>- </Field>-- <Field>- <FieldLabel>- <span className="flex items-center gap-1.5">- Who can send instructions- <InfoTooltip- label="More info about addressing"- content="Sending instructions means an @mention, a targeted message, or a delegated task. A new agent answers only you; grant other agents to let them delegate to it. You can change this later from the agent's settings."- />- </span>- </FieldLabel>- <AddressingPolicyControl- value={form.addressingPolicy}- onChange={form.setAddressingPolicy}- rooms={roomOptions}- roomGroups={groupOptions}- users={userOptions}- agents={agentOptions}- linkedIdentities={identities}- // No claim button: this panel is inside a modal, and the app shows one- // at a time — opening the claim dialog here would throw away the form- // the user is halfway through. The warning names where to go instead.- onClaimIdentity={null}- />+ <span className="text-xs text-foreground-muted">+ Helps other people and agents understand what this agent is for.+ </span></Field></FieldGroup>);-});+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/content.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/content.tsxdeleted file mode 100644index f218b5c7a..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/content.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { useId } from 'react';-import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import { LocalDirectorySelector } from './local-directory-selector';-import { type PickModeState } from './modes';--// Switch Console adds agents from existing local directories only. The SSH / create-new /-// clone panels from Switch Console are out of scope for v0 and have been removed.-export function PickExistingPanel({- state,- showName = true,-}: {- state: PickModeState;- /** Hide the local display-name field — used when onboarding a brand-new agent,- * where the name is derived from the directory and the Switch agent name is- * collected separately in the configure panel. */- showName?: boolean;-}) {- const nameId = useId();- return (- <FieldGroup>- <Field>- <FieldLabel>Directory</FieldLabel>- <LocalDirectorySelector- path={state.path}- onPathChange={state.handlePathChange}- title="Select a Switch agent directory"- message="Select the agent's working directory"- />- </Field>- {showName && (- <Field>- <FieldLabel htmlFor={nameId}>Name</FieldLabel>- <Input- id={nameId}- placeholder="Enter an agent name"- value={state.name}- onChange={(e) => state.handleNameChange(e.target.value)}- />- </Field>- )}- </FieldGroup>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsxindex 86d00b455..b0e07a513 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx@@ -1,14 +1,13 @@import { useQuery } from '@tanstack/react-query';-import { ChevronRight } from 'lucide-react';import { useCallback, useEffect, useMemo, useState } from 'react';import { rpc } from '@renderer/lib/ipc';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';-import { cn } from '@renderer/utils/utils';import {type AgentProviderConfig,providerConfigFromAttributes,} from '@shared/core/agents/agent-provider-config';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';import {attributesFromForm,DefinitionFieldInput,@@ -101,18 +100,18 @@ export function LaunchProfileConfig({if (!providerId || fields.length === 0) return null;+ const providerLabel = getProvider(providerId)?.name ?? providerId;+return (- <div className="rounded-md border border-border">- <button- type="button"- className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"- onClick={() => setOpen((v) => !v)}- >- <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />- Advanced configuration- </button>+ <div>+ <DisclosureRow+ open={open}+ title="Advanced configuration"+ meta={`${providerLabel} · ${fields.length} ${fields.length === 1 ? 'field' : 'fields'}`}+ onToggle={() => setOpen((v) => !v)}+ />{open && (- <div className="flex flex-col gap-4 border-t border-border px-3 py-3">+ <div className="flex flex-col gap-4 pt-3">{fields.map((field) => {const catalogueState = fieldCatalogueState(field, state, catalogue);const rendered = fieldWithCatalogue(field, catalogueState);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsxindex e07cb1d4a..0b570f831 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx@@ -1,4 +1,3 @@-import { Folder } from 'lucide-react';import { useState } from 'react';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';@@ -33,23 +32,31 @@ export function LocalDirectorySelector({};return (- <button- className="flex h-9 w-full items-center gap-2 rounded-md border border-border p-2 pr-1.5 transition-colors hover:bg-background-quaternary-1"- onClick={handleOpenFileDialog}- >- <Folder className="size-4 text-foreground-muted" />+ // A field with a button in it rather than one large button: the path is the+ // value being read, and making the whole row pressable made it look like the+ // value itself was the control.+ <div className="flex h-9 w-full items-center gap-2 rounded-md border border-border pr-1 pl-3"><pclassName={cn(- 'text-sm text-foreground-passive truncate min-w-0 flex-1 w-full text-left',+ 'w-full min-w-0 flex-1 truncate text-left text-sm text-foreground-passive',path ? 'text-foreground' : '')}+ // The tail of a path is the part that identifies it, so a long one is+ // clipped at the front; the whole thing stays available on hover.+ title={path || undefined}+ dir="rtl">- {' '}{path || placeholder}</p>- <Button variant="outline" size="xs">- Choose+ <Button+ type="button"+ variant="secondary"+ size="sm"+ className="cursor-pointer text-foreground"+ onClick={handleOpenFileDialog}+ >+ Choose…</Button>- </button>+ </div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsindex 734e91ea5..a799f992d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts@@ -1,10 +1,7 @@-import { useQuery } from '@tanstack/react-query';-import { useEffect, useState } from 'react';-import { rpc } from '@renderer/lib/ipc';+import { useCallback, useState } from 'react';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';-import { basenameFromAnyPath } from '@shared/path-name';/** Switch agent-name charset, enforced server-side too: lowercase letters,* digits, `.`, `-`, `_`, starting with a letter or digit. */@@ -12,36 +9,16 @@ export const AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;export function usePickMode() {const [path, setPath] = useState('');- const [name, setName] = useState('');const [serverId, setServerId] = useState<string | null>(null);const [providerId, setProviderId] = useState<AgentProviderId | null>(null);- const [nameIsTouched, setNameIsTouched] = useState<boolean>(false);-- const handlePathChange = (newPath: string) => {- setPath(newPath);- if (!nameIsTouched) {- const dirName = basenameFromAnyPath(newPath);- if (dirName && !nameIsTouched) setName(dirName);- }- };-- const handleNameChange = (newName: string) => {- setName(newName);- setNameIsTouched(true);- };-- const isValid = name.trim().length > 0 && path.trim().length > 0 && !!serverId && !!providerId;return {path,- name,+ handlePathChange: setPath,serverId,setServerId,providerId,setProviderId,- handlePathChange,- handleNameChange,- isValid,};}@@ -50,56 +27,50 @@ export type PickModeState = ReturnType<typeof usePickMode>;/*** Form state for creating a brand-new Switch agent in a directory. Collects the* Switch agent name and description (advanced definition attributes are gathered- * separately in the Advanced section), seeding name/description from a- * server-derived default until the user edits them. Switch Console always registers- * the agent as a managed, session-addressable identity — there is no run-mode or+ * separately in the Advanced section). Switch Console always registers the agent+ * as a managed, session-addressable identity — there is no run-mode or* notify-handle choice (CHOO-1440).+ *+ * Neither field is derived from the working directory. The name is how the+ * agent is addressed in rooms and the description is what other people read to+ * know what it is for; a directory basename answers neither question, and+ * rewriting both when the directory changed moved text the user had already+ * looked at and accepted.+ *+ * One instance serves both run locations. There used to be two — one for a+ * local agent, one for a remote one — and switching between them swapped which+ * was on screen, so the name and description the user had typed vanished.*/-export function useConfigureAgentForm(- dir: string,- defaultAutoApprove: boolean,- providerId: AgentProviderId | null-) {- const [agentName, setAgentNameRaw] = useState('');- const [agentNameTouched, setAgentNameTouched] = useState(false);- const [description, setDescriptionRaw] = useState('');- const [descriptionTouched, setDescriptionTouched] = useState(false);+export function useConfigureAgentForm() {+ const [agentName, setAgentName] = useState('');+ const [description, setDescription] = useState('');const [autoSession, setAutoSession] = useState(true);- const [autoApprove, setAutoApprove] = useState(defaultAutoApprove);+ const [autoApprove, setAutoApproveRaw] = useState(false);+ const [autoApproveTouched, setAutoApproveTouched] = useState(false);// Scoped addressing policy (CHOO-1585). null = open; a new agent starts// owner-scoped (CHOO-2137). Applied via a follow-up PUT after creation.const [addressingPolicy, setAddressingPolicy] = useState<AddressingPolicy | null>(() =>ownerOnlyPolicy());- const trimmedDir = dir.trim();- // suggestAgentDefaults derives name/description from the directory basename and- // the local user — pure, no filesystem read — so it works identically for a- // local path or a remote working dir, giving remote agents the same defaults.- const defaultsQuery = useQuery({- queryKey: ['agentDefaults', trimmedDir, providerId],- queryFn: () => {- if (providerId === null) throw new Error('providerId is required for agent defaults');- return rpc.switchServers.suggestAgentDefaults({ dir: trimmedDir, providerId });- },- enabled: trimmedDir.length > 0 && providerId !== null,- });-- const defaults = defaultsQuery.data;- useEffect(() => {- if (!defaults) return;- if (!agentNameTouched) setAgentNameRaw(defaults.name);- if (!descriptionTouched) setDescriptionRaw(defaults.description);- }, [defaults, agentNameTouched, descriptionTouched]);+ const setAutoApprove = useCallback((value: boolean) => {+ setAutoApproveRaw(value);+ setAutoApproveTouched(true);+ }, []);- const setAgentName = (value: string) => {- setAgentNameRaw(value);- setAgentNameTouched(true);- };- const setDescription = (value: string) => {- setDescriptionRaw(value);- setDescriptionTouched(true);- };+ /**+ * What the run location implies, for as long as the user has not answered+ * themselves: an agent on a host is put there to run unattended, and a+ * permission prompt nobody is watching stalls the session. Kept as a+ * suggestion rather than a reset so a deliberate answer survives a change of+ * mind about where the agent runs.+ */+ const suggestAutoApprove = useCallback(+ (value: boolean) => {+ setAutoApproveRaw((current) => (autoApproveTouched ? current : value));+ },+ [autoApproveTouched]+ );const nameIsValid = AGENT_NAME_PATTERN.test(agentName);const isValid = nameIsValid && description.trim().length > 0;@@ -114,6 +85,7 @@ export function useConfigureAgentForm(setAutoSession,autoApprove,setAutoApprove,+ suggestAutoApprove,addressingPolicy,setAddressingPolicy,isValid,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsxdeleted file mode 100644index 6659f29ed..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx+++ /dev/null@@ -1,104 +0,0 @@-import { Checkbox } from '@renderer/lib/ui/checkbox';--/**- * How an agent found in the directory will be brought into this Switch Console.- *- * - `import` — a provider definition that already carries Switch credentials;- * its identity is reused.- * - `adopt` — a plain provider definition with no Switch setup; Switch Console mints- * an identity for it.- * - `attach` — credentials found in the directory with no definition of ours to- * go with them, which is what an agent set up by another Switch Console (or for a- * provider with no definition concept, such as Codex) looks like. Its identity- * is reused and nothing in the directory is written (CHOO-1937).- */-export type AdoptKind = 'import' | 'adopt' | 'attach';--/** A discovered agent the modal can bring in. Structurally a subset of the- * main-process discovery types, kept local so the renderer does not import- * across the process boundary. */-export type OnboardableAgent = {- name: string;- description: string | null;- kind: AdoptKind;- /** For `attach`: the provider that will run it. Null when nothing on disk- * names one and the modal has no provider picked to fall back on, in which- * case the row cannot be selected. */- providerLabel: string | null;- /** Why this row cannot be brought in, or null when it can. Listed-and-disabled- * rather than hidden: a missing row says nothing, and the reason is usually- * something the user can act on. */- blockedReason: string | null;-};--const BADGE: Record<AdoptKind, string> = {- import: 'Switch agent · import',- adopt: 'adopt as new',- attach: 'configured here · attach',-};--/**- * Multi-select list of agents found in a directory that aren't yet Switch Console- * agents on this client — provider definitions (CHOO-1440) and agents another- * install already configured here (CHOO-1937), in one list because the user is- * answering one question: which of these should this Switch Console manage.- */-export function OnboardExistingPanel({- agents,- selected,- onToggle,-}: {- agents: OnboardableAgent[];- selected: Set<string>;- onToggle: (name: string, checked: boolean) => void;-}) {- return (- <div className="flex flex-col gap-2 rounded-md border border-border bg-background-1 px-3 py-2.5 text-sm">- <span className="text-foreground-muted">- {agents.length} agent{agents.length === 1 ? '' : 's'} in this directory{' '}- {agents.length === 1 ? "isn't" : "aren't"} in Switch Console yet — pick which to bring in,- or create a new one below.- </span>- <div className="flex flex-col gap-0.5">- {agents.map((a) => {- const blocked = a.blockedReason !== null;- return (- <label- key={a.name}- className={`flex items-start gap-2 rounded px-1.5 py-1 ${- blocked ? 'cursor-not-allowed opacity-60' : 'cursor-pointer hover:bg-background-2'- }`}- >- <Checkbox- checked={selected.has(a.name)}- disabled={blocked}- onCheckedChange={(checked) => onToggle(a.name, checked === true)}- className="mt-0.5"- />- <div className="flex min-w-0 flex-col">- <div className="flex items-center gap-2">- <span className="font-mono text-xs text-foreground">{a.name}</span>- <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">- {BADGE[a.kind]}- </span>- {a.kind === 'attach' && a.providerLabel !== null && (- <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">- {a.providerLabel}- </span>- )}- </div>- {a.blockedReason !== null ? (- <span className="text-xs text-foreground-muted">{a.blockedReason}</span>- ) : (- a.description && (- <span className="truncate text-xs text-foreground-muted">{a.description}</span>- )- )}- </div>- </label>- );- })}- </div>- </div>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex 311841296..476aad280 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -7,46 +7,16 @@ import {asMounted,getLocationStore,} from '@renderer/features/locations/stores/location-selectors';-import type { LocationView } from '@renderer/features/locations/stores/location-view';import { useParams } from '@renderer/lib/layout/navigation-provider';-import { cn } from '@renderer/utils/utils';--function LocationViewNav({- items,- activeView,- onChange,-}: {- items: Array<{ id: LocationView; label: string }>;- activeView: LocationView;- onChange: (view: LocationView) => void;-}) {- return (- <div>- <nav className="flex min-h-0 w-52 flex-col gap-0.5 overflow-y-auto" aria-label="Location">- {items.map((item) => {- const isActive = item.id === activeView;-- return (- <button- key={item.id}- type="button"- onClick={() => onChange(item.id)}- aria-current={isActive ? 'page' : undefined}- className={cn(- 'flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-normal text-foreground-muted transition-colors hover:bg-background-1 hover:text-foreground',- isActive &&- 'bg-background-2 text-foreground hover:bg-background-2 hover:text-foreground'- )}- >- <span className="truncate text-left">{item.label}</span>- </button>- );- })}- </nav>- </div>- );-}+/**+ * An agent, on one page: who it is, how it behaves, the process keeping it+ * connected, and its sessions — read top to bottom.+ *+ * It used to be three tabs down a side nav, which asked the reader to know+ * which of them held what before they could look at anything. The page is short+ * enough to scroll instead.+ */export const ActiveLocation = observer(function ActiveLocation() {const {params: { locationId },@@ -58,36 +28,13 @@ export const ActiveLocation = observer(function ActiveLocation() {// The sidecar is a remote-only concern — a local agent runs no on-host process.const isRemote = store.data.sshHost !== null;- const items: Array<{ id: LocationView; label: string }> = [- { id: 'sessions', label: 'Sessions' },- { id: 'settings', label: 'Settings' },- ...(isRemote ? [{ id: 'sidecar' as const, label: 'Sidecar' }] : []),- ];-- // Resolve the active view, falling back to Sessions for a retired ('subagents')- // or now-unavailable ('sidecar' on a local location) stored view.- const stored = store.view.activeView;- const activeView: LocationView =- stored === 'settings' || (stored === 'sidecar' && isRemote) ? stored : 'sessions';-return (- <div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden">- <div className="mx-auto flex h-full min-h-0 w-full max-w-[1060px] flex-col gap-6 px-8">+ <div className="min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto">+ <div className="mx-auto flex w-full max-w-[820px] flex-col gap-10 px-8 pb-20"><AgentPageHeader />- <div className="grid min-h-0 flex-1 grid-cols-[13rem_minmax(0,1fr)] gap-8 overflow-hidden">- <LocationViewNav- items={items}- activeView={activeView}- onChange={(view) => store.view.setLocationView(view)}- />- <div className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto">- <div className="mx-auto flex h-full min-h-0 w-full max-w-4xl flex-col px-1 pb-10">- {activeView === 'sessions' && <SessionList />}- {activeView === 'settings' && <SettingsPanel />}- {activeView === 'sidecar' && <SidecarPanel />}- </div>- </div>- </div>+ <SettingsPanel />+ {isRemote && <SidecarPanel />}+ <SessionList /></div></div>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsxindex 45bcc5af0..a10332cb7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx@@ -1,3 +1,4 @@+import { useQuery } from '@tanstack/react-query';import { Bot } from 'lucide-react';import { observer } from 'mobx-react-lite';import { agentsStore } from '@renderer/features/locations/stores/agents-store';@@ -5,58 +6,86 @@ import {getLocationStore,locationDisplayName,} from '@renderer/features/locations/stores/location-selectors';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';import { BoundShortcut } from '@renderer/lib/ui/shortcut';import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';/**- * Who this page is about, above its tabs: the agent's mark, its name, where it- * is registered and what it runs on, and the one action the page exists for.+ * Who this page is about: the agent's mark, its name and provider, the+ * description the rest of the team reads to know what it is for, and the two+ * things you come here to do.*- * The page used to open straight onto a session list with the agent named only- * in the titlebar, which read as a list of sessions that happened to be- * somewhere rather than as an agent you are looking at.+ * The description is the agent's own, held on its Switch server — the same+ * sentence written when it was created. It is not editable from here.*/export const AgentPageHeader = observer(function AgentPageHeader() {const {params: { locationId, agentName },} = useParams('location');const showCreateSessionModal = useShowModal('sessionModal');+ const showAddToRoom = useShowModal('addAgentToRoomModal');const agent = agentsStore.agentAtLocation(locationId, agentName);const title = agent?.name ?? agentName ?? locationDisplayName(getLocationStore(locationId)) ?? '';+ const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;- const serverName = agent?.serverId- ? (switchServersStore.servers.find((s) => s.id === agent.serverId)?.name ?? null)- : null;- const provider = providerDisplayName(agent?.providerId ?? null);- const subtitle = [serverName && `Agent on ${serverName}`, provider].filter(Boolean).join(' · ');+ const serverId = agent?.serverId ?? null;+ const { data: remoteAgents } = useQuery({+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),+ enabled: serverId !== null,+ });+ const description =+ (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId)?.description ?? null;++ const roomable = serverId !== null && agent?.switchAgentId != null;return (- <header className="flex shrink-0 items-start justify-between gap-4 pt-10">- <div className="flex min-w-0 items-center gap-3">- <span className="flex size-11 shrink-0 items-center justify-center rounded-lg border border-border bg-background-secondary">- {agent?.providerId ? (- <AgentIcon id={agent.providerId} size={22} />- ) : (- <Bot className="size-5 text-foreground-muted" />+ <header className="flex shrink-0 items-start gap-5 pt-10">+ <span className="flex size-20 shrink-0 items-center justify-center rounded-[18px] bg-[var(--surface-2)]">+ {agent?.providerId ? (+ <AgentIcon id={agent.providerId} size={40} />+ ) : (+ <Bot className="size-9 text-foreground-muted" />+ )}+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <div className="flex min-w-0 items-center gap-2.5">+ <h1 className="truncate text-3xl font-semibold tracking-tight text-foreground">+ {title}+ </h1>+ {provider && (+ <Badge variant="secondary" className="h-5 shrink-0 px-2 text-[11px]">+ {provider}+ </Badge>+ )}+ </div>+ {description && <p className="text-sm text-foreground-muted">{description}</p>}+ <div className="mt-2 flex flex-wrap items-center gap-2">+ <Button onClick={() => showCreateSessionModal({ locationId, agentName })}>+ New Session <BoundShortcut settingsKey="newSession" />+ </Button>+ {roomable && (+ <Button+ variant="outline"+ onClick={() =>+ showAddToRoom({+ serverId: serverId as string,+ switchAgentId: agent.switchAgentId as string,+ agentName: title,+ })+ }+ >+ Add to room+ </Button>)}- </span>- <div className="min-w-0">- <h1 className="truncate text-2xl font-semibold text-foreground">{title}</h1>- {subtitle && <p className="mt-0.5 truncate text-sm text-foreground-muted">{subtitle}</p>}</div></div>- <Button- className="shrink-0"- onClick={() => showCreateSessionModal({ locationId, agentName })}- >- Create Session <BoundShortcut settingsKey="newSession" />- </Button></header>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-section.tsxnew file mode 100644index 000000000..511f40f92--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-section.tsx@@ -0,0 +1,18 @@+import { cn } from '@renderer/utils/utils';++/**+ * The quiet heading over a run of settings on the agent page — General, Sidecar,+ * Sessions. Smaller and greyer than anything under it: it groups rows rather+ * than competing with them for the eye.+ */+export function SectionLabel({+ children,+ className,+}: {+ children: React.ReactNode;+ className?: string;+}) {+ return (+ <h2 className={cn('text-[13px] font-medium text-foreground-muted', className)}>{children}</h2>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsxdeleted file mode 100644index 765294372..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsx+++ /dev/null@@ -1,53 +0,0 @@-import { Plus } from 'lucide-react';-import { observer } from 'mobx-react-lite';-import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { useArrowKeyNavigation } from '@renderer/lib/hooks/use-arrow-key-navigation';-import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { ActionListItem } from '@renderer/lib/ui/action-list-item';-import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';--export const SessionListEmptyState = observer(function SessionListEmptyState({- locationId,- agentName,-}: {- locationId: string;- agentName?: string;-}) {- const showSessionModal = useShowModal('sessionModal');-- const agent = agentsStore.agentAtLocation(locationId, agentName);- const provider = providerDisplayName(agent?.providerId ?? null);-- const actions = [- {- label: 'New Session',- description: agentName- ? `Start a ${provider ?? 'new'} session as ${agentName}`- : `Start a ${provider ?? 'new'} session for this agent`,- icon: Plus,- onActivate: () => showSessionModal({ locationId, agentName }),- },- ];-- const { selectedIndex, setSelectedIndex } = useArrowKeyNavigation(actions.length, (index) => {- actions[index]?.onActivate();- });-- return (- <div className="flex h-full flex-col items-center justify-center bg-background p-8">- <div className="flex w-full max-w-sm flex-col gap-1">- {actions.map((action, i) => (- <ActionListItem- key={action.label}- label={action.label}- description={action.description}- icon={action.icon}- isSelected={i === selectedIndex}- onMouseEnter={() => setSelectedIndex(i)}- onClick={action.onActivate}- />- ))}- </div>- </div>- );-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list.tsxindex 03dbf8040..c967af2ce 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-list.tsx@@ -1,8 +1,7 @@import { useHotkey } from '@tanstack/react-hotkeys';-import { useVirtualizer } from '@tanstack/react-virtual';-import { Archive, RotateCcw, Trash2, X } from 'lucide-react';+import { Archive, Plus, RotateCcw, Trash2, X } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useRef } from 'react';+import { SectionLabel } from '@renderer/features/locations/components/main-panel/agent-page-section';import {asMounted,getLocationStore,@@ -17,75 +16,9 @@ import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { modalStore } from '@renderer/lib/modal/modal-store';import { Button } from '@renderer/lib/ui/button';-import { EmptyState } from '@renderer/lib/ui/empty-state';-import { SearchInput } from '@renderer/lib/ui/search-input';import { BoundShortcut } from '@renderer/lib/ui/shortcut';-import { ToggleGroup, ToggleGroupItem } from '@renderer/lib/ui/toggle-group';-import { cn } from '@renderer/utils/utils';-import { SessionListEmptyState } from './session-list-empty-state';import { SessionRow, type ReadySession } from './session-row';-function SessionVirtualList({- sessions,- selectedIds,- onToggleSelect,-}: {- sessions: ReadySession[];- selectedIds: Set<string>;- onToggleSelect: (id: string, shiftKey: boolean) => void;-}) {- const parentRef = useRef<HTMLDivElement>(null);-- const virtualizer = useVirtualizer({- count: sessions.length,- getScrollElement: () => parentRef.current,- estimateSize: () => 60,- overscan: 5,- measureElement: (el) => el.getBoundingClientRect().height,- });-- const virtualItems = virtualizer.getVirtualItems();-- if (sessions.length === 0) {- return <EmptyState label="No sessions" description="No sessions found" />;- }-- return (- <div- ref={parentRef}- className="min-h-0 flex-1 overflow-y-auto py-1"- style={{ scrollbarWidth: 'none' }}- >- <div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>- {virtualItems.map((virtualItem) => {- const session = sessions[virtualItem.index]!;- return (- <div- key={virtualItem.key}- data-index={virtualItem.index}- ref={virtualizer.measureElement}- className={cn(virtualItem.index === sessions.length - 1 && 'border-b-0')}- style={{- position: 'absolute',- top: 0,- left: 0,- width: '100%',- transform: `translateY(${virtualItem.start}px)`,- }}- >- <SessionRow- session={session}- isSelected={selectedIds.has(session.data.id)}- onToggleSelect={(shiftKey) => onToggleSelect(session.data.id, shiftKey)}- />- </div>- );- })}- </div>- </div>- );-}-function SelectionBar({count,tab,@@ -138,6 +71,7 @@ export const SessionList = observer(function SessionList() {const store = asMounted(getLocationStore(locationId));const sessionManager = getSessionManagerStore(locationId);const showDeleteSession = useShowModal('deleteSessionModal');+ const showCreateSessionModal = useShowModal('sessionModal');const sessionView = store?.view.sessionView ?? null;@@ -207,59 +141,68 @@ export const SessionList = observer(function SessionList() {if (!sessionView) return null;- const displaySessions = sessionView.tab === 'active' ? activeSessions : archivedSessions;- const q = sessionView.searchQuery.trim().toLowerCase();- const filteredSessions = q- ? displaySessions.filter((t) => t.data.title.toLowerCase().includes(q))- : displaySessions;+ const showingArchived = sessionView.tab === 'archived';+ const displaySessions = showingArchived ? archivedSessions : activeSessions;return (- <div className="relative flex h-full min-h-0 w-full flex-col gap-3">- <div className="flex shrink-0 flex-col gap-4">- <div className="flex flex-wrap items-center justify-between gap-2">- <ToggleGroup- multiple={false}- value={[sessionView.tab]}- onValueChange={([value]) => {- if (value) sessionView.setTab(value as 'active' | 'archived');- }}- >- <ToggleGroupItem value="active">Active ({activeSessions.length})</ToggleGroupItem>- <ToggleGroupItem value="archived">Archived ({archivedSessions.length})</ToggleGroupItem>- </ToggleGroup>- <SearchInput- placeholder="Search sessions…"- value={sessionView.searchQuery}- onChange={(e) => sessionView.setSearchQuery(e.target.value)}- className="w-56"- />- </div>+ <section className="relative flex w-full flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <SectionLabel>Sessions</SectionLabel>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="New session"+ onClick={() => showCreateSessionModal({ locationId, agentName })}+ >+ <Plus className="size-4" />+ </Button></div>- {/* The border frames a list. With nothing to list it frames empty space,- which reads as a list that failed to load rather than as an agent with- no sessions yet. */}- {filteredSessions.length === 0 && sessionView.tab === 'active' ? (- <SessionListEmptyState locationId={locationId} agentName={agentName} />+ {displaySessions.length === 0 && !showingArchived ? (+ // No call to action here: New Session sits at the top of the page and+ // again beside this heading, so a third one would be the loudest thing+ // on an empty section.+ <p className="py-2 text-sm text-foreground-muted">No sessions yet.</p>) : (- <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border">- <SessionVirtualList- sessions={filteredSessions}- selectedIds={sessionView.selectedIds}- onToggleSelect={(id, shiftKey) => {- if (shiftKey) {- sessionView.selectRange(- filteredSessions.map((t) => t.data.id),- id- );- } else {- sessionView.toggleSelect(id);- }- }}- />+ <div className="-mx-3 flex flex-col">+ {displaySessions.map((session) => (+ <SessionRow+ key={session.data.id}+ session={session}+ isSelected={sessionView.selectedIds.has(session.data.id)}+ onToggleSelect={(shiftKey) => {+ if (shiftKey) {+ sessionView.selectRange(+ displaySessions.map((t) => t.data.id),+ session.data.id+ );+ } else {+ sessionView.toggleSelect(session.data.id);+ }+ }}+ />+ ))}</div>)}+ {/* Archiving is otherwise a one-way door: with no way back to an archived+ session, Archive and Delete would look like the same action. One quiet+ line, and only when there is something behind it. */}+ {archivedSessions.length > 0 && (+ <button+ type="button"+ className="-mx-1 w-fit cursor-pointer rounded px-1 py-1 text-xs text-foreground-muted underline underline-offset-2 transition-colors hover:bg-background-1 hover:text-foreground"+ onClick={() => {+ clearSelection();+ sessionView.setTab(showingArchived ? 'active' : 'archived');+ }}+ >+ {showingArchived+ ? 'Back to active sessions'+ : `${archivedSessions.length} archived ${archivedSessions.length === 1 ? 'session' : 'sessions'}`}+ </button>+ )}+<SelectionBarcount={sessionView.selectedIds.size}tab={sessionView.tab}@@ -268,6 +211,6 @@ export const SessionList = observer(function SessionList() {onRestore={bulkRestore}onDelete={bulkDelete}/>- </div>+ </section>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-row.tsxindex 7a0552b83..20b86e3e8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/session-view/session-row.tsx@@ -50,7 +50,9 @@ export const SessionRow = observer(function SessionRow({});const isArchived = Boolean(session.data.archivedAt);const canPin = session.state !== 'unregistered';- const agentAttention = sessionAgentStatus(session);+ // Only working still draws something, so only working may take the row's+ // trailing slot from the timestamp.+ const isWorking = sessionAgentStatus(session) === 'working';return (<SessionContextMenu@@ -114,11 +116,11 @@ export const SessionRow = observer(function SessionRow({<divclassName={cn('flex min-w-8 shrink-0 items-center justify-end',- agentAttention ? 'justify-end' : 'justify-middle'+ isWorking ? 'justify-end' : 'justify-middle')}>- {agentAttention ? (- <AgentStatusIndicator status={agentAttention} />+ {isWorking ? (+ <AgentStatusIndicator status="working" />) : (<RelativeTimevalue={session.data.createdAt}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxindex ef232d401..024a099db 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -8,9 +8,7 @@ import {} from '@renderer/features/switch-servers/addressing-policy-editor';import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';import { rpc } from '@renderer/lib/ipc';-import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { Button } from '@renderer/lib/ui/button';-import { Field, FieldTitle } from '@renderer/lib/ui/field';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { log } from '@renderer/utils/logger';import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';@@ -38,28 +36,17 @@ export function AddressingPolicySettingsSection({if (switchAgents.length === 0) return null;return (- <Field>- <FieldTitle>- <span className="flex items-center gap-1.5">- Who can send instructions- <InfoTooltip- label="More info about addressing"- content="Sending instructions means an @mention, a targeted message, or a delegated task. Only you, anyone in the agent's rooms, or whoever a rule admits."- />- </span>- </FieldTitle>- <div className="flex flex-col gap-4">- {switchAgents.map((agent) => (- <AddressingPolicyRow- key={agent.id}- serverId={agent.serverId as string}- agentId={agent.switchAgentId as string}- agentName={agent.name}- showName={switchAgents.length > 1}- />- ))}- </div>- </Field>+ <div className="flex flex-col gap-4">+ {switchAgents.map((agent) => (+ <AddressingPolicyRow+ key={agent.id}+ serverId={agent.serverId as string}+ agentId={agent.switchAgentId as string}+ agentName={agent.name}+ showName={switchAgents.length > 1}+ />+ ))}+ </div>);}@@ -75,8 +62,8 @@ function AddressingPolicyRow({showName: boolean;}) {const queryClient = useQueryClient();- const showClaimIdentity = useShowModal('claimIdentityModal');- const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);+ const { navigate } = useNavigate();+ const { identities } = useMyIdentities(serverId);const [draft, setDraft] = useState<AddressingPolicy | null>(null);const [dirty, setDirty] = useState(false);const [error, setError] = useState<string | null>(null);@@ -106,11 +93,15 @@ function AddressingPolicyRow({queryKey: ['remote-bridges', serverId],queryFn: () => rpc.switchServers.listRemoteBridges(serverId),});- // Which workspace the "link my account" button opens on. The claim modal is- // per-bridge, so one has to be named: the default bridge is where this- // server's rooms land, and the rest are reachable from the server page.- const claimBridge =- (bridges.data ?? []).find((b) => b.isDefault) ?? (bridges.data ?? [])[0] ?? null;+ // The apps on this server the user has claimed no account on. Null until both+ // halves have arrived: a bridge list without the identities would read as+ // every app unlinked.+ const unlinkedApps =+ identities === null || bridges.data === undefined+ ? null+ : bridges.data+ .filter((bridge) => !identities.some((identity) => identity.bridgeId === bridge.id))+ .map((bridge) => bridge.displayName);// Until the user edits, show the saved policy; once dirty, show the draft.const value = dirty ? draft : (saved ?? null);@@ -142,42 +133,44 @@ function AddressingPolicyRow({// Prefer the registered Switch agent name over the local directory basename.const displayName = agentOptions.find((o) => o.id === agentId)?.label ?? agentName;+ // Saved the moment it is changed — there is no Save button. A rule set that+ // admits nobody is the one exception: it is held as a draft rather than+ // written, because saving it mid-edit would silently shut the agent off.+ const change = (next: AddressingPolicy | null) => {+ setDraft(next);+ setDirty(true);+ if (!policyHasDeadRule(next)) mutation.mutate(next);+ };+return (<div className="flex flex-col gap-2">{showName && <span className="text-sm font-medium">{displayName}</span>}<AddressingPolicyControlvalue={value}- onChange={(next) => {- setDraft(next);- setDirty(true);- }}+ onChange={change}+ inlineLabel={+ <span className="flex items-center gap-1.5 text-sm leading-snug font-medium">+ Who can send instructions+ <InfoTooltip+ label="More info about addressing"+ content="Sending instructions means an @mention, a targeted message, or a delegated task. Only you, anyone in the agent's rooms, or whoever a rule admits."+ />+ </span>+ }rooms={roomOptions}roomGroups={groupOptions}users={userOptions}agents={agentOptions}- linkedIdentities={identities}- onClaimIdentity={- claimBridge === null- ? null- : () =>- showClaimIdentity({- serverId,- bridgeId: claimBridge.id,- onSuccess: () => refreshIdentities(),- })- }+ unlinkedApps={unlinkedApps}+ onOpenMessagingApps={() => navigate('server', { serverId })}disabled={mutation.isPending}/>{error && <span className="text-destructive text-xs">{error}</span>}- <div>- <Button- size="sm"- disabled={!dirty || mutation.isPending || policyHasDeadRule(value)}- onClick={() => mutation.mutate(value)}- >- Save policy- </Button>- </div>+ {policyHasDeadRule(value) && (+ <span className="text-xs text-foreground-warning">+ Not saved — a rule admits nobody. It is kept here until it names a sender.+ </span>+ )}</div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsxindex a25d1678a..263319926 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx@@ -21,8 +21,10 @@ import { isProvisioned } from '@renderer/features/sessions/stores/session-store'import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';-import { Field, FieldDescription, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';+import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';import { log } from '@renderer/utils/logger';+import { cn } from '@renderer/utils/utils';/*** Per-agent "Advanced configuration" in the Settings tab: the model, reasoning@@ -44,6 +46,7 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSettiagentId: string | undefined;}) {const queryClient = useQueryClient();+ const [open, setOpen] = useState(false);const { data: agents } = useQuery({queryKey: ['location-agents', locationId],@@ -196,12 +199,19 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetticonst showStaleNotice = restartable && staleSessionIds.length > 0 && (dirty || save.isSuccess);return (- <Field>- <FieldTitle>Advanced configuration</FieldTitle>- <FieldDescription className="text-foreground-muted">- The agent's model, reasoning effort, tools, and system prompt. The agent name is fixed.- </FieldDescription>- <div className="flex flex-col gap-4">+ <div>+ <DisclosureRow+ open={open}+ title="Advanced configuration"+ summary={summariseValues(fields, savedForm)}+ meta={`${fields.length} ${fields.length === 1 ? 'setting' : 'settings'}`}+ onToggle={() => setOpen((v) => !v)}+ />+ <div className={cn('flex flex-col gap-4 pt-3', !open && 'hidden')}>+ <FieldDescription className="text-foreground-muted">+ The agent's model, reasoning effort, tools, and system prompt. The agent name is+ fixed.+ </FieldDescription>{fields.map((field) => {const catalogueState = fieldCatalogueState(field, form, catalogue);const rendered = fieldWithCatalogue(field, catalogueState);@@ -271,10 +281,33 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti</div>)}</div>- </Field>+ </div>);});+/**+ * What the section is holding, read off the saved values rather than the form —+ * a collapsed row has to say what is set without being opened, and the form may+ * be mid-edit.+ *+ * Values, not labels: "claude-opus-4-6 · high" reads as configuration where+ * "Model claude-opus-4-6 · Reasoning effort high" reads as a table of contents.+ */+function summariseValues(fields: { key: string; label: string }[], saved: FormState): string {+ const set = fields+ .map((field) => {+ const value = saved[field.key];+ if (value === true) return field.label.toLowerCase();+ if (typeof value === 'string' && value.trim().length > 0) return value.trim();+ return null;+ })+ .filter((v): v is string => v !== null);++ if (set.length === 0) return 'defaults';+ const shown = set.slice(0, 2).join(' · ');+ return set.length > 2 ? `${shown} · +${set.length - 2}` : shown;+}+/*** The agent's sessions that already started a conversation, and so are running* on whatever configuration was in place at the time.diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsxindex f32e45cc0..0a2e75b26 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx@@ -1,10 +1,15 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import {AlertTriangle,+ ArrowRight,+ Check,CheckCircle2,+ ChevronRight,+ Copy,Loader2,Power,RefreshCw,+ Server,Users,XCircle,} from 'lucide-react';@@ -12,8 +17,10 @@ import { useEffect, useState } from 'react';import { events, rpc } from '@renderer/lib/ipc';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';-import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';+import { DisclosureRow, disclosureRowClass } from '@renderer/lib/ui/disclosure-row';+import { Field, FieldDescription } from '@renderer/lib/ui/field';import { log } from '@renderer/utils/logger';+import { cn } from '@renderer/utils/utils';import type { AgentSidecarStatus, SidecarVerdict } from '@shared/events/sidecarEvents';import { sidecarStatusChannel } from '@shared/events/sidecarEvents';@@ -102,10 +109,8 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {return (<Field>- <div className="flex items-center justify-between gap-3">- <FieldTitle>Remote sidecar</FieldTitle>- {data && <VerdictBadge verdict={data.verdict} />}- </div>+ {data && <StatusStrip status={data} />}+<FieldDescription className="text-foreground-muted">The on-host process that keeps this agent connected to its Switch rooms while Switch Consoleis closed. Updated automatically when Switch Console connects; you can also manage it here.@@ -129,13 +134,11 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {)}{data && (- <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-4"><VersionRows status={data} /><div className="flex flex-wrap items-center gap-2"><Button- size="sm"- variant="outline"disabled={busy || NOTHING_TO_UPDATE.has(data.verdict)}onClick={() => upgrade.mutate()}>@@ -146,7 +149,7 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {)}Update</Button>- <Button size="sm" variant="outline" disabled={busy} onClick={() => restart.mutate()}>+ <Button variant="outline" disabled={busy} onClick={() => restart.mutate()}>{restart.isPending ? (<Loader2 className="size-3.5 animate-spin" />) : (@@ -154,9 +157,19 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {)}{data.verdict === 'incompatible' ? 'Replace' : 'Restart'}</Button>++ <p className="min-w-0 flex-1 px-2 text-xs text-foreground-muted">+ {data.verdict === 'other-install' &&+ 'Another Switch Console install on this host deployed the running sidecar, from the same release as yours. Neither build is newer, so this one leaves it alone rather than the two of you replacing it in turn. Use Restart to run your build instead — the other install will then leave yours alone.'}+ {data.verdict === 'upgrade-pending' &&+ `An update is ready but held back because ${data.liveSessions} session${+ data.liveSessions === 1 ? ' is' : 's are'+ } running. It applies next time the sidecar is idle — or use Restart to apply it now (running sessions reconnect automatically).`}+ </p>+<Button- size="sm"variant="outline"+ className="text-destructive hover:text-destructive ml-auto"disabled={busy || !data.running}onClick={() => stop.mutate()}>@@ -169,24 +182,6 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {</Button></div>- {data.verdict === 'other-install' && (- <p className="text-xs text-foreground-muted">- Another Switch Console install on this host deployed the running sidecar, from the- same release as yours. Neither build is newer, so this one leaves it alone rather than- the two of you replacing it in turn. Use Restart to run your build instead — the other- install will then leave yours alone.- </p>- )}-- {data.verdict === 'upgrade-pending' && (- <p className="text-xs text-foreground-muted">- An update is ready but held back because {data.liveSessions} session- {data.liveSessions === 1 ? '' : 's'} {data.liveSessions === 1 ? 'is' : 'are'} running.- It applies next time the sidecar is idle — or use Restart to apply it now (running- sessions reconnect automatically).- </p>- )}-<SidecarLog agentId={agentId} /></div>)}@@ -194,6 +189,34 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {);}+/**+ * What the host is running right now, in one line: the verdict, the build with+ * its restart count and pid, and which host it is. The first thing to look at,+ * so it is the first thing on the section.+ */+function StatusStrip({ status }: { status: AgentSidecarStatus }) {+ return (+ <div className="flex items-center gap-3 rounded-[10px] bg-[var(--surface-2)] px-3 py-2.5">+ <VerdictBadge verdict={status.verdict} />+ <span className="min-w-0 flex-1 truncate font-mono text-xs">+ {status.running ? runningBuildLine(status) : 'not running'}+ </span>+ <span className="flex shrink-0 items-center gap-1.5 text-xs text-foreground-muted">+ <Server className="size-3.5" />+ {status.sshHost}+ </span>+ </div>+ );+}++function runningBuildLine(status: AgentSidecarStatus): string {+ return (+ `${status.deployedVersion ?? '?'}+${shortHash(status.deployedHash)}` ++ (status.epoch !== null ? ` · restart #${status.epoch}` : '') ++ (status.pid !== null ? ` · pid ${status.pid}` : '')+ );+}+function VerdictBadge({ verdict }: { verdict: SidecarVerdict }) {const { label, variant, icon: Icon } = VERDICT_DISPLAY[verdict];return (@@ -204,36 +227,78 @@ function VerdictBadge({ verdict }: { verdict: SidecarVerdict }) {}function VersionRows({ status }: { status: AgentSidecarStatus }) {+ const clientBuild = `${status.clientVersion}+${shortHash(status.clientHash)}`;+ const hostBuild = status.running+ ? `${status.deployedVersion ?? '?'}+${shortHash(status.deployedHash)}`+ : null;+return (- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">- <Row- label="This client ships"- value={`${status.clientVersion}+${shortHash(status.clientHash)}`}- />- <Row- label="Host running"- value={- status.running- ? `${status.deployedVersion ?? '?'}+${shortHash(status.deployedHash)}` +- (status.epoch !== null ? ` · restart #${status.epoch}` : '') +- (status.pid !== null ? ` · pid ${status.pid}` : '')- : 'not running'- }- />- {status.running && <Row label="Deployed by" value={deployedByLabel(status)} />}- <Row label="Live sessions" value={String(status.liveSessions)} />- <Row label="Host" value={status.sshHost} />- <Row label="Working dir" value={status.repoDir} mono />+ <dl className="divide-y divide-border overflow-hidden rounded-[10px] border border-border text-sm">+ <Row label="Version">+ {/* Both builds on one line, in the direction the update would go. Read+ as two rows they were two facts to compare; read as one they are the+ gap itself. */}+ <span className="flex flex-wrap items-center gap-2 font-mono text-xs">+ {hostBuild === null ? (+ <span className="text-foreground-muted">not running</span>+ ) : (+ <>+ <span>{hostBuild}</span>+ {hostBuild !== clientBuild && (+ <>+ <ArrowRight className="size-3.5 text-foreground-muted" />+ <span>{clientBuild}</span>+ </>+ )}+ </>+ )}+ {hostBuild !== clientBuild && (+ <span className="font-sans text-foreground-muted">this client ships</span>+ )}+ </span>+ </Row>+ <Row label="Live sessions">{String(status.liveSessions)}</Row>+ {status.running && <Row label="Deployed by">{deployedByLabel(status)}</Row>}+ <Row label="Working dir">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate font-mono text-xs">{status.repoDir}</span>+ <CopyButton value={status.repoDir} label="Copy the working directory" />+ </span>+ </Row></dl>);}-function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {+function Row({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex items-center gap-4 px-3 py-2.5">+ <dt className="w-32 shrink-0 text-foreground-muted">{label}</dt>+ <dd className="min-w-0 flex-1 truncate">{children}</dd>+ </div>+ );+}++function CopyButton({ value, label }: { value: string; label: string }) {+ const [copied, setCopied] = useState(false);+return (- <>- <dt className="text-foreground-muted">{label}</dt>- <dd className={mono ? 'truncate font-mono text-xs' : 'truncate'}>{value}</dd>- </>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={label}+ className="ml-auto shrink-0"+ onClick={() => {+ void navigator.clipboard.writeText(value).then(+ () => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ },+ (error: unknown) => log.error('Failed to copy to the clipboard', { error })+ );+ }}+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </Button>);}@@ -246,17 +311,21 @@ function SidecarLog({ agentId }: { agentId: string }) {});if (!open) {- return (- <Button size="xs" variant="ghost" className="self-start" onClick={() => setOpen(true)}>- Show recent log- </Button>- );+ return <DisclosureRow open={false} title="Show recent log" onToggle={() => setOpen(true)} />;}return (<div className="flex flex-col gap-1">- <div className="flex items-center justify-between">- <span className="text-xs text-foreground-muted">Recent sidecar log</span>+ <div className={cn(disclosureRowClass, 'justify-between hover:bg-transparent')}>+ <button+ type="button"+ aria-expanded+ className="-mx-2 flex cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 text-sm transition-colors hover:bg-background-1"+ onClick={() => setOpen(false)}+ >+ <ChevronRight className="size-4 rotate-90 text-foreground-muted" />+ <span className="font-medium text-foreground">Recent sidecar log</span>+ </button><Button size="xs" variant="ghost" disabled={isFetching} onClick={() => void refetch()}>{isFetching ? (<Loader2 className="size-3 animate-spin" />diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex d550dc9ca..5950c44f8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -1,5 +1,6 @@import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';+import { SectionLabel } from '@renderer/features/locations/components/main-panel/agent-page-section';import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';import { AgentAdvancedSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section';import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';@@ -38,10 +39,13 @@ export const SettingsPanel = observer(function SettingsPanel() {const agentId = agent?.id;return (- <div className="flex flex-col gap-6">- <AutoSessionSettingsSection locationId={locationId} agentId={agentId} />- <AutoApproveSettingsSection locationId={locationId} agentId={agentId} />- <AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />+ <div className="flex flex-col gap-10">+ <section className="flex flex-col gap-6">+ <SectionLabel>General</SectionLabel>+ <AutoSessionSettingsSection locationId={locationId} agentId={agentId} />+ <AutoApproveSettingsSection locationId={locationId} agentId={agentId} />+ <AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />+ </section><AgentAdvancedSettingsSection locationId={locationId} agentId={agentId} /></div>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsxindex e3cf7b635..3c151437a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx@@ -1,5 +1,6 @@import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';+import { SectionLabel } from '@renderer/features/locations/components/main-panel/agent-page-section';import { SidecarSettingsSection } from '@renderer/features/locations/components/settings-view/sections/sidecar-settings-section';import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';@@ -37,8 +38,9 @@ export const SidecarPanel = observer(function SidecarPanel() {}return (- <div className="flex flex-col gap-6">+ <section className="flex flex-col gap-4">+ <SectionLabel>Sidecar</SectionLabel><SidecarSettingsSection agentId={agent.id} />- </div>+ </section>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/components/agent-status-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/components/agent-status-indicator.tsxindex 00b014642..607844f6a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/components/agent-status-indicator.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/components/agent-status-indicator.tsx@@ -1,4 +1,4 @@-import { CLISpinner } from '@renderer/features/sessions/components/cliSpinner';+import { Spinner } from '@renderer/lib/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';import type { AgentStatus } from '@shared/core/providers/agentEvents';@@ -11,55 +11,27 @@ interface AgentStatusIndicatorProps {disableTooltip?: boolean;}-const STATUS_LABELS = {- working: 'Agent is working',- 'awaiting-input': 'Agent is awaiting input',- error: 'Agent error',- completed: 'Agent completed',-};-+/**+ * What a session is doing, shown only while it is doing something.+ *+ * Working is the one state worth a mark in a list: it is the reason to wait,+ * and it ends on its own. The resting states — awaiting input, errored,+ * completed — used to each carry a coloured dot, and a column of them said+ * little at a glance while costing every row the same space. They are gone;+ * what a finished session actually did belongs on the session, not in a dot+ * whose colour has to be learned.+ */export function AgentStatusIndicator({status,className,disableTooltip,}: AgentStatusIndicatorProps) {- if (!status || status === 'idle') return null;-- const renderIndicator = () => {- switch (status) {- case 'working':- return <CLISpinner />;- case 'awaiting-input':- return (- <span- className={cn('rounded-full bg-foreground-info size-2', className)}- aria-label="Agent is awaiting input"- title="Agent is awaiting input"- />- );- case 'error':- return (- <span- className={cn('rounded-full bg-foreground-error size-2', className)}- aria-label="Agent error"- title="Agent error"- />- );- case 'completed':- return (- <span- className={cn('rounded-full bg-foreground-info size-2', className)}- aria-label="Agent completed"- title="Agent completed"- />- );- default:- return null;- }- };+ if (status !== 'working') return null;const indicator = (- <span className="flex size-6 items-center justify-center">{renderIndicator()}</span>+ <span className="flex size-6 items-center justify-center">+ <Spinner className={cn('size-3.5 text-foreground-muted', className)} />+ </span>);if (disableTooltip) return indicator;@@ -67,7 +39,7 @@ export function AgentStatusIndicator({return (<Tooltip><TooltipTrigger render={indicator} />- <TooltipContent>{STATUS_LABELS[status]}</TooltipContent>+ <TooltipContent>Agent is working</TooltipContent></Tooltip>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/components/cliSpinner.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/components/cliSpinner.tsxdeleted file mode 100644index 6c0fae894..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/components/cliSpinner.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useEffect, useState } from 'react';--const FRAMES_1 = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];-const FRAMES_2 = [- '⠈',- '⠉',- '⠋',- '⠓',- '⠒',- '⠐',- '⠐',- '⠒',- '⠖',- '⠦',- '⠤',- '⠠',- '⠠',- '⠤',- '⠦',- '⠖',- '⠒',- '⠐',- '⠐',- '⠒',- '⠓',- '⠋',- '⠉',- '⠈',-];--export function CLISpinner({ variant = '1' }: { variant?: '1' | '2' }) {- const [index, setIndex] = useState(0);-- useEffect(() => {- const interval = setInterval(() => {- setIndex((index + 1) % (variant === '1' ? FRAMES_1.length : FRAMES_2.length));- }, 80);- return () => clearInterval(interval);- }, [index, variant]);-- return (- <span className="text-foreground/60">- {variant === '1' ? FRAMES_1[index] : FRAMES_2[index]}- </span>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsxindex 3851f1cb7..c28949802 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -6,6 +6,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';@@ -105,6 +106,27 @@ function useRoomMemberAgents(roomId: string | undefined): {return { agents, serverId, loading: membersQuery.isLoading || !agentsStore.loaded };}+/**+ * Every agent on the active server, for the case where the caller named none.+ *+ * Scoped to the active server because that is the workspace on screen: the+ * sidebar, its tree and this dialog are all showing one server, and offering+ * agents from another would start a session outside the thing being looked at.+ */+function useAllServerAgents(enabled: boolean): { agents: Agent[]; loading: boolean } {+ useEffect(() => {+ if (enabled) void agentsStore.load();+ }, [enabled]);++ const serverId = switchServersStore.activeServerId;+ const agents = [...agentsStore.byLocation.values()]+ .flat()+ .filter((a) => a.serverId === serverId)+ .sort((a, b) => a.name.localeCompare(b.name));++ return { agents, loading: !agentsStore.loaded };+}+export const CreateSessionModal = observer(function CreateSessionModal({locationId,agentName,@@ -136,6 +158,12 @@ export const CreateSessionModal = observer(function CreateSessionModal({// the room), in which case the picker just shows that agent, still switchable.const roomFirst = !!roomId;const roomMembers = useRoomMemberAgents(roomId);+ // Opened from the sidebar's own New Session row, which names neither an agent+ // nor a room. A session is owned by an agent, so one has to be chosen here;+ // falling back to the most recent location would start the session as+ // whichever agent happened to be last, with nothing on screen saying which.+ const agentFirstNeedsPick = !roomId && !agentName && !locationId;+ const pickableAgents = useAllServerAgents(agentFirstNeedsPick);const presetAgent =roomMembers.agents.find((a) => a.name === agentName && (!locationId || a.locationId === locationId)@@ -144,11 +172,19 @@ export const CreateSessionModal = observer(function CreateSessionModal({// formality, and the user still sees which agent it resolved to.const effectiveAgent =pickedAgent ?? presetAgent ?? (roomMembers.agents.length === 1 ? roomMembers.agents[0] : null);- const selectedLocationId = roomFirst ? effectiveAgent?.locationId : defaultLocationId;+ const selectedLocationId = roomFirst+ ? effectiveAgent?.locationId+ : agentFirstNeedsPick+ ? pickedAgent?.locationId+ : defaultLocationId;// Every Switch Console agent is its own Switch identity, so a session is always// owned by a named agent row (CHOO-1440) — the picked agent's name plays the// same part here as the `agentName` an agent row passes in.- const effectiveAgentName = roomFirst ? effectiveAgent?.name : agentName;+ const effectiveAgentName = roomFirst+ ? effectiveAgent?.name+ : agentFirstNeedsPick+ ? pickedAgent?.name+ : agentName;// A session belongs to an agent; resolve the location's agent up front so we// can offer the rooms it belongs to.@@ -279,6 +315,60 @@ export const CreateSessionModal = observer(function CreateSessionModal({</DialogHeader><DialogContentArea><div className="flex w-full flex-col gap-5">+ {agentFirstNeedsPick && (+ <Field>+ <FieldLabel>Agent</FieldLabel>+ <Combobox+ items={pickableAgents.agents}+ value={pickedAgent}+ onValueChange={(next: Agent | null) => setPickedAgent(next)}+ isItemEqualToValue={(a: Agent, b: Agent) => a.id === b.id}+ filter={(item: Agent, query) =>+ item.name.toLowerCase().includes(query.toLowerCase())+ }+ autoHighlight+ >+ <ComboboxTrigger+ disabled={pickableAgents.loading || pickableAgents.agents.length === 0}+ className={cn(+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',+ (pickableAgents.loading || pickableAgents.agents.length === 0) &&+ 'cursor-not-allowed opacity-60'+ )}+ >+ <span+ className={cn(+ 'flex-1 truncate text-left',+ !pickedAgent && 'text-foreground-muted'+ )}+ >+ {pickedAgent+ ? pickedAgent.name+ : pickableAgents.loading+ ? 'Loading agents…'+ : 'Choose an agent'}+ </span>+ <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />+ </ComboboxTrigger>+ <ComboboxContent className="min-w-(--anchor-width)">+ <ComboboxInput showTrigger={false} placeholder="Search agents…" />+ <ComboboxList>+ {(item: Agent) => (+ <ComboboxItem key={item.id} value={item}>+ <span className="min-w-0 flex-1 truncate">{item.name}</span>+ </ComboboxItem>+ )}+ </ComboboxList>+ <ComboboxEmpty>No agents found</ComboboxEmpty>+ </ComboboxContent>+ </Combobox>+ {!pickableAgents.loading && pickableAgents.agents.length === 0 && (+ <p className="mt-1 text-xs text-foreground-muted">+ This server has no agents yet. Add one first, then start a session for it.+ </p>+ )}+ </Field>+ )}{roomFirst && (<Field><FieldLabel>Agent</FieldLabel>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsxindex d35b049d2..8792e701d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/session-titlebar.tsx@@ -12,6 +12,7 @@ import {getSessionStore,sessionDisplayName,} from '@renderer/features/sessions/stores/session-selectors';+import { openRoom } from '@renderer/features/switch-rooms/open-room';import { switchRoomsStore as sessionRoomsStore } from '@renderer/features/switch-rooms/switch-rooms-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';@@ -74,7 +75,7 @@ export const SessionTitlebar = observer(function SessionTitlebar() {),label: roomName,maxWidthClassName: 'max-w-40',- onClick: () => navigate('room', { roomId }),+ onClick: () => void openRoom(roomId),});}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsxindex 4ccbac263..6ba7c23c0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx@@ -1,13 +1,4 @@-import {- Bot,- ChevronRight,- ExternalLink,- Plus,- RotateCcw,- Server,- Trash2,- TriangleAlert,-} from 'lucide-react';+import { Bot, ChevronRight, Plus, RotateCcw, Server, Trash2, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';import {@@ -21,7 +12,6 @@ import {hasDiscardableSessionError,hasSessionError,} from '@renderer/features/sessions/stores/session-selectors';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -96,11 +86,6 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({const sshHost = location.data?.sshHost ?? null;const hostUnreachable = hostReachabilityStore.isBlocked(sshHost);- const gatewayUrl =- agent.serverId && agent.switchAgentId- ? switchRoomsStore.gatewayAgentUrl(agent.serverId, agent.switchAgentId)- : null;-// Opening the agent does not expand it. Expanding is the chevron's job alone,// so what is unfolded in the tree stays as the reader left it.const open = () => navigate('location', { locationId: agent.locationId, agentName });@@ -109,15 +94,17 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({<ContextMenu><ContextMenuTrigger><SidebarMenuRow- className="group/row flex h-8 justify-between px-1"- style={depthIndent(depth)}+ className="group/row flex justify-between"data-active={isActive || undefined}isActive={isActive}onMouseDown={(e) => e.preventDefault()}onClick={open}>- <div className="flex min-w-0 flex-1 items-center gap-1">- <span className="flex size-6 shrink-0 items-center justify-center">+ {/* The indent lives on the content, not the row, so the hover and+ selection highlight still spans the sidebar's full width at every+ depth. */}+ <div className="flex min-w-0 flex-1 items-center gap-[9px]" style={depthIndent(depth)}>+ <span className="flex size-4 shrink-0 items-center justify-center">{agent.providerId ? (<AgentIcon id={agent.providerId} size={16} className="h-4 w-4" />) : (@@ -180,29 +167,6 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({</span></SidebarMenuAction></div>- {gatewayUrl && agent.serverId && (- <Tooltip>- <TooltipTrigger- render={- <SidebarItemMiniButton- type="button"- aria-label={`Open ${label} in gateway`}- className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"- onClick={(e) => {- e.stopPropagation();- void rpc.switchServers.openGatewayPage({- serverId: agent.serverId!,- url: gatewayUrl,- });- }}- >- <ExternalLink className="h-3.5 w-3.5" />- </SidebarItemMiniButton>- }- />- <TooltipContent>Open in gateway</TooltipContent>- </Tooltip>- )}<Tooltip><TooltipTriggerclassName="h-6"diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsxindex f6b06e7c0..a6780bf04 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx@@ -9,7 +9,6 @@ import {groupByRoom,isRoomNameKnown,isRoomViewActive,- openRoomInGateway,openRoomInMessagingApp,openRoomView,RoomRow,@@ -69,7 +68,6 @@ const AgentSessions = observer(function AgentSessions({onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}onSelect={() => openRoomView(roomKey)}isActive={isRoomViewActive(roomKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}onOpenChannel={switchRoomsStore.roomChannelUrl(roomKey)? () => openRoomInMessagingApp(roomKey)diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsxindex 8a733dadd..84c5f2a4f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx@@ -37,7 +37,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {return (<divclassName={cn(- 'relative flex flex-col h-full bg-background-tertiary text-foreground-tertiary-muted transition-colors',+ 'relative flex flex-col h-full text-foreground-tertiary-muted transition-colors',isDragOver && 'bg-accent/10 ring-2 ring-inset ring-accent/50')}onDragOver={onDragOver}@@ -56,13 +56,14 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {<SidebarContent className="flex flex-col"><SidebarPinnedSessionList />{/* The sidebar reads as three blocks — which server, that server's- pages, then its sessions — so the vertical rhythm between them- lives here rather than as padding each block sets for itself. */}- <div className="flex flex-col gap-3">+ pages, then its sessions. The switcher and the nav under it are+ one block, 8px apart, which the nav owns as its own top padding;+ the sessions section sets the larger gap that separates it. */}+ <div className="flex flex-col"><WorkspaceSwitcher /><WorkspaceNav /></div>- <SidebarGroup className="mt-5 mb-0 flex min-h-0 flex-1 flex-col">+ <SidebarGroup className="mt-0 mb-0 flex min-h-0 flex-1 flex-col"><SessionsSectionHeader /><SidebarGroupContent className="flex min-h-0 flex-1 flex-col"><SidebarMenu className="flex min-h-0 flex-1 flex-col">@@ -104,7 +105,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {</SidebarMenuButton></SidebarMenu></SidebarFooter>- <div className="flex items-center justify-between gap-2 border-t border-border px-3 py-2">+ <div className="flex items-center justify-between gap-2 px-3 py-2">{/* The mark doubles as the way back to the welcome screen — the oneview with no other entry point once you have navigated away. */}<button@@ -112,7 +113,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {onClick={() => navigate('home')}aria-label="Go to home"title="Home"- className="rounded-md text-foreground-passive transition-colors hover:text-foreground"+ className="rounded-md text-[var(--fg-passive)] transition-colors hover:text-foreground"><SwitchConsoleMark size={18} /></button>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsxindex 9b551ee99..ef28d774f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx@@ -95,8 +95,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({<ContextMenu><ContextMenuTrigger><SidebarMenuRow- className="group/row flex h-8 justify-between px-1"- style={depthIndent(depth)}+ className="group/row flex justify-between"data-active={isActive || undefined}isActive={isActive}onMouseDown={(e) => e.preventDefault()}@@ -104,8 +103,10 @@ export const RoomAgentRow = observer(function RoomAgentRow({navigate('location', { locationId: agent.locationId, agentName: agent.name, roomId })}>- <div className="flex min-w-0 flex-1 items-center gap-1">- <span className="flex size-6 shrink-0 items-center justify-center">+ {/* Indent on the content, not the row, so the highlight still spans+ the sidebar's full width at every depth. */}+ <div className="flex min-w-0 flex-1 items-center gap-[9px]" style={depthIndent(depth)}>+ <span className="flex size-4 shrink-0 items-center justify-center">{agent.providerId ? (<AgentIcon id={agent.providerId} size={16} className="h-4 w-4" />) : (diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsxindex 71e83a0b9..82b53a2ed 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx@@ -12,7 +12,7 @@ import {groupByRoom,isRoomNameKnown,isRoomViewActive,- openRoomInGateway,+ deleteRoomAction,openRoomInMessagingApp,openRoomView,RoomRow,@@ -64,6 +64,7 @@ function membersByRoom(): Map<string, AgentEntry[]> {export const RoomTree = observer(function RoomTree() {const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');+ const showDeleteRoomModal = useShowModal('deleteRoomModal');// Tag every visible session with the agent it belongs to, then group by room.const bySession = new Map<string, AgentEntry>();@@ -142,13 +143,13 @@ export const RoomTree = observer(function RoomTree() {onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}onSelect={() => openRoomView(roomKey)}isActive={isRoomViewActive(roomKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}onOpenChannel={switchRoomsStore.roomChannelUrl(roomKey)? () => openRoomInMessagingApp(roomKey): null}onAddAgent={() => showAddAgentsToRoomModal({ roomId: roomKey })}+ onDelete={deleteRoomAction(roomKey, showDeleteRoomModal)}/>}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsxindex e465c722c..bd1de4908 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx@@ -91,31 +91,36 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({return (<SessionContextMenu {...actions}><SidebarMenuRow- className={cn(- 'group/row flex items-center justify-between px-1 h-8 gap-1',- rowVariant === 'pinned' && 'pl-2'- )}- style={rowVariant === 'pinned' ? undefined : depthIndent(depth)}+ className="group/row flex items-center justify-between gap-[9px]"isActive={isActive}onMouseDown={(e) => e.preventDefault()}onClick={openSession}>- <span className="flex h-6 w-6 shrink-0 items-center justify-center">- <MessageSquare className="h-4 w-4 text-foreground-muted" />- </span>- <SidebarMenuAction- aria-label={`Open session ${sessionName || 'session'}`}- className="gap-1 overflow-hidden"+ {/* Indent on the content, not the row, so the highlight still spans the+ sidebar's full width at every depth. The icon box is wider than a+ header row's and the gap tighter, which is what optically continues+ the 16px step without a third indent value. */}+ <div+ className="flex h-6 min-w-0 flex-1 items-center gap-1"+ style={rowVariant === 'pinned' ? { paddingLeft: 4 } : depthIndent(depth)}>- <span- className={cn(- 'min-w-0 truncate text-left transition-colors',- session.isBootstrapping && 'text-foreground/40'- )}- >- {sessionName}+ <span className="flex h-6 w-6 shrink-0 items-center justify-center">+ <MessageSquare className="h-4 w-4 text-foreground-muted" /></span>- </SidebarMenuAction>+ <SidebarMenuAction+ aria-label={`Open session ${sessionName || 'session'}`}+ className="gap-1 overflow-hidden"+ >+ <span+ className={cn(+ 'min-w-0 truncate text-left transition-colors',+ session.isBootstrapping && 'text-foreground/40'+ )}+ >+ {sessionName}+ </span>+ </SidebarMenuAction>+ </div>{/* The status and the actions button take turns in one slot rather thansitting side by side: the row is narrow, and a second controlappearing on hover would shorten the title just as it is being read. */}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsxindex 8be90191f..b626d4dd3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx@@ -1,20 +1,20 @@import { observer } from 'mobx-react-lite';import { AgentStatusIndicator } from '@renderer/features/sessions/components/agent-status-indicator';-import { CLISpinner } from '@renderer/features/sessions/components/cliSpinner';import { sessionAgentStatus } from '@renderer/features/sessions/stores/session-selectors';import { type SessionStore } from '@renderer/features/sessions/stores/session-store';import { useDelayedBoolean } from '@renderer/lib/hooks/use-delay-boolean';import { sidebarStore } from '@renderer/lib/stores/app-state';import { RelativeTime } from '@renderer/lib/ui/relative-time';+import { Spinner } from '@renderer/lib/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { getSortInstant, sortKindFor } from './sidebar-store';/**- * Sidebar trailing slot: spinner while bootstrapping, the live agent status- * indicator while an agent is active (non-idle), otherwise the relative- * timestamp. The whole metadata cluster is right-aligned by the parent, so- * the slot just hugs its content — no fixed width to avoid an empty gap- * between the timestamp and the line-changes / PR icon to its left.+ * Sidebar trailing slot: a spinner while the session is being created or its+ * agent is working, otherwise the relative timestamp. The whole metadata+ * cluster is right-aligned by the parent, so the slot just hugs its content —+ * no fixed width to avoid an empty gap between the timestamp and the+ * line-changes / PR icon to its left.*/function Slot({ children }: { children: React.ReactNode }) {return <span className="flex w-[3ch] shrink-0 items-center justify-end">{children}</span>;@@ -33,7 +33,7 @@ export const SessionSidebarTrailingSlot = observer(function SessionSidebarTraili<Tooltip><TooltipTrigger><span className="flex size-6 items-center justify-center">- <CLISpinner variant="2" />+ <Spinner className="size-3.5 text-foreground-muted" /></span></TooltipTrigger><TooltipContent>Creating session…</TooltipContent>@@ -42,12 +42,13 @@ export const SessionSidebarTrailingSlot = observer(function SessionSidebarTraili);}- // Show the agent status indicator for any active/unseen state; fall back to timestamp for null (idle).- const status = sessionAgentStatus(session);- if (status !== null) {+ // Only a working agent takes the slot from the timestamp. The other non-idle+ // states no longer draw anything, so testing for "not idle" here would hand+ // the slot to an indicator that renders nothing and blank the time instead.+ if (sessionAgentStatus(session) === 'working') {return (<Slot>- <AgentStatusIndicator status={status} />+ <AgentStatusIndicator status="working" /></Slot>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsxindex d06236089..c55bd9d2e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx@@ -1,11 +1,19 @@-import { ArrowUpDown, DoorOpen, Filter, Laptop, Plus, Server, UserPlus } from 'lucide-react';+import {+ ChevronsDownUp,+ DoorOpen,+ Laptop,+ MoreHorizontal,+ Plus,+ Server,+ UserPlus,+} from 'lucide-react';import { observer } from 'mobx-react-lite';+import { useState } from 'react';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { buttonVariants } from '@renderer/lib/ui/button';import {DropdownMenu,DropdownMenuCheckboxItem,@@ -19,7 +27,7 @@ import {DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';import { SectionLabel } from '@renderer/lib/ui/label';-import { ToggleGroup, ToggleGroupItem } from '@renderer/lib/ui/toggle-group';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';@@ -47,33 +55,12 @@ const GROUPING_OPTIONS: { value: SidebarGrouping; label: string }[] = [*/const ViewGroupingToggle = observer(function ViewGroupingToggle() {return (- <ToggleGroup- size="sm"- spacing={1}- multiple={false}- value={[sidebarStore.grouping]}- onValueChange={([value]) => {- const opt = GROUPING_OPTIONS.find((o) => o.value === value);- if (opt) sidebarStore.setGrouping(opt.value);- }}- aria-label="Group sidebar by"- // The raised option has to read as sitting *in* the track, not as a- // button dropped on top of a box: concentric corners (inner radius =- // outer radius less the padding) and only a hairline of track showing- // around it.- className="h-7 gap-px rounded-lg border-transparent bg-background-tertiary-2 p-px"- >- {GROUPING_OPTIONS.map((opt) => (- <ToggleGroupItem- key={opt.value}- value={opt.value}- aria-label={opt.label}- className="rounded-[7px] px-2.5 hover:bg-transparent aria-pressed:bg-background data-pressed:bg-background data-[state=on]:bg-background"- >- {opt.label}- </ToggleGroupItem>- ))}- </ToggleGroup>+ <SegmentedControl+ value={sidebarStore.grouping}+ onChange={(value) => sidebarStore.setGrouping(value)}+ options={GROUPING_OPTIONS}+ ariaLabel="Group sidebar by"+ />);});@@ -194,83 +181,35 @@ const AgentFilterSections = observer(function AgentFilterSections() {);});-/**- * Optional additive filters for the grouped sidebar — a funnel button whose- * sections belong to the view you are in, since the two views filter different- * things. A dot on the icon signals that the view on screen is being narrowed.- */-const FilterDropdown = observer(function FilterDropdown() {- const roomMode = sidebarStore.grouping === 'room';- const active = sidebarStore.hasActiveFiltersInCurrentView;-- return (- <DropdownMenu>- <Tooltip>- <DropdownMenuTrigger- render={- <TooltipTrigger- render={- <button- type="button"- aria-label={roomMode ? 'Filter rooms' : 'Filter agents'}- className={buttonVariants({- size: 'icon-xs',- variant: 'ghost',- className: cn(- 'relative hover:bg-transparent hover:text-foreground',- active ? 'text-foreground' : 'text-foreground-muted'- ),- })}- >- <Filter />- {active && (- <span className="bg-accent absolute top-0.5 right-0.5 h-1.5 w-1.5 rounded-full" />- )}- </button>- }- />- }- />- <TooltipContent>Filter</TooltipContent>- </Tooltip>- <DropdownMenuContent className="min-w-52" align="end">- <DropdownMenuGroup>- <DropdownMenuLabel>{roomMode ? 'Filter rooms' : 'Filter agents'}</DropdownMenuLabel>- </DropdownMenuGroup>- {roomMode ? <RoomFilterSections /> : <AgentFilterSections />}- <DropdownMenuSeparator />- <DropdownMenuItem disabled={!active} onClick={() => sidebarStore.clearFilters()}>- Clear filters- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-});-/*** The Sessions section's header: what the list below is, then how it is- * arranged. The grouping toggle used to sit alone on a single row, where it- * read as the sidebar's whole navigation rather than as one list's setting.+ * arranged, then the one thing you most often want to do next.+ *+ * The toggle shares the label's line rather than owning one of its own. Alone+ * on a row it read as the sidebar's whole navigation instead of as one list's+ * setting, which is why it previously sat under a "Group by" caption; keeping+ * it beside "Sessions" says the same thing without spending a second row.*/export const SessionsSectionHeader = observer(function SessionsSectionHeader() {const showAddLocationModal = useShowModal('addAgentModal');const showCreateRoomModal = useShowModal('createRoomModal');- // The add button offers both actions rather than the one matching the current- // view. Which grouping you are looking at says how you want the list- // arranged, not which thing you next want to make, and reaching the other- // action used to mean switching view first.+ const showCreateSessionModal = useShowModal('sessionModal');+ const [optionsOpen, setOptionsOpen] = useState(false);+ // The add actions offer both rather than the one matching the current view.+ // Which grouping you are looking at says how you want the list arranged, not+ // which thing you next want to make, and reaching the other action used to+ // mean switching view first.const roomMode = sidebarStore.grouping === 'room';return (<>- <div className="flex h-[22px] items-center justify-between pr-2.5 pl-2.5">- <SectionLabel>Sessions</SectionLabel>- <span className="text-xs text-foreground-passive">Group by</span>- </div>- <div className="flex h-[36px] items-center justify-between pr-2.5 pl-2.5">- <ViewGroupingToggle />- <div className="flex items-center gap-1">- <DropdownMenu>+ {/* Label, its overflow menu and the grouping toggle share one line. The+ three icon buttons that used to sit on a second line — sort, filter,+ add — are all in the menu now; the actions are unchanged. */}+ <div className="group/sessions flex items-center justify-between px-5 pt-[18px] pb-2">+ <div className="flex items-center gap-[6px]">+ <SectionLabel>Sessions</SectionLabel>+ <DropdownMenu onOpenChange={setOptionsOpen}><Tooltip><DropdownMenuTriggerrender={@@ -278,23 +217,25 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {render={<buttontype="button"- aria-label={roomMode ? 'Sort rooms' : 'Sort agents'}- className={buttonVariants({- size: 'icon-xs',- variant: 'ghost',- className:- 'hover:bg-transparent text-foreground-muted hover:text-foreground',- })}+ aria-label="Session list options"+ // Hidden until the section is hovered, and held visible+ // while its own menu is open so the trigger does not+ // vanish from under the pointer. Opacity rather than+ // `hidden` so the row does not reflow on hover.+ className={cn(+ 'flex size-[18px] items-center justify-center rounded-[6px] text-[var(--fg-passive)] transition-opacity duration-150 hover:bg-[var(--sel-soft)] hover:text-foreground focus-visible:opacity-100',+ optionsOpen ? 'opacity-100' : 'opacity-0 group-hover/sessions:opacity-100'+ )}>- <ArrowUpDown />+ <MoreHorizontal className="size-[13px]" /></button>}/>}/>- <TooltipContent>Sort by</TooltipContent>+ <TooltipContent>Sort, filter and more</TooltipContent></Tooltip>- <DropdownMenuContent className="min-w-48">+ <DropdownMenuContent className="min-w-52" align="start"><DropdownMenuGroup><DropdownMenuLabel>Sort by</DropdownMenuLabel>{roomMode ? (@@ -338,34 +279,23 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {</DropdownMenuRadioGroup>)}</DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenu>- <FilterDropdown />- <DropdownMenu>- <Tooltip>- <DropdownMenuTrigger- render={- <TooltipTrigger- render={- <button- type="button"- aria-label="Add"- className={buttonVariants({- size: 'icon-xs',- variant: 'ghost',- className:- 'hover:bg-transparent text-foreground-muted hover:text-foreground',- })}- >- <Plus />- </button>- }- />- }- />- <TooltipContent>Add</TooltipContent>- </Tooltip>- <DropdownMenuContent className="min-w-48" align="start">+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuLabel>{roomMode ? 'Filter rooms' : 'Filter agents'}</DropdownMenuLabel>+ </DropdownMenuGroup>+ {roomMode ? <RoomFilterSections /> : <AgentFilterSections />}+ <DropdownMenuItem+ disabled={!sidebarStore.hasActiveFiltersInCurrentView}+ onClick={() => sidebarStore.clearFilters()}+ >+ Clear filters+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => sidebarStore.collapseAll()}>+ <ChevronsDownUp className="mr-1.5 h-4 w-4" />+ Collapse all+ </DropdownMenuItem>+ <DropdownMenuSeparator /><DropdownMenuItem onClick={() => showAddLocationModal({})}><UserPlus className="mr-1.5 h-4 w-4" />Add an agent@@ -377,6 +307,18 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {</DropdownMenuContent></DropdownMenu></div>+ <ViewGroupingToggle />+ </div>+ {/* Outside the tree's scroller, so it stays put as the list scrolls. */}+ <div className="px-2 pb-1">+ <button+ type="button"+ onClick={() => showCreateSessionModal({})}+ className="flex w-full cursor-pointer items-center gap-[9px] rounded-lg px-[9px] py-[6px] text-sm text-foreground-muted transition-colors hover:bg-[var(--sel-soft)] hover:text-foreground"+ >+ <Plus className="size-4 shrink-0" />+ New Session+ </button></div></>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-dnd.tsxindex 815bde46b..4afcea6fb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx@@ -107,7 +107,10 @@ export function SortableBranch({}) {const { setNodeRef, style, listeners } = useSortableRow(id);return (- <div ref={setNodeRef} style={style}>+ // The 2px gap is the same at every level, including between a branch's+ // header and its children: an extra step around groups would read as+ // stacked blocks rather than one tree.+ <div ref={setNodeRef} style={style} className="flex flex-col gap-[2px]"><div {...listeners}>{header}</div>{children}</div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex d30bc4b92..7aa54ec13 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -100,7 +100,10 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {switchRoomsStore.listedRoomsInActiveScope.length === 0;return (- <div ref={scrollerRef} className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">+ <div+ ref={scrollerRef}+ className="flex min-h-0 flex-1 flex-col gap-[2px] overflow-y-auto px-2 pt-0 pb-3"+ ><RoomStateDisclosure />{showFilterEmptyState ? (<p className="px-2 py-3 text-xs text-foreground-muted">No agents match filters</p>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-primitives.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-primitives.tsxindex ecd41c356..c9c8f4ec7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-primitives.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-primitives.tsx@@ -49,11 +49,7 @@ SidebarGroupContent.displayName = 'SidebarGroupContent';export const SidebarFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (- <div- ref={ref}- className={cn('mt-auto flex flex-col border-t px-3 py-3', className)}- {...props}- />+ <div ref={ref} className={cn('mt-auto flex flex-col px-3 py-3', className)} {...props} />));SidebarFooter.displayName = 'SidebarFooter';@@ -80,8 +76,11 @@ export const SidebarItemMiniButton = React.forwardRef<));SidebarItemMiniButton.displayName = 'SidebarItemMiniButton';+// Selection and hover are the translucent `--sel` pair rather than an opaque+// fill, so a row tints the material under it instead of cutting an opaque+// patch through the window's vibrancy.const sidebarMenuItemClass =- 'flex w-full cursor-pointer font-normal h-8 text-foreground-tertiary-muted rounded-lg items-center hover:bg-background-tertiary-1 hover:text-foreground-tertiary gap-2 px-3 py-2 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-[active=true]:bg-background-tertiary-2 data-[active=true]:text-foreground-tertiary';+ 'flex w-full cursor-pointer font-normal text-foreground-tertiary-muted rounded-lg items-center hover:bg-[var(--sel-soft)] hover:text-foreground-tertiary gap-[9px] px-[9px] py-[6px] text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-[active=true]:bg-[var(--sel)] data-[active=true]:font-medium data-[active=true]:text-foreground';interface SidebarMenuButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {isActive?: boolean;diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex c2ce3d4b4..e59f34399 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -1,11 +1,18 @@-import { ChevronRight, DoorOpen, ExternalLink, Plus } from 'lucide-react';+import { ChevronRight, DoorOpen, MoreVertical, Plus, Trash2 } from 'lucide-react';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';-import { openRoomChannel, openRoomGatewayPage } from '@renderer/features/switch-rooms/room-links';+import { openRoomChannel } from '@renderer/features/switch-rooms/room-links';import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { appState } from '@renderer/lib/stores/app-state';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@renderer/lib/ui/dropdown-menu';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';import { SidebarItemMiniButton, SidebarMenuRow } from './sidebar-primitives';@@ -35,10 +42,26 @@ export function isRoomNameKnown(roomKey: string): boolean {return switchRoomsStore.roomNameById(roomKey) !== null;}-/** Open a room's detail page in the gateway web app (no-op for Unassigned). */-export function openRoomInGateway(roomKey: string): void {- if (roomKey === UNASSIGNED_ROOM_KEY) return;- openRoomGatewayPage(roomKey);+/**+ * What a room row needs to offer deletion, or null when it must not offer it —+ * because the row is the Unassigned bucket, because the room's server or+ * summary has not loaded, or because this user is neither its owner nor an+ * admin.+ *+ * Returning the target rather than a boolean keeps the confirmation's arguments+ * and the decision to show it in one place; a row cannot end up with the button+ * and no idea what it would delete.+ */+export function deleteRoomAction(+ roomKey: string,+ showDeleteRoomModal: (args: { serverId: string; roomId: string; roomName: string }) => void+): (() => void) | null {+ if (roomKey === UNASSIGNED_ROOM_KEY) return null;+ const serverId = switchRoomsStore.roomServerId(roomKey);+ const room = switchRoomsStore.roomSummaryById(roomKey);+ if (!serverId || !room) return null;+ if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;+ return () => showDeleteRoomModal({ serverId, roomId: roomKey, roomName: room.name });}/** Show a room's conversation in the main panel (no-op for Unassigned, which@@ -107,16 +130,20 @@ export function groupByRoom(* chevron at the far end and to nothing else, so reading a room never rearranges* the tree underneath it. A row with no room behind it (Unassigned) has nothing* to open and so is not clickable at all.+ *+ * Everything else a room can do sits behind one menu rather than a strip of+ * icon buttons. A row that grows a button per capability spends the width it+ * needs for the room's name on affordances most people never press.*/export function RoomRow({label,hasChildren,expanded,onToggle,- onOpenGateway,onOpenChannel = null,onSelect = null,onAddAgent = null,+ onDelete = null,isActive = false,depth = 0,bridgeType = null,@@ -134,7 +161,6 @@ export function RoomRow({nameBlockedBySignIn?: boolean;expanded: boolean;onToggle: () => void;- onOpenGateway: () => void;/** Open the room's conversation in the main panel. Null for rows that have* no room behind them (Unassigned), which stay expand-only. */onSelect?: (() => void) | null;@@ -146,23 +172,31 @@ export function RoomRow({/** Add an agent to this room. Null for rows with no room behind them* (Unassigned), or where membership is not editable from here. */onAddAgent?: (() => void) | null;+ /** Delete the room. Null unless the signed-in user may — the gateway allows+ * its owner and admins, and offering it to anyone else only earns a refusal. */+ onDelete?: (() => void) | null;depth?: number;/** Bridge platform type (`slack`, `mattermost`, …) when the room is bridged. */bridgeType?: string | null;}) {const channelLinkable = onOpenChannel !== null && hasBridgeIcon(bridgeType);+ const hasRoomActions = onAddAgent !== null || channelLinkable || onDelete !== null;return (<SidebarMenuRowclassName={cn(- 'group/room flex h-8 items-center gap-1 px-1',+ 'group/room flex items-center gap-[9px]',onSelect === null && 'cursor-default')}isActive={isActive}- style={depthIndent(depth)}+ // Indent on the content below, not here, so the highlight still spans the+ // sidebar's full width at every depth.onMouseDown={(e) => e.preventDefault()}onClick={onSelect ?? undefined}>- <span className="flex size-6 shrink-0 items-center justify-center">+ <span+ className="flex size-4 shrink-0 items-center justify-center"+ style={{ marginLeft: depthIndent(depth).paddingLeft }}+ >{hasBridgeIcon(bridgeType) ? (<BridgeIcon bridgeType={bridgeType} size={16} className="h-4 w-4" />) : (@@ -187,64 +221,45 @@ export function RoomRow({</TooltipContent></Tooltip>)}- {channelLinkable && (- <Tooltip>- <TooltipTrigger+ {hasRoomActions && (+ <DropdownMenu>+ <DropdownMenuTriggerrender={<SidebarItemMiniButtontype="button"- aria-label={`Open ${label} in ${bridgePlatformLabel(bridgeType)}`}- className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100"- onClick={(e) => {- e.stopPropagation();- onOpenChannel?.();- }}+ aria-label={`Actions for ${label}`}+ className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100 data-[popup-open]:opacity-100"+ onClick={(e) => e.stopPropagation()}>- <BridgeIcon bridgeType={bridgeType} size={14} className="h-3.5 w-3.5" />+ <MoreVertical className="h-3.5 w-3.5" /></SidebarItemMiniButton>}/>- <TooltipContent>Open in {bridgePlatformLabel(bridgeType)}</TooltipContent>- </Tooltip>- )}- {onAddAgent && (- <Tooltip>- <TooltipTrigger- render={- <SidebarItemMiniButton- type="button"- aria-label={`Add an agent to ${label}`}- className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100"- onClick={(e) => {- e.stopPropagation();- onAddAgent();- }}- >- <Plus className="h-3.5 w-3.5" />- </SidebarItemMiniButton>- }- />- <TooltipContent>Add an agent to this room</TooltipContent>- </Tooltip>+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>+ {onAddAgent && (+ <DropdownMenuItem onClick={onAddAgent}>+ <Plus className="size-4" />+ Add an agent to this room+ </DropdownMenuItem>+ )}+ {channelLinkable && (+ <DropdownMenuItem onClick={() => onOpenChannel?.()}>+ <BridgeIcon bridgeType={bridgeType} size={16} className="size-4" />+ Open in {bridgePlatformLabel(bridgeType)}+ </DropdownMenuItem>+ )}+ {onDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 className="size-4" />+ Delete room…+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>)}- <Tooltip>- <TooltipTrigger- render={- <SidebarItemMiniButton- type="button"- aria-label={`Open ${label} in gateway`}- className="opacity-0 transition-opacity duration-150 group-hover/room:opacity-100"- onClick={(e) => {- e.stopPropagation();- onOpenGateway();- }}- >- <ExternalLink className="h-3.5 w-3.5" />- </SidebarItemMiniButton>- }- />- <TooltipContent>Open in gateway</TooltipContent>- </Tooltip>{hasChildren && (<SidebarItemMiniButtontype="button"diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-space.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-space.tsxindex 1c4cc2674..6ff02b464 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-space.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-space.tsx@@ -8,7 +8,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltiexport function SidebarSpace() {const { isLeftOpen, setCollapsed } = useWorkspaceLayoutContext();return (- <div className="flex h-10 w-full items-center justify-end gap-2 px-2 [-webkit-app-region:drag]">+ <div className="flex h-11 w-full items-center justify-end gap-2 px-2 [-webkit-app-region:drag]"><NavButtons /><Tooltip><TooltipTrigger>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.tsindex 0d5edf657..85f19932d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -532,6 +532,21 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}}+ /**+ * Close every top-level branch of the tree, in whichever grouping is on+ * screen. Second-level groups are left alone: they are tracked inverted+ * (absence means open), so collapsing them would mean enumerating every key+ * that exists, and they are hidden under a closed parent anyway.+ *+ * A location re-expands on its own if a session starts in it while+ * collapsed — see the reaction in the constructor. That is deliberate: a new+ * session appearing nowhere visible is worse than a branch reopening.+ */+ collapseAll(): void {+ this.expandedLocationIds.clear();+ this.expandedRoomKeys.clear();+ }+toggleLocationExpanded(locationId: string): void {if (this.expandedLocationIds.has(locationId)) {this.expandedLocationIds.delete(locationId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsxindex 7e209f31d..893453860 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx@@ -29,7 +29,7 @@ import {import { cn } from '@renderer/utils/utils';const TONE_TRIGGER_STYLES: Record<UpdateTone, string> = {- neutral: 'text-foreground-passive hover:text-foreground',+ neutral: 'text-[var(--fg-passive)] hover:text-foreground',info: 'border border-border-info bg-background-info text-foreground-info hover:bg-background-info-hover',success:'border border-border-success bg-background-success text-foreground-success hover:bg-background-success-hover',diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsxindex de0743fb5..90cd39f8a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx@@ -28,15 +28,14 @@ export const WorkspaceNav = observer(function WorkspaceNav() {] as const;return (- <SidebarMenu className="px-2">+ <SidebarMenu className="flex flex-col gap-[2px] px-2 pt-2">{destinations.map(({ view, icon: Icon, label, params }) => (<SidebarMenuButtonkey={view}isActive={isCurrentView(currentView, view) && params?.serverId === active.id}onClick={() => navigate(view, { serverId: active.id })}- className="h-7 px-2.5">- <Icon className="size-4 shrink-0" />+ <Icon className="size-[15px] shrink-0" />{label}</SidebarMenuButton>))}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsxnew file mode 100644index 000000000..1e5154cd7--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx@@ -0,0 +1,232 @@+import { Hash, Search, X } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useState } from 'react';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { rpc } from '@renderer/lib/ipc';+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+} from '@renderer/lib/ui/combobox';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldLabel } from '@renderer/lib/ui/field';++type Props = BaseModalProps<void> & {+ serverId: string;+ switchAgentId: string;+ agentName: string;+};++/** A room the agent can be put in: one on its own server it is not already in. */+type Candidate = { id: string; name: string; bridgeType: string | null };++/** Where a room's conversation actually happens, for the right of its row. */+function whereLabel(bridgeType: string | null): string {+ return bridgeType ? bridgePlatformLabel(bridgeType) : 'Switch only';+}++/** The mark of the app a room is bridged to, or a plain channel mark when it+ * lives on Switch alone. */+function RoomMark({ bridgeType, size }: { bridgeType: string | null; size: number }) {+ if (!hasBridgeIcon(bridgeType)) {+ return <Hash className="size-4 shrink-0 text-foreground-muted" />;+ }+ return <BridgeIcon bridgeType={bridgeType} size={size} />;+}++/**+ * Puts one agent into rooms — the agent's side of `AddAgentsToRoomModal`, which+ * puts agents into one room.+ *+ * Both write the same membership through `addRoomAgents`; which one you reach+ * for is only a matter of what you were looking at. An agent can only join rooms+ * on the server it is registered with, so the choice is scoped to that server.+ */+export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({+ serverId,+ switchAgentId,+ agentName,+ onSuccess,+ onClose,+}: Props) {+ const { setCloseGuard } = useModalContext();++ const [selected, setSelected] = useState<Candidate[]>([]);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Membership comes from the same cache the sidebar draws the room tree from,+ // so the rooms offered here and the rooms the agent is shown under cannot+ // disagree. Undefined means it was never fetched — offering every room then+ // would invite a join that is already in place, so say so instead.+ const memberships = switchRoomsStore.roomsFor(serverId, switchAgentId);+ const membershipUnknown = memberships === undefined;+ const alreadyIn = new Set((memberships ?? []).map((m) => m.roomId));++ // Every room the server let us see, not only the ones this user created: an+ // agent's usefulness is mostly in rooms someone else set up, and a picker that+ // omitted them made those rooms unreachable from here entirely.+ const candidates: Candidate[] = switchRoomsStore+ .readableRoomsOnServer(serverId)+ .filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id))+ .map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));+ const nothingToAdd = candidates.length === 0 && selected.length === 0;++ const handleSubmit = useCallback(async () => {+ if (selected.length === 0) return;+ setIsSubmitting(true);+ setCloseGuard(true);+ setError(null);+ try {+ for (const room of selected) {+ await rpc.switchServers.addRoomAgents({+ serverId,+ roomId: room.id,+ agentIds: [switchAgentId],+ });+ }+ await switchRoomsStore.refreshRoomState();+ onSuccess();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setIsSubmitting(false);+ setCloseGuard(false);+ }+ }, [serverId, switchAgentId, selected, onSuccess, setCloseGuard]);++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Add {agentName} to rooms</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-4">+ <Field>+ <div className="flex items-center justify-between gap-3">+ <FieldLabel>Rooms</FieldLabel>+ {selected.length > 0 && (+ <span className="text-sm text-foreground-muted">{selected.length} selected</span>+ )}+ </div>++ {selected.length > 0 && (+ <div className="grid grid-cols-3 gap-2.5">+ {selected.map((room) => (+ <ChosenRoomTile+ key={room.id}+ room={room}+ onRemove={() =>+ setSelected((current) => current.filter((r) => r.id !== room.id))+ }+ />+ ))}+ </div>+ )}++ <Combobox+ items={candidates}+ value={null}+ onValueChange={(next: Candidate | null) => {+ if (next) setSelected((current) => [...current, next]);+ setError(null);+ }}+ isItemEqualToValue={(a: Candidate, b: Candidate) => a.id === b.id}+ filter={(item: Candidate, query) =>+ item.name.toLowerCase().includes(query.toLowerCase())+ }+ autoHighlight+ >+ {/* The search box is the control rather than something a button+ has to open: putting an agent in several rooms at once is the+ reason this dialog exists. */}+ <ComboboxInput+ showTrigger={false}+ disabled={nothingToAdd}+ placeholder="Search rooms to add..."+ leftAddon={<Search className="size-3.5 text-foreground-muted" />}+ />+ <ComboboxContent className="min-w-(--anchor-width)">+ <ComboboxList>+ {(item: Candidate) => (+ <ComboboxItem key={item.id} value={item} showCheck={false}>+ <RoomMark bridgeType={item.bridgeType} size={16} />+ <span className="min-w-0 flex-1 truncate">{item.name}</span>+ <span className="shrink-0 text-xs text-foreground-muted">+ {whereLabel(item.bridgeType)}+ </span>+ </ComboboxItem>+ )}+ </ComboboxList>+ <ComboboxEmpty>No rooms found</ComboboxEmpty>+ </ComboboxContent>+ </Combobox>+ {membershipUnknown && (+ <p className="mt-1 text-xs text-foreground-warning">+ Which rooms {agentName} is already in could not be read, so every room on the server+ is listed. Adding it to one it already belongs to changes nothing.+ </p>+ )}+ {nothingToAdd && !membershipUnknown && (+ <p className="mt-1 text-xs text-foreground-muted">+ {agentName} is already in every room you can see on this server.+ </p>+ )}+ </Field>++ {error && <p className="text-destructive text-xs">{error}</p>}+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={isSubmitting}>+ Cancel+ </Button>+ <ConfirmButton+ onClick={() => void handleSubmit()}+ disabled={selected.length === 0 || isSubmitting}+ >+ {isSubmitting ? 'Adding…' : 'Add to rooms'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+});++/** A room already chosen, with the way to take it back out. */+function ChosenRoomTile({ room, onRemove }: { room: Candidate; onRemove: () => void }) {+ return (+ // `--fill` rather than `--surface-2`: in dark mode that surface is the+ // dialog's own background, so a tile drawn in it was a tile nobody could+ // see.+ <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">+ <RoomMark bridgeType={room.bridgeType} size={22} />+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-foreground">{room.name}</span>+ <span className="truncate text-xs text-foreground-muted">+ {whereLabel(room.bridgeType)}+ </span>+ </div>+ <button+ type="button"+ aria-label={`Remove ${room.name}`}+ onClick={onRemove}+ className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"+ >+ <X className="size-3.5" />+ </button>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsxindex da71ac328..b904b4e70 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx@@ -1,8 +1,9 @@-import { ChevronDown, X } from 'lucide-react';+import { Search, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useState } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { AgentMark, agentProviderLabel } from '@renderer/lib/components/agent-mark';import { rpc } from '@renderer/lib/ipc';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';import { Button } from '@renderer/lib/ui/button';@@ -13,7 +14,6 @@ import {ComboboxInput,ComboboxItem,ComboboxList,- ComboboxTrigger,} from '@renderer/lib/ui/combobox';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -23,12 +23,11 @@ import {DialogTitle,} from '@renderer/lib/ui/dialog';import { Field, FieldLabel } from '@renderer/lib/ui/field';-import { cn } from '@renderer/utils/utils';type Props = BaseModalProps<void> & { roomId: string };/** An agent that can be added: this install's agent, by its Switch identity. */-type Candidate = { id: string; name: string };+type Candidate = { id: string; name: string; providerId: string | null };export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({roomId,@@ -54,7 +53,11 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({const candidates: Candidate[] = serverId? agentsStore.agentsOnServer(serverId)- .map((agent) => ({ id: agent.switchAgentId as string, name: agent.name }))+ .map((agent) => ({+ id: agent.switchAgentId as string,+ name: agent.name,+ providerId: agent.providerId ?? null,+ })).filter((a) => !members.has(a.id) && !selected.some((s) => s.id === a.id)): [];const nothingToAdd = candidates.length === 0 && selected.length === 0;@@ -94,7 +97,27 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({)}<Field>- <FieldLabel>Agents</FieldLabel>+ <div className="flex items-center justify-between gap-3">+ <FieldLabel>Agents</FieldLabel>+ {selected.length > 0 && (+ <span className="text-sm text-foreground-muted">{selected.length} selected</span>+ )}+ </div>++ {selected.length > 0 && (+ <div className="grid grid-cols-3 gap-2.5">+ {selected.map((agent) => (+ <ChosenAgentTile+ key={agent.id}+ agent={agent}+ onRemove={() =>+ setSelected((current) => current.filter((a) => a.id !== agent.id))+ }+ />+ ))}+ </div>+ )}+<Comboboxitems={candidates}value={null}@@ -108,52 +131,30 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({}autoHighlight>- <ComboboxTrigger+ {/* The search box is the control rather than something a button+ has to open: putting several agents in a room at once is the+ reason this dialog exists. */}+ <ComboboxInput+ showTrigger={false}disabled={nothingToAdd}- className={cn(- 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',- nothingToAdd && 'cursor-not-allowed opacity-60'- )}- >- <span className="flex-1 truncate text-left text-foreground-muted">- Add an agent- </span>- <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />- </ComboboxTrigger>+ placeholder="Search agents to add..."+ leftAddon={<Search className="size-3.5 text-foreground-muted" />}+ /><ComboboxContent className="min-w-(--anchor-width)">- <ComboboxInput showTrigger={false} placeholder="Search agents…" /><ComboboxList>{(item: Candidate) => (- <ComboboxItem key={item.id} value={item}>+ <ComboboxItem key={item.id} value={item} showCheck={false}>+ <AgentMark providerId={item.providerId} size={16} /><span className="min-w-0 flex-1 truncate">{item.name}</span>+ <span className="shrink-0 text-xs text-foreground-muted">+ {agentProviderLabel(item.providerId)}+ </span></ComboboxItem>)}</ComboboxList><ComboboxEmpty>No agents found</ComboboxEmpty></ComboboxContent></Combobox>- {selected.length > 0 && (- <div className="mt-2 flex flex-wrap gap-1.5">- {selected.map((agent) => (- <span- key={agent.id}- className="flex items-center gap-1 rounded-md border border-border px-2 py-0.5 text-xs"- >- {agent.name}- <button- type="button"- aria-label={`Remove ${agent.name}`}- className="text-foreground-muted hover:text-foreground"- onClick={() =>- setSelected((current) => current.filter((a) => a.id !== agent.id))- }- >- <X className="h-3 w-3" />- </button>- </span>- ))}- </div>- )}{nothingToAdd && (<p className="mt-1 text-xs text-foreground-muted">Every agent on this copy of Switch Console is already in the room. Agents registered@@ -179,3 +180,29 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({</>);});++/** An agent already chosen, with the way to take it back out. */+function ChosenAgentTile({ agent, onRemove }: { agent: Candidate; onRemove: () => void }) {+ return (+ // `--fill` rather than `--surface-2`: in dark mode that surface is the+ // dialog's own background, so a tile drawn in it was a tile nobody could+ // see.+ <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">+ <AgentMark providerId={agent.providerId} size={22} />+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-foreground">{agent.name}</span>+ <span className="truncate text-xs text-foreground-muted">+ {agentProviderLabel(agent.providerId)}+ </span>+ </div>+ <button+ type="button"+ aria-label={`Remove ${agent.name}`}+ onClick={onRemove}+ className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"+ >+ <X className="size-3.5" />+ </button>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsxnew file mode 100644index 000000000..cc11e5e75--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx@@ -0,0 +1,94 @@+import { TriangleAlert } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useState } from 'react';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';++type Props = BaseModalProps<void> & {+ serverId: string;+ roomId: string;+ roomName: string;+};++/**+ * Confirm deleting a room.+ *+ * Deleting is not leaving: the room stops existing for everyone in it, and on a+ * bridged room the channel goes with it. Both are things you cannot find out by+ * trying, so they are said before rather than reported after.+ */+export const DeleteRoomModal = observer(function DeleteRoomModal({+ serverId,+ roomId,+ roomName,+ onSuccess,+ onClose,+}: Props) {+ const { setCloseGuard } = useModalContext();+ const [isDeleting, setIsDeleting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const room = switchRoomsStore.roomSummaryById(roomId);+ const platform = room?.bridgeType ? bridgePlatformLabel(room.bridgeType) : null;+ const agentCount = room?.agentCount ?? 0;++ const handleDelete = useCallback(async () => {+ setIsDeleting(true);+ setCloseGuard(true);+ setError(null);+ try {+ await switchRoomsStore.deleteRoom(serverId, roomId);+ onSuccess();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ setIsDeleting(false);+ } finally {+ setCloseGuard(false);+ }+ }, [serverId, roomId, onSuccess, setCloseGuard]);++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <div className="flex items-center gap-2">+ <TriangleAlert className="size-4 text-red-500" />+ <DialogTitle>Delete “{roomName}”?</DialogTitle>+ </div>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ <p className="text-sm text-foreground-muted">+ This deletes the room for everyone in it, along with its conversation+ {platform ? ` and its ${platform} channel` : ''}. It can’t be undone.+ </p>+ {agentCount > 0 && (+ <p className="text-sm text-foreground-muted">+ {agentCount} {agentCount === 1 ? 'agent leaves' : 'agents leave'} the room. The agents+ themselves are kept.+ </p>+ )}+ {error && <p className="text-destructive text-xs">{error}</p>}+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={isDeleting}>+ Cancel+ </Button>+ <ConfirmButton+ variant="destructive"+ onClick={() => void handleDelete()}+ disabled={isDeleting}+ >+ {isDeleting ? 'Deleting…' : 'Delete room'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.tsnew file mode 100644index 000000000..05981eb11--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts@@ -0,0 +1,19 @@+import { scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';+import { appState, sidebarStore } from '@renderer/lib/stores/app-state';++/**+ * Open a room, and leave the sidebar showing where you are.+ *+ * Navigating alone is not enough. The agent grouping does not list rooms at+ * all, so opening one from anywhere outside the tree left the main panel on a+ * room the sidebar had no row for — the app looking like it had moved+ * somewhere it could not show. Scoping to the room's server, switching to the+ * room grouping and expanding it are the three things that make the open room+ * findable in the tree it belongs to.+ */+export async function openRoom(roomId: string): Promise<void> {+ await scopeToRoomServer(roomId);+ sidebarStore.setGrouping('room');+ sidebarStore.ensureRoomExpanded(roomId);+ appState.navigation.navigate('room', { roomId });+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsxnew file mode 100644index 000000000..bf0e0657a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx@@ -0,0 +1,575 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { Bot, ExternalLink, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { Input } from '@renderer/lib/ui/input';+import {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+} from '@renderer/lib/ui/input-group';+import { Textarea } from '@renderer/lib/ui/textarea';+import { cn } from '@renderer/utils/utils';+import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';+import type {+ RemoteAgentSummary,+ RemoteRoomDetail,+} from '@shared/core/switch-servers/switch-servers';+import { membershipSummary, roomTitle } from './room-labels';+import { openRoomChannel } from './room-links';++/** Query key for one room's own settings — shared so a save can write the+ * server's answer straight back into what the page is reading. */+function roomDetailKey(serverId: string, roomId: string) {+ return ['remote-room-detail', serverId, roomId] as const;+}++/**+ * A room's settings: what it is for, what it tells agents on arrival, and who is+ * in it.+ *+ * Read one room at a time rather than from the room list, which carries neither+ * the instructions nor the membership — and written straight back from the+ * server's reply, so the page always shows what was actually stored.+ */+export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({+ roomId,+}: {+ roomId: string;+}) {+ const serverId = switchRoomsStore.roomServerId(roomId);+ const query = useQuery({+ queryKey: roomDetailKey(serverId ?? '', roomId),+ queryFn: () => rpc.switchServers.getRoomDetail({ serverId: serverId as string, roomId }),+ enabled: serverId !== null,+ });++ if (serverId === null) {+ return <PanelNotice title="This room’s server is still loading." />;+ }++ if (query.isPending) {+ return (+ <PanelNotice+ icon={<Loader2 className="size-5 animate-spin" />}+ title="Loading this room’s settings…"+ />+ );+ }++ if (query.isError) {+ return (+ <PanelNotice+ title="Couldn’t read this room’s settings"+ detail={errorText(query.error)}+ action={+ <Button variant="outline" size="sm" onClick={() => void query.refetch()}>+ <RefreshCw className="size-3" />+ Retry+ </Button>+ }+ />+ );+ }++ const room = query.data;+ return (+ <div className="h-full overflow-y-auto">+ <div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-10 py-8">+ <RoomHeading room={room} />+ {/* Keyed on the room so the drafts below belong to the room on screen:+ switching rooms starts a fresh form rather than carrying half-typed+ text across. */}+ <GeneralSection key={room.id} serverId={serverId} room={room} />+ <ParticipantsSection serverId={serverId} room={room} />+ <DeleteRoomSection serverId={serverId} room={room} />+ </div>+ </div>+ );+});++/**+ * Deleting the room, last on its page and below a rule.+ *+ * Absent entirely for anyone who may not delete it, rather than shown disabled:+ * a greyed control invites you to go and find the permission, and here there is+ * none to find — the room is someone else's.+ */+const DeleteRoomSection = observer(function DeleteRoomSection({+ serverId,+ room,+}: {+ serverId: string;+ room: RemoteRoomDetail;+}) {+ const showDeleteRoomModal = useShowModal('deleteRoomModal');+ const { navigate } = useNavigate();++ if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;++ return (+ <section className="border-t border-border pt-6">+ <div className="flex items-center justify-between gap-3">+ <div className="space-y-0.5">+ <h3 className="text-sm font-medium text-foreground">Delete room</h3>+ <p className="text-xs text-foreground-muted">+ Removes the room and its conversation for everyone in it+ {room.bridgeType ? `, and its ${bridgePlatformLabel(room.bridgeType)} channel` : ''}.+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500"+ onClick={() =>+ showDeleteRoomModal({+ serverId,+ roomId: room.id,+ roomName: roomTitle(room),+ // The page this is on is the deleted room's own, so staying would+ // leave a settings form for something that no longer exists.+ onSuccess: () => navigate('home'),+ })+ }+ >+ Delete room…+ </Button>+ </div>+ </section>+ );+});++function RoomHeading({ room }: { room: RemoteRoomDetail }) {+ const platform = bridgePlatformLabel(room.bridgeType);+ return (+ <div className="flex items-start justify-between gap-4">+ <div className="flex min-w-0 flex-col gap-1">+ <h1 className="truncate text-2xl font-semibold text-foreground">{roomTitle(room)}</h1>+ <p className="text-sm text-foreground-muted">+ {room.bridgeDisplayName+ ? `Room bridged to ${room.bridgeDisplayName}`+ : 'Room with no messaging app'}+ </p>+ </div>+ {room.externalChannelUrl && (+ <div className="flex shrink-0 items-center gap-2">+ {room.bridgeDisplayName && (+ <span className="rounded-md bg-[var(--fill)] px-2.5 py-1.5 text-xs text-foreground-muted">+ {room.bridgeDisplayName}+ </span>+ )}+ <Button variant="outline" size="sm" onClick={() => openRoomChannel(room.id)}>+ <ExternalLink className="size-3.5" />+ Open in {platform}+ </Button>+ </div>+ )}+ </div>+ );+}++/** What the field is doing, once the user has stopped typing in it. */+type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; message: string };++/**+ * Description and instructions, saved when the field is left.+ *+ * There is no Save button, so the saving has to be visible: a field says when it+ * is writing, when it has written, and — in the field's own words rather than a+ * toast that has already gone — when the server refused. Silence would leave a+ * typed value looking stored when it is not.+ */+function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {+ const queryClient = useQueryClient();+ const [description, setDescription] = useState(room.description);+ const [instructions, setInstructions] = useState(room.instructions ?? '');+ const [descriptionSave, setDescriptionSave] = useState<SaveState>({ phase: 'idle' });+ const [instructionsSave, setInstructionsSave] = useState<SaveState>({ phase: 'idle' });++ async function save(+ changes: { description: string } | { instructions: string },+ setState: (state: SaveState) => void+ ) {+ setState({ phase: 'saving' });+ try {+ const updated = await rpc.switchServers.updateRoom({ serverId, roomId: room.id, ...changes });+ queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);+ setState({ phase: 'saved' });+ } catch (cause) {+ setState({ phase: 'failed', message: errorText(cause) });+ }+ }++ return (+ <section className="flex flex-col gap-4">+ <h2 className="text-sm font-semibold text-foreground">General</h2>++ <Field+ label="Description"+ hint="Helps other people and agents understand what this room is for."+ state={descriptionSave}+ >+ <Input+ className="h-9"+ placeholder="What this room is for"+ value={description}+ onChange={(e) => {+ setDescription(e.target.value);+ setDescriptionSave({ phase: 'idle' });+ }}+ onBlur={() => {+ if (description === room.description) return;+ void save({ description }, setDescriptionSave);+ }}+ />+ </Field>++ <Field+ label="Instructions"+ hint="Sent to every agent as it joins the room."+ state={instructionsSave}+ >+ <Textarea+ rows={4}+ placeholder="Optional guidance shown to agents when they enter the room"+ value={instructions}+ onChange={(e) => {+ setInstructions(e.target.value);+ setInstructionsSave({ phase: 'idle' });+ }}+ onBlur={() => {+ if (instructions === (room.instructions ?? '')) return;+ void save({ instructions }, setInstructionsSave);+ }}+ />+ </Field>+ </section>+ );+}++function Field({+ label,+ hint,+ state,+ children,+}: {+ label: string;+ hint: string;+ state: SaveState;+ children: React.ReactNode;+}) {+ return (+ <div className="flex flex-col gap-1.5">+ <span className="text-sm text-foreground-muted">{label}</span>+ {children}+ {state.phase === 'failed' ? (+ <span className="text-destructive text-xs">Not saved — {state.message}</span>+ ) : (+ <span className="text-xs text-foreground-muted">+ {state.phase === 'saving' ? 'Saving…' : state.phase === 'saved' ? 'Saved.' : hint}+ </span>+ )}+ </div>+ );+}++/**+ * Who is in the room, and the one way to change it from here.+ *+ * Agents and people are drawn as the same kind of card because they are the same+ * kind of fact — membership — and separating them into two lists implied a+ * hierarchy the room does not have.+ */+const ParticipantsSection = observer(function ParticipantsSection({+ serverId,+ room,+}: {+ serverId: string;+ room: RemoteRoomDetail;+}) {+ const queryClient = useQueryClient();+ const [adding, setAdding] = useState(false);++ // Names for agents belonging to other installs, which this computer has no+ // local record of. Shares its key with the rest of the app, so it is usually+ // already in hand.+ const remoteAgents = useQuery({+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId),+ });+ const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));++ async function refresh() {+ await queryClient.invalidateQueries({ queryKey: roomDetailKey(serverId, room.id) });+ await switchRoomsStore.refreshRoomState();+ }++ return (+ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-baseline gap-2">+ <h2 className="text-sm font-semibold text-foreground">Participants</h2>+ <span className="text-xs text-foreground-muted">+ {membershipSummary(room.agentIds.length, room.connectedUserNames.length)}+ </span>+ </div>+ <Button+ variant="outline"+ size="sm"+ aria-expanded={adding}+ onClick={() => setAdding((v) => !v)}+ >+ <Plus className="size-3.5" />+ Add agent+ </Button>+ </div>++ {room.agentIds.length === 0 && room.connectedUserNames.length === 0 ? (+ <p className="text-sm text-foreground-muted">Nobody is in this room yet.</p>+ ) : (+ <div className="grid grid-cols-2 gap-2.5">+ {room.agentIds.map((agentId) => (+ <ParticipantCard+ key={agentId}+ mark={<AgentMark agentId={agentId} serverId={serverId} />}+ name={agentNameFor(agentId, serverId, remoteById)}+ detail={agentKindFor(agentId, serverId, remoteById)}+ />+ ))}+ {room.connectedUserNames.map((name) => (+ <ParticipantCard+ key={`user:${name}`}+ mark={+ <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-[var(--fill-2)] text-xs font-medium text-foreground">+ {name.charAt(0).toUpperCase()}+ </span>+ }+ name={name}+ detail="person"+ />+ ))}+ </div>+ )}++ {adding && <AddAgentPanel serverId={serverId} room={room} onAdded={refresh} />}+ </section>+ );+});++function ParticipantCard({+ mark,+ name,+ detail,+}: {+ mark: React.ReactNode;+ name: string;+ detail: string;+}) {+ return (+ <div className="flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3">+ {mark}+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium text-foreground">{name}</span>+ <span className="truncate text-xs text-foreground-muted">{detail}</span>+ </div>+ </div>+ );+}++/**+ * Search this computer's agents and put one in the room.+ *+ * Scoped to agents this install owns, like every other add-an-agent surface:+ * adding somebody else's agent from here would put a room in front of an agent+ * whose owner never agreed to it.+ */+const AddAgentPanel = observer(function AddAgentPanel({+ serverId,+ room,+ onAdded,+}: {+ serverId: string;+ room: RemoteRoomDetail;+ onAdded: () => Promise<void>;+}) {+ const [filter, setFilter] = useState('');+ const [busyId, setBusyId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const members = new Set(room.agentIds);+ const query = filter.trim().toLowerCase();+ const candidates = agentsStore+ .agentsOnServer(serverId)+ .filter((agent) => agent.switchAgentId !== null && !members.has(agent.switchAgentId))+ .filter((agent) => query === '' || agent.name.toLowerCase().includes(query));++ async function add(switchAgentId: string) {+ setBusyId(switchAgentId);+ setError(null);+ try {+ await rpc.switchServers.addRoomAgents({+ serverId,+ roomId: room.id,+ agentIds: [switchAgentId],+ });+ await onAdded();+ } catch (cause) {+ setError(errorText(cause));+ } finally {+ setBusyId(null);+ }+ }++ return (+ <div className="flex flex-col gap-2 pt-1">+ <InputGroup>+ <InputGroupAddon>+ <Search className="size-3.5 text-foreground-muted" />+ </InputGroupAddon>+ <InputGroupInput+ autoFocus+ placeholder="Search agents on this computer…"+ aria-label="Search agents to add"+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ />+ {filter !== '' && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ size="icon-xs"+ aria-label="Clear the search"+ onClick={() => setFilter('')}+ >+ <X className="size-3.5" />+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>++ {error !== null && <p className="text-destructive text-xs">Not added — {error}</p>}++ {candidates.length === 0 ? (+ <p className="px-1 py-2 text-sm text-foreground-muted">+ {query === ''+ ? 'Every agent on this computer is already in this room.'+ : `No agent here matches “${filter.trim()}”.`}+ </p>+ ) : (+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {candidates.map((agent) => {+ const switchAgentId = agent.switchAgentId as string;+ const busy = busyId === switchAgentId;+ return (+ <button+ key={agent.id}+ type="button"+ disabled={busyId !== null}+ onClick={() => void add(switchAgentId)}+ className={cn(+ 'flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]',+ busyId !== null && 'cursor-wait'+ )}+ >+ {agent.providerId ? (+ <AgentIcon id={agent.providerId} size={18} />+ ) : (+ <Bot className="size-4 shrink-0 text-foreground-muted" />+ )}+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">+ {agent.name}+ </span>+ <span className="shrink-0 text-xs text-foreground-muted">+ {providerDisplayName(agent.providerId) ?? 'Agent'}+ </span>+ <span className="shrink-0 text-xs font-medium text-foreground">+ {busy ? 'Adding…' : 'Add'}+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>+ );+});++function PanelNotice({+ icon,+ title,+ detail,+ action,+}: {+ icon?: React.ReactNode;+ title: string;+ detail?: string;+ action?: React.ReactNode;+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">+ {icon && <div className="text-foreground-passive">{icon}</div>}+ <p className="text-sm font-medium text-foreground">{title}</p>+ {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}+ {action}+ </div>+ );+}++/** The mark of what an agent runs, resolved through this install's copy of it. */+function AgentMark({ agentId, serverId }: { agentId: string; serverId: string }) {+ const providerId = localAgentFor(agentId, serverId)?.providerId ?? null;+ if (!providerId) {+ return (+ <span className="flex size-7 shrink-0 items-center justify-center">+ <Bot className="size-4 text-foreground-muted" />+ </span>+ );+ }+ return (+ <span className="flex size-7 shrink-0 items-center justify-center">+ <AgentIcon id={providerId} size={20} />+ </span>+ );+}++/** This install's record of a Switch agent, which is where its provider is+ * known — the server says what type an agent is, not what runs it here. */+function localAgentFor(switchAgentId: string, serverId: string) {+ return (+ agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null+ );+}++function agentNameFor(+ switchAgentId: string,+ serverId: string,+ remoteById: Map<string, RemoteAgentSummary>+): string {+ return (+ localAgentFor(switchAgentId, serverId)?.name ?? remoteById.get(switchAgentId)?.name ?? 'Agent'+ );+}++/** What an agent runs, in words: this install's provider when it has one,+ * otherwise the type the server knows it by. */+function agentKindFor(+ switchAgentId: string,+ serverId: string,+ remoteById: Map<string, RemoteAgentSummary>+): string {+ const providerId = localAgentFor(switchAgentId, serverId)?.providerId ?? null;+ const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;+ return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';+}++function errorText(cause: unknown): string {+ return cause instanceof Error ? cause.message : String(cause);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsxindex 10e1f7484..4e9ad9554 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx@@ -9,6 +9,7 @@ import { Button } from '@renderer/lib/ui/button';import { cn } from '@renderer/utils/utils';import type { RoomEmbed } from '@shared/core/switch-rooms/room-embed';import { openRoomChannel } from './room-links';+import { roomTabStore } from './room-tab-store';import { currentMattermostTheme } from './theme-tokens';import { WEBVIEW_ALLOW_POPUPS } from './webview-attrs';@@ -159,8 +160,11 @@ export const RoomEmbedLayer = observer(function RoomEmbedLayer() {// every live <webview> and reload Mattermost on the way back, which is the// exact cost this layer exists to avoid. Hide the whole layer instead —// display:none keeps the guests running and takes the layer out of both- // layout and hit-testing, so the view underneath behaves normally.- const visible = isRoomView && activeRoomId !== null;+ // layout and hit-testing, so the view underneath behaves normally. The same+ // applies to a room showing its settings: the conversation is still there,+ // just not on screen.+ const visible =+ isRoomView && activeRoomId !== null && roomTabStore.tabFor(activeRoomId) === 'chat';const active = activeRoomId ? states.get(activeRoomId) : undefined;return (diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.tsnew file mode 100644index 000000000..728cb1d17--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';+import { membershipSummary, roomTitle } from './room-labels';++describe('roomTitle', () => {+ it('marks a bridged room as the channel it is', () => {+ expect(roomTitle({ name: 'louis-dev', bridgeType: 'mattermost' })).toBe('#louis-dev');+ });++ it('leaves a room in no messaging app alone — there is no channel to name', () => {+ expect(roomTitle({ name: 'louis-dev', bridgeType: null })).toBe('louis-dev');+ });++ it('does not double the sigil on a name that already carries one', () => {+ expect(roomTitle({ name: '#general', bridgeType: 'slack' })).toBe('#general');+ });+});++describe('membershipSummary', () => {+ it('counts agents and people separately', () => {+ expect(membershipSummary(1, 1)).toBe('1 agent · 1 person');+ expect(membershipSummary(3, 2)).toBe('3 agents · 2 people');+ });++ it('omits people rather than reporting none', () => {+ expect(membershipSummary(2, 0)).toBe('2 agents');+ });++ it('says an empty room has no agents rather than saying nothing', () => {+ expect(membershipSummary(0, 0)).toBe('0 agents');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.tsnew file mode 100644index 000000000..ca1bd7611--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts@@ -0,0 +1,25 @@+/**+ * A room's name as it is written where the room actually lives.+ *+ * The `#` is the channel sigil of the apps these rooms are bridged into — so it+ * says "this is that channel" rather than decorating the name. Added only when+ * the name does not already carry one, and never to a room in no app at all,+ * where there is no channel for it to name.+ */+export function roomTitle(room: { name: string; bridgeType: string | null }): string {+ if (!room.bridgeType || room.name.startsWith('#')) return room.name;+ return `#${room.name}`;+}++/**+ * "1 agent · 1 person" — the two kinds of member counted separately, because+ * they are not interchangeable.+ *+ * People are left out rather than shown as zero: an unbridged room has no way+ * for anyone to be in it, and "0 people" reads as a room nobody came to.+ */+export function membershipSummary(agentCount: number, personCount: number): string {+ const agents = `${agentCount} ${agentCount === 1 ? 'agent' : 'agents'}`;+ if (personCount === 0) return agents;+ return `${agents} · ${personCount} ${personCount === 1 ? 'person' : 'people'}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.tsnew file mode 100644index 000000000..4ca4ed3ad--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts@@ -0,0 +1,34 @@+import { makeAutoObservable } from 'mobx';++/** The two things a room page can show. */+export type RoomTab = 'chat' | 'configuration';++/**+ * Which tab the open room is showing.+ *+ * Held outside the room view because the conversation is drawn by+ * `RoomEmbedLayer`, which lives above the view switch and has to know when to+ * get out of the way. One selection rather than one per room: the conversation+ * is what a room is for, so opening a different room starts on it again — which+ * is why the tab is remembered against the room id and forgotten the moment the+ * id changes.+ */+export class RoomTabStore {+ private roomId: string | null = null;+ private tab: RoomTab = 'chat';++ constructor() {+ makeAutoObservable(this, {}, { autoBind: true });+ }++ tabFor(roomId: string): RoomTab {+ return this.roomId === roomId ? this.tab : 'chat';+ }++ setTab(roomId: string, tab: RoomTab): void {+ this.roomId = roomId;+ this.tab = tab;+ }+}++export const roomTabStore = new RoomTabStore();diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-room-label.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-room-label.tsxindex 255fada91..950aef31c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-room-label.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-room-label.tsx@@ -1,6 +1,8 @@+import { Hash } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import { switchRoomsStore as serverRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { switchRoomsStore } from './switch-rooms-store';/**@@ -31,5 +33,19 @@ export const SessionRoomLabel = observer(function SessionRoomLabel({const name = serverRoomsStore.roomNameById(roomId);if (!name) return null;- return <span className="max-w-32 shrink-0 truncate text-xs text-foreground-muted">{name}</span>;+ // The platform the room lives on, marked the way the rest of the app marks it.+ // A room name on its own says which conversation; the icon says where it is+ // happening, which is what tells two similarly-named rooms apart.+ const bridgeType = serverRoomsStore.roomBridgeTypeById(roomId);++ return (+ <span className="flex max-w-40 shrink-0 items-center gap-1.5 text-xs text-foreground-muted">+ {hasBridgeIcon(bridgeType) ? (+ <BridgeIcon bridgeType={bridgeType} size={12} />+ ) : (+ <Hash className="size-3 shrink-0" />+ )}+ <span className="truncate">{name}</span>+ </span>+ );});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsxindex 2d20e76fd..5a205a239 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx@@ -8,8 +8,11 @@ import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';import { useParams } from '@renderer/lib/layout/navigation-provider';import { Button } from '@renderer/lib/ui/button';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import { RoomConfigurationPanel } from './room-configuration-panel';import { openRoomChannel } from './room-links';+import { type RoomTab, roomTabStore } from './room-tab-store';/*** Opens the room's channel in the messaging app it is bridged to. The embedded@@ -49,10 +52,19 @@ const OpenInMessagingApp = observer(function OpenInMessagingApp({ roomId }: { ro);});+const TABS = [+ { value: 'chat', label: 'Chat' },+ { value: 'configuration', label: 'Configuration' },+] as const satisfies readonly { value: RoomTab; label: string }[];+/*** A room opened on its own is its own root: it belongs to a server and to every* agent in it, and picking one of those to stand in front of it would be a* claim about how you got here rather than about where you are.+ *+ * The two sides of a room sit next to its name rather than in a sidebar or a+ * menu: there are only two, and which one you are on is the first thing you+ * need to know about the page under it.*/const RoomTitlebar = observer(function RoomTitlebar() {const { params } = useParams('room');@@ -62,19 +74,27 @@ const RoomTitlebar = observer(function RoomTitlebar() {return (<TitlebarleftSlot={- <TitlebarBreadcrumb- crumbs={[- {- key: 'room',- icon: hasBridgeIcon(bridgeType) ? (- <BridgeIcon bridgeType={bridgeType} size={14} className="shrink-0" />- ) : (- <DoorOpen className="size-3.5 shrink-0" />- ),- label: name ?? 'Room',- },- ]}- />+ <div className="flex min-w-0 items-center gap-3">+ <TitlebarBreadcrumb+ crumbs={[+ {+ key: 'room',+ icon: hasBridgeIcon(bridgeType) ? (+ <BridgeIcon bridgeType={bridgeType} size={14} className="shrink-0" />+ ) : (+ <DoorOpen className="size-3.5 shrink-0" />+ ),+ label: name ?? 'Room',+ },+ ]}+ />+ <SegmentedControl+ value={roomTabStore.tabFor(params.roomId)}+ onChange={(tab) => roomTabStore.setTab(params.roomId, tab)}+ options={TABS}+ ariaLabel="Room view"+ />+ </div>}rightSlot={<div className="mr-2 flex items-center gap-1">@@ -85,12 +105,21 @@ const RoomTitlebar = observer(function RoomTitlebar() {);});+/** Settings when the room is showing them; otherwise nothing, and the+ * conversation drawn by `RoomEmbedLayer` above shows through. */+const RoomMainPanel = observer(function RoomMainPanel() {+ const { params } = useParams('room');+ if (roomTabStore.tabFor(params.roomId) !== 'configuration') return null;+ return <RoomConfigurationPanel roomId={params.roomId} />;+});+export const roomView = {WrapView: ({ children }: { children: React.ReactNode; roomId: string }) => <>{children}</>,TitlebarSlot: RoomTitlebar,// The conversation itself is drawn by RoomEmbedLayer, which is mounted above- // the view switch so its <webview> survives navigating away and back.- MainPanel: () => null,+ // the view switch so its <webview> survives navigating away and back. This+ // panel only ever holds the room's other side.+ MainPanel: RoomMainPanel,canActivate: (params: unknown): GuardResult => {const roomId =typeof params === 'object' && params !== nulldiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsxindex 30f4b22c5..ffe81bb5c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from 'react';import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';@@ -17,10 +18,16 @@ import {import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Spinner } from '@renderer/lib/ui/spinner';-import type { ServerApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';+import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';+import type {+ ServerApiUrlPropagation,+ SwitchServer,+} from '@shared/core/switch-servers/switch-servers';+import { LinkAccountsStep } from './link-accounts-step';import { localServerStore } from './local-server-store';import { LogTail } from './log-tail';import { remoteServerStore } from './remote-server-store';+import { ServerSignInFields, useServerSignIn } from './server-sign-in';import { switchServersStore } from './switch-servers-store';/**@@ -65,11 +72,52 @@ type Props = BaseModalProps<void> & {mode?: 'local' | 'remoteHost' | 'external';};-type Step = 'choose' | 'local' | 'remoteHost' | 'external';+type Step = 'choose' | 'local' | 'remoteHost' | 'external' | 'signIn' | 'linkAccounts';+/**+ * How many steps connecting to a server someone else runs takes: choose that+ * path, point at the server, sign in, then say which messaging account is you.+ *+ * The chooser is step 1 but carries no counter — the other two paths it leads+ * to are not four steps, and a count shown before the choice would promise a+ * length that depends on what is clicked next.+ */+const CONNECT_STEPS = 4;++/**+ * Add a Switch server: run one here, run one on a host you have onboarded, or+ * connect to one someone else runs.+ *+ * Only the third is a wizard. Connecting to an existing server is not finished+ * when the URL is saved — that server already has its own accounts and its own+ * messaging apps, and until you have signed in and said which account in each+ * app is you, the entry in the sidebar is a name with nothing behind it. So+ * those two steps follow in the same dialog rather than waiting on the server's+ * page to be discovered (CHOO-2164).+ */export const AddServerModal = observer(function AddServerModal(props: Props) {const isEdit = props.serverId != null;const [step, setStep] = useState<Step>(isEdit ? 'external' : (props.mode ?? 'choose'));+ // The server the wizard just created, and the subject of every step after+ // it. Null in edit mode and on the two managed paths, which is what+ // distinguishes the standalone edit form from step 2 of the wizard.+ const [connected, setConnected] = useState<SwitchServer | null>(null);+ const { navigate } = useNavigate();++ /**+ * End the flow on the new server's own page.+ *+ * Adding a server is done in order to use it, and the dialog closing onto+ * whatever was behind it left no sign anything had happened. A path that+ * cannot name the server it made lands nowhere rather than guessing.+ */+ const finish = (serverId: string | null) => {+ if (serverId) {+ void switchServersStore.setActive(serverId);+ navigate('server', { serverId });+ }+ props.onSuccess();+ };if (step === 'choose') {return (@@ -85,7 +133,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {return (<LocalSetupSteponBack={isEdit ? undefined : () => setStep('choose')}- onSuccess={props.onSuccess}+ onDone={finish}onClose={props.onClose}/>);@@ -94,16 +142,42 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {return (<RemoteHostSetupSteponBack={() => setStep('choose')}- onSuccess={props.onSuccess}+ onDone={finish}onClose={props.onClose}/>);}+ if (step === 'signIn' && connected) {+ return (+ <SignInStep+ server={connected}+ onBack={() => setStep('external')}+ onClose={props.onClose}+ onSignedIn={() => setStep('linkAccounts')}+ />+ );+ }+ if (step === 'linkAccounts' && connected) {+ return (+ <LinkAccountsStep+ serverId={connected.id}+ serverName={connected.name}+ step={CONNECT_STEPS}+ of={CONNECT_STEPS}+ onDone={() => finish(connected.id)}+ />+ );+ }return (<ExternalServerStep{...props}isEdit={isEdit}+ existing={connected}onBack={isEdit ? undefined : () => setStep('choose')}+ onConnected={(server) => {+ setConnected(server);+ setStep('signIn');+ }}/>);});@@ -200,11 +274,12 @@ function SetupStepItem({ children }: { children: React.ReactNode }) {const LocalSetupStep = observer(function LocalSetupStep({onBack,- onSuccess,+ onDone,onClose,}: {onBack?: () => void;- onSuccess: () => void;+ /** Reports the server the stack registered, so the flow can end on it. */+ onDone: (serverId: string | null) => void;onClose: () => void;}) {const store = localServerStore;@@ -223,7 +298,7 @@ const LocalSetupStep = observer(function LocalSetupStep({const primaryLabel = running ? 'Done' : store.phase === 'error' ? 'Retry' : 'Start';const onPrimary = () => {- if (running) onSuccess();+ if (running) onDone(store.status?.serverId ?? null);else void store.start();};@@ -361,11 +436,12 @@ function DockerStatus({const RemoteHostSetupStep = observer(function RemoteHostSetupStep({onBack,- onSuccess,+ onDone,onClose,}: {onBack: () => void;- onSuccess: () => void;+ /** Reports the server the stack registered, so the flow can end on it. */+ onDone: (serverId: string | null) => void;onClose: () => void;}) {const store = remoteServerStore;@@ -400,7 +476,7 @@ const RemoteHostSetupStep = observer(function RemoteHostSetupStep({const canStart = !!sshHost && name.trim().length > 0 && dockerReady && !starting && !hostBlocked;const primaryLabel = running ? 'Done' : status?.phase === 'error' ? 'Retry' : 'Start';const onPrimary = () => {- if (running) onSuccess();+ if (running) onDone(sshHost ? (store.statusFor(sshHost).serverId ?? null) : null);else if (sshHost) void store.start(sshHost, name.trim());};@@ -570,10 +646,19 @@ const ExternalServerStep = observer(function ExternalServerStep({initialName,serverId,isEdit,-}: Props & { isEdit: boolean; onBack?: () => void }) {- const [name, setName] = useState(initialName ?? '');- const [gatewayUrl, setGatewayUrl] = useState(initialGatewayUrl ?? '');- const [apiUrl, setApiUrl] = useState(initialApiUrl ?? '');+ existing,+ onConnected,+}: Props & {+ isEdit: boolean;+ onBack?: () => void;+ /** Set when the wizard has already created the server and the user came back+ * to fix what they typed — the same form, saving instead of adding. */+ existing: SwitchServer | null;+ onConnected: (server: SwitchServer) => void;+}) {+ const [name, setName] = useState(initialName ?? existing?.name ?? '');+ const [gatewayUrl, setGatewayUrl] = useState(initialGatewayUrl ?? existing?.gatewayUrl ?? '');+ const [apiUrl, setApiUrl] = useState(initialApiUrl ?? existing?.apiUrl ?? '');const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -595,13 +680,17 @@ const ExternalServerStep = observer(function ExternalServerStep({? 'Enter a full URL, e.g. https://switch-api.example.com': undefined;+ // The row this form writes to, when one already exists: the server being+ // edited, or the one the wizard created before the user stepped back.+ const savedId = isEdit ? serverId : existing?.id;+const handleSubmit = useCallback(async () => {if (!isValid) return;setSubmitting(true);setError(null);- if (isEdit && serverId) {+ if (savedId) {const result = await switchServersStore.updateServer(- serverId,+ savedId,trimmedName,trimmedGateway,trimmedApi@@ -612,6 +701,10 @@ const ExternalServerStep = observer(function ExternalServerStep({return;}notifyPropagation(result.propagation);+ if (!isEdit) {+ onConnected(result.server);+ return;+ }} else {const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);if (!saved) {@@ -619,15 +712,21 @@ const ExternalServerStep = observer(function ExternalServerStep({setSubmitting(false);return;}+ onConnected(saved);+ return;}onSuccess();- }, [isValid, isEdit, serverId, trimmedName, trimmedGateway, trimmedApi, onSuccess]);+ }, [isValid, isEdit, savedId, trimmedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);return (<>- <DialogHeader showCloseButton={false}>- <DialogTitle>{isEdit ? 'Edit connection' : 'Connect to an existing server'}</DialogTitle>- </DialogHeader>+ {isEdit ? (+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Edit connection</DialogTitle>+ </DialogHeader>+ ) : (+ <WizardStepHeader title="Connect to an existing server" step={2} of={CONNECT_STEPS} />+ )}<DialogContentArea className="pt-0"><FieldGroup>{!isEdit && (@@ -671,9 +770,76 @@ const ExternalServerStep = observer(function ExternalServerStep({{onBack ? 'Back' : 'Cancel'}</Button><ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>- {submitting ? (isEdit ? 'Saving…' : 'Adding…') : isEdit ? 'Save changes' : 'Add server'}+ {submitting ? (savedId ? 'Saving…' : 'Adding…') : savedId ? 'Save changes' : 'Add server'}</ConfirmButton></DialogFooter></>);});++// ---------------------------------------------------------------------------+// Step 3 — sign in to the server that was just added+// ---------------------------------------------------------------------------++/**+ * Signing in here rather than on the server's page, because everything the+ * next step and the sidebar want to show is behind the session: an added but+ * signed-out server lists no rooms, no agents and no messaging apps, and looks+ * broken rather than unauthenticated.+ */+const SignInStep = observer(function SignInStep({+ server,+ onBack,+ onClose,+ onSignedIn,+}: {+ server: SwitchServer;+ onBack: () => void;+ onClose: () => void;+ onSignedIn: () => void;+}) {+ const signIn = useServerSignIn(server.id);+ const canUsePassword = signIn.config?.passwordLoginEnabled ?? false;+ const canUseOidc = signIn.config?.oidcEnabled ?? false;++ const submit = async () => {+ if (await signIn.signInWithPassword()) onSignedIn();+ };++ return (+ <>+ <WizardStepHeader title={`Sign in to ${server.name}`} step={3} of={CONNECT_STEPS} />+ <DialogContentArea className="pt-0">+ <ServerSignInFields+ signIn={signIn}+ idPrefix="connect-server-sign-in"+ gatewayUrl={server.gatewayUrl}+ onSignedIn={onSignedIn}+ />+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onBack} disabled={signIn.submitting}>+ Back+ </Button>+ {canUsePassword ? (+ <ConfirmButton+ onClick={() => void submit()}+ disabled={!signIn.canSubmitPassword || signIn.submitting}+ >+ {signIn.submitting ? 'Signing in…' : 'Sign in'}+ </ConfirmButton>+ ) : (+ // Nothing for a primary button to do: either the only method is the+ // provider button in the body, or the server offers none at all and+ // the body says so. Leaving a dead "Sign in" there would imply the+ // form was incomplete rather than absent.+ !canUseOidc && (+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ )+ )}+ </DialogFooter>+ </>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsxindex 46f21c29f..bb76cf125 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx@@ -15,6 +15,7 @@ import {DialogHeader,DialogTitle,} from '@renderer/lib/ui/dialog';+import { DropdownMenuItem } from '@renderer/lib/ui/dropdown-menu';import { Spinner } from '@renderer/lib/ui/spinner';function CopyButton({ value, label }: { value: string; label: string }) {@@ -96,15 +97,21 @@ function CredentialRow({export function BundledChatSignIn({serverId,bridgeDisplayName,+ asMenuItem = false,}: {serverId: string;bridgeDisplayName: string;+ /** Render the opener as a dropdown entry rather than a standalone icon+ * button, for the row menu that now carries this action. */+ asMenuItem?: boolean;}) {const [open, setOpen] = useState(false);const signInQuery = useQuery({queryKey: ['bundled-chat-sign-in', serverId],queryFn: () => rpc.switchServers.getBundledChatSignIn(serverId),+ // The password only crosses into the renderer once the dialog is actually+ // opened, so merely listing the app never fetches it.enabled: open,});@@ -113,15 +120,25 @@ export function BundledChatSignIn({return (<>- <Button- variant="ghost"- size="icon-xs"- aria-label={`${bridgeDisplayName} sign-in details`}- title={`${bridgeDisplayName} sign-in details`}- onClick={() => setOpen(true)}- >- <KeyRound className="size-3" />- </Button>+ {asMenuItem ? (+ // `closeOnClick={false}` would leave the menu over the dialog; letting+ // it close and opening the dialog from the same click is what keeps one+ // surface on screen at a time.+ <DropdownMenuItem onClick={() => setOpen(true)}>+ <KeyRound className="size-4" />+ Sign-in details…+ </DropdownMenuItem>+ ) : (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={`${bridgeDisplayName} sign-in details`}+ title={`${bridgeDisplayName} sign-in details`}+ onClick={() => setOpen(true)}+ >+ <KeyRound className="size-3" />+ </Button>+ )}<Dialog open={open} onOpenChange={setOpen}><DialogContent>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsxindex cfa3aa07c..68a63b7ba 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx@@ -1,12 +1,9 @@-import { useQuery, useQueryClient } from '@tanstack/react-query';-import { CircleAlert, Info } from 'lucide-react';+import { useQuery } from '@tanstack/react-query';+import { Info } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useState } from 'react';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';-import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { rpc } from '@renderer/lib/ipc';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';-import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';import {DialogContentArea,@@ -14,27 +11,11 @@ import {DialogHeader,DialogTitle,} from '@renderer/lib/ui/dialog';-import { Field, FieldLabel } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import { Spinner } from '@renderer/lib/ui/spinner';-import type {- BridgeDirectorySearchResult,- BridgeDirectoryUser,- ClaimIdentityResult,- LinkedIdentity,-} from '@shared/core/switch-servers/switch-servers';+import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';+import { BridgeIdentitySearch } from './bridge-identity-search';import { switchServersStore } from './switch-servers-store';import { useMyIdentities } from './use-my-identities';-/** How long to wait after the last keystroke before asking the platform. Every- * search is a live call out to Slack or Mattermost, so this is a courtesy to- * their rate limits as much as to ours. */-const SEARCH_DEBOUNCE_MS = 300;--/** Below this the directory returns most of the workspace, which is neither- * useful to scan nor cheap to fetch. */-const MIN_QUERY_LENGTH = 2;-type ClaimIdentityModalArgs = {/** Claim on this server instead of the active one. */serverId?: string;@@ -65,18 +46,12 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({onSuccess,onClose,}: Props) {- const { setCloseGuard } = useModalContext();- const queryClient = useQueryClient();-const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';- const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;+ // The search raises the close guard while a claim or unlink is in flight, so+ // this is also the signal that leaving now would abandon one.+ const { hasActiveCloseGuard } = useModalContext();- const [search, setSearch] = useState('');- const [claiming, setClaiming] = useState<string | null>(null);- const [releasing, setReleasing] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);-- const { identities, refresh: refreshIdentities } = useMyIdentities(serverId || null);+ const { identities } = useMyIdentities(serverId || null);const bridgesQuery = useQuery({queryKey: ['remote-bridges', serverId],@@ -92,69 +67,6 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({const bridgeIsGone = !bridgesQuery.isLoading && bridges.length > 0 && selectedBridge === null;const alreadyLinked = (identities ?? []).find((i) => i.bridgeId === bridgeId) ?? null;- const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);- const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;- const directoryQuery = useQuery({- queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],- queryFn: () =>- rpc.switchServers.searchBridgeDirectory({- serverId,- bridgeId,- query: debouncedQuery,- }),- enabled: searchable,- });-- const handleClaim = async (person: BridgeDirectoryUser) => {- setClaiming(person.externalUserId);- setCloseGuard(true);- setError(null);- try {- const result = await rpc.switchServers.claimBridgeIdentity({- serverId,- bridgeId,- externalUserId: person.externalUserId,- username: person.username,- });- if (result.kind !== 'claimed') {- setError(claimFailureText(result));- return;- }- refreshIdentities();- onSuccess({ identity: result.identity });- } catch (cause) {- setError(cause instanceof Error ? cause.message : String(cause));- } finally {- setClaiming(null);- setCloseGuard(false);- }- };-- // Undo, in place: the row the user just linked is the row they look at when- // they realise it is the wrong account, so the modal stays open and the- // directory is re-read to show who is left holding the account.- const handleRelease = async (person: BridgeDirectoryUser) => {- if (person.knownExternalUserId === null) return;- setReleasing(person.externalUserId);- setCloseGuard(true);- setError(null);- try {- await rpc.switchServers.releaseBridgeIdentity({- serverId,- bridgeId,- identityId: person.knownExternalUserId,- userId: currentUserId,- });- refreshIdentities();- await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });- } catch (cause) {- setError(cause instanceof Error ? cause.message : String(cause));- } finally {- setReleasing(null);- setCloseGuard(false);- }- };-return (<><DialogHeader showCloseButton={false}>@@ -192,223 +104,25 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({</div>)}- {/* The workspace, not the platform: two of them on the same platform- can be connected, and only the name tells them apart. */}- <Field>- <FieldLabel>Search {selectedBridge?.displayName ?? 'the workspace'}</FieldLabel>- <Input- autoFocus- placeholder="Your name, handle or email"- value={search}- spellCheck={false}- onChange={(e) => {- setSearch(e.target.value);- setError(null);- }}- />- </Field>-- <DirectoryResults- query={debouncedQuery}- searchable={searchable}+ <BridgeIdentitySearch+ serverId={serverId}+ bridgeId={bridgeId}+ bridgeDisplayName={selectedBridge?.displayName ?? 'the workspace'}platform={bridgePlatformLabel(selectedBridge?.type ?? '')}- hasDirectory={selectedBridge?.directorySearchSupported ?? true}- isFetching={directoryQuery.isFetching}- result={directoryQuery.data ?? null}- fetchError={directoryQuery.error}- currentUserId={currentUserId}- claimingId={claiming}- releasingId={releasing}- onClaim={(person) => void handleClaim(person)}- onRelease={(person) => void handleRelease(person)}+ directorySearchSupported={selectedBridge?.directorySearchSupported ?? true}+ autoFocus+ onClaimed={(identity) => onSuccess({ identity })}/>-- {error && <p className="text-destructive text-xs">{error}</p>}</div></DialogContentArea><DialogFooter>{/* Skippable on purpose: this modal interrupts whatever the user came todo, and an unlinked account costs them nothing until they restrict anagent to its owner. */}- <Button- variant="outline"- onClick={onClose}- disabled={claiming !== null || releasing !== null}- >+ <Button variant="outline" onClick={onClose} disabled={hasActiveCloseGuard}>Skip for now</Button></DialogFooter></>);});--function DirectoryResults({- query,- searchable,- platform,- hasDirectory,- isFetching,- result,- fetchError,- currentUserId,- claimingId,- releasingId,- onClaim,- onRelease,-}: {- query: string;- searchable: boolean;- /** The platform as a person names it, for the line that says what is being- * searched. */- platform: string;- /** Whether the platform has a directory at all. When it does not, the only- * people findable are those Switch has already seen — so the prompt has to- * say that rather than promise a workspace directory the platform has no- * concept of. */- hasDirectory: boolean;- isFetching: boolean;- result: BridgeDirectorySearchResult | null;- fetchError: unknown;- currentUserId: string | null;- /** The platform id of the account being linked, or null when none is. */- claimingId: string | null;- /** The platform id of the account being unlinked, or null when none is. */- releasingId: string | null;- onClaim: (person: BridgeDirectoryUser) => void;- onRelease: (person: BridgeDirectoryUser) => void;-}) {- if (!searchable) {- return (- <p className="text-xs text-foreground-muted">- {hasDirectory- ? `Type at least ${MIN_QUERY_LENGTH} characters to search the workspace directory.`- : `Type at least ${MIN_QUERY_LENGTH} characters to search the people Switch has seen on ${platform}. It has no directory to search — someone appears here once they have sent a message.`}- </p>- );- }- if (fetchError) {- return (- <p className="text-destructive text-xs">- Could not search the directory:{' '}- {fetchError instanceof Error ? fetchError.message : String(fetchError)}- </p>- );- }- if (isFetching && result === null) {- return (- <p className="flex items-center gap-2 text-xs text-foreground-muted">- <Spinner className="size-3.5" />- Searching…- </p>- );- }- if (result === null) return null;-- // A platform with no directory to search is not an empty result — the server- // says what has to happen instead, and that is the only useful thing to show.- if (result.kind === 'unsupported' || result.kind === 'bridge-unavailable') {- return (- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <span>{result.message}</span>- </div>- );- }- if (result.kind === 'unauthenticated') {- return (- <p className="text-destructive text-xs">- Your session for this server expired. Sign in again, then retry.- </p>- );- }- if (result.kind === 'error') {- return <p className="text-destructive text-xs">{result.message}</p>;- }- // Set when the platform has no directory and the server answered from the- // accounts it has already seen. The list is real but cannot be complete, so- // it is captioned rather than replaced — replacing it is what left Telegram- // with a warning and no way forward.- const narrowed = result.note !== null && (- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <span>{result.note}</span>- </div>- );-- if (result.users.length === 0) {- return (- <div className="flex flex-col gap-2">- {narrowed}- <p className="text-xs text-foreground-muted">- {result.note === null- ? `Nobody in this workspace matches “${query}”.`- : `Nobody Switch has seen here matches “${query}”.`}- </p>- </div>- );- }-- // Nothing here is disabled because someone else holds the account: several- // people can be recognised on the same one, and the other claimants are shown- // so a shared or misidentified account is visible rather than silent.- const pending = claimingId !== null || releasingId !== null;- return (- <div className="flex flex-col gap-2">- {narrowed}- <ul className="flex max-h-64 flex-col gap-1 overflow-y-auto">- {result.users.map((person) => {- const linkedToMe = person.claimedBy.some((c) => c.userId === currentUserId);- const others = person.claimedBy.filter((c) => c.userId !== currentUserId);- return (- <li- key={person.externalUserId}- className="flex items-center justify-between gap-3 rounded-md border border-border p-2"- >- <div className="flex min-w-0 flex-col">- <span className="truncate text-sm text-foreground">{person.displayName}</span>- <span className="truncate text-xs text-foreground-muted">- @{person.username}- {person.email ? ` · ${person.email}` : ''}- </span>- {others.length > 0 && (- <span className="truncate text-xs text-foreground-muted">- Also linked to {others.map((c) => c.userName).join(', ')}- </span>- )}- </div>- {linkedToMe ? (- <span className="flex shrink-0 items-center gap-2">- <Badge variant="secondary">Linked to you</Badge>- <Button- variant="outline"- size="sm"- disabled={pending || person.knownExternalUserId === null}- onClick={() => onRelease(person)}- >- {releasingId === person.externalUserId ? 'Unlinking…' : 'Unlink'}- </Button>- </span>- ) : (- <Button size="sm" disabled={pending} onClick={() => onClaim(person)}>- {claimingId === person.externalUserId ? 'Linking…' : 'This is me'}- </Button>- )}- </li>- );- })}- </ul>- </div>- );-}--/** Turn a failed claim into something the user can act on. */-function claimFailureText(result: Exclude<ClaimIdentityResult, { kind: 'claimed' }>): string {- switch (result.kind) {- case 'unauthenticated':- return 'Your session for this server expired. Sign in again, then retry.';- case 'bridge-unavailable':- return result.message;- case 'error':- return result.message;- }-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsxindex 7a0c69bbf..c737dfa36 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx@@ -1,10 +1,16 @@import { useQuery } from '@tanstack/react-query';-import { ChevronDown, X } from 'lucide-react';+import { MessageSquare, Search, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useState } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';+import {+ AgentMark as SharedAgentMark,+ agentProviderLabel,+} from '@renderer/lib/components/agent-mark';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { rpc } from '@renderer/lib/ipc';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';@@ -16,7 +22,6 @@ import {ComboboxInput,ComboboxItem,ComboboxList,- ComboboxTrigger,} from '@renderer/lib/ui/combobox';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -25,19 +30,17 @@ import {DialogHeader,DialogTitle,} from '@renderer/lib/ui/dialog';-import { Field, FieldLabel } from '@renderer/lib/ui/field';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Input } from '@renderer/lib/ui/input';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';import { Textarea } from '@renderer/lib/ui/textarea';import { cn } from '@renderer/utils/utils';-import type { RemoteAgentSummary, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import type {+ LinkedIdentity,+ RemoteAgentSummary,+ RemoteBridge,+} from '@shared/core/switch-servers/switch-servers';import { switchServersStore } from './switch-servers-store';+import { useMyIdentities } from './use-my-identities';type CreateRoomModalArgs = {/** Create on this server instead of the active one — for callers that are not@@ -63,6 +66,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({const [name, setName] = useState('');const [description, setDescription] = useState('');const [instructions, setInstructions] = useState('');+ const [instructionsOpen, setInstructionsOpen] = useState(false);const [bridgeId, setBridgeId] = useState<string | null>(null);const [agents, setAgents] = useState<RemoteAgentSummary[]>([]);const [isSubmitting, setIsSubmitting] = useState(false);@@ -78,6 +82,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({queryFn: () => rpc.switchServers.listRemoteAgents(serverId),enabled: !!serverId,});+ // Which account on each app is the person creating the room. A room on an app+ // they have not claimed an account on works, but their own messages in it are+ // from a stranger as far as the agents are concerned — so it is said here,+ // while the app is being chosen, rather than discovered later.+ const { identities } = useMyIdentities(serverId);/*** Only agents this install registered on the server.@@ -95,10 +104,9 @@ export const CreateRoomModal = observer(function CreateRoomModal({// Only a running bridge can back a new room, and creating a room here means// creating a channel on it — a bridge withheld from that (an operator's// switch, or a platform like Telegram that has no such call at all) is just- // as unusable for this form. Keeping both kinds out of the picker (rather- // than letting the create call fail) means the one thing shown is the one- // thing that works — and each reason for an empty list is stated outright,- // rather than collapsed into one generic "no bridges".+ // as unusable for this form. Every connected app is shown, but an unusable+ // one is not selectable and says which of these it is: an app that is simply+ // absent from the grid explains nothing, and the user goes looking for it.const allBridges = bridgesQuery.data ?? [];const activeBridges = allBridges.filter((b) => b.status === 'active');const bridges = activeBridges.filter((b) => b.canCreateChannels);@@ -111,7 +119,6 @@ export const CreateRoomModal = observer(function CreateRoomModal({const noBridgesAtAll = loaded && allBridges.length === 0;const noneRunning = loaded && allBridges.length > 0 && activeBridges.length === 0;const noneCanCreateChannels = loaded && activeBridges.length > 0 && bridges.length === 0;- const noUsableBridge = noBridgesAtAll || noneRunning || noneCanCreateChannels;const trimmedName = name.trim();const trimmedDescription = description.trim();@@ -174,13 +181,17 @@ export const CreateRoomModal = observer(function CreateRoomModal({setCloseGuard,]);+ const submitOnEnter = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' && canSubmit) void handleSubmit();+ };+return (<>- <DialogHeader showCloseButton={false}>- <DialogTitle>New room{server ? ` on ${server.name}` : ''}</DialogTitle>+ <DialogHeader>+ <DialogTitle>New room</DialogTitle></DialogHeader><DialogContentArea className="pt-0">- <div className="flex w-full flex-col gap-5">+ <div className="flex w-full flex-col gap-6">{!server && (<p className="text-destructive text-xs">No Switch server is selected, so there is nowhere to create a room. Choose a server in@@ -188,90 +199,113 @@ export const CreateRoomModal = observer(function CreateRoomModal({</p>)}- <Field>- <FieldLabel>Name</FieldLabel>- <Input- autoFocus- placeholder="e.g. design-review"- value={name}- onChange={(e) => {- setName(e.target.value);- setError(null);- }}- onKeyDown={(e) => {- if (e.key === 'Enter' && canSubmit) void handleSubmit();- }}- />- </Field>-- <Field>- <FieldLabel>Description</FieldLabel>- <Input- placeholder="What this room is for"- value={description}- onChange={(e) => {- setDescription(e.target.value);- setError(null);- }}- onKeyDown={(e) => {- if (e.key === 'Enter' && canSubmit) void handleSubmit();- }}- />- </Field>-- <Field>- <FieldLabel>Messaging app</FieldLabel>- <Select- value={selectedBridge?.id ?? ''}- onValueChange={(next) => setBridgeId(next ?? null)}- disabled={bridgesQuery.isLoading || noUsableBridge}- >- <SelectTrigger>- {/* Resolve the label ourselves: the trigger shows the raw value- otherwise, which for a bridge is an opaque uuid. */}- <SelectValue- placeholder={bridgesQuery.isLoading ? 'Loading…' : 'No messaging app available'}- >- {selectedBridge ? bridgeLabel(selectedBridge) : undefined}- </SelectValue>- </SelectTrigger>- <SelectContent>- {bridges.map((bridge) => (- <SelectItem key={bridge.id} value={bridge.id}>- {bridgeLabel(bridge)}- </SelectItem>- ))}- </SelectContent>- </Select>+ {/* The app comes first because it decides the rest: the room's name+ becomes a channel name there, and who can reach the room is+ whoever is in that workspace. */}+ <section className="flex flex-col gap-3">+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium text-foreground">Messaging app</span>+ <span className="text-sm text-foreground-muted">+ Where the collaboration happens — people and agents talk in this room.+ </span>+ </div>+ <div className="grid grid-cols-2 gap-2.5">+ {allBridges.map((bridge) => (+ <BridgeTile+ key={bridge.id}+ bridge={bridge}+ identity={identities?.find((i) => i.bridgeId === bridge.id) ?? null}+ identitiesKnown={identities !== null}+ selected={selectedBridge?.id === bridge.id}+ onSelect={() => setBridgeId(bridge.id)}+ />+ ))}+ </div>{noBridgesAtAll && (- <p className="text-destructive mt-1 text-xs">+ <p className="text-destructive text-xs">This server has no messaging app connected, so a room created here would beunreachable. Connect one first.</p>)}{noneRunning && (- <p className="text-destructive mt-1 text-xs">- This server's messaging apps are not running, so a room created here would be+ <p className="text-destructive text-xs">+ This server's messaging apps are not running, so a room created here would beunreachable. Start one, or connect another.</p>)}{noneCanCreateChannels && (- <p className="text-destructive mt-1 text-xs">+ <p className="text-destructive text-xs">None of the running messaging apps can create a channel from Switch — for example, a- Telegram bot can't create chats on its own. Make the chat directly in the messaging- app instead (for Telegram, create the group and add the bot to it) and it becomes a- room here once it exists.+ Telegram bot can't create chats on its own. Make the chat directly in the+ messaging app instead (for Telegram, create the group and add the bot to it) and it+ becomes a room here once it exists.</p>)}{bridgesQuery.isError && (- <p className="text-destructive mt-1 text-xs">+ <p className="text-destructive text-xs">Could not load messaging apps: {errorText(bridgesQuery.error)}</p>)}- </Field>+ </section>++ <div className="flex flex-col gap-4">+ <FormRow label="Name">+ <Input+ autoFocus+ placeholder="e.g. design-review"+ value={name}+ onChange={(e) => {+ setName(e.target.value);+ setError(null);+ }}+ onKeyDown={submitOnEnter}+ />+ {/* What the name becomes, where it becomes it. A room is a channel+ in the app it is bridged to, and the two names are the same+ one — saying so here is what makes that predictable. */}+ {trimmedName !== '' && selectedBridge && (+ <span className="text-xs text-foreground-muted">+ Created as #{trimmedName} in {selectedBridge.displayName}.+ </span>+ )}+ </FormRow>++ <FormRow label="Description">+ <Input+ placeholder="What this room is for"+ value={description}+ onChange={(e) => {+ setDescription(e.target.value);+ setError(null);+ }}+ onKeyDown={submitOnEnter}+ />+ </FormRow>+ </div>++ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium text-foreground">Agents</span>+ {agents.length > 0 && (+ <span className="text-sm text-foreground-muted">{agents.length} added</span>+ )}+ </div>++ {agents.length > 0 && (+ <div className="grid grid-cols-3 gap-2.5">+ {agents.map((agent) => (+ <ChosenAgentTile+ key={agent.id}+ agent={agent}+ serverId={serverId}+ onRemove={() =>+ setAgents((current) => current.filter((a) => a.id !== agent.id))+ }+ />+ ))}+ </div>+ )}- <Field>- <FieldLabel>Agents</FieldLabel><Comboboxitems={invitableAgents.filter((a) => !agents.some((s) => s.id === a.id))}value={null}@@ -284,66 +318,54 @@ export const CreateRoomModal = observer(function CreateRoomModal({}autoHighlight>- <ComboboxTrigger+ {/* The search box is the control, rather than a button that opens+ one: adding several agents is the normal case, and a picker+ that has to be reopened per agent makes the normal case the+ laborious one. */}+ <ComboboxInput+ showTrigger={false}disabled={agentsQuery.isLoading}- className={cn(- 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',- agentsQuery.isLoading && 'cursor-not-allowed opacity-60'- )}- >- <span className="flex-1 truncate text-left text-foreground-muted">- {agentsQuery.isLoading ? 'Loading agents…' : 'Add an agent'}- </span>- <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />- </ComboboxTrigger>+ placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}+ leftAddon={<Search className="size-3.5 text-foreground-muted" />}+ /><ComboboxContent className="min-w-(--anchor-width)">- <ComboboxInput showTrigger={false} placeholder="Search agents…" /><ComboboxList>{(item: RemoteAgentSummary) => (- <ComboboxItem key={item.id} value={item}>+ <ComboboxItem key={item.id} value={item} showCheck={false}>+ <AgentMark agentId={item.id} serverId={serverId} size={16} /><span className="min-w-0 flex-1 truncate">{item.name}</span>+ <span className="shrink-0 text-xs text-foreground-muted">+ {providerLabelFor(item.id, serverId)}+ </span></ComboboxItem>)}</ComboboxList><ComboboxEmpty>No agents found</ComboboxEmpty></ComboboxContent></Combobox>- {agents.length > 0 && (- <div className="mt-2 flex flex-wrap gap-1.5">- {agents.map((agent) => (- <span- key={agent.id}- className="flex items-center gap-1 rounded-md border border-border px-2 py-0.5 text-xs"- >- {agent.name}- <button- type="button"- aria-label={`Remove ${agent.name}`}- className="text-foreground-muted hover:text-foreground"- onClick={() =>- setAgents((current) => current.filter((a) => a.id !== agent.id))- }- >- <X className="h-3 w-3" />- </button>- </span>- ))}- </div>- )}- <p className="mt-1 text-xs text-foreground-muted">++ <span className="text-xs text-foreground-muted">Optional — agents can be added to the room later.- </p>- </Field>-- <Field>- <FieldLabel>Instructions</FieldLabel>- <Textarea- placeholder="Optional guidance shown to agents when they connect"- value={instructions}- onChange={(e) => setInstructions(e.target.value)}- rows={3}+ </span>+ </section>++ <div>+ <DisclosureRow+ open={instructionsOpen}+ title="Instructions"+ meta="shown to agents when they enter"+ onToggle={() => setInstructionsOpen((v) => !v)}/>- </Field>+ {instructionsOpen && (+ <Textarea+ className="mt-3"+ placeholder="Optional guidance shown to agents when they enter a room"+ value={instructions}+ onChange={(e) => setInstructions(e.target.value)}+ rows={3}+ />+ )}+ </div>{error && <p className="text-destructive text-xs">{error}</p>}</div>@@ -360,8 +382,156 @@ export const CreateRoomModal = observer(function CreateRoomModal({);});-function bridgeLabel(bridge: RemoteBridge): string {- return bridge.isDefault ? `${bridge.displayName} (default)` : bridge.displayName;+/** A labelled row: the setting's name on the left, the control on the right. */+function FormRow({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex items-start gap-4">+ <span className="w-24 shrink-0 pt-2 text-sm text-foreground">{label}</span>+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">{children}</div>+ </div>+ );+}++/**+ * One messaging app to put the room in, with the account the user has on it.+ *+ * Every connected app is drawn, including the ones that cannot back a new room+ * — those are disabled and say why. Omitting them would be quieter and worse:+ * the user knows their server has Telegram on it, and a grid that simply does+ * not mention it reads as a bug rather than as a refusal.+ */+function BridgeTile({+ bridge,+ identity,+ identitiesKnown,+ selected,+ onSelect,+}: {+ bridge: RemoteBridge;+ identity: LinkedIdentity | null;+ identitiesKnown: boolean;+ selected: boolean;+ onSelect: () => void;+}) {+ const platform = bridgePlatformLabel(bridge.type);+ const unusable =+ bridge.status !== 'active'+ ? 'Not running'+ : !bridge.channelCreationSupported+ ? `${platform} cannot create channels`+ : !bridge.canCreateChannels+ ? 'Channel creation is off'+ : null;++ return (+ <button+ type="button"+ disabled={unusable !== null}+ aria-pressed={selected}+ onClick={onSelect}+ className={cn(+ 'flex cursor-pointer items-center gap-2.5 rounded-[10px] border p-3 text-left transition-colors',+ // Overlay tokens rather than `background-1`, which in dark mode is+ // exactly the dialog's own surface — the hover was being drawn, in the+ // colour of the thing behind it.+ selected ? 'border-foreground bg-[var(--sel)]' : 'border-border hover:bg-[var(--sel-soft)]',+ unusable !== null && 'cursor-not-allowed opacity-50 hover:bg-transparent'+ )}+ >+ <span className="flex size-6 shrink-0 items-center justify-center">+ {hasBridgeIcon(bridge.type) ? (+ <BridgeIcon bridgeType={bridge.type} size={20} />+ ) : (+ <MessageSquare className="size-5 text-foreground-muted" />+ )}+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-foreground">{bridge.displayName}</span>+ {/* Three different things, never conflated: why this app cannot be+ used, which account on it is you, or that Switch cannot tell. */}+ {unusable !== null ? (+ <span className="truncate text-xs text-foreground-muted">{unusable}</span>+ ) : !identitiesKnown ? null : identity === null ? (+ <span className="truncate text-xs text-amber-600 dark:text-amber-500">+ No account linked+ </span>+ ) : (+ <span className="truncate text-xs text-foreground-muted">{handleOf(identity)}</span>+ )}+ </span>+ </button>+ );+}++/** An agent already added to the room, with the way to take it back out. */+function ChosenAgentTile({+ agent,+ serverId,+ onRemove,+}: {+ agent: RemoteAgentSummary;+ serverId: string;+ onRemove: () => void;+}) {+ return (+ // `--fill` rather than `--surface-2`: in dark mode that surface is the+ // dialog's own background, so a tile drawn in it was a tile nobody could+ // see.+ <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">+ <AgentMark agentId={agent.id} serverId={serverId} size={22} />+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-foreground">{agent.name}</span>+ <span className="truncate text-xs text-foreground-muted">+ {providerLabelFor(agent.id, serverId)}+ </span>+ </div>+ <button+ type="button"+ aria-label={`Remove ${agent.name}`}+ onClick={onRemove}+ className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"+ >+ <X className="size-3.5" />+ </button>+ </div>+ );+}++/** The mark of what an agent runs, resolved through this install's copy of it. */+function AgentMark({+ agentId,+ serverId,+ size,+}: {+ agentId: string;+ serverId: string;+ size: number;+}) {+ return (+ <SharedAgentMark+ providerId={localAgentFor(agentId, serverId)?.providerId ?? null}+ size={size}+ />+ );+}++/** This install's record of a Switch agent, which is where its provider is+ * known — the server's summary says what type it is, not what runs it here. */+function localAgentFor(switchAgentId: string, serverId: string) {+ return (+ agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null+ );+}++function providerLabelFor(switchAgentId: string, serverId: string): string {+ return agentProviderLabel(localAgentFor(switchAgentId, serverId)?.providerId);+}++/** The claimed account as a handle. Platforms differ on whether the username+ * they report already carries the sigil, so add one only when it is missing. */+function handleOf(identity: LinkedIdentity): string {+ const username = identity.externalUsername;+ return username.startsWith('@') ? username : `@${username}`;}function errorText(cause: unknown): string {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsxindex caf7fdaf4..f532e56c6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx@@ -67,7 +67,7 @@ export const DeleteServerModal = observer(function DeleteServerModal({return (<><DialogHeader showCloseButton={false}>- <DialogTitle>Delete server</DialogTitle>+ <DialogTitle>Remove server</DialogTitle></DialogHeader><DialogContentArea className="pt-0"><p className="text-sm text-foreground-muted">This server is no longer available.</p>@@ -91,7 +91,9 @@ export const DeleteServerModal = observer(function DeleteServerModal({<DialogHeader showCloseButton={false}><div className="flex items-center gap-2"><TriangleAlert className="size-4 text-red-500" />- <DialogTitle>Delete “{server.name}”?</DialogTitle>+ <DialogTitle>+ {managed ? `Delete “${server.name}”?` : `Disconnect from “${server.name}”?`}+ </DialogTitle></div></DialogHeader><DialogContentArea className="space-y-3 pt-0">@@ -106,8 +108,8 @@ export const DeleteServerModal = observer(function DeleteServerModal({</p>) : (<p className="text-sm text-foreground-muted">- This removes the server from Switch Console. The server itself isn’t touched — you can- add it again later.+ This disconnects Switch Console from the server and signs you out of it. The server+ itself isn’t touched — you can connect to it again later.</p>)}<p className="text-sm text-foreground-muted">{agentsNote}</p>@@ -144,7 +146,13 @@ export const DeleteServerModal = observer(function DeleteServerModal({onClick={() => void handleDelete()}disabled={!typeConfirmed || isDeleting}>- {isDeleting ? 'Deleting…' : 'Delete server'}+ {managed+ ? isDeleting+ ? 'Deleting…'+ : 'Delete server'+ : isDeleting+ ? 'Disconnecting…'+ : 'Disconnect'}</ConfirmButton></DialogFooter></>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsxindex d0d656f58..2a7526330 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx@@ -1,12 +1,11 @@-import { CircleStop, Play, RefreshCw, TriangleAlert } from 'lucide-react';+import { TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect } from 'react';+import { useEffect, useState } from 'react';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';-import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import { localServerStore } from './local-server-store';import { LogTail } from './log-tail';-import { StackSection, StackStatusRow } from './server-stack-section';+import { phaseLabel, StackAction, StackSection, StackStatusRow } from './server-stack-section';/*** Lifecycle for the managed local Switch stack: live status, Docker guidance,@@ -15,6 +14,7 @@ import { StackSection, StackStatusRow } from './server-stack-section';*/export const LocalServerControls = observer(function LocalServerControls() {const store = localServerStore;+ const [showActivity, setShowActivity] = useState(false);useEffect(() => {void store.checkDocker();@@ -30,46 +30,49 @@ export const LocalServerControls = observer(function LocalServerControls() {const downgradeBlocked = store.drift?.direction === 'downgrade';return (- <StackSection title="Local server">+ <StackSection><StackStatusRow+ title="Local server"phase={store.phase}- detail={store.isRunning ? `switch-core ${runningVersion}` : 'not running'}+ summary={store.isRunning ? 'Running on this computer' : phaseLabel(store.phase)}+ versionDetail={runningVersion ? `switch-core ${runningVersion}` : null}+ activity={+ store.logs.length > 0 ? (+ <button+ type="button"+ onClick={() => setShowActivity((s) => !s)}+ className="text-foreground-muted underline-offset-2 transition-colors hover:text-foreground hover:underline"+ >+ {showActivity ? 'Hide activity' : 'Recent activity'}+ </button>+ ) : null+ }actions={store.isRunning ? (<>- <Button- variant="outline"- size="sm"+ <StackAction+ label="Restart"disabled={transitioning}onClick={() => void store.start()}- >- <RefreshCw className="size-4" />- Restart- </Button>- <Button- variant="outline"- size="sm"+ />+ <StackAction+ label="Stop"+ dangerdisabled={transitioning}onClick={() => void store.stop()}- >- <CircleStop className="size-4" />- Stop- </Button>+ /></>) : (- <Button- size="sm"+ <StackAction+ label={store.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}disabled={transitioning || downgradeBlocked}onClick={() => void store.start()}- >- <Play className="size-4" />- {store.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}- </Button>+ />)}/>- <div className="space-y-3 p-3">+ <div className="space-y-3">{store.message && transitioning && (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -96,17 +99,9 @@ export const LocalServerControls = observer(function LocalServerControls() {</Alert>)}- {/* What the stack is, until it has said something itself. Once it is- talking, its own output is the more useful thing to keep on screen. */}- {store.logs.length > 0 ? (- <LogTail lines={store.logs} placeholder={null} />- ) : (- <p className="text-xs text-foreground-muted">- Runs the full Switch stack on this computer with Docker- {runningVersion ? ` (switch-core ${runningVersion})` : ''}. It keeps running when you- close Switch Console — your agents, rooms and messaging apps come back with it.- </p>- )}+ {/* Behind the disclosure rather than shown the moment there is output:+ the log is what you go looking for, not what the section is for. */}+ {showActivity && store.logs.length > 0 && <LogTail lines={store.logs} placeholder={null} />}</div></StackSection>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex 8492931dd..1c816ad22 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -8,6 +8,7 @@ import {MoreVertical,Plus,Trash2,+ TriangleAlert,Unlink,} from 'lucide-react';import { observer } from 'mobx-react-lite';@@ -22,12 +23,12 @@ import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,DropdownMenuContent,+ DropdownMenuCheckboxItem,DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';import { Spinner } from '@renderer/lib/ui/spinner';-import { Switch } from '@renderer/lib/ui/switch';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { log } from '@renderer/utils/logger';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';@@ -48,10 +49,11 @@ import { useMyIdentities } from './use-my-identities';* signed-in user, and — for an admin — the way to connect another* (CHOO-1784, CHOO-2137).*- * One row per app, read as a table: the app on the left, your account on it in- * a column of its own, its actions on the right. An app you have not linked- * says so by offering a Link button and nothing else — the fact is worth one- * control, not a sentence repeated down the card.+ * One row per app: its name with the account you have claimed on it underneath,+ * a Link button while you have not, and a menu holding everything else. Read+ * far more often than changed, so it is a list rather than a table of controls+ * — the settings that used to be columns are in the menu, where they cost+ * nothing to ignore.** Listing is offered on every server type, not just managed ones: a bridge is* registered through the server's own admin API, so there is nothing@@ -59,6 +61,20 @@ import { useMyIdentities } from './use-my-identities';* signed-in user being an admin, because the endpoint is; linking an account is* not, because claiming an identity is something every user does for themselves.*/+/** Why a server has messaging apps at all: the agents registered here become+ * reachable in them. Linking is deliberately not explained here — it has its+ * own hover on the rows and the warning that are actually about it, and saying+ * both on the heading made the section's purpose the smaller half of a wall of+ * text. */+const MESSAGING_APPS_PURPOSE =+ 'Connecting a messaging app puts this server’s agents in it, so you can talk to them where you already work.';++/** Shown beside a row that has no linked account, and beside the card-level+ * warning, so the consequence is one hover away from the thing warning about+ * it rather than only in the section heading. */+const NO_ACCOUNT_EXPLANATION =+ 'Switch cannot tell which account in this app is you. Agents set to answer only their owner will not recognise you here, and messages from you read as if from a stranger.';+export const MessagingAppsCard = observer(function MessagingAppsCard({serverId,className,@@ -158,6 +174,25 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({<div className="flex items-center justify-between gap-3"><div className="flex items-center gap-2"><h3 className="text-sm font-medium text-foreground">Messaging apps</h3>+ {/* What the section is for, in the order the two facts matter:+ connecting puts the agents somewhere people already are, and+ linking is what lets those agents tell who is talking to them.+ It used to be the "Your account" column's header tooltip; with+ the columns gone it belongs to the heading. */}+ <Tooltip>+ <TooltipTrigger+ render={+ <span+ tabIndex={0}+ aria-label={MESSAGING_APPS_PURPOSE}+ className="inline-flex text-foreground-muted"+ >+ <Info className="size-3.5" />+ </span>+ }+ />+ <TooltipContent className="max-w-xs">{MESSAGING_APPS_PURPOSE}</TooltipContent>+ </Tooltip>{bridgesQuery.isLoading && <Spinner className="size-3.5" />}</div>{isAdmin && (@@ -197,7 +232,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({</div>{/* Same shape as the addressing editor's owner warning, so the two- readings of one problem look like one problem. */}+ readings of one problem look like one problem.++ The warning states the consequence itself, and each unlinked row below+ carries the longer explanation — a third hover here was one more thing+ to hover for something already said. */}{unrecognisedIn.length > 0 && (<div className="mt-2 flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs"><CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />@@ -226,81 +265,43 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({: 'No messaging app is connected. An admin on this server can connect one.'}</p>) : (- <div className="mt-2 overflow-hidden rounded-lg border border-border">- <table className="w-full table-fixed border-collapse text-sm">- <thead>- <tr className="border-b border-border bg-background-secondary text-xs text-foreground-muted">- <th scope="col" className="px-3 py-2 text-left font-normal">- App- </th>- <th scope="col" className="px-3 py-2 text-left font-normal">- <span className="inline-flex items-center gap-1">- Your account- <Tooltip>- <TooltipTrigger- render={- <span- tabIndex={0}- aria-label="Which account is you in each app, so your agents can recognise you."- className="inline-flex"- >- <Info className="size-3.5" />- </span>- }- />- <TooltipContent>- Which account is you in each app, so your agents can recognise you.- </TooltipContent>- </Tooltip>- </span>- </th>- <th scope="col" className="w-32 px-3 py-2 text-left font-normal">- Channels- </th>- <th scope="col" className="w-28 px-3 py-2 text-right font-normal">- Actions- </th>- </tr>- </thead>- <tbody className="divide-y divide-border">- {bridges.map((bridge) => (- <MessagingAppRow- key={bridge.id}- serverId={serverId}- bridge={bridge}- /* Nothing is drawn in the identity column until the list+ <div className="mt-2 flex flex-col">+ {bridges.map((bridge) => (+ <MessagingAppRow+ key={bridge.id}+ serverId={serverId}+ bridge={bridge}+ /* Nothing is drawn in the identity column until the listarrives: "not linked" and "not known yet" look identical,and offering to link an account the user already has is themore confusing of the two. */- identities={identities}- currentUserId={currentUserId}- onReleased={refreshIdentities}- showBundledSignIn={isManaged && bridge.type === 'mattermost'}- isAdmin={isAdmin}- savingChannelCreation={savingBridgeId === bridge.id}- onToggleChannelCreation={(enabled) =>- void handleToggleChannelCreation(bridge, enabled)- }- onDisconnect={() =>- showDisconnectMessagingApp({- serverId,- bridgeId: bridge.id,- bridgeDisplayName: bridge.displayName,- onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: ['remote-bridges', serverId],- });- // The rooms on that bridge went with it, so the sidebar- // is stale in a way the bridge list alone does not- // repair.- void switchRoomsStore.refreshRoomState();- },- })- }- />- ))}- </tbody>- </table>+ identities={identities}+ currentUserId={currentUserId}+ onReleased={refreshIdentities}+ showBundledSignIn={isManaged && bridge.type === 'mattermost'}+ isAdmin={isAdmin}+ savingChannelCreation={savingBridgeId === bridge.id}+ onToggleChannelCreation={(enabled) =>+ void handleToggleChannelCreation(bridge, enabled)+ }+ onDisconnect={() =>+ showDisconnectMessagingApp({+ serverId,+ bridgeId: bridge.id,+ bridgeDisplayName: bridge.displayName,+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: ['remote-bridges', serverId],+ });+ // The rooms on that bridge went with it, so the sidebar+ // is stale in a way the bridge list alone does not+ // repair.+ void switchRoomsStore.refreshRoomState();+ },+ })+ }+ />+ ))}</div>)}{toggleError && <p className="text-destructive mt-2 text-xs">{toggleError}</p>}@@ -312,10 +313,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({* One app: its name, which account on it is the signed-in user, whether Switch* may open channels on it, and a menu of everything else.*- * Unlinking and channel creation are read far more often than they are changed,- * so they are columns rather than menu items — the menu keeps the rarer and the- * destructive. The trailing controls always occupy their slot so several apps- * keep a straight right edge.+ * Only Link stays outside the menu: an app you have not claimed an account on+ * has exactly one thing worth doing to it, and burying that is what would make+ * the row's warning unactionable. Everything else — changing or dropping the+ * account, channel creation, the bundled chat's credentials, opening the app,+ * disconnecting it — is in the menu.*/export function MessagingAppRow({serverId,@@ -377,146 +379,147 @@ export function MessagingAppRow({: null;return (- <tr className="text-sm">- {/* The badges belong to the name, so they travel with it rather than- drifting into the middle of the row on a wide table. */}- <td className="px-3 py-2">+ <div className="flex items-center gap-3 py-2 text-sm">+ <span className="flex size-5 shrink-0 items-center justify-center">+ {hasBridgeIcon(bridge.type) ? (+ <BridgeIcon bridgeType={bridge.type} size={16} />+ ) : (+ <MessageSquare className="size-4 text-foreground-muted" />+ )}+ </span>++ {/* Name over account: the account is a property of the app, so it reads+ under its name rather than in a column of its own. */}+ <div className="flex min-w-0 flex-1 flex-col"><div className="flex min-w-0 items-center gap-2">- {hasBridgeIcon(bridge.type) ? (- <BridgeIcon bridgeType={bridge.type} size={16} />- ) : (- <MessageSquare className="size-4 text-foreground-muted" />- )}<span className="truncate text-foreground">{bridge.displayName}</span>{bridge.isDefault && <Badge variant="secondary">Default</Badge>}- {/* Surfaced only when it is NOT active: a bridge that is down cannot- back a new room, and the room-creation picker silently omits it, so- this is where that becomes visible. */}- {bridge.status !== 'active' && <Badge variant="destructive">{bridge.status}</Badge>}+ {/* Only when it is NOT active, and never otherwise. A bridge that is+ down cannot back a new room and the room-creation picker omits it+ silently, so without this the app simply is not in the list and+ nothing anywhere says why. */}+ {bridge.status !== 'active' && (+ <span className="text-destructive shrink-0 text-xs">{bridge.status}</span>+ )}</div>- </td>-- {/* One control in both states, so the column reads as a column: the- handle when there is one, the invitation to supply it when not. */}- <td className="px-3 py-2">{identities === null ? null : identity === null ? (- <Button variant="outline" size="xs" onClick={claim}>- <Link2 className="size-3" />- Link- </Button>+ <span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">+ <TriangleAlert className="size-3 shrink-0" />+ No account linked+ <Tooltip>+ <TooltipTrigger+ render={+ <span+ tabIndex={0}+ aria-label={NO_ACCOUNT_EXPLANATION}+ className="inline-flex text-foreground-muted"+ >+ <Info className="size-3" />+ </span>+ }+ />+ <TooltipContent className="max-w-xs">{NO_ACCOUNT_EXPLANATION}</TooltipContent>+ </Tooltip>+ </span>) : (- // One control, not two. Unlinking is irreversible and rare, and a- // cross beside the handle puts it one mis-click from the button you- // press to *change* the account (CHOO-2137); it lives in the row menu.- <Button- variant="ghost"- size="xs"- className="min-w-0 font-mono text-foreground-muted"- title={`Change which ${bridge.displayName} account is you`}- onClick={claim}- >- <span className="truncate">{handleOf(identity)}</span>- </Button>+ <span className="truncate font-mono text-xs text-foreground-muted">+ {handleOf(identity)}+ </span>)}{releaseError !== null && <p className="text-destructive mt-0.5 text-xs">{releaseError}</p>}- </td>-- <td className="px-3 py-2">- <Tooltip>- <TooltipTrigger- render={- <div className="flex w-fit items-center gap-2">- <Switch- checked={bridge.canCreateChannels}- disabled={channelsLockedReason !== null || savingChannelCreation}- onCheckedChange={(next) => onToggleChannelCreation(next)}- aria-label={`Let Switch create channels on ${bridge.displayName}`}- />- {/* "Off" and "this platform has no such thing" are different- claims, and an unticked disabled switch makes them look the- same (CHOO-2137). Say which one it is. */}- <span className="text-xs text-foreground-muted">- {!bridge.channelCreationSupported- ? 'Not supported'- : bridge.canCreateChannels- ? 'On'- : 'Off'}- </span>- </div>- }- />- <TooltipContent>- {channelsLockedReason ??- `Whether Switch may create a channel on ${platform} when you make a room.`}- </TooltipContent>- </Tooltip>- </td>+ </div>- <td className="px-3 py-2">- <div className="flex items-center justify-end">- {showBundledSignIn && (- <BundledChatSignIn serverId={serverId} bridgeDisplayName={bridge.displayName} />- )}+ {/* Linking is the one thing an unlinked app needs, so it stays a button+ rather than going into the menu with the rest. A linked app shows no+ button at all: the only thing left to do to it is destructive, and a+ control next to the handle would sit one mis-click from the action+ that *changes* the account (CHOO-2137). */}+ {identities !== null && identity === null && (+ <Button variant="outline" size="xs" className="shrink-0" onClick={claim}>+ <Link2 className="size-3" />+ Link+ </Button>+ )}- {/* Offered only when the link resolves — an older server, or a bridge- that is down, reports none, and a button that cannot do anything is- worse than no button. The slot is held either way so the rows keep a- straight right edge. */}- {bridge.homeUrl ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Buttonvariant="ghost"size="icon-xs"- aria-label={`Open ${platform}`}- title={`Open ${platform}`}- onClick={() =>- void openExternalUrl(bridge.homeUrl as string, `Could not open ${platform}`)- }+ className="shrink-0"+ aria-label={`${bridge.displayName} actions`}+ disabled={releasing}>- <ExternalLink className="size-3" />+ <MoreVertical className="size-3" /></Button>+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={claim}>+ <Link2 className="size-4" />+ {identity === null ? 'Link my account…' : 'Change my account…'}+ </DropdownMenuItem>+ {identity !== null && (+ <DropdownMenuItem onClick={() => void release(identity.id)}>+ <Unlink className="size-4" />+ Unlink {handleOf(identity)}+ </DropdownMenuItem>+ )}++ <DropdownMenuSeparator />+ {/* "Off" and "this platform has no such thing" are different claims,+ and an unticked box makes them look the same (CHOO-2137). A+ platform that cannot do it at all gets a plain disabled line+ saying so, never an unchecked box. */}+ {bridge.channelCreationSupported ? (+ <DropdownMenuCheckboxItem+ checked={bridge.canCreateChannels}+ disabled={!isAdmin || savingChannelCreation}+ onCheckedChange={(next) => onToggleChannelCreation(next)}+ >+ Create channels on {platform}+ </DropdownMenuCheckboxItem>) : (- <span aria-hidden className="size-6 shrink-0" />+ <DropdownMenuItem disabled>Channels not supported on {platform}</DropdownMenuItem>+ )}+ {channelsLockedReason !== null && (+ <p className="px-2 py-1 text-xs text-foreground-muted">{channelsLockedReason}</p>)}- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="ghost"- size="icon-xs"- aria-label={`${bridge.displayName} actions`}- disabled={releasing}- >- <MoreVertical className="size-3" />- </Button>- }+ {(showBundledSignIn || bridge.homeUrl) && <DropdownMenuSeparator />}+ {showBundledSignIn && (+ <BundledChatSignIn+ serverId={serverId}+ bridgeDisplayName={bridge.displayName}+ asMenuItem/>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={claim}>- <Link2 className="size-4" />- {identity === null ? 'Link my account…' : 'Change my account…'}- </DropdownMenuItem>- {identity !== null && (- <DropdownMenuItem onClick={() => void release(identity.id)}>- <Unlink className="size-4" />- Unlink {handleOf(identity)}- </DropdownMenuItem>- )}+ )}+ {/* Offered only when the link resolves — an older server, or a bridge+ that is down, reports none. */}+ {bridge.homeUrl && (+ <DropdownMenuItem+ onClick={() =>+ void openExternalUrl(bridge.homeUrl as string, `Could not open ${platform}`)+ }+ >+ <ExternalLink className="size-4" />+ Open in {platform}+ </DropdownMenuItem>+ )}- {isAdmin && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" onClick={onDisconnect}>- <Trash2 className="size-4" />- Disconnect app…- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>- </td>- </tr>+ {isAdmin && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDisconnect}>+ <Trash2 className="size-4" />+ Disconnect app…+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsxindex fa00cc9bc..8a40d8c70 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx@@ -1,12 +1,11 @@-import { CircleStop, Play, RefreshCw, TriangleAlert } from 'lucide-react';+import { TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect } from 'react';+import { useEffect, useState } from 'react';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';-import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import { LogTail } from './log-tail';import { remoteServerStore } from './remote-server-store';-import { StackSection, StackStatusRow } from './server-stack-section';+import { phaseLabel, StackAction, StackSection, StackStatusRow } from './server-stack-section';/*** Lifecycle for a managed Switch stack running in Docker on an SSH host. The@@ -21,6 +20,7 @@ export const RemoteServerControls = observer(function RemoteServerControls({name: string;}) {const store = remoteServerStore;+ const [showActivity, setShowActivity] = useState(false);useEffect(() => {void store.init();@@ -44,46 +44,51 @@ export const RemoteServerControls = observer(function RemoteServerControls({const logs = store.logsFor(sshHost);return (- <StackSection title={`Server on ${sshHost}`}>+ <StackSection><StackStatusRow+ title={`Server on ${sshHost}`}phase={hostBlocked ? 'unreachable' : status.phase}- detail={running ? `switch-core ${runningVersion}` : 'not running'}+ summary={+ running ? `Running on ${sshHost}` : phaseLabel(hostBlocked ? 'unreachable' : status.phase)+ }+ versionDetail={runningVersion ? `switch-core ${runningVersion}` : null}+ activity={+ logs.length > 0 ? (+ <button+ type="button"+ onClick={() => setShowActivity((s) => !s)}+ className="text-foreground-muted underline-offset-2 transition-colors hover:text-foreground hover:underline"+ >+ {showActivity ? 'Hide activity' : 'Recent activity'}+ </button>+ ) : null+ }actions={running ? (<>- <Button- variant="outline"- size="sm"+ <StackAction+ label="Restart"disabled={transitioning}onClick={() => void store.start(sshHost, name)}- >- <RefreshCw className="size-4" />- Restart- </Button>- <Button- variant="outline"- size="sm"+ />+ <StackAction+ label="Stop"+ dangerdisabled={transitioning}onClick={() => void store.stop(sshHost)}- >- <CircleStop className="size-4" />- Stop- </Button>+ /></>) : (- <Button- size="sm"+ <StackAction+ label={status.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}disabled={transitioning || downgradeBlocked}onClick={() => void store.start(sshHost, name)}- >- <Play className="size-4" />- {status.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}- </Button>+ />)}/>- <div className="space-y-3 p-3">+ <div className="space-y-3">{status.message && transitioning && (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -110,17 +115,9 @@ export const RemoteServerControls = observer(function RemoteServerControls({</Alert>)}- {/* What the stack is, until it has said something itself. Once it is- talking, its own output is the more useful thing to keep on screen. */}- {logs.length > 0 ? (- <LogTail lines={logs} placeholder={null} />- ) : (- <p className="text-xs text-foreground-muted">- Runs the full Switch stack in Docker on {sshHost}, bridged to this computer over SSH- {runningVersion ? ` (switch-core ${runningVersion})` : ''}. It keeps running when you- close Switch Console; agents on this computer can reach it while Switch Console is open.- </p>- )}+ {/* Behind the disclosure rather than shown the moment there is output:+ the log is what you go looking for, not what the section is for. */}+ {showActivity && logs.length > 0 && <LogTail lines={logs} placeholder={null} />}</div></StackSection>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsxindex 61385d305..5b18b94fb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx@@ -1,6 +1,5 @@import { CircleAlert } from 'lucide-react';import { useState } from 'react';-import { Button } from '@renderer/lib/ui/button';import {Select,SelectContent,@@ -8,13 +7,14 @@ import {SelectTrigger,SelectValue,} from '@renderer/lib/ui/select';+import { cn } from '@renderer/utils/utils';import {type AddressingMode,addressingModeOf,policyForMode,policyNamesOwner,} from '@shared/core/switch-servers/owner-policy';-import type { AddressingPolicy, LinkedIdentity } from '@shared/core/switch-servers/switch-servers';+import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';import { AddressingPolicyEditor, type OptionItem } from './addressing-policy-editor';const MODE_ORDER: AddressingMode[] = ['owner', 'ownerAndAgents', 'anyone', 'custom'];@@ -49,8 +49,9 @@ export function AddressingPolicyControl({roomGroups,users,agents,- linkedIdentities,- onClaimIdentity,+ unlinkedApps,+ onOpenMessagingApps,+ inlineLabel,disabled = false,}: {value: AddressingPolicy | null;@@ -59,15 +60,18 @@ export function AddressingPolicyControl({roomGroups: OptionItem[];users: OptionItem[];agents: OptionItem[];- /** Messaging accounts the signed-in user has claimed on this server. An- * owner rule resolves through these, so an empty list means such a rule- * admits nobody. Null while unknown — no warning is drawn from a list that- * has not arrived. */- linkedIdentities: LinkedIdentity[] | null;- /** Opens the claim-your-identity modal. Null where a modal cannot be opened- * over the current one (the add-agent dialog), which turns the warning into- * a statement rather than an action that would discard the form. */- onClaimIdentity: (() => void) | null;+ /** Messaging apps on this server the signed-in user has claimed no account+ * on, by display name. An owner rule resolves through a claimed account, so+ * in those apps it admits nobody — and that is true of one unclaimed app even+ * when others are linked. Null while unknown; no warning is drawn from a list+ * that has not arrived. */+ unlinkedApps: string[] | null;+ /** Opens the server's Messaging apps, which is where an account is linked. */+ onOpenMessagingApps: () => void;+ /** The setting's own title, rendered beside the chooser as one settings row.+ * Null where the caller already labels the control above it, which keeps the+ * chooser stacked and full-width. */+ inlineLabel: React.ReactNode | null;disabled?: boolean;}) {// Custom is sticky while it is chosen: a rule set can pass through a shape@@ -89,32 +93,56 @@ export function AddressingPolicyControl({onChange(policyForMode(next, next === 'custom' ? (customDraft ?? value) : value));};+ const chooser = (+ <Select+ value={mode}+ onValueChange={(next) => selectMode(next as AddressingMode)}+ disabled={disabled}+ >+ <SelectTrigger className={inlineLabel === null ? 'w-full' : 'shrink-0'}>+ {/* The label, not the value. Left to itself the trigger renders what+ is stored — "ownerAndAgents" — so the box contradicted the option+ just picked from it. */}+ <SelectValue>{MODE_LABELS[mode]}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {MODE_ORDER.map((option) => (+ <SelectItem key={option} value={option}>+ {MODE_LABELS[option]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );++ const hint = (+ <span className={cn('text-foreground-muted', inlineLabel === null ? 'text-xs' : 'text-sm')}>+ {MODE_HINTS[mode]}+ </span>+ );+return (<div className="flex flex-col gap-3">- <Select- value={mode}- onValueChange={(next) => selectMode(next as AddressingMode)}- disabled={disabled}- >- <SelectTrigger className="w-full">- {/* The label, not the value. Left to itself the trigger renders what- is stored — "ownerAndAgents" — so the box contradicted the option- just picked from it. */}- <SelectValue>{MODE_LABELS[mode]}</SelectValue>- </SelectTrigger>- <SelectContent>- {MODE_ORDER.map((option) => (- <SelectItem key={option} value={option}>- {MODE_LABELS[option]}- </SelectItem>- ))}- </SelectContent>- </Select>-- <span className="text-xs text-foreground-muted">{MODE_HINTS[mode]}</span>+ {inlineLabel === null ? (+ <>+ {chooser}+ {hint}+ </>+ ) : (+ <div className="flex items-start justify-between gap-4">+ <div className="flex min-w-0 flex-col gap-1">+ {inlineLabel}+ {hint}+ </div>+ {chooser}+ </div>+ )}- {policyNamesOwner(value) && linkedIdentities?.length === 0 && (- <OwnerUnreachableWarning onClaimIdentity={onClaimIdentity} />+ {policyNamesOwner(value) && unlinkedApps !== null && unlinkedApps.length > 0 && (+ <OwnerUnreachableWarning+ unlinkedApps={unlinkedApps}+ onOpenMessagingApps={onOpenMessagingApps}+ />)}{mode === 'custom' && value !== null && (@@ -133,31 +161,47 @@ export function AddressingPolicyControl({}/**- * Shown when a rule admits the agent's owner but the signed-in user has claimed- * no messaging account, which is exactly the case where a privacy control ends- * up admitting nobody. Silence here would look like a working restriction right- * up until someone wonders why the agent never answers.+ * Shown when a rule admits the agent's owner but there are messaging apps the+ * signed-in user has claimed no account on — exactly the case where a privacy+ * control ends up admitting nobody. Silence here would look like a working+ * restriction right up until someone wonders why the agent never answers.+ *+ * It names the apps rather than saying "this server": linking Slack and leaving+ * Mattermost unclaimed leaves the rule half-working, and a message that only+ * fires when nothing at all is linked would have called that fine.*/-function OwnerUnreachableWarning({ onClaimIdentity }: { onClaimIdentity: (() => void) | null }) {+function OwnerUnreachableWarning({+ unlinkedApps,+ onOpenMessagingApps,+}: {+ unlinkedApps: string[];+ onOpenMessagingApps: () => void;+}) {return (<div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs"><CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" /><div className="flex min-w-0 flex-1 flex-col gap-1.5"><span>- This admits the agent's owner, but you have not linked a messaging account on this- server — so Switch cannot tell that a message from you is from you, and the agent will- answer nobody.+ This admits the agent's owner, but you have not linked a messaging account on{' '}+ {listApps(unlinkedApps)} — so Switch cannot tell that a message from you there is from+ you, and the agent will answer nobody in those rooms.</span>- {onClaimIdentity === null ? (- <span className="text-foreground-muted">- Link your account from the server page, under “Messaging apps”.- </span>- ) : (- <Button variant="outline" size="sm" className="self-start" onClick={onClaimIdentity}>- Link my messaging account- </Button>- )}+ {/* Messaging apps, not a claim dialog: an account is linked per app, and+ which app is being claimed is a decision that belongs beside the list+ of them rather than inside a button pressed from here. */}+ <button+ type="button"+ className="-mx-1 w-fit cursor-pointer rounded px-1 text-foreground underline underline-offset-2 transition-colors hover:bg-background-2"+ onClick={onOpenMessagingApps}+ >+ Open Messaging apps+ </button></div></div>);}++function listApps(names: string[]): string {+ if (names.length === 1) return names[0] as string;+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsxnew file mode 100644index 000000000..dd6599f4e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx@@ -0,0 +1,334 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { CircleAlert } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { useDebounce } from '@renderer/lib/hooks/useDebounce';+import { rpc } from '@renderer/lib/ipc';+import { useModalContext } from '@renderer/lib/modal/modal-provider';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Field, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { Spinner } from '@renderer/lib/ui/spinner';+import type {+ BridgeDirectorySearchResult,+ BridgeDirectoryUser,+ ClaimIdentityResult,+ LinkedIdentity,+} from '@shared/core/switch-servers/switch-servers';+import { switchServersStore } from './switch-servers-store';+import { useMyIdentities } from './use-my-identities';++/** How long to wait after the last keystroke before asking the platform. Every+ * search is a live call out to Slack or Mattermost, so this is a courtesy to+ * their rate limits as much as to ours. */+const SEARCH_DEBOUNCE_MS = 300;++/** Below this the directory returns most of the workspace, which is neither+ * useful to scan nor cheap to fetch. */+const MIN_QUERY_LENGTH = 2;++/**+ * Find yourself in a messaging app's directory and say that account is you.+ *+ * Two surfaces ask for this — the modal reached from a server's messaging-app+ * row, and the last step of connecting to a server — so the search, the claim+ * and every way either can fail live here rather than in whichever one was+ * written first.+ */+export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({+ serverId,+ bridgeId,+ bridgeDisplayName,+ platform,+ directorySearchSupported,+ autoFocus,+ onClaimed,+}: {+ serverId: string;+ bridgeId: string;+ /** The workspace being searched — two connections on the same platform can+ * exist, and only the name tells them apart. */+ bridgeDisplayName: string;+ /** The platform as a person names it, for prose about what is searchable. */+ platform: string;+ directorySearchSupported: boolean;+ autoFocus: boolean;+ onClaimed: (identity: LinkedIdentity) => void;+}) {+ const { setCloseGuard } = useModalContext();+ const queryClient = useQueryClient();+ const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;++ const [search, setSearch] = useState('');+ const [claiming, setClaiming] = useState<string | null>(null);+ const [releasing, setReleasing] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const { refresh: refreshIdentities } = useMyIdentities(serverId || null);++ const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);+ const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;+ const directoryQuery = useQuery({+ queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],+ queryFn: () =>+ rpc.switchServers.searchBridgeDirectory({ serverId, bridgeId, query: debouncedQuery }),+ enabled: searchable,+ });++ const handleClaim = async (person: BridgeDirectoryUser) => {+ setClaiming(person.externalUserId);+ setCloseGuard(true);+ setError(null);+ try {+ const result = await rpc.switchServers.claimBridgeIdentity({+ serverId,+ bridgeId,+ externalUserId: person.externalUserId,+ username: person.username,+ });+ if (result.kind !== 'claimed') {+ setError(claimFailureText(result));+ return;+ }+ refreshIdentities();+ onClaimed(result.identity);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setClaiming(null);+ setCloseGuard(false);+ }+ };++ // Undo, in place: the row the user just linked is the row they look at when+ // they realise it is the wrong account, so the search stays open and the+ // directory is re-read to show who is left holding the account.+ const handleRelease = async (person: BridgeDirectoryUser) => {+ if (person.knownExternalUserId === null) return;+ setReleasing(person.externalUserId);+ setCloseGuard(true);+ setError(null);+ try {+ await rpc.switchServers.releaseBridgeIdentity({+ serverId,+ bridgeId,+ identityId: person.knownExternalUserId,+ userId: currentUserId,+ });+ refreshIdentities();+ await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setReleasing(null);+ setCloseGuard(false);+ }+ };++ return (+ <div className="flex w-full flex-col gap-4">+ <Field>+ <FieldLabel>Search {bridgeDisplayName}</FieldLabel>+ <Input+ autoFocus={autoFocus}+ placeholder="Your name, handle or email"+ value={search}+ spellCheck={false}+ onChange={(e) => {+ setSearch(e.target.value);+ setError(null);+ }}+ />+ </Field>++ <DirectoryResults+ query={debouncedQuery}+ searchable={searchable}+ platform={platform}+ hasDirectory={directorySearchSupported}+ isFetching={directoryQuery.isFetching}+ result={directoryQuery.data ?? null}+ fetchError={directoryQuery.error}+ currentUserId={currentUserId}+ claimingId={claiming}+ releasingId={releasing}+ onClaim={(person) => void handleClaim(person)}+ onRelease={(person) => void handleRelease(person)}+ />++ {error && <p className="text-destructive text-xs">{error}</p>}+ </div>+ );+});++function DirectoryResults({+ query,+ searchable,+ platform,+ hasDirectory,+ isFetching,+ result,+ fetchError,+ currentUserId,+ claimingId,+ releasingId,+ onClaim,+ onRelease,+}: {+ query: string;+ searchable: boolean;+ /** The platform as a person names it, for the line that says what is being+ * searched. */+ platform: string;+ /** Whether the platform has a directory at all. When it does not, the only+ * people findable are those Switch has already seen — so the prompt has to+ * say that rather than promise a workspace directory the platform has no+ * concept of. */+ hasDirectory: boolean;+ isFetching: boolean;+ result: BridgeDirectorySearchResult | null;+ fetchError: unknown;+ currentUserId: string | null;+ /** The platform id of the account being linked, or null when none is. */+ claimingId: string | null;+ /** The platform id of the account being unlinked, or null when none is. */+ releasingId: string | null;+ onClaim: (person: BridgeDirectoryUser) => void;+ onRelease: (person: BridgeDirectoryUser) => void;+}) {+ if (!searchable) {+ return (+ <p className="text-xs text-foreground-muted">+ {hasDirectory+ ? `Type at least ${MIN_QUERY_LENGTH} characters to search the workspace directory.`+ : `Type at least ${MIN_QUERY_LENGTH} characters to search the people Switch has seen on ${platform}. It has no directory to search — someone appears here once they have sent a message.`}+ </p>+ );+ }+ if (fetchError) {+ return (+ <p className="text-destructive text-xs">+ Could not search the directory:{' '}+ {fetchError instanceof Error ? fetchError.message : String(fetchError)}+ </p>+ );+ }+ if (isFetching && result === null) {+ return (+ <p className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3.5" />+ Searching…+ </p>+ );+ }+ if (result === null) return null;++ // A platform with no directory to search is not an empty result — the server+ // says what has to happen instead, and that is the only useful thing to show.+ if (result.kind === 'unsupported' || result.kind === 'bridge-unavailable') {+ return (+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />+ <span>{result.message}</span>+ </div>+ );+ }+ if (result.kind === 'unauthenticated') {+ return (+ <p className="text-destructive text-xs">+ Your session for this server expired. Sign in again, then retry.+ </p>+ );+ }+ if (result.kind === 'error') {+ return <p className="text-destructive text-xs">{result.message}</p>;+ }+ // Set when the platform has no directory and the server answered from the+ // accounts it has already seen. The list is real but cannot be complete, so+ // it is captioned rather than replaced — replacing it is what left Telegram+ // with a warning and no way forward.+ const narrowed = result.note !== null && (+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />+ <span>{result.note}</span>+ </div>+ );++ if (result.users.length === 0) {+ return (+ <div className="flex flex-col gap-2">+ {narrowed}+ <p className="text-xs text-foreground-muted">+ {result.note === null+ ? `Nobody in this workspace matches “${query}”.`+ : `Nobody Switch has seen here matches “${query}”.`}+ </p>+ </div>+ );+ }++ // Nothing here is disabled because someone else holds the account: several+ // people can be recognised on the same one, and the other claimants are shown+ // so a shared or misidentified account is visible rather than silent.+ const pending = claimingId !== null || releasingId !== null;+ return (+ <div className="flex flex-col gap-2">+ {narrowed}+ <ul className="flex max-h-64 flex-col gap-1 overflow-y-auto">+ {result.users.map((person) => {+ const linkedToMe = person.claimedBy.some((c) => c.userId === currentUserId);+ const others = person.claimedBy.filter((c) => c.userId !== currentUserId);+ return (+ <li+ key={person.externalUserId}+ className="flex items-center justify-between gap-3 rounded-md border border-border p-2"+ >+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-foreground">{person.displayName}</span>+ <span className="truncate text-xs text-foreground-muted">+ @{person.username}+ {person.email ? ` · ${person.email}` : ''}+ </span>+ {others.length > 0 && (+ <span className="truncate text-xs text-foreground-muted">+ Also linked to {others.map((c) => c.userName).join(', ')}+ </span>+ )}+ </div>+ {linkedToMe ? (+ <span className="flex shrink-0 items-center gap-2">+ <Badge variant="secondary">Linked to you</Badge>+ <Button+ variant="outline"+ size="sm"+ disabled={pending || person.knownExternalUserId === null}+ onClick={() => onRelease(person)}+ >+ {releasingId === person.externalUserId ? 'Unlinking…' : 'Unlink'}+ </Button>+ </span>+ ) : (+ <Button size="sm" disabled={pending} onClick={() => onClaim(person)}>+ {claimingId === person.externalUserId ? 'Linking…' : 'This is me'}+ </Button>+ )}+ </li>+ );+ })}+ </ul>+ </div>+ );+}++/** Turn a failed claim into something the user can act on. */+function claimFailureText(result: Exclude<ClaimIdentityResult, { kind: 'claimed' }>): string {+ switch (result.kind) {+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'bridge-unavailable':+ return result.message;+ case 'error':+ return result.message;+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.test.tsnew file mode 100644index 000000000..2f2af8361--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { connectedAppsSummary, LINK_ACCOUNTS_LATER, spellCount } from './link-accounts-prose';++describe('connectedAppsSummary', () => {+ it('names the server and counts its apps in words', () => {+ expect(connectedAppsSummary('Pilot', 3)).toBe('Pilot has three messaging apps connected.');+ });++ it('agrees with a single app', () => {+ expect(connectedAppsSummary('Pilot', 1)).toBe('Pilot has one messaging app connected.');+ });++ it('says a server with none has none, rather than counting zero apps', () => {+ expect(connectedAppsSummary('Pilot', 0)).toBe('Pilot has no messaging apps connected yet.');+ });++ it('falls back to the numeral past the words it knows', () => {+ expect(spellCount(9)).toBe('nine');+ expect(connectedAppsSummary('Pilot', 12)).toBe('Pilot has 12 messaging apps connected.');+ });+});++describe('LINK_ACCOUNTS_LATER', () => {+ // The mock said rooms on an unlinked app are read-only. They are not — an+ // unlinked account only costs you owner-restricted agents recognising you,+ // and promising a lock that does not exist is the kind of claim a user finds+ // out is false the first time they type in one of those rooms.+ it('does not claim an unlinked app locks you out', () => {+ expect(LINK_ACCOUNTS_LATER).not.toMatch(/read-only/i);+ expect(LINK_ACCOUNTS_LATER).toMatch(/only their owner/);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.tsnew file mode 100644index 000000000..c71f473ba--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts@@ -0,0 +1,21 @@+/**+ * What linking is for, said where someone is deciding whether to bother.+ *+ * Not "the app is read-only until you do" — an unlinked account costs nothing+ * until an agent is restricted to its owner, and overstating it here is the one+ * claim on this screen a user could catch us in.+ */+export const LINK_ACCOUNTS_LATER =+ 'You can link the rest later from the server’s page. Until you do, agents set to answer only their owner will not recognise you in that app.';++/** Small counts read better as words in a sentence; past that the numeral wins. */+export function spellCount(n: number): string {+ const words = ['no', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];+ return words[n] ?? String(n);+}++/** "Pilot has three messaging apps connected." */+export function connectedAppsSummary(serverName: string, count: number): string {+ if (count === 0) return `${serverName} has no messaging apps connected yet.`;+ return `${serverName} has ${spellCount(count)} messaging app${count === 1 ? '' : 's'} connected.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsxnew file mode 100644index 000000000..5c72b98a5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx@@ -0,0 +1,236 @@+import { useQuery } from '@tanstack/react-query';+import { Check, Link2, MessageSquare, TriangleAlert } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import { DialogContentArea, DialogFooter } from '@renderer/lib/ui/dialog';+import { Spinner } from '@renderer/lib/ui/spinner';+import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import { BridgeIdentitySearch } from './bridge-identity-search';+import { connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';+import { orderBridges } from './messaging-apps-order';+import { useMyIdentities } from './use-my-identities';++/**+ * The last step of connecting to a server someone else runs: say which account+ * in each of its messaging apps is you.+ *+ * It is here rather than only on the server page because a server you connect+ * to already has its apps attached — the moment you arrive is the moment the+ * question is answerable, and the only moment you are certain to be asked.+ */+export const LinkAccountsStep = observer(function LinkAccountsStep({+ serverId,+ serverName,+ step,+ of,+ onDone,+}: {+ serverId: string;+ serverName: string;+ step: number;+ of: number;+ onDone: () => void;+}) {+ // Which app's directory is open, or null while the list is. Linking happens+ // in place: a second dialog on top of this one would bury the step it belongs+ // to and give the user two Backs meaning different things.+ const [linking, setLinking] = useState<RemoteBridge | null>(null);++ const bridgesQuery = useQuery({+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ });+ const { identities } = useMyIdentities(serverId);++ if (linking) {+ return (+ <>+ <WizardStepHeader+ title={`Link your ${bridgePlatformLabel(linking.type)} account`}+ step={step}+ of={of}+ />+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-4">+ <p className="text-sm text-foreground-muted">+ Find yourself in {linking.displayName} and tell Switch that account is you.+ </p>+ <BridgeIdentitySearch+ serverId={serverId}+ bridgeId={linking.id}+ bridgeDisplayName={linking.displayName}+ platform={bridgePlatformLabel(linking.type)}+ directorySearchSupported={linking.directorySearchSupported}+ autoFocus+ onClaimed={() => setLinking(null)}+ />+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={() => setLinking(null)}>+ Back+ </Button>+ </DialogFooter>+ </>+ );+ }++ return (+ <>+ <WizardStepHeader title="Link your messaging accounts" step={step} of={of} />+ <DialogContentArea className="pt-0">+ <BridgeList+ serverName={serverName}+ bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}+ identities={identities}+ isPending={bridgesQuery.isPending}+ error={bridgesQuery.isError ? bridgesQuery.error : null}+ onRetry={() => void bridgesQuery.refetch()}+ onLink={setLinking}+ />+ </DialogContentArea>+ <DialogFooter>+ <ConfirmButton onClick={onDone}>Done</ConfirmButton>+ </DialogFooter>+ </>+ );+});++function BridgeList({+ serverName,+ bridges,+ identities,+ isPending,+ error,+ onRetry,+ onLink,+}: {+ serverName: string;+ /** Null until the read succeeds — pending and failed are separate states+ * below, so this never stands in for either. */+ bridges: RemoteBridge[] | null;+ identities: LinkedIdentity[] | null;+ isPending: boolean;+ error: unknown;+ onRetry: () => void;+ onLink: (bridge: RemoteBridge) => void;+}) {+ if (isPending) {+ return (+ <p className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner className="size-3.5" />+ Reading this server’s messaging apps…+ </p>+ );+ }++ if (error !== null) {+ return (+ <div className="flex flex-col items-start gap-3">+ <p className="text-destructive text-sm">+ Could not read this server’s messaging apps:{' '}+ {error instanceof Error ? error.message : String(error)}+ </p>+ <Button variant="outline" size="sm" onClick={onRetry}>+ Retry+ </Button>+ </div>+ );+ }++ if (bridges === null) return null;++ return (+ <div className="flex w-full flex-col gap-4">+ <p className="text-sm text-foreground-muted">+ {connectedAppsSummary(serverName, bridges.length)}+ {bridges.length > 0 && ' Link the accounts you use so your agents know who you are.'}+ </p>++ {bridges.length === 0 ? (+ <p className="text-sm text-foreground-muted">+ There is nothing to link yet. Once an admin connects one, its row appears on the server’s+ page.+ </p>+ ) : (+ <>+ <ul className="flex flex-col gap-2">+ {bridges.map((bridge) => (+ <BridgeLinkRow+ key={bridge.id}+ bridge={bridge}+ identities={identities}+ onLink={() => onLink(bridge)}+ />+ ))}+ </ul>+ <p className="text-xs text-foreground-muted">{LINK_ACCOUNTS_LATER}</p>+ </>+ )}+ </div>+ );+}++function BridgeLinkRow({+ bridge,+ identities,+ onLink,+}: {+ bridge: RemoteBridge;+ /** Null while unknown — which is not the same as none, so the row shows+ * neither a handle nor a Link button until the answer arrives. */+ identities: LinkedIdentity[] | null;+ onLink: () => void;+}) {+ const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;++ return (+ <li className="flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3">+ <span className="flex size-6 shrink-0 items-center justify-center">+ {hasBridgeIcon(bridge.type) ? (+ <BridgeIcon bridgeType={bridge.type} size={20} />+ ) : (+ <MessageSquare className="size-5 text-foreground-muted" />+ )}+ </span>++ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-foreground">{bridge.displayName}</span>+ {identities === null ? null : identity === null ? (+ <span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">+ <TriangleAlert className="size-3 shrink-0" />+ No account linked+ </span>+ ) : (+ <span className="truncate font-mono text-xs text-foreground-muted">+ {handleOf(identity)}+ </span>+ )}+ </div>++ {identities !== null &&+ (identity === null ? (+ <Button variant="outline" size="sm" className="shrink-0" onClick={onLink}>+ <Link2 className="size-3.5" />+ Link account+ </Button>+ ) : (+ <span className="flex shrink-0 items-center gap-1.5 text-sm text-green-600 dark:text-green-500">+ <Check className="size-4" />+ Linked+ </span>+ ))}+ </li>+ );+}++function handleOf(identity: LinkedIdentity): string {+ const username = identity.externalUsername;+ return username.startsWith('@') ? username : `@${username}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsxindex 1fb8be817..b5c742bf8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx@@ -19,21 +19,13 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';-import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import type { Agent } from '@shared/core/agents/agents';import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';-import { ServerPage, ServerTable, ServerTableEmpty } from './server-page';+import { ServerPage } from './server-page';import { ServerSectionTitlebar } from './server-section-titlebar';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';-const COLUMNS = [- { key: 'agent', label: 'Agent' },- { key: 'provider', label: 'Provider' },- { key: 'rooms', label: 'Rooms', className: 'w-24' },- { key: 'actions', label: 'Actions', className: 'w-28 text-right' },-] as const;-function useServerId(): string {return useParams('serverAgents').params.serverId;}@@ -59,29 +51,33 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {<ServerPagetitle="Your Agents"description={`Agents on ${server?.name ?? 'this server'}. Add one, set how it is addressed, and start sessions.`}- action={- <Button size="sm" onClick={() => showAddAgentModal({})}>- <Plus className="size-4" />- Add agent- </Button>- }>- {agents.length === 0 ? (- <ServerTableEmpty>- No agents are registered on this server yet. Add one to start sessions with it.- </ServerTableEmpty>- ) : (- <ServerTable columns={COLUMNS}>- {agents.map((agent) => (- <AgentRow key={agent.id} agent={agent} serverId={serverId} />- ))}- </ServerTable>- )}+ {/* The add tile leads the grid rather than sitting as a button in the+ page header: it is the same kind of thing as the cards after it, and+ on an empty server it is the only thing on screen, which says what to+ do without needing an empty-state sentence.++ Four columns at the design's content width, reflowing narrower rather+ than squashing. The height is a floor rather than a ratio, so a card+ keeps its shape as the column width changes. */}+ <div className="grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-[14px]">+ <button+ type="button"+ onClick={() => showAddAgentModal({})}+ className="flex min-h-[184px] cursor-pointer items-center justify-center rounded-[11px] border border-dashed border-border text-foreground-muted transition-colors hover:border-border-1 hover:bg-[var(--sel-soft)] hover:text-foreground"+ aria-label="Add agent"+ >+ <Plus className="size-5" />+ </button>+ {agents.map((agent) => (+ <AgentCard key={agent.id} agent={agent} serverId={serverId} />+ ))}+ </div></ServerPage>);});-const AgentRow = observer(function AgentRow({+const AgentCard = observer(function AgentCard({agent,serverId,}: {@@ -89,7 +85,6 @@ const AgentRow = observer(function AgentRow({serverId: string;}) {const { navigate } = useNavigate();- const showCreateSessionModal = useShowModal('sessionModal');const showConfirmReset = useShowModal('resetAgentModal');const confirmDeleteAgent = useConfirmDeleteAgent();const { toastPromise } = useToast();@@ -103,133 +98,102 @@ const AgentRow = observer(function AgentRow({agent.switchAgentId && switchRoomsStore.gatewayAgentUrl(serverId, agent.switchAgentId);return (- <tr className="text-sm">- <td className="px-3 py-2">- <button- type="button"- className="flex min-w-0 items-center gap-2 text-left hover:underline"- onClick={() => navigate('location', { locationId: agent.locationId, agentName: label })}- >- {agent.providerId ? (- <AgentIcon id={agent.providerId} size={16} className="shrink-0" />- ) : (- <Bot className="size-4 shrink-0 text-foreground-muted" />- )}- <span className="truncate">{label}</span>- </button>- </td>-- <td className="truncate px-3 py-2 text-foreground-muted">- {provider ? `${provider} · ` : ''}- {sshHost ?? 'this computer'}- </td>-- <td className="px-3 py-2 text-foreground-muted">- <AgentRoomCount agent={agent} serverId={serverId} />- </td>-- <td className="px-3 py-2">- <div className="flex items-center justify-end">- <Tooltip>- <TooltipTrigger- render={- <Button- variant="ghost"- size="icon-xs"- aria-label={`New session for ${label}`}- onClick={() =>- showCreateSessionModal({ locationId: agent.locationId, agentName: label })- }- >- <Plus className="size-3" />- </Button>- }- />- <TooltipContent>New session</TooltipContent>- </Tooltip>-- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button variant="ghost" size="icon-xs" aria-label={`${label} actions`}>- <MoreVertical className="size-3" />- </Button>- }- />- <DropdownMenuContent align="end">- {gatewayUrl && (- <DropdownMenuItem- onClick={() =>- void rpc.switchServers.openGatewayPage({ serverId, url: gatewayUrl })- }- >- <ExternalLink className="size-4" />- Open in gateway- </DropdownMenuItem>- )}- {sshHost != null && (- <DropdownMenuItem- onClick={() =>- showConfirmReset({- agentLabel: label,- onSuccess: () => {- void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {- loading: `Resetting ${label}…`,- success: `${label} was reset`,- error: (error) =>- `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,- });- },- })- }- >- <RotateCcw className="size-4" />- Reset agent…- </DropdownMenuItem>- )}- <DropdownMenuSeparator />+ <div className="group relative flex min-h-[184px] flex-col rounded-[11px] bg-[var(--surface-2)] transition-colors hover:bg-[var(--fill)]">+ {/* One real button covering the card, so the whole tile is the target and+ screen readers get a single named control rather than a grid of+ nested ones. The visible content below it is inert; the actions after+ it sit on top and keep their own clicks. */}+ <button+ type="button"+ aria-label={`Open ${label}`}+ className="focus-visible:ring-ring absolute inset-0 cursor-pointer rounded-[11px] focus-visible:ring-2 focus-visible:outline-none"+ onClick={() => navigate('location', { locationId: agent.locationId, agentName: label })}+ />++ <div className="pointer-events-none flex flex-1 flex-col p-[14px]">+ <div className="flex flex-1 items-center justify-center py-3">+ <span className="flex size-16 items-center justify-center rounded-full bg-background">+ {agent.providerId ? (+ <AgentIcon id={agent.providerId} size={30} />+ ) : (+ <Bot className="size-7 text-foreground-muted" />+ )}+ </span>+ </div>+ <div className="min-w-0">+ <div className="truncate text-sm font-medium text-foreground">{label}</div>+ <div className="truncate text-xs text-foreground-muted">+ {provider ? `${provider} · ` : ''}+ {sshHost ?? 'this computer'}+ </div>+ </div>+ </div>++ {/* Open in gateway, Reset and Remove, on hover. Kept rather than dropped+ with the table: none of them has another entry point from this page.+ Starting a session is not here — the sidebar is where sessions begin. */}+ <div className="absolute top-2 right-2 flex items-center opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="ghost" size="icon-xs" aria-label={`${label} actions`}>+ <MoreVertical className="size-3" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {gatewayUrl && (<DropdownMenuItem- variant="destructive"- onClick={() => {- void confirmDeleteAgent({- locationId: agent.locationId,- agentId: agent.id,- locationLabel: label,- onDeleted: () => {},- });- }}+ onClick={() =>+ void rpc.switchServers.openGatewayPage({ serverId, url: gatewayUrl })+ }>- <Trash2 className="size-4" />- Remove agent…+ <ExternalLink className="size-4" />+ Open in gateway</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </td>- </tr>+ )}+ {sshHost != null && (+ <DropdownMenuItem+ onClick={() =>+ showConfirmReset({+ agentLabel: label,+ onSuccess: () => {+ void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {+ loading: `Resetting ${label}…`,+ success: `${label} was reset`,+ error: (error) =>+ `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,+ });+ },+ })+ }+ >+ <RotateCcw className="size-4" />+ Reset agent…+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => {+ void confirmDeleteAgent({+ locationId: agent.locationId,+ agentId: agent.id,+ locationLabel: label,+ onDeleted: () => {},+ });+ }}+ >+ <Trash2 className="size-4" />+ Remove agent…+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>);});-/**- * How many of this server's rooms the agent is in.- *- * An agent whose membership has not been read yet shows an em dash, not a zero:- * "in no rooms" is a thing you would go and fix, and it must not be said about- * an agent we simply have not asked about.- */-const AgentRoomCount = observer(function AgentRoomCount({- agent,- serverId,-}: {- agent: Agent;- serverId: string;-}) {- if (!agent.switchAgentId) return <span>—</span>;- const memberships = switchRoomsStore.roomsFor(serverId, agent.switchAgentId);- if (memberships === undefined) return <span>—</span>;- return <span>{memberships.filter((room) => !room.archived).length}</span>;-});-export const serverAgentsView = {WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,TitlebarSlot: ServerAgentsTitlebar,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsxindex 4e0097df1..cd80e2b23 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx@@ -14,7 +14,9 @@ export function ServerPage({}: {title: string;description: string;- action: ReactNode;+ /** Header-level action, where the page has one. Agents has none: its add+ * affordance is the first tile of its grid. */+ action?: ReactNode;children: ReactNode;}) {return (@@ -25,7 +27,7 @@ export function ServerPage({<h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2><p className="mt-1 text-sm text-foreground-muted">{description}</p></div>- <div className="flex shrink-0 items-center gap-2">{action}</div>+ {action && <div className="flex shrink-0 items-center gap-2">{action}</div>}</header>{children}</div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsxindex d779f7d2f..eaac3c619 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx@@ -92,7 +92,7 @@ export function serverDrift(server: SwitchServer): SwitchVersionDrift | null {const AVATAR_SIZE = {sm: 'size-6 text-xs',- md: 'size-7 text-sm',+ md: 'size-[26px] text-xs',lg: 'size-9 rounded-lg text-lg',} as const;@@ -108,7 +108,7 @@ export function ServerAvatar({<spanaria-hiddenclassName={cn(- 'flex shrink-0 items-center justify-center rounded-md bg-foreground font-medium text-background',+ 'flex shrink-0 items-center justify-center rounded-lg bg-[var(--accent-solid)] font-semibold text-white',AVATAR_SIZE[size])}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-reset-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-reset-section.tsxindex d0270e914..b8883f45a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-reset-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-reset-section.tsx@@ -32,7 +32,7 @@ export function ServerResetSection({const [open, setOpen] = useState(false);return (- <section className="border-t border-border pt-5">+ <section><div className="flex items-center justify-between gap-3"><div className="space-y-0.5"><h3 className="text-sm font-medium text-foreground">Reset</h3>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex 70df96eb2..81ac90753 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -1,34 +1,28 @@-import { DoorOpen, ExternalLink, MoreVertical, Plus, UserPlus } from 'lucide-react';+import { Bot, ChevronDown, DoorOpen, MessageSquare, Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect } from 'react';+import { useEffect, useState } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';+import { openRoom } from '@renderer/features/switch-rooms/open-room';+import { roomTitle } from '@renderer/features/switch-rooms/room-labels';+import { AgentIcon } from '@renderer/lib/components/agent-icon';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';-import { rpc } from '@renderer/lib/ipc';-import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { openExternalUrl } from '@renderer/lib/open-external';import { Button } from '@renderer/lib/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@renderer/lib/ui/dropdown-menu';+import { SearchInput } from '@renderer/lib/ui/search-input';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import { cn } from '@renderer/utils/utils';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';-import { ServerPage, ServerTable, ServerTableEmpty } from './server-page';+import { ServerPage, ServerTableEmpty } from './server-page';import { ServerSectionTitlebar } from './server-section-titlebar';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';-const COLUMNS = [- { key: 'room', label: 'Room' },- { key: 'bridge', label: 'Bridged to' },- { key: 'agents', label: 'Agents', className: 'w-24' },- { key: 'actions', label: 'Actions', className: 'w-28 text-right' },-] as const;+/** Group key for a room with no messaging app behind it. */+const UNBRIDGED = '';function useServerId(): string {return useParams('serverRooms').params.serverId;@@ -42,6 +36,7 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {const serverId = useServerId();const server = switchServersStore.servers.find((s) => s.id === serverId);const showCreateRoomModal = useShowModal('createRoomModal');+ const [filter, setFilter] = useState('');useEffect(() => {void refreshSidebarRoomState(false);@@ -51,6 +46,10 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {const signedOut = switchRoomsStore.serversNotSignedIn.some((s) => s.id === serverId);const failed = switchRoomsStore.serversThatFailedToLoad.some((s) => s.id === serverId);+ const query = filter.trim().toLowerCase();+ const matching = query === '' ? rooms : rooms.filter((r) => r.name.toLowerCase().includes(query));+ const groups = groupByMessagingApp(matching);+return (<ServerPagetitle="Your Rooms"@@ -78,109 +77,237 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {No rooms here yet. Create one to give your agents somewhere to work.</ServerTableEmpty>) : (- <ServerTable columns={COLUMNS}>- {rooms.map((room) => (- <RoomRow key={room.id} room={room} serverId={serverId} />- ))}- </ServerTable>+ <div className="flex flex-col gap-6">+ <SearchInput+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ placeholder="Filter rooms by name…"+ aria-label="Filter rooms by name"+ />+ {/* The filter finding nothing is not the same as the server having no+ rooms, and the empty state above answers a question this user is not+ asking. */}+ {groups.length === 0 ? (+ <p className="py-2 text-sm text-foreground-muted">+ No room here matches “{filter.trim()}”.+ </p>+ ) : (+ groups.map((group) => (+ <MessagingAppGroup+ key={group.key}+ group={group}+ serverId={serverId}+ // Nothing folds while a filter is on. Typing a name and being+ // shown a "Show 3 more" where the match is hiding is the one+ // moment the fold would cost more than it saves.+ fold={query === ''}+ />+ ))+ )}+ </div>)}</ServerPage>);});-const RoomRow = observer(function RoomRow({- room,+type RoomGroup = {+ key: string;+ label: string;+ bridgeType: string | null;+ rooms: RemoteRoomSummary[];+};++/**+ * Rooms under the messaging app they are reachable in.+ *+ * Which app a room is in is the thing people scan this page for — it decides+ * where a conversation actually happens — so it is the heading rather than a+ * column. Grouped by the bridge's own display name, because a server can have+ * two of the same platform (two Slack workspaces) and calling both "Slack"+ * would merge two different places into one list. Rooms in no app sort last:+ * they are the exception, and leading with them buries the rest.+ */+function groupByMessagingApp(rooms: RemoteRoomSummary[]): RoomGroup[] {+ const groups = new Map<string, RoomGroup>();+ for (const room of rooms) {+ const key = room.bridgeType ? (room.bridgeDisplayName ?? room.bridgeType) : UNBRIDGED;+ const existing = groups.get(key);+ if (existing) {+ existing.rooms.push(room);+ continue;+ }+ groups.set(key, {+ key,+ label: room.bridgeType+ ? (room.bridgeDisplayName ?? bridgePlatformLabel(room.bridgeType))+ : 'No messaging app',+ bridgeType: room.bridgeType ?? null,+ rooms: [room],+ });+ }+ for (const group of groups.values()) {+ group.rooms.sort((a, b) => a.name.localeCompare(b.name));+ }+ return [...groups.values()].sort((a, b) => {+ if (a.key === UNBRIDGED) return 1;+ if (b.key === UNBRIDGED) return -1;+ return a.label.localeCompare(b.label);+ });+}++/**+ * How many rooms a messaging app shows before the rest are folded away.+ *+ * A single busy workspace can hold more rooms than the whole page otherwise+ * has, and left whole it pushes every other app off the screen — so the page+ * stops answering "where are my rooms" and answers only "what is in Slack".+ * Five is enough to see the group is real and to recognise the room you came+ * for; the count in the heading always says how many there are in total, so+ * nothing is hidden silently.+ */+const ROOMS_BEFORE_FOLD = 5;++const MessagingAppGroup = observer(function MessagingAppGroup({+ group,serverId,+ fold,}: {- room: RemoteRoomSummary;+ group: RoomGroup;serverId: string;+ /** Whether long groups are cut short. False while the list is filtered. */+ fold: boolean;}) {- const { navigate } = useNavigate();- const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');+ const [open, setOpen] = useState(true);+ const [visible, setVisible] = useState(ROOMS_BEFORE_FOLD);- const platform = bridgePlatformLabel(room.bridgeType);- const gatewayUrl = switchRoomsStore.gatewayRoomUrl(room.id);- const channelUrl = switchRoomsStore.roomChannelUrl(room.id);+ const shown = fold ? group.rooms.slice(0, visible) : group.rooms;+ const remaining = group.rooms.length - shown.length;+ // One page at a time rather than the whole tail at once: a workspace with+ // forty rooms in it would otherwise unfold into the same wall the fold+ // exists to prevent, and there would be no way back to a readable page+ // short of collapsing the app entirely.+ const nextBatch = Math.min(remaining, ROOMS_BEFORE_FOLD);return (- <tr className="text-sm">- <td className="px-3 py-2">- <button- type="button"- className="flex min-w-0 items-center gap-2 text-left hover:underline"- onClick={() => navigate('room', { roomId: room.id })}- >- {hasBridgeIcon(room.bridgeType) ? (- <BridgeIcon bridgeType={room.bridgeType} size={16} className="shrink-0" />- ) : (- <DoorOpen className="size-4 shrink-0 text-foreground-muted" />+ <section className="flex flex-col gap-2">+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((v) => !v)}+ className="-mx-2 flex w-fit cursor-pointer items-center gap-2 rounded-md px-2 py-1 transition-colors hover:bg-[var(--sel-soft)]"+ >+ <ChevronDown+ className={cn(+ 'size-3.5 shrink-0 text-foreground-muted transition-transform',+ !open && '-rotate-90')}- <span className="truncate">{room.name}</span>- </button>- </td>-- <td className="truncate px-3 py-2 text-foreground-muted">- {room.bridgeType ? (room.bridgeDisplayName ?? platform) : 'Not bridged'}- </td>-- <td className="px-3 py-2 text-foreground-muted">{room.agentCount}</td>-- <td className="px-3 py-2">- <div className="flex items-center justify-end">- <Tooltip>- <TooltipTrigger- render={- <Button- variant="ghost"- size="icon-xs"- aria-label={`Add agents to ${room.name}`}- onClick={() => showAddAgentsToRoomModal({ roomId: room.id })}- >- <Plus className="size-3" />- </Button>- }- />- <TooltipContent>Add agents</TooltipContent>- </Tooltip>-- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button variant="ghost" size="icon-xs" aria-label={`${room.name} actions`}>- <MoreVertical className="size-3" />- </Button>+ />+ {hasBridgeIcon(group.bridgeType) ? (+ <BridgeIcon bridgeType={group.bridgeType} size={16} />+ ) : (+ <MessageSquare className="size-4 text-foreground-muted" />+ )}+ <span className="truncate text-sm font-medium text-foreground">{group.label}</span>+ <span className="shrink-0 text-xs text-foreground-muted">+ {group.rooms.length} {group.rooms.length === 1 ? 'room' : 'rooms'}+ </span>+ </button>++ {open && (+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {shown.map((room) => (+ <RoomRow key={room.id} room={room} serverId={serverId} />+ ))}+ {fold && group.rooms.length > ROOMS_BEFORE_FOLD && (+ <button+ type="button"+ onClick={() =>+ setVisible((v) => (remaining > 0 ? v + ROOMS_BEFORE_FOLD : ROOMS_BEFORE_FOLD))}- />- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => showAddAgentsToRoomModal({ roomId: room.id })}>- <UserPlus className="size-4" />- Add agents…- </DropdownMenuItem>- {channelUrl && (- <DropdownMenuItem- onClick={() =>- void openExternalUrl(channelUrl, `Could not open the room in ${platform}`)- }- >- <ExternalLink className="size-4" />- Open in {platform}- </DropdownMenuItem>- )}- {gatewayUrl && (- <DropdownMenuItem- onClick={() =>- void rpc.switchServers.openGatewayPage({ serverId, url: gatewayUrl })- }- >- <ExternalLink className="size-4" />- Open in gateway- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>+ className="flex w-full cursor-pointer items-center gap-1.5 px-4 py-2.5 text-sm text-foreground-muted transition-colors hover:bg-[var(--fill)] hover:text-foreground"+ >+ <ChevronDown className={cn('size-4 shrink-0', remaining === 0 && 'rotate-180')} />+ {remaining > 0 ? `Show ${nextBatch} more` : 'Show fewer'}+ </button>+ )}</div>- </td>- </tr>+ )}+ </section>+ );+});++const RoomRow = observer(function RoomRow({+ room,+ serverId,+}: {+ room: RemoteRoomSummary;+ serverId: string;+}) {+ const members = switchRoomsStore.localMemberIds(room.id);+ const localAgents = agentsStore+ .agentsOnServer(serverId)+ .filter((agent) => agent.switchAgentId != null && members.includes(agent.switchAgentId));++ return (+ <button+ type="button"+ onClick={() => void openRoom(room.id)}+ // A solid hover rather than a translucent one, because the discs holding+ // the agent marks have to be filled with whatever the row is filled with+ // — an overlay would leave them reading as holes punched in the row.+ className="group/room flex w-full cursor-pointer items-center gap-3 bg-background px-4 py-3 text-left transition-colors hover:bg-[var(--fill)]"+ >+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-foreground">{roomTitle(room)}</span>+ {/* An empty room is a state, not a quantity. "0 agents" reads as a+ measurement of something that is working; a room nobody is in is a+ room that cannot answer, and it should say so in words. */}+ <span className="text-xs text-foreground-muted">+ {room.agentCount === 0+ ? 'No agent in this room yet'+ : `${room.agentCount} ${room.agentCount === 1 ? 'agent' : 'agents'}`}+ </span>+ </div>++ {/* The agents of this install that are in the room, by the mark of what+ they run. Deliberately not a second count: the number above is the+ server's, other people's agents included, and only these are ones this+ app could open. The tooltip says so rather than leaving two numbers on+ one row disagreeing in silence. */}+ {localAgents.length > 0 && (+ <Tooltip>+ <TooltipTrigger+ render={+ // Overlapped rather than spaced: this is one fact — who is in+ // the room — and a stack reads as that, where an evenly spaced+ // row reads as a set of separate controls to click.+ //+ // Each mark sits in a filled disc, so what a mark in front hides+ // is a clean circle rather than the silhouette of its own logo —+ // the marks are different shapes, and letting them interlock made+ // two agents read as one broken glyph.+ <span className="flex shrink-0 items-center -space-x-1.5">+ {localAgents.map((agent) => (+ <span+ key={agent.id}+ className="flex size-6 items-center justify-center rounded-full bg-background ring-1 ring-[var(--hair-soft)] transition-colors group-hover/room:bg-[var(--fill)]"+ >+ {agent.providerId ? (+ <AgentIcon id={agent.providerId} size={14} />+ ) : (+ <Bot className="size-3.5 text-foreground-muted" />+ )}+ </span>+ ))}+ </span>+ }+ />+ <TooltipContent>+ Your agents here: {localAgents.map((agent) => agent.name).join(', ')}+ </TooltipContent>+ </Tooltip>+ )}+ </button>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsxnew file mode 100644index 000000000..d15ad1384--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx@@ -0,0 +1,175 @@+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import { Button } from '@renderer/lib/ui/button';+import { Input } from '@renderer/lib/ui/input';+import { Label } from '@renderer/lib/ui/label';+import type { SwitchAuthConfig } from '@shared/core/switch-servers/switch-servers';+import { switchServersStore } from './switch-servers-store';++/**+ * Signing in to a Switch server, wherever that is asked for.+ *+ * Two surfaces ask: the wizard that connects to a server for the first time,+ * and the panel on the page of a server whose session has gone. They read the+ * same auth config and call the same two methods, so both live here — a login+ * method added to one and not the other would be invisible until someone tried+ * to use it.+ */+export type ServerSignIn = {+ /** Which methods the server offers, or null while that is still unknown. */+ config: SwitchAuthConfig | null;+ email: string;+ password: string;+ setEmail: (value: string) => void;+ setPassword: (value: string) => void;+ submitting: boolean;+ /** The server's own refusal, kept out of the global banner so it lands+ * beside the form that caused it. */+ error: string | null;+ canSubmitPassword: boolean;+ /** Both resolve true only when the session is live afterwards. */+ signInWithPassword: () => Promise<boolean>;+ signInWithOidc: () => Promise<boolean>;+};++export function useServerSignIn(serverId: string): ServerSignIn {+ const [email, setEmail] = useState('');+ const [password, setPassword] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ void switchServersStore.ensureAuthConfig(serverId);+ }, [serverId]);++ const attempt = async (run: () => Promise<boolean>): Promise<boolean> => {+ setSubmitting(true);+ setError(null);+ try {+ const ok = await run();+ if (!ok) setError(switchServersStore.error ?? 'Could not sign in.');+ return ok;+ } finally {+ setSubmitting(false);+ }+ };++ return {+ config: switchServersStore.authConfigFor(serverId),+ email,+ password,+ setEmail,+ setPassword,+ submitting,+ error,+ canSubmitPassword: email.length > 0 && password.length > 0,+ signInWithPassword: () =>+ attempt(() => switchServersStore.passwordLogin(serverId, email, password)),+ signInWithOidc: () => attempt(() => switchServersStore.oidcLogin(serverId)),+ };+}++/**+ * The fields themselves: email and password when the server takes them, the+ * provider button when it speaks OIDC, and both separated by an "or" when it+ * offers the two.+ *+ * `passwordSubmit` is where the caller puts its own Sign in button. The wizard+ * has a dialog footer to put it in and passes nothing; the server page has no+ * footer, so its button goes under the password field where it belongs.+ */+export const ServerSignInFields = observer(function ServerSignInFields({+ signIn,+ idPrefix,+ gatewayUrl,+ passwordSubmit,+ onSignedIn,+}: {+ signIn: ServerSignIn;+ /** Distinguishes the label/input pairs when two of these are ever on screen. */+ idPrefix: string;+ /** Shown under the password as the address being signed in to. Omit where+ * the surrounding page already says which server this is. */+ gatewayUrl?: string;+ passwordSubmit?: React.ReactNode;+ onSignedIn: () => void;+}) {+ const { config } = signIn;++ const submitPassword = async () => {+ if (!signIn.canSubmitPassword || signIn.submitting) return;+ if (await signIn.signInWithPassword()) onSignedIn();+ };++ const submitOidc = async () => {+ if (signIn.submitting) return;+ if (await signIn.signInWithOidc()) onSignedIn();+ };++ if (!config) {+ return <p className="text-sm text-foreground-muted">Checking sign-in options…</p>;+ }++ return (+ <div className="flex flex-col gap-4">+ {config.passwordLoginEnabled && (+ <div className="flex flex-col gap-3">+ <div className="space-y-1.5">+ <Label htmlFor={`${idPrefix}-email`}>Email</Label>+ <Input+ id={`${idPrefix}-email`}+ type="email"+ autoComplete="username"+ placeholder="[email protected]"+ value={signIn.email}+ onChange={(e) => signIn.setEmail(e.target.value)}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor={`${idPrefix}-password`}>Password</Label>+ <Input+ id={`${idPrefix}-password`}+ type="password"+ autoComplete="current-password"+ value={signIn.password}+ onChange={(e) => signIn.setPassword(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submitPassword();+ }}+ />+ {gatewayUrl && (+ <p className="truncate text-xs text-foreground-muted">Signing in to {gatewayUrl}</p>+ )}+ </div>+ {passwordSubmit}+ </div>+ )}++ {config.oidcEnabled && (+ <div className="flex flex-col gap-3">+ {config.passwordLoginEnabled && (+ <div className="flex items-center gap-3">+ <span className="h-px flex-1 bg-border" />+ <span className="text-xs text-foreground-muted">or</span>+ <span className="h-px flex-1 bg-border" />+ </div>+ )}+ <Button+ variant="outline"+ className="w-full"+ disabled={signIn.submitting}+ onClick={() => void submitOidc()}+ >+ Continue with {config.oidcProviderLabel ?? 'SSO'}+ </Button>+ </div>+ )}++ {!config.passwordLoginEnabled && !config.oidcEnabled && (+ <p className="text-destructive text-sm">This server has no enabled sign-in methods.</p>+ )}++ {signIn.error && <p className="text-destructive text-xs">{signIn.error}</p>}+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsxindex 340fbee4e..3a68f74bc 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx@@ -1,4 +1,5 @@import type { ReactNode } from 'react';+import { Button } from '@renderer/lib/ui/button';/** The lifecycle states a managed stack reports, local or remote. */export type StackPhase = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'unreachable';@@ -22,48 +23,94 @@ const PHASE_DOT: Record<StackPhase, string> = {};/**- * The managed stack's own section of a server page — a titled card holding a- * status line and whatever the stack currently has to say for itself.+ * The managed stack's own section of a server page — a heading, a one-line+ * status, and whatever the stack currently has to say for itself.** Shared by the local and remote controls so the two read as the same thing in* two places rather than as two features that happen to look alike.*/-export function StackSection({ title, children }: { title: string; children: ReactNode }) {- return (- <section className="space-y-2">- <h3 className="text-sm font-medium text-foreground">{title}</h3>- <div className="bg-card divide-y divide-border rounded-lg border border-border">- {children}- </div>- </section>- );+export function StackSection({ children }: { children: ReactNode }) {+ return <section className="space-y-3">{children}</section>;}/**- * Where the stack is and what can be done about it, on one line.+ * Where the stack is and what can be done about it.*- * `detail` is deliberately terse and monospaced: it is the machine's answer,- * not a sentence, and it sits beside the state rather than explaining it.+ * `summary` is a sentence rather than the machine's own terse answer — the+ * heading above it already says which stack this is, so the line's job is to+ * say whether it is up and where. The deployed version is carried on its+ * `title` instead of on screen: it is worth having, but only when something has+ * gone wrong enough to look for it, and the drift notice states both versions+ * whenever they actually disagree.*/export function StackStatusRow({+ title,phase,- detail,+ summary,+ versionDetail,+ activity,actions,}: {+ title: string;phase: StackPhase;- detail: string;+ summary: string;+ versionDetail: string | null;+ /** The "Recent activity" disclosure, when there is any output to disclose. */+ activity?: ReactNode;actions: ReactNode;}) {return (- <div className="flex items-center justify-between gap-3 p-3">- <div className="flex min-w-0 items-center gap-2.5">- <span className="flex shrink-0 items-center gap-1.5 rounded-full bg-background-tertiary px-2 py-0.5 text-xs text-foreground-muted">- <span aria-hidden className={`size-1.5 rounded-full ${PHASE_DOT[phase]}`} />- {PHASE_LABEL[phase]}- </span>- <span className="truncate font-mono text-xs text-foreground-muted">{detail}</span>+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h3 className="text-sm font-medium text-foreground">{title}</h3>+ <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">+ <span aria-hidden className={`size-1.5 shrink-0 rounded-full ${PHASE_DOT[phase]}`} />+ <span className="truncate" title={versionDetail ?? undefined}>+ {summary}+ </span>+ {activity && (+ <>+ <span aria-hidden>·</span>+ {activity}+ </>+ )}+ </div></div>- <div className="flex shrink-0 items-center gap-2">{actions}</div>+ <div className="flex shrink-0 items-center gap-3">{actions}</div></div>);}++/** A stack lifecycle action. Bordered rather than bare text: starting, stopping+ * and restarting a server are consequential enough to look pressable, and a+ * red word with no edge to it reads as a status rather than a control. */+export function StackAction({+ label,+ danger = false,+ disabled = false,+ onClick,+}: {+ label: string;+ danger?: boolean;+ disabled?: boolean;+ onClick: () => void;+}) {+ return (+ <Button+ variant="outline"+ size="sm"+ disabled={disabled}+ onClick={onClick}+ className={+ danger ? 'border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500' : undefined+ }+ >+ {label}+ </Button>+ );+}++/** The phase's own words, for the states that are not simply "running". */+export function phaseLabel(phase: StackPhase): string {+ return PHASE_LABEL[phase];+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex 2691a60a2..5ea29536a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';const listRemoteRooms = vi.hoisted(() => vi.fn());@@ -378,3 +378,92 @@ describe('agent memberships', () => {expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');});});++describe('rooms offered to a picker', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ serversStore.servers = [{ id: 'srv-a' }];+ serversStore.activeServerId = 'srv-a';+ });++ it('offers every room the server returned, not only the ones this user made', async () => {+ // The sidebar deliberately lists a narrower set — see `listedRoomsOnServer`.+ // A picker is a list you went looking for, so it must not hide a room you+ // are entitled to join.+ listRemoteRooms.mockResolvedValue([+ room('mine', 'user-of-srv-a'),+ room('someone-elses', 'user-of-someone-else'),+ room('ownerless', null),+ ]);++ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual([+ 'mine',+ 'someone-elses',+ 'ownerless',+ ]);+ expect(store.listedRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['mine']);+ });++ it('leaves out archived rooms, which are not joinable', async () => {+ listRemoteRooms.mockResolvedValue([+ room('live', 'user-of-someone-else'),+ room('gone', 'user-of-someone-else', { archived: true }),+ ]);++ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['live']);+ });++ it('offers nothing for a server whose rooms were never read', () => {+ expect(new SwitchRoomsStore().readableRoomsOnServer('srv-a')).toEqual([]);+ });+});++describe('who may delete a room', () => {+ const statusWithRole = (role: string | undefined) => (serverId: string) => ({+ user: { id: `user-of-${serverId}`, role },+ });+ const originalStatusFor = serversStore.statusFor;++ beforeEach(() => {+ vi.clearAllMocks();+ serversStore.servers = [{ id: 'srv-a' }];+ serversStore.statusFor = statusWithRole(undefined);+ });++ afterEach(() => {+ serversStore.statusFor = originalStatusFor;+ });++ it('lets the owner delete their own room', () => {+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(true);+ });++ it('refuses someone else’s room', () => {+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(false);+ });++ it('lets an admin delete a room they do not own, matching the gateway', () => {+ serversStore.statusFor = statusWithRole('admin');+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(true);+ });++ it('refuses an ownerless room to a non-admin, rather than treating it as unclaimed', () => {+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('srv-a', room('r', null))).toBe(false);+ });++ it('refuses while signed out, when there is no one to compare against', () => {+ serversStore.statusFor = () => ({ user: null }) as never;+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 1594f4baa..ec61244d2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -143,6 +143,19 @@ export class SwitchRoomsStore {);}+ /**+ * Every active room the signed-in user can see on a server — what the gateway+ * returned, which is already scoped to rooms they may read.+ *+ * Wider than {@link listedRoomsOnServer} on purpose. A standing list has to+ * earn its place on screen, so the sidebar shows only rooms with a claim on+ * you; a picker is a list you went looking for, and one that hides rooms you+ * have every right to join cannot be searched into showing them.+ */+ readableRoomsOnServer(serverId: string): RemoteRoomSummary[] {+ return this.allRoomsByServer.get(serverId) ?? [];+ }+/*** The same listed rooms as {@link listedRoomsInActiveScope}, but across every* server rather than the active one.@@ -187,6 +200,33 @@ export class SwitchRoomsStore {return this.allRoomsByServer.get(serverId)?.find((room) => room.id === roomId) ?? null;}+ /**+ * Whether the signed-in user may delete a room: they own it, or they are an+ * admin on its server.+ *+ * This mirrors the gateway's own rule so the action is not offered where it+ * would only be refused. It is not the check that protects anything — the+ * server's is — and where ownership is unknown the answer is no, since+ * showing a delete that fails is worse than not showing one.+ */+ canDeleteRoom(serverId: string, room: RemoteRoomSummary): boolean {+ const user = switchServersStore.statusFor(serverId)?.user ?? null;+ if (!user) return false;+ return room.ownerId === user.id || user.role === 'admin';+ }++ /**+ * Delete a room on its server, then re-read what is left.+ *+ * Throws on refusal rather than reporting a boolean: the caller is a+ * confirmation dialog, and a delete that quietly did nothing would leave the+ * room on screen with no account of why.+ */+ async deleteRoom(serverId: string, roomId: string): Promise<void> {+ await rpc.switchServers.deleteRoom({ serverId, roomId });+ await this.refreshRoomState();+ }+/*** The servers whose state is on screen: the active one, or all of them when* none is active (the same scope rule the room and location lists follow).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 ce6ae18a6..17f6adac0 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@@ -7,6 +7,7 @@ import {PlugZap,RefreshCw,Trash2,+ Unplug,} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useState } from 'react';@@ -27,8 +28,6 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';-import { Input } from '@renderer/lib/ui/input';-import { Label } from '@renderer/lib/ui/label';import { Spinner } from '@renderer/lib/ui/spinner';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';@@ -40,6 +39,7 @@ import { serverIcon } from './server-icon';import { ServerAvatar, serverDrift, serverPlacementLabel } from './server-presentation';import { ServerResetSection } from './server-reset-section';import { ServerSectionTitlebar } from './server-section-titlebar';+import { ServerSignInFields, useServerSignIn } from './server-sign-in';import { ServerStatTiles } from './server-stat-tiles';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';@@ -241,14 +241,17 @@ const ServerMainPanel = observer(function ServerMainPanel() {</DropdownMenuItem>)}<DropdownMenuSeparator />+ {/* Only a server Switch Console runs is one it can delete; for+ anyone else's, all we can do is let go of it. Both stay red:+ either way every agent pointed at this server loses it. */}<DropdownMenuItemvariant="destructive"onClick={() =>showDeleteServerModal({ serverId, onSuccess: () => navigate('home') })}>- <Trash2 className="size-4" />- Delete server…+ {server.managed ? <Trash2 className="size-4" /> : <Unplug className="size-4" />}+ {server.managed ? 'Delete server…' : 'Disconnect from server…'}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>@@ -301,7 +304,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {))}{detailsVisible && !unreachable && (- <div className={`${card} flex items-center justify-between gap-3`}>+ <div className="flex items-center justify-between gap-3"><div className="min-w-0 space-y-0.5"><h3 className="text-sm font-medium text-foreground">Full admin interface</h3><p className="text-xs text-foreground-muted">@@ -447,94 +450,26 @@ function StatusDot({ connected }: { connected: boolean }) {}const LoginPanel = observer(function LoginPanel({ serverId }: { serverId: string }) {- const store = switchServersStore;- const config = store.authConfigFor(serverId);- const [email, setEmail] = useState('');- const [password, setPassword] = useState('');- const [submitting, setSubmitting] = useState(false);-- const doPasswordLogin = async () => {- setSubmitting(true);- try {- await store.passwordLogin(serverId, email, password);- } finally {- setSubmitting(false);- }- };-- const doOidcLogin = async () => {- setSubmitting(true);- try {- await store.oidcLogin(serverId);- } finally {- setSubmitting(false);- }- };-- if (!config) {- return <div className={card}>Checking sign-in options…</div>;- }+ const signIn = useServerSignIn(serverId);return (<div className={`${card} space-y-4`}><p className="text-sm text-foreground-muted">Sign in to connect to this server.</p>-- {config.passwordLoginEnabled && (- <div className="space-y-3">- <div className="space-y-1.5">- <Label htmlFor="switch-login-email">Email</Label>- <Input- id="switch-login-email"- type="email"- autoComplete="username"- value={email}- onChange={(e) => setEmail(e.target.value)}- />- </div>- <div className="space-y-1.5">- <Label htmlFor="switch-login-password">Password</Label>- <Input- id="switch-login-password"- type="password"- autoComplete="current-password"- value={password}- onChange={(e) => setPassword(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') void doPasswordLogin();- }}- />- </div>+ <ServerSignInFields+ signIn={signIn}+ idPrefix="switch-login"+ onSignedIn={() => {}}+ passwordSubmit={<Buttonsize="sm"- disabled={submitting || !email || !password}- onClick={() => void doPasswordLogin()}+ className="self-start"+ disabled={signIn.submitting || !signIn.canSubmitPassword}+ onClick={() => void signIn.signInWithPassword()}>- Sign in+ {signIn.submitting ? 'Signing in…' : 'Sign in'}</Button>- </div>- )}-- {config.oidcEnabled && (- <div className="space-y-2">- {config.passwordLoginEnabled && (- <div className="text-xs tracking-wide text-foreground-passive uppercase">or</div>- )}- <Button- variant="outline"- size="sm"- disabled={submitting}- onClick={() => void doOidcLogin()}- >- Sign in with {config.oidcProviderLabel ?? 'SSO'}- </Button>- </div>- )}-- {!config.passwordLoginEnabled && !config.oidcEnabled && (- <Alert variant="destructive">- <AlertDescription>This server has no enabled login methods.</AlertDescription>- </Alert>- )}+ }+ /></div>);});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 87652481c..aaa72a706 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,4 +1,4 @@-import { Check, ChevronsUpDown, Plus } from 'lucide-react';+import { ChevronsUpDown, Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import { useNavigate } from '@renderer/lib/layout/navigation-provider';@@ -69,7 +69,7 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {<buttontype="button"onClick={() => showAddServerModal({})}- className="flex w-full items-center gap-2 rounded-lg border border-border px-2.5 py-2 text-sm text-foreground-tertiary hover:bg-background-tertiary-1"+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-foreground-tertiary hover:bg-[var(--sel-soft)]"><Plus className="size-4 shrink-0 text-foreground-muted" />Add a server@@ -90,7 +90,7 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {<buttontype="button"aria-label="Switch server"- className="flex w-full items-center gap-2 rounded-lg border border-border px-2 py-1.5 text-left hover:bg-background-tertiary-1"+ className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]"><ServerAvatar server={active} size="md" /><span className="min-w-0 flex-1">@@ -150,7 +150,7 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {<buttontype="button"onClick={() => showAddServerModal({ mode: 'local' })}- className="flex w-full items-center gap-2 rounded-lg border border-border px-2.5 py-2 text-sm text-foreground-tertiary hover:bg-background-tertiary-1"+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-foreground-tertiary hover:bg-[var(--sel-soft)]"><span className="min-w-0 flex-1 truncate text-left">{failed ? 'Local server (setup failed)' : 'Local Switch server'}@@ -174,17 +174,26 @@ const ServerMenuItem = observer(function ServerMenuItem({ server }: { server: Swreturn (<DropdownMenuItem+ // The active server 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.+ aria-current={isActive ? 'true' : undefined}+ className={cn(isActive && 'bg-[var(--sel)]')}onClick={() => {void store.setActive(server.id);navigate('server', { serverId: server.id });}}>- <ServerAvatar server={server} size="sm" />+ <ServerAvatar server={server} size="md" /><span className="min-w-0 flex-1">- <span className="block truncate text-sm text-foreground">{server.name}</span>+ <span className="block truncate text-sm font-medium text-foreground">{server.name}</span><span className="flex min-w-0 items-center gap-1.5 text-xs 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. */}+ <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}@@ -193,8 +202,6 @@ const ServerMenuItem = observer(function ServerMenuItem({ server }: { server: Sw</span></span>{drift && <ServerDriftIndicator drift={drift} />}- <ServerStatusDot server={server} />- {isActive && <Check className="size-3.5 shrink-0 text-foreground" />}</DropdownMenuItem>);});diff --git a/console/apps/switch-console-desktop/src/renderer/index.css b/console/apps/switch-console-desktop/src/renderer/index.cssindex 000544b31..d147d710a 100644--- a/console/apps/switch-console-desktop/src/renderer/index.css+++ b/console/apps/switch-console-desktop/src/renderer/index.css@@ -108,6 +108,10 @@--radius-lg: var(--radius);--radius-md: calc(var(--radius) - 2px);--radius-sm: calc(var(--radius) - 4px);+ /* Dialogs, popovers and bordered cards sit one step above the 8px of+ buttons and rows. Without this `rounded-xl` falls back to Tailwind's+ 12px, which reads as the panel's radius rather than an elevated one. */+ --radius-xl: var(--radius-elevated);--animate-accordion-down: accordion-down 0.2s ease-out;--animate-accordion-up: accordion-up 0.2s ease-out;@@ -393,6 +397,48 @@--ring: hsl(0 0% 3.9%);--radius: 0.5rem;+ /* The window is one material surface. The sidebar has no fill of its own —+ it is this showing through — and the content panel is an inset card of+ `--surface` on top of it, so the gap and the radius separate the two+ rather than a divider. `--material` is the vibrancy colour flattened:+ until the window itself is translucent there is nothing behind it to+ blur, and the translucent form composites against whatever desktop+ happens to be there. */+ --material: #f7f6f2;+ --material-vibrant: rgb(247 246 242 / 0.78);+ --surface: #ffffff;+ --surface-2: #f9f9f9;++ --hair: rgb(0 0 0 / 0.14);+ --hair-strong: rgb(0 0 0 / 0.18);+ --hair-soft: rgb(0 0 0 / 0.06);++ /* Row selection and hover. Distinct from `--selection`, which is the+ browser's text-selection colour and unrelated. Both are translucent so+ they tint the material rather than punching an opaque patch through the+ vibrancy. */+ --sel: rgb(36 58 49 / 0.12);+ --sel-soft: rgb(36 58 49 / 0.1);++ --fill: #f0f0f0;+ --fill-2: #e8e8e8;+ --fill-3: #d4d4d4;+ --btn-1: #ffffff;+ --accent-solid: #243a31;++ /* The existing `--foreground-passive` is the design's *faint* step, which+ is too weak for a label that has to be readable without hovering. This+ is the design's passive step, one stop darker. */+ --fg-passive: #8d8d8d;++ /* The segmented control's track. Its own token rather than `--hair-soft`,+ which in dark lands within a couple of levels of the raised segment and+ leaves the active option indistinguishable from the inactive one. */+ --segment-track: rgb(0 0 0 / 0.06);++ --panel-radius: 12px;+ --radius-elevated: 11px;+--selection: var(--blue-6);--selection-foreground: var(--blue-12);@@ -695,6 +741,35 @@--ring: hsl(0 0% 3.9%);--radius: 0.5rem;+ /* Inverted against light: the panel is darker than the material it sits on,+ not lighter. */+ --material: #1a1a1a;+ --material-vibrant: rgb(24 24 24 / 0.72);+ --surface: #111111;+ --surface-2: #191919;++ --hair: rgb(255 255 255 / 0.12);+ --hair-strong: rgb(255 255 255 / 0.18);+ --hair-soft: rgb(255 255 255 / 0.07);++ --sel: rgb(255 255 255 / 0.11);+ --sel-soft: rgb(255 255 255 / 0.08);++ --fill: #222222;+ --fill-2: #2a2a2a;+ --fill-3: #3a3a3a;+ --btn-1: #2c2c2c;+ --accent-solid: #33513f;++ --fg-passive: #8d8d8d;++ /* Darker than the material rather than lighter, so the raised segment+ reads as sitting on top of the track instead of merging into it. */+ --segment-track: rgb(0 0 0 / 0.32);++ --panel-radius: 12px;+ --radius-elevated: 11px;+--selection: var(--blue-9);--selection-foreground: var(--blue-12);@@ -796,7 +871,13 @@overflow: hidden;}body {- @apply bg-background text-foreground;+ @apply text-foreground;+ background: var(--material);+ }+ /* Set by the pre-paint script in index.html where the compositor is actually+ blurring behind the window. */+ html.has-vibrancy body {+ background: var(--material-vibrant);}/* Tailwind's reset gives buttons the arrow cursor, on the reasoning that adiff --git a/console/apps/switch-console-desktop/src/renderer/index.html b/console/apps/switch-console-desktop/src/renderer/index.htmlindex ff21d11d1..461d61c55 100644--- a/console/apps/switch-console-desktop/src/renderer/index.html+++ b/console/apps/switch-console-desktop/src/renderer/index.html@@ -17,6 +17,16 @@: 'emlight';document.documentElement.classList.add(effective);} catch (_) {}+ try {+ // Paired with the `vibrancy` branch in main/app/window.ts: only+ // macOS gets a translucent window, so only there may the renderer+ // leave the material see-through. Anywhere else the same colour has+ // to be opaque, or the window shows the desktop through an effect+ // the compositor never applied.+ if (navigator.userAgent.indexOf('Macintosh') !== -1) {+ document.documentElement.classList.add('has-vibrancy');+ }+ } catch (_) {}})();</script></head>diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-mark.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-mark.tsxnew file mode 100644index 000000000..83af7f415--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-mark.tsx@@ -0,0 +1,29 @@+import { Bot } from 'lucide-react';+import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';+import { AgentIcon } from './agent-icon';++/**+ * The mark of what an agent runs, with a fallback for an agent whose provider+ * this install cannot resolve.+ *+ * Every picker that lists agents wants the same pair — this mark and the name+ * beside it — and each had grown its own copy. One copy means a provider+ * without an icon looks the same everywhere rather than only where someone+ * remembered the fallback.+ */+export function AgentMark({+ providerId,+ size = 16,+}: {+ /** Null when the agent is known to Switch but not to this install. */+ providerId: string | null;+ size?: number;+}) {+ if (!providerId) return <Bot className="size-4 shrink-0 text-foreground-muted" />;+ return <AgentIcon id={providerId} size={size} />;+}++/** What to call an agent's provider in a list — "Claude Code", "Codex". */+export function agentProviderLabel(providerId: string | null | undefined): string {+ return (providerId ? providerDisplayName(providerId) : null) ?? 'Agent';+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsxindex e1080f2e9..f7488b5ac 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/Titlebar.tsx@@ -8,21 +8,24 @@ import { BoundShortcut } from '@renderer/lib/ui/shortcut';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';-const platform = detectPlatform();-const isMac = platform === 'mac';-const isLinux = platform === 'linux';+const isLinux = detectPlatform() === 'linux';export function Titlebar({ leftSlot, rightSlot }: { leftSlot?: ReactNode; rightSlot?: ReactNode }) {const { setCollapsed, isLeftOpen } = useWorkspaceLayoutContext();return (<headerclassName={cn(- 'flex h-10 shrink-0 items-center bg-background-secondary border-b border-border [-webkit-app-region:drag] dark:bg-background',- // macOS traffic lights sit at the top-left, so clear room only there.- !isLeftOpen && isMac && 'pl-18',+ // No fill and no bottom rule: the header is part of the panel's own+ // surface, so a bar across the top of it would read as a second+ // divider next to the gutter that already separates panel from+ // sidebar.+ 'flex h-11 shrink-0 items-center [-webkit-app-region:drag]',+ // No traffic-light padding here: with the sidebar collapsed the panel+ // itself now starts below them (see `WorkspaceLayout`), which also+ // covers the views that render no titlebar at all.// Linux draws its own controls flush to the right corner (no native// frame); everywhere else keep the normal right padding.- isLinux ? 'pr-0' : 'pr-2'+ isLinux ? 'pr-0' : 'pr-[18px]')}><div className="pointer-events-auto flex min-w-0 flex-1 items-center gap-1">diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.test.tsnew file mode 100644index 000000000..724b63b97--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.test.ts@@ -0,0 +1,64 @@+import { JSDOM } from 'jsdom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const back = vi.hoisted(() => vi.fn());+const forward = vi.hoisted(() => vi.fn());+const eventsOn = vi.hoisted(() => vi.fn(() => () => {}));++vi.mock('@renderer/lib/components/nav-buttons', () => ({ applyHistoryEntry: vi.fn() }));+vi.mock('@renderer/lib/ipc', () => ({ events: { on: eventsOn } }));+vi.mock('@renderer/lib/stores/app-state', () => ({ appState: { history: { back, forward } } }));++const { wireMouseNavigation } = await import('./mouse-navigation');++let dom: JSDOM;+let teardown: () => void;++function press(button: number): MouseEvent {+ const event = new dom.window.MouseEvent('mouseup', { button, bubbles: true, cancelable: true });+ dom.window.document.body.dispatchEvent(event);+ return event as unknown as MouseEvent;+}++beforeEach(() => {+ dom = new JSDOM('<!doctype html><html><body></body></html>');+ vi.stubGlobal('window', dom.window);+ vi.clearAllMocks();+ teardown = wireMouseNavigation();+});++afterEach(() => {+ teardown();+ vi.unstubAllGlobals();+});++describe('mouse back and forward buttons', () => {+ it('sends button 3 back and button 4 forward, not the other way round', () => {+ press(3);+ expect(back).toHaveBeenCalledTimes(1);+ expect(forward).not.toHaveBeenCalled();++ press(4);+ expect(forward).toHaveBeenCalledTimes(1);+ expect(back).toHaveBeenCalledTimes(1);+ });++ it('leaves the ordinary buttons alone', () => {+ for (const button of [0, 1, 2]) press(button);+ expect(back).not.toHaveBeenCalled();+ expect(forward).not.toHaveBeenCalled();+ });++ it('claims the event so nothing underneath also acts on it', () => {+ // A side button pressed over a row must navigate without also opening that+ // row — the press is consumed, not merely observed.+ expect(press(3).defaultPrevented).toBe(true);+ expect(press(0).defaultPrevented).toBe(false);+ });++ it('stops listening once torn down', () => {+ teardown();+ press(3);+ expect(back).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.tsnew file mode 100644index 000000000..1477fc94b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/mouse-navigation.ts@@ -0,0 +1,69 @@+import { applyHistoryEntry } from '@renderer/lib/components/nav-buttons';+import { events } from '@renderer/lib/ipc';+import { appState } from '@renderer/lib/stores/app-state';+import { appCommandNavigateChannel } from '@shared/events/appEvents';++/**+ * `MouseEvent.button` for the two side buttons most mice carry. Chromium+ * reports them like any other button; it is only in a browser that they also+ * move through history on their own.+ */+const BACK_BUTTON = 3;+const FORWARD_BUTTON = 4;++function goBack(): void {+ appState.history.back(applyHistoryEntry);+}++function goForward(): void {+ appState.history.forward(applyHistoryEntry);+}++/**+ * Make the mouse's back and forward buttons drive the app's own history.+ *+ * Switch Console is one page that never changes URL, so there is no browser+ * history behind these buttons and Chromium's default handling has nothing to+ * do — the buttons appear broken rather than absent. The app keeps its own+ * navigation stack (the same one the arrows in the titlebar and the keyboard+ * shortcuts use), so this points them at that.+ *+ * Two paths, because the platforms deliver these buttons differently: macOS and+ * Linux hand them to the page as ordinary mouse events, while Windows routes+ * them past the page as an `app-command` the main process has to forward.+ *+ * Returns a teardown for symmetry with the app's other wiring; nothing calls it+ * today because this lives as long as the window does.+ */+export function wireMouseNavigation(): () => void {+ const onMouseUp = (event: MouseEvent) => {+ if (event.button !== BACK_BUTTON && event.button !== FORWARD_BUTTON) return;+ // A side button means navigate and nothing else. Left unclaimed it can+ // still reach a control underneath as an `auxclick`.+ event.preventDefault();+ if (event.button === BACK_BUTTON) goBack();+ else goForward();+ };++ // Claim the press too: some elements act on `mousedown`, and swallowing only+ // the release would let them fire while the navigation happens under them.+ const swallow = (event: MouseEvent) => {+ if (event.button === BACK_BUTTON || event.button === FORWARD_BUTTON) event.preventDefault();+ };++ window.addEventListener('mouseup', onMouseUp);+ window.addEventListener('mousedown', swallow);+ window.addEventListener('auxclick', swallow);++ const offAppCommand = events.on(appCommandNavigateChannel, ({ direction }) => {+ if (direction === 'back') goBack();+ else goForward();+ });++ return () => {+ window.removeEventListener('mouseup', onMouseUp);+ window.removeEventListener('mousedown', swallow);+ window.removeEventListener('auxclick', swallow);+ offAppCommand();+ };+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsxindex 9d15af018..a7b00dbf4 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx@@ -1,14 +1,17 @@+import { detectPlatform } from '@tanstack/hotkeys';import { type ReactNode } from 'react';import { useDefaultLayout } from 'react-resizable-panels';import { useWorkspaceLayoutContext } from '@renderer/lib/layout/layout-provider';import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@renderer/lib/ui/resizable';import { cn } from '@renderer/utils/utils';-const LEFT_PANEL_DEFAULT_SIZE = '20%';+const LEFT_PANEL_DEFAULT_SIZE = '274px';const LEFT_SIDEBAR_MIN_SIZE = '200px';const LEFT_SIDEBAR_MAX_SIZE = '30%';const MAIN_PANEL_MIN_SIZE = '30%';+const isMac = detectPlatform() === 'mac';+interface WorkspaceLayoutProps {leftSidebar: ReactNode;mainContent: ReactNode;@@ -61,15 +64,38 @@ export function WorkspaceLayout({}}onPointerUp={() => handleDragging('left', false)}onPointerCancel={() => handleDragging('left', false)}+ // The gutter and the panel's radius already separate sidebar from+ // content, so the handle carries no line of its own — it only shows+ // one while the pointer is on it, to say the edge can be dragged.className={cn(- 'items-center justify-center transition-colors hover:bg-border/80',+ 'items-center justify-center bg-transparent transition-colors hover:bg-[var(--hair)]',isLeftOpen ? 'flex' : 'hidden')}/><ResizablePanel id="workspace-main" minSize={MAIN_PANEL_MIN_SIZE}>- <div className="relative h-full w-full">- {mainContent}- {persistentLayer}+ {/* The panel is an inset card on the window's material rather than a+ pane butted against the sidebar: the gutter and the radius separate+ the two, in place of a divider. Flush to the sidebar on the left,+ 8px away on the other three sides. The hairline is a spread shadow+ rather than a border so it lands on a half pixel and does not take+ a whole one out of the panel.++ With the sidebar collapsed there is no sidebar to be flush against,+ so the card insets on the left too — and on macOS it starts below+ the traffic lights instead of behind them. The sidebar's empty top+ strip was what kept them clear; without it the card was drawing its+ own corner under the close button. */}+ <div+ className={cn(+ 'relative h-full w-full overflow-hidden pr-2 pb-2',+ isLeftOpen ? 'pt-2' : 'pl-2',+ !isLeftOpen && (isMac ? 'pt-9' : 'pt-2')+ )}+ >+ <div className="relative h-full w-full overflow-hidden rounded-[var(--panel-radius)] shadow-[0_0_0_0.5px_var(--hair)]">+ {mainContent}+ {persistentLayer}+ </div></div></ResizablePanel></ResizablePanelGroup>diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/dialog.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/dialog.tsxindex fe3be134d..ebc21da59 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/dialog.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/dialog.tsx@@ -131,10 +131,7 @@ function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {return (<DialogPrimitive.Titledata-slot="dialog-title"- className={cn(- 'text-xs font-mono tracking-wider uppercase text-foreground-tertiary-passive',- className- )}+ className={cn('text-base font-semibold tracking-tight text-foreground', className)}{...props}/>);diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/disclosure-row.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/disclosure-row.tsxnew file mode 100644index 000000000..ea8c7f1be--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/disclosure-row.tsx@@ -0,0 +1,51 @@+import { ChevronRight } from 'lucide-react';+import { cn } from '@renderer/utils/utils';++/**+ * The class a collapsed section's header row wears. Exported for the one header+ * that cannot use `DisclosureRow` — the sidecar log's open state carries a+ * Refresh button beside its title, so it is a row containing two controls+ * rather than one control shaped like a row.+ */+export const disclosureRowClass =+ '-mx-2 flex w-[calc(100%+1rem)] cursor-pointer items-center gap-1.5 rounded-md px-2 py-1.5 text-sm text-foreground-muted transition-colors hover:bg-[var(--sel-soft)]';++/**+ * The header of a collapsible section: a chevron, what it is, and what it is+ * holding while shut.+ *+ * The whole row highlights on hover rather than the chevron alone. A pointer+ * change is the only feedback a bare row gives, and it arrives after you have+ * already guessed the thing is clickable.+ */+export function DisclosureRow({+ open,+ title,+ summary,+ meta,+ className,+ onToggle,+}: {+ open: boolean;+ title: string;+ /** What the section holds, beside the title. */+ summary?: React.ReactNode;+ /** How much it holds, pushed to the right edge. */+ meta?: React.ReactNode;+ className?: string;+ onToggle: () => void;+}) {+ return (+ <button+ type="button"+ aria-expanded={open}+ onClick={onToggle}+ className={cn(disclosureRowClass, className)}+ >+ <ChevronRight className={cn('size-4 shrink-0 transition-transform', open && 'rotate-90')} />+ <span className="shrink-0 font-medium text-foreground">{title}</span>+ {summary !== undefined && <span className="min-w-0 truncate">{summary}</span>}+ {meta !== undefined && <span className="ml-auto shrink-0 pl-2">{meta}</span>}+ </button>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/label.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/label.tsxindex e5abcaa67..02d3f23c4 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/label.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/label.tsx@@ -40,7 +40,10 @@ export function SectionLabel({ className, ...props }: React.ComponentProps<'labe<labeldata-slot="label"className={cn(- 'cursor-default text-xs font-medium text-foreground-passive select-none',+ // `--fg-passive`, not the `foreground-passive` token: that one is the+ // design's faint step and leaves a section heading too weak to read+ // without hovering it.+ 'cursor-default text-xs font-medium text-[var(--fg-passive)] select-none',className)}{...props}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsxnew file mode 100644index 000000000..d49a6fb73--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx@@ -0,0 +1,59 @@+import { ToggleGroup, ToggleGroupItem } from '@renderer/lib/ui/toggle-group';+import { cn } from '@renderer/utils/utils';++/**+ * A small segmented control: every choice visible at once, the active one+ * raised out of a recessed track.+ *+ * The raised option has to read as sitting *in* the track, not as a button+ * dropped on top of a box: concentric corners (inner radius = outer radius less+ * the padding) and only a hairline of track showing around it.+ *+ * Re-selecting the active option is a no-op rather than a deselect — with only+ * these choices on offer, "none of them" is not a state the caller can draw.+ */+export function SegmentedControl<T extends string>({+ value,+ onChange,+ options,+ ariaLabel,+ className,+}: {+ value: T;+ onChange: (value: T) => void;+ options: readonly { value: T; label: string }[];+ ariaLabel: string;+ className?: string;+}) {+ return (+ <ToggleGroup+ size="sm"+ spacing={1}+ multiple={false}+ value={[value]}+ onValueChange={([next]) => {+ const option = options.find((o) => o.value === next);+ if (option) onChange(option.value);+ }}+ aria-label={ariaLabel}+ className={cn(+ 'h-auto gap-0 rounded-[9px] border-transparent bg-[var(--segment-track)] p-[2px]',+ className+ )}+ >+ {options.map((option) => (+ <ToggleGroupItem+ key={option.value}+ value={option.value}+ aria-label={option.label}+ // The hover fill is an overlay, and only on the option that is not+ // already chosen: the default `background-1` is the dialog and panel+ // surface itself in dark mode, so it draws nothing.+ className="h-auto cursor-pointer rounded-[7px] px-[9px] py-[2px] text-[11.5px] font-medium text-foreground-muted transition-colors hover:bg-transparent hover:text-foreground aria-pressed:bg-[var(--btn-1)] aria-pressed:text-foreground aria-pressed:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)] aria-[pressed=false]:hover:bg-[var(--sel-soft)] data-pressed:bg-[var(--btn-1)] data-[state=on]:bg-[var(--btn-1)] data-[state=on]:text-foreground data-[state=on]:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)]"+ >+ {option.label}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/select.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/select.tsxindex 2b2247245..6079844ea 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/select.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/select.tsx@@ -42,7 +42,10 @@ function SelectTrigger({data-slot="select-trigger"data-size={size}className={cn(- "flex w-fit items-center justify-between gap-1.5 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ // Hovering says the box can be opened, in the same language the text+ // inputs use for the same fact — the pointer alone left a control that+ // looked inert until it was clicked.+ "flex w-fit items-center justify-between gap-1.5 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm whitespace-nowrap transition-[color,background-color,box-shadow] outline-none not-disabled:hover:border-border-1 not-disabled:hover:bg-background-1 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...props}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/spinner.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/spinner.tsxindex 4da6f55ab..b34b37034 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/spinner.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/spinner.tsx@@ -22,11 +22,20 @@ const Spinner = React.forwardRef<viewBox="0 0 24 24"{...props}>- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />+ <circle+ className="opacity-20"+ cx="12"+ cy="12"+ r="10"+ stroke="currentColor"+ strokeWidth="2.25"+ /><path- className="opacity-75"- fill="currentColor"- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"+ className="opacity-80"+ d="M22 12a10 10 0 0 0-10-10"+ stroke="currentColor"+ strokeWidth="2.25"+ strokeLinecap="round"/></svg>);diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/switch.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/switch.tsxindex c6d870b43..c4c6de7ba 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/switch.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/switch.tsx@@ -14,6 +14,10 @@ function Switch({data-size={size}className={cn('peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-border-1 transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:ring-destructive/40 data-checked:bg-background-neutral data-unchecked:bg-background data-disabled:cursor-not-allowed data-disabled:opacity-50',+ // Hovering has to show the switch can be moved. Written as explicit+ // selectors so a disabled one stays inert rather than inviting a click+ // it will refuse.+ '[&[data-unchecked]:not([data-disabled]):hover]:border-border-1 [&[data-unchecked]:not([data-disabled]):hover]:bg-background-1 [&[data-checked]:not([data-disabled]):hover]:bg-background-neutral/85',className)}onKeyDown={(e) => {diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsxnew file mode 100644index 000000000..61c2c4a9c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx@@ -0,0 +1,19 @@+import { DialogHeader, DialogTitle } from './dialog';++/**+ * A dialog header that says where in a sequence you are.+ *+ * The count is only honest once the sequence has a fixed length, so a step that+ * might or might not be reached must not be counted — a wizard that renumbers+ * itself halfway through is worse than one that never numbered itself at all.+ */+export function WizardStepHeader({ title, step, of }: { title: string; step: number; of: number }) {+ return (+ <DialogHeader className="flex-col items-start gap-1">+ <DialogTitle>{title}</DialogTitle>+ <p className="text-xs text-foreground-muted">+ Step {step} of {of}+ </p>+ </DialogHeader>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/main.tsx b/console/apps/switch-console-desktop/src/renderer/main.tsxindex e1ea76958..41e8fb94f 100644--- a/console/apps/switch-console-desktop/src/renderer/main.tsx+++ b/console/apps/switch-console-desktop/src/renderer/main.tsx@@ -11,6 +11,7 @@ import {} from '@renderer/lib/commands/registry';import { wireExternalLinkRequests } from '@renderer/lib/external-link-requests';import { rpc } from '@renderer/lib/ipc';+import { wireMouseNavigation } from '@renderer/lib/layout/mouse-navigation';import { viewStateCache } from '@renderer/lib/stores/view-state-cache';import { log } from '@renderer/utils/logger';import { initSoundPlayer } from '@renderer/utils/soundPlayer';@@ -39,6 +40,7 @@ async function bootstrap() {if (navResult) appState.navigation.restoreSnapshot(navResult);setupAppCommandProvider();setupViewCommandProvider(views as unknown as ViewCommandProviders);+ wireMouseNavigation();if (sidebarResult) {appState.sidebar.restoreSnapshot(sidebarResult as Partial<SidebarSnapshot>);} else {diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsxindex 75d4b22c4..370785b00 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx@@ -92,7 +92,7 @@ async function pickOption(label: string): Promise<void> {}describe('the chooser', () => {- async function control(value: AddressingPolicy | null) {+ async function control(value: AddressingPolicy | null, unlinkedApps: string[] = ['Slack Test']) {let last: AddressingPolicy | null | 'unset' = 'unset';const el = await render(<AddressingPolicyControl@@ -104,8 +104,9 @@ describe('the chooser', () => {roomGroups={[]}users={USERS}agents={AGENTS}- linkedIdentities={[]}- onClaimIdentity={null}+ unlinkedApps={unlinkedApps}+ onOpenMessagingApps={() => {}}+ inlineLabel={null}/>);return { el, emitted: () => last };@@ -182,6 +183,20 @@ describe('the chooser', () => {expect(el.textContent).toContain('you have not linked a messaging account');});+ it('warns about the one app with no account, not only about having none at all', async () => {+ // Linking Slack and leaving Mattermost unclaimed leaves an owner rule+ // half-working, and the agent silent in exactly the rooms nobody checked.+ const { el } = await control({ rules: [rule({ owner: true })] }, ['Mattermost']);++ expect(el.textContent).toContain('Mattermost');+ });++ it('stays quiet once every app has an account on it', async () => {+ const { el } = await control({ rules: [rule({ owner: true })] }, []);++ expect(el.textContent).not.toContain('you have not linked a messaging account');+ });+it('stays quiet when only the owner’s agents are admitted', async () => {// Agent senders are recognised by their agent id, so no messaging account// has to be linked for this rule to work. Warning here would be a warningdiff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsxindex de5ef131a..e01ec87f7 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx@@ -86,8 +86,11 @@ async function sectionCount(): Promise<number> {await act(async () => {await new Promise((resolve) => setTimeout(resolve, 0));});- return [...container.querySelectorAll('button')].filter(- (b) => b.textContent?.trim() === 'Advanced configuration'+ // Matched on the opening words rather than the whole string: the disclosure+ // also summarises what it holds ("Claude Code · 1 field"), and how it is+ // summarised is not what this test is about.+ return [...container.querySelectorAll('button')].filter((b) =>+ b.textContent?.trim().startsWith('Advanced configuration')).length;}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsxindex 2a739f8a4..b5acc042d 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx@@ -109,13 +109,15 @@ async function openMenu(el: HTMLElement): Promise<string[]> {}describe('the identity column', () => {- it('offers one control, not two, once an account is linked', async () => {- // The second control was the unlink cross. Its removal is the point: the- // one thing on the row is the handle, and pressing it changes the account.+ it('states the handle without hanging a control off it', async () => {+ // The control that was removed is the unlink cross, and its absence is+ // still the point. The handle now reads as a fact about the app; both+ // things you can do to it — change it, drop it — are in the menu, where+ // neither sits a mis-click from the other.const el = await render(row({ identities: [IDENTITY] }));- const inColumn = buttonLabels(el).filter((l) => l.includes('amaudruz.louis'));- expect(inColumn).toEqual(['@amaudruz.louis']);+ expect(el.textContent).toContain('@amaudruz.louis');+ expect(buttonLabels(el).filter((l) => l.includes('amaudruz.louis'))).toEqual([]);});it('cannot unlink straight from the row', async () => {@@ -146,7 +148,8 @@ describe('the identity column', () => {row({ identities: [{ ...IDENTITY, externalUsername: '@already.sigilled' }] }));- expect(buttonLabels(el)).toContain('@already.sigilled');+ expect(el.textContent).toContain('@already.sigilled');+ expect(el.textContent).not.toContain('@@already.sigilled');});});@@ -225,44 +228,70 @@ describe('the row menu', () => {});/**- * Channel creation moved out of the row menu into a column of the table- * (CHOO-2158), so it can be read down the page rather than opened one row at a- * time. What it has to say did not change with the shape.+ * Whether Switch may open channels on an app.+ *+ * It has been in both places. CHOO-2158 pulled it onto the row as a column, so+ * it could be read down the page; the card is a list rather than a table of+ * controls now, and it is back in the menu — read far less often than the app+ * name and the account under it, and a switch in a list of names reads as the+ * loudest thing there.+ *+ * What it has to say did not change with either move, and that is what these+ * are for.*/-describe('the channel-creation column', () => {- function channelSwitch(el: HTMLElement): HTMLElement {- const found = el.querySelector<HTMLElement>('[aria-label^="Let Switch create channels"]');- expect(found).not.toBeNull();+describe('channel creation', () => {+ /** Opens the row menu and returns the item with this label. Base UI portals+ * the menu, so this reads the whole document. */+ async function menuItem(el: HTMLElement, label: string): Promise<HTMLElement> {+ await openMenu(el);+ const found = [+ ...document.querySelectorAll<HTMLElement>('[role="menuitem"], [role="menuitemcheckbox"]'),+ ].find((i) => i.textContent?.trim() === label);+ expect(found, `no menu item labelled ${label}`).toBeDefined();return found!;}- it('puts the toggle on the row rather than behind the menu', async () => {+ it('is in the menu, not on the row', async () => {+ const el = await render(row({ isAdmin: true }));++ expect(el.querySelector('[role="switch"]')).toBeNull();+ expect(await openMenu(el)).toContain('Create channels on Slack');+ });++ it('shows the current answer', async () => {const el = await render(row({ isAdmin: true }));- expect(channelSwitch(el).getAttribute('aria-checked')).toBe('true');- expect(await openMenu(el)).not.toContain('Can create channels');+ expect((await menuItem(el, 'Create channels on Slack')).getAttribute('aria-checked')).toBe(+ 'true'+ );});it('says a platform cannot create channels rather than just showing it off', async () => {- // An unticked disabled switch reads as "switched off", which is a different- // claim from "this platform has no such thing".+ // An unticked box reads as "switched off", which is a different claim from+ // "this platform has no such thing". Telegram is the case: it never gets a+ // box at all, only a line saying so.const el = await render(row({ bridge: bridge({ channelCreationSupported: false, canCreateChannels: false }) }));- expect(el.textContent).toContain('Not supported');- expect(el.textContent).not.toContain('Off');+ const labels = await openMenu(el);+ expect(labels).toContain('Channels not supported on Slack');+ expect(document.querySelector('[role="menuitemcheckbox"]')).toBeNull();});- it('leaves the toggle alone for a non-admin', async () => {+ it('leaves it alone for a non-admin', async () => {const el = await render(row({ isAdmin: false }));- expect(channelSwitch(el).getAttribute('data-disabled')).not.toBeNull();+ expect(+ (await menuItem(el, 'Create channels on Slack')).getAttribute('data-disabled')+ ).not.toBeNull();});it('lets an admin move it', async () => {const el = await render(row({ isAdmin: true }));- expect(channelSwitch(el).getAttribute('data-disabled')).toBeNull();+ expect(+ (await menuItem(el, 'Create channels on Slack')).getAttribute('data-disabled')+ ).toBeNull();});});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsxindex aac335dfa..6f50dbe64 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx@@ -1,8 +1,7 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';-+import { afterEach, describe, expect, it } from 'vitest';/*** What "Who can send instructions" starts on for a brand-new agent (CHOO-2137).*@@ -12,19 +11,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';* to everyone still works perfectly, which is exactly why this needs pinning* rather than watching.*/--vi.mock('@renderer/lib/ipc', () => ({- rpc: {- switchServers: {- // The form seeds its name and description from this; the policy is not- // derived from it and must not become so.- suggestAgentDefaults: vi.fn(() =>- Promise.resolve({ name: 'louis-ama', description: 'Claude Code running in repo' })- ),- },- },-}));-import { useConfigureAgentForm } from '@renderer/features/locations/components/add-agent-modal/modes';import { addressingModeOf } from '@shared/core/switch-servers/owner-policy';@@ -42,7 +28,7 @@ afterEach(async () => {async function initialMode(): Promise<string> {let seen = '';function Probe() {- const form = useConfigureAgentForm('/tmp/repo', false, 'claude' as never);+ const form = useConfigureAgentForm();seen = addressingModeOf(form.addressingPolicy);return null;}diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex 7c0c699ad..9ad6fe52e 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -216,6 +216,33 @@ export type RemoteRoomSummary = {createdAt: string;};+/**+ * One room read on its own (mirrors the gateway `RoomDetail`), for the room's+ * own configuration page.+ *+ * The room list cannot answer this: it carries neither the instructions nor who+ * is in the room, only how many agents there are. Both are read one room at a+ * time because both are what that room's page is for.+ */+export type RemoteRoomDetail = RemoteRoomSummary & {+ /** Room-specific system prompt shown to agents on connect; null when unset. */+ instructions: string | null;+ /** Switch agent ids in the room — every install's agents, not just this one's. */+ agentIds: string[];+ /** Display names of the people in the room, via the messaging app it is+ * bridged to. Empty for an unbridged room, which has no people in it. */+ connectedUserNames: string[];+};++/** The room fields Switch Console can change. Anything omitted is left alone;+ * an empty string clears the field rather than leaving it. */+export type UpdateRoomParams = {+ serverId: string;+ roomId: string;+ description?: string;+ instructions?: string;+};+/*** A room a specific agent belongs to, with that agent's presence there (mirrors* the gateway `AgentRoomMembership`). Drives the "connect to room" picker atdiff --git a/console/apps/switch-console-desktop/src/shared/events/appEvents.ts b/console/apps/switch-console-desktop/src/shared/events/appEvents.tsindex bcf60c6a4..cae27d74f 100644--- a/console/apps/switch-console-desktop/src/shared/events/appEvents.ts+++ b/console/apps/switch-console-desktop/src/shared/events/appEvents.ts@@ -18,6 +18,15 @@ export const externalLinkOpenRequestedChannel = defineEvent<{ url: string }>('external-link:open-requested');+/**+ * A mouse back/forward button pressed on Windows, where those buttons arrive as+ * an `app-command` on the window rather than as a mouse event in the page.+ * Elsewhere the renderer sees them directly and this never fires.+ */+export const appCommandNavigateChannel = defineEvent<{ direction: 'back' | 'forward' }>(+ 'app-command:navigate'+);+export const tabNavigationShortcutChannel = defineEvent<{source: { kind: 'browser'; browserId: string };direction: TabNavigationDirection;