The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): switch sources from the Sessions rail
David Dudok de Wit0ca7443824f8
diff --git a/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx b/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsxnew file mode 100644index 00000000000..1dcaa2d21a6--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx@@ -0,0 +1,115 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { atom } from 'nanostores'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { DesktopConnectionsRegistry } from '@/global'++import { ConnectionSwitcher } from './connection-switcher'++vi.mock('@/store/connections', () => ({+ $activeConnectionId: atom<null | string>('local'),+ $connectionsRegistry: atom<DesktopConnectionsRegistry | null>(null),+ $pendingConnectionId: atom<null | string>(null),+ refreshConnectionsRegistry: vi.fn(async () => null),+ selectConnection: vi.fn(async () => undefined)+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ profiles: {+ switchConnectionFailed: (name: string) => `Could not connect to ${name}`,+ switchToConnection: (name: string) => `Switch to ${name}`+ },+ settings: { connections: { title: 'Connections' } }+ }+ })+}))++const connectionStore = await import('@/store/connections')+const $activeConnectionId = connectionStore.$activeConnectionId as ReturnType<typeof atom<null | string>>+const $connectionsRegistry = connectionStore.$connectionsRegistry+const $pendingConnectionId = connectionStore.$pendingConnectionId+const selectConnection = vi.mocked(connectionStore.selectConnection)++const connection = (id: string, label: string, kind: 'local' | 'remote' = 'remote') => ({+ id,+ kind,+ label,+ tokenPreview: null,+ tokenSet: false+})++const registry = (connections: ReturnType<typeof connection>[]): DesktopConnectionsRegistry => ({+ connections,+ primary: connections[0]?.id ?? 'local',+ secureTokenStorage: true,+ version: 2+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ $connectionsRegistry.set(null)+ $activeConnectionId.set('local')+ $pendingConnectionId.set(null)+})++describe('ConnectionSwitcher', () => {+ it('adds no source chrome for a local-only setup', () => {+ $connectionsRegistry.set(registry([connection('local', 'This device', 'local')]))+ render(<ConnectionSwitcher />)++ expect(screen.queryByRole('group', { name: 'Connections' })).toBeNull()+ })++ it('shows direct local and remote source controls for a small registry', () => {+ $connectionsRegistry.set(+ registry([+ connection('local', 'This device', 'local'),+ connection('homelab', 'Homelab'),+ connection('work-vps', 'Work VPS')+ ])+ )+ render(<ConnectionSwitcher />)++ expect(screen.getByRole('button', { name: 'Switch to This device' }).getAttribute('aria-pressed')).toBe('true')+ fireEvent.click(screen.getByRole('button', { name: 'Switch to Homelab' }))+ expect(selectConnection).toHaveBeenCalledWith('homelab')+ })++ it('keeps source controls stable while a remote is opening', () => {+ $connectionsRegistry.set(registry([connection('local', 'This device', 'local'), connection('homelab', 'Homelab')]))+ $pendingConnectionId.set('homelab')+ render(<ConnectionSwitcher />)++ expect(screen.getByRole('button', { name: 'Switch to Homelab' }).getAttribute('aria-busy')).toBe('true')+ expect(screen.getByRole('button', { name: 'Switch to This device' }).getAttribute('aria-busy')).toBe('false')+ })++ it('collapses a larger registry into one compact source select', () => {+ $connectionsRegistry.set(+ registry([+ connection('local', 'This device', 'local'),+ ...Array.from({ length: 6 }, (_, index) => connection(`remote-${index}`, `Remote ${index}`))+ ])+ )+ render(<ConnectionSwitcher />)++ expect(screen.getByRole('combobox', { name: 'Connections' })).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'Switch to Homelab' })).toBeNull()+ })++ it('announces a pending switch in the compact source menu', () => {+ $connectionsRegistry.set(+ registry([+ connection('local', 'This device', 'local'),+ ...Array.from({ length: 6 }, (_, index) => connection(`remote-${index}`, `Remote ${index}`))+ ])+ )+ $pendingConnectionId.set('remote-3')+ render(<ConnectionSwitcher />)++ expect(screen.getByRole('group', { name: 'Connections' }).getAttribute('aria-busy')).toBe('true')+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsxnew file mode 100644index 00000000000..4f409858b55--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx@@ -0,0 +1,167 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { Button } from '@/components/ui/button'+import { ProfileGlyph } from '@/components/ui/profile-glyph'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Tip } from '@/components/ui/tooltip'+import type { DesktopRegistryConnection } from '@/global'+import { useI18n } from '@/i18n'+import { triggerHaptic } from '@/lib/haptics'+import { Loader2 } from '@/lib/icons'+import { profileColor } from '@/lib/profile-color'+import { cn } from '@/lib/utils'+import {+ $activeConnectionId,+ $connectionsRegistry,+ $pendingConnectionId,+ refreshConnectionsRegistry,+ selectConnection+} from '@/store/connections'+import { notifyError } from '@/store/notifications'++// Direct glyphs are faster for the common local + a few remote machines. At+// larger fleet sizes, one stable-width select prevents sources from crowding+// profiles and the create/manage actions out of the sidebar foot.+const CONNECTION_DROPDOWN_THRESHOLD = 5++export function ConnectionSwitcher() {+ const { t } = useI18n()+ const registry = useStore($connectionsRegistry)+ const activeConnectionId = useStore($activeConnectionId)+ const pendingConnectionId = useStore($pendingConnectionId)++ useEffect(() => {+ void refreshConnectionsRegistry().catch(() => undefined)++ // Registry events are local IPC notifications, not remote polling. They+ // keep a second Settings window or a removal/edit reflected here.+ const off = window.hermesDesktop?.connections?.onChanged?.(() => {+ void refreshConnectionsRegistry().catch(() => undefined)+ })++ return off+ }, [])++ const connections = registry?.connections ?? []++ if (connections.length <= 1) {+ return null+ }++ const choose = (connectionId: string) => {+ triggerHaptic('selection')+ const connection = connections.find(candidate => candidate.id === connectionId)++ void selectConnection(connectionId).catch(error =>+ notifyError(error, t.profiles.switchConnectionFailed(connection?.label ?? connectionId))+ )+ }++ if (connections.length > CONNECTION_DROPDOWN_THRESHOLD) {+ return (+ <div+ aria-busy={pendingConnectionId !== null}+ aria-label={t.settings.connections.title}+ className="min-w-0 shrink"+ role="group"+ >+ <Select onValueChange={choose} value={activeConnectionId ?? ''}>+ <SelectTrigger aria-label={t.settings.connections.title} className="w-28 max-w-full" size="xs">+ <span className="flex min-w-0 items-center gap-1.5">+ {pendingConnectionId && <Loader2 aria-hidden="true" className="size-3 shrink-0 animate-spin" />}+ <SelectValue placeholder={t.settings.connections.title} />+ </span>+ </SelectTrigger>+ <SelectContent collisionPadding={{ bottom: 44, left: 8, right: 8, top: 8 }} side="top">+ {connections.map(connection => (+ <SelectItem key={connection.id} value={connection.id}>+ <ConnectionLabel connection={connection} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )+ }++ return (+ <div+ aria-label={t.settings.connections.title}+ className="flex shrink-0 items-center gap-1"+ data-slot="connection-switcher"+ role="group"+ >+ {connections.map(connection => (+ <ConnectionButton+ active={connection.id === activeConnectionId}+ connection={connection}+ key={connection.id}+ onSelect={() => choose(connection.id)}+ pending={connection.id === pendingConnectionId}+ />+ ))}+ </div>+ )+}++function ConnectionButton({+ active,+ connection,+ onSelect,+ pending+}: {+ active: boolean+ connection: DesktopRegistryConnection+ onSelect: () => void+ pending: boolean+}) {+ const { t } = useI18n()+ const label = t.profiles.switchToConnection(connection.label)++ return (+ <Tip label={label}>+ <Button+ aria-busy={pending}+ aria-label={label}+ aria-pressed={active}+ className={cn(+ 'bg-transparent text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground',+ active && 'bg-(--ui-control-active-background) text-foreground'+ )}+ onClick={onSelect}+ size="icon-xs"+ type="button"+ variant="ghost"+ >+ {pending ? (+ <Loader2 aria-hidden="true" className="size-3.5 animate-spin" />+ ) : (+ <ConnectionGlyph connection={connection} />+ )}+ </Button>+ </Tip>+ )+}++function ConnectionGlyph({ connection }: { connection: DesktopRegistryConnection }) {+ const local = connection.kind === 'local'++ return (+ <ProfileGlyph+ aria-hidden="true"+ color={local ? null : profileColor(`connection:${connection.id}`)}+ isDefault={local}+ name={connection.label}+ />+ )+}++function ConnectionLabel({ connection }: { connection: DesktopRegistryConnection }) {+ return (+ <span className="flex min-w-0 items-center gap-1.5">+ <ConnectionGlyph connection={connection} />+ <span className="truncate">{connection.label}</span>+ </span>+ )+}diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsxindex 10e93f23e59..69384133123 100644--- a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx@@ -59,6 +59,10 @@ vi.mock('@/store/profile', () => ({sortByProfileOrder: (profiles: unknown[]) => profiles}))+vi.mock('@/store/connections', () => ({ $hasMultipleConnections: atom(false) }))++vi.mock('./connection-switcher', () => ({ ConnectionSwitcher: () => null }))+vi.mock('@/store/profile-share', () => ({runExportProfileFlow: vi.fn(),runImportProfileFlow: vi.fn()@@ -78,6 +82,9 @@ vi.mock('../../profiles/create-profile-dialog', () => ({ CreateProfileDialog: ()vi.mock('../../profiles/delete-profile-dialog', () => ({ DeleteProfileDialog: () => null }))vi.mock('../../profiles/rename-profile-dialog', () => ({ RenameProfileDialog: () => null }))+const { $hasMultipleConnections } = await import('@/store/connections')+const hasMultipleConnections = $hasMultipleConnections as ReturnType<typeof atom<boolean>>+describe('ProfileRail multi-gateway entry point', () => {it('deep-links to the unified Settings → Gateways page from the rail', () => {render(<ProfileRail />)@@ -96,4 +103,12 @@ describe('ProfileRail multi-gateway entry point', () => {expect(screen.getByRole('button', { name: 'Connect another Hermes gateway…' })).toBeTruthy()expect(screen.getByRole('button', { name: 'Manage profiles…' })).toBeTruthy()})++ it('does not duplicate the default home when source buttons identify multiple single-profile backends', () => {+ hasMultipleConnections.set(true)+ render(<ProfileRail />)++ expect(screen.queryByRole('button', { name: 'default' })).toBeNull()+ expect(screen.getByRole('button', { name: 'Manage profiles…' })).toBeTruthy()+ })})diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex 4a98d23cbb8..1f40dd889bb 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -43,6 +43,7 @@ import {reorderStepHaptic} from '@/lib/reorder'import { cn } from '@/lib/utils'+import { $hasMultipleConnections } from '@/store/connections'import { notify, notifyError } from '@/store/notifications'import {$activeGatewayProfile,@@ -69,6 +70,7 @@ import { DeleteProfileDialog } from '../../profiles/delete-profile-dialog'import { RenameProfileDialog } from '../../profiles/rename-profile-dialog'import { PROFILES_ROUTE, SETTINGS_ROUTE } from '../../routes'+import { ConnectionSwitcher } from './connection-switcher'import { useProfilePrewarm } from './use-profile-prewarm'import { useProfileRailRefreshOnActive } from './use-profile-rail-refresh-on-active'@@ -105,9 +107,10 @@ const stepThroughCells: Modifier = ({ containerNodeRect, draggingNodeRect, trans// Arc-Spaces-style profile rail at the sidebar foot: a default↔all toggle pinned// left, the colored named profiles scrolling between, and Manage pinned right.// The active profile pops in its own color — the "where am I" cue. Single--// profile users see the "+" (create their first profile) and the Manage-// overflow (edit the default profile's SOUL.md); the colored named squares-// and the default↔all toggle only appear once a second profile exists.+// source users see the default home, "+", and Manage; with several sources the+// active source glyph replaces that redundant home. Colored named squares and+// the default↔all toggle only appear once a second profile exists on the active+// source.export function ProfileRail() {const { t } = useI18n()const p = t.profiles@@ -116,6 +119,7 @@ export function ProfileRail() {const gatewayProfile = useStore($activeGatewayProfile)const order = useStore($profileOrder)const colors = useStore($profileColors)+ const multipleConnections = useStore($hasMultipleConnections)const navigate = useNavigate()const [createOpen, setCreateOpen] = useState(false)@@ -230,7 +234,9 @@ export function ProfileRail() {}, [createRequest])return (- <div aria-label="Profiles" className="flex items-center gap-0.5" data-slot="profile-rail" role="tablist">+ <div aria-label={p.title} className="flex items-center gap-0.5" data-slot="profile-rail" role="group">+ <ConnectionSwitcher />+ {multipleConnections && <span aria-hidden="true" className="mx-0.5 h-3.5 w-px bg-(--ui-stroke-tertiary)" />}{/* One button toggles default ↔ all: home face when scoped to a profile,layers face when showing everything. Pinned left like Manage is right.Hidden until a second profile exists. */}@@ -249,7 +255,7 @@ export function ProfileRail() {))}{/* Single-profile: the active default's home icon next to the create +. */}- {!multiProfile && defaultProfile && (+ {!multipleConnections && !multiProfile && defaultProfile && (<ProfilePillactiveglyph="home"diff --git a/apps/desktop/src/app/settings/connections-registry.tsx b/apps/desktop/src/app/settings/connections-registry.tsxindex 76c7a48075b..6bc7479f1e2 100644--- a/apps/desktop/src/app/settings/connections-registry.tsx+++ b/apps/desktop/src/app/settings/connections-registry.tsx@@ -12,6 +12,7 @@ import type {import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { Cloud, Globe, Loader2, Monitor, Pencil, Plus, RefreshCw, Terminal, Trash2 } from '@/lib/icons'+import { setConnectionsRegistry } from '@/store/connections'import { notify, notifyError } from '@/store/notifications'import { EmptyState, ListRow, Pill, SectionHeading } from './primitives'@@ -216,6 +217,10 @@ export function ConnectionsRegistrySection() {const bridge = window.hermesDesktop?.connectionsconst hasLocal = Boolean(registry?.connections.some(c => c.kind === 'local'))+ const publishRegistry = useCallback((next: DesktopConnectionsRegistry) => {+ setRegistry(next)+ setConnectionsRegistry(next)+ }, [])const load = useCallback(async () => {if (!bridge) {@@ -227,13 +232,13 @@ export function ConnectionsRegistrySection() {setLoading(true)try {- setRegistry(await bridge.list())+ publishRegistry(await bridge.list())} catch (err) {notifyError(err, s.loadFailed)} finally {setLoading(false)}- }, [bridge, s.loadFailed])+ }, [bridge, publishRegistry, s.loadFailed])useEffect(() => {void load()@@ -312,7 +317,7 @@ export function ConnectionsRegistrySection() {}const result = await bridge.save(payload)- setRegistry(result.registry)+ publishRegistry(result.registry)setEditor(null)setPlainTextConfirm(false)} catch (err) {@@ -336,7 +341,7 @@ export function ConnectionsRegistrySection() {setSaving(false)}},- [bridge, editor, registry?.connections, registry?.secureTokenStorage, s]+ [bridge, editor, publishRegistry, registry?.connections, registry?.secureTokenStorage, s])const remove = useCallback(async () => {@@ -348,14 +353,14 @@ export function ConnectionsRegistrySection() {try {const result = await bridge.remove(removeTarget.id)- setRegistry(result.registry)+ publishRegistry(result.registry)} catch (err) {notifyError(err, s.removeFailed)} finally {setBusyId(null)setRemoveTarget(null)}- }, [bridge, removeTarget, s.removeFailed])+ }, [bridge, publishRegistry, removeTarget, s.removeFailed])const makePrimary = useCallback(async (id: string) => {@@ -367,14 +372,14 @@ export function ConnectionsRegistrySection() {try {const result = await bridge.setPrimary(id)- setRegistry(result.registry)+ publishRegistry(result.registry)} catch (err) {notifyError(err, s.saveFailed)} finally {setBusyId(null)}},- [bridge, s.saveFailed]+ [bridge, publishRegistry, s.saveFailed])const test = useCallback(@@ -446,8 +451,8 @@ export function ConnectionsRegistrySection() {<div className="mt-8 border-t border-border/60 pt-6"><SectionHeading icon={Globe} title={s.title} /><p className="mb-1 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{s.intro}</p>- {/* Storage-only slice: be explicit that routing consumption is staged so- "Make primary" isn't read as an immediate connection switch. */}+ {/* Source selection lives in Sessions. Primary is the registry fallback,+ not an immediate workspace switch. */}<p className="mb-4 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{s.stagedNote}</p>diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex ec765be5cca..de0fdd71b81 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1351,6 +1351,8 @@ export const ar = defineLocale({allProfiles: 'كل الملفات الشخصية',showAllProfiles: 'إظهار كل الملفات الشخصية',switchToProfile: name => `التبديل إلى ${name}`,+ switchToConnection: name => `التبديل إلى ${name}`,+ switchConnectionFailed: name => `تعذّر الاتصال بـ ${name}`,manageProfiles: 'إدارة الملفات الشخصية',actions: 'إجراءات',color: 'اللون',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 05990c44f13..54fe9e05b4b 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -705,7 +705,7 @@ export const en: Translations = {intro:'Register every place your agents live — this device, remote gateways on your network, and Hermes Cloud instances. All of them are stored here.',stagedNote:- 'Chats and the agent roster follow the source you pick; the app-managed window backend is still chosen in Settings → Gateway.',+ 'Switch sources from the Sessions sidebar. Profiles, chats, messaging, and cron stay scoped to that source; Primary is the registry default and does not switch your current workspace.',loadFailed: 'Could not load connections',primaryPill: 'Primary',managedPill: 'This device',@@ -1762,6 +1762,8 @@ export const en: Translations = {allProfiles: 'All profiles',showAllProfiles: 'Show all profiles',switchToProfile: name => `Switch to ${name}`,+ switchToConnection: name => `Switch to ${name}`,+ switchConnectionFailed: name => `Could not connect to ${name}`,manageProfiles: 'Manage profiles…',connectGateway: 'Connect another Hermes gateway…',actions: 'Actions',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex bbe89872101..5aa5a0318de 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -1480,6 +1480,8 @@ export const ja = defineLocale({allProfiles: 'すべてのプロファイル',showAllProfiles: 'すべてのプロファイルを表示',switchToProfile: name => `${name} に切り替え`,+ switchToConnection: name => `${name} に切り替え`,+ switchConnectionFailed: name => `${name} に接続できませんでした`,manageProfiles: 'プロファイルを管理…',actions: 'アクション',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 49275a74fd3..255b4aa5efe 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1487,6 +1487,8 @@ export interface Translations {allProfiles: stringshowAllProfiles: stringswitchToProfile: (name: string) => string+ switchToConnection: (name: string) => string+ switchConnectionFailed: (name: string) => stringmanageProfiles: stringconnectGateway: stringactions: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex b56687236b3..1220464ba4d 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1426,6 +1426,8 @@ export const zhHant = defineLocale({allProfiles: '全部設定檔',showAllProfiles: '顯示全部設定檔',switchToProfile: name => `切換至 ${name}`,+ switchToConnection: name => `切換至 ${name}`,+ switchConnectionFailed: name => `無法連線至 ${name}`,manageProfiles: '管理設定檔…',actions: '動作',color: '顏色…',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 3b43d0a3b20..017f380b25d 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -908,7 +908,8 @@ export const zh: Translations = {connections: {title: '连接',intro: '注册你的智能体所在的每个位置——本机、局域网中的远程网关、Hermes Cloud 实例——全部保存在这里。',- stagedNote: '聊天和智能体列表会跟随你选择的来源;应用管理的窗口后端仍在“设置 → 网关”中选择。',+ stagedNote:+ '可在“会话”侧边栏切换来源。配置档案、聊天、消息和定时任务始终限定在所选来源;“主连接”是注册表的默认值,不会切换当前工作区。',loadFailed: '无法加载连接',primaryPill: '主连接',managedPill: '本机',@@ -1948,6 +1949,8 @@ export const zh: Translations = {allProfiles: '全部配置档案',showAllProfiles: '显示全部配置档案',switchToProfile: name => `切换到 ${name}`,+ switchToConnection: name => `切换到 ${name}`,+ switchConnectionFailed: name => `无法连接到 ${name}`,manageProfiles: '管理配置档案…',connectGateway: '连接另一个 Hermes 网关…',actions: '操作',diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.tsnew file mode 100644index 00000000000..5602cb605c8--- /dev/null+++ b/apps/desktop/src/store/connections.test.ts@@ -0,0 +1,219 @@+import { atom } from 'nanostores'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { DesktopConnectionsRegistry } from '@/global'++const $activeGatewayProfile = atom('default')+const $newChatProfile = atom<null | string>(null)+const $showAllProfiles = atom(false)++const $connection = atom<null | {+ connectionId?: string+ mode?: 'local' | 'remote'+ profile?: string+ registryScoped?: boolean+}>(null)++const ensureGatewayAgent = vi.fn(async (_connectionId: null | string, _profile: string): Promise<void> => undefined)+const refreshActiveProfile = vi.fn(async () => undefined)+const requestFreshSession = vi.fn()+const wipeSessionListsForGatewaySwitch = vi.fn()++vi.mock('@/store/session', () => ({ $connection }))+vi.mock('@/store/gateway-switch', () => ({ wipeSessionListsForGatewaySwitch }))+vi.mock('@/store/profile', () => ({+ $activeGatewayProfile,+ $newChatProfile,+ $showAllProfiles,+ ensureGatewayAgent,+ normalizeProfileKey: (name: null | string | undefined) => (name ?? '').trim() || 'default',+ refreshActiveProfile,+ requestFreshSession+}))++const {+ $activeConnectionId,+ $connectionsRegistry,+ $pendingConnectionId,+ refreshConnectionsRegistry,+ _resetConnectionsForTests,+ selectConnection,+ setConnectionsRegistry+} = await import('./connections')++const registry: DesktopConnectionsRegistry = {+ connections: [+ { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false },+ { id: 'homelab', kind: 'remote', label: 'Homelab', tokenPreview: '...abc', tokenSet: true },+ { id: 'work-vps', kind: 'remote', label: 'Work VPS', tokenPreview: '...xyz', tokenSet: true }+ ],+ primary: 'local',+ secureTokenStorage: true,+ version: 2+}++const list = vi.fn(async () => registry)++beforeEach(() => {+ localStorage.clear()+ _resetConnectionsForTests()+ $connectionsRegistry.set(null)+ $connection.set(null)+ $activeGatewayProfile.set('default')+ $newChatProfile.set(null)+ $showAllProfiles.set(false)+ ensureGatewayAgent.mockReset()+ ensureGatewayAgent.mockImplementation(async connectionId => {+ $connection.set({+ connectionId: connectionId ?? undefined,+ mode: connectionId === 'local' ? 'local' : 'remote',+ profile: 'default',+ registryScoped: true+ })+ })+ refreshActiveProfile.mockClear()+ requestFreshSession.mockClear()+ wipeSessionListsForGatewaySwitch.mockClear()+ list.mockClear()+ vi.stubGlobal('window', { hermesDesktop: { connections: { list } }, localStorage })+})++afterEach(() => vi.unstubAllGlobals())++describe('connection registry cache', () => {+ it('loads only Electron local registry state', async () => {+ await refreshConnectionsRegistry()++ expect(list).toHaveBeenCalledTimes(1)+ expect($connectionsRegistry.get()).toEqual(registry)+ expect($activeConnectionId.get()).toBeNull()+ })++ it('uses the resolved descriptor identity for a primary gateway', () => {+ setConnectionsRegistry({ ...registry, primary: 'homelab' })+ $connection.set({ connectionId: 'work-vps', mode: 'remote' })+ expect($activeConnectionId.get()).toBe('work-vps')++ $connection.set({ mode: 'remote' })+ expect($activeConnectionId.get()).toBe('homelab')++ $connection.set({ connectionId: 'work-vps', mode: 'remote' })+ expect($activeConnectionId.get()).toBe('work-vps')+ })+})++describe('selectConnection', () => {+ it('dials a secondary source and starts a fresh source-scoped draft', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })++ await selectConnection('homelab')++ expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default')+ expect(requestFreshSession).toHaveBeenCalledTimes(1)+ expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)+ expect($newChatProfile.get()).toBe('default')+ expect(refreshActiveProfile).toHaveBeenCalledTimes(1)+ })++ it('does not reset or dial when the active source/profile is selected again', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })++ await selectConnection('local')++ expect(ensureGatewayAgent).not.toHaveBeenCalled()+ expect(requestFreshSession).not.toHaveBeenCalled()+ })++ it('uses an explicit local id when This device is not primary', async () => {+ setConnectionsRegistry({ ...registry, primary: 'homelab' })+ $connection.set({ connectionId: 'homelab', mode: 'remote' })++ await selectConnection('local')++ expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'default')+ })++ it('lets a later source choice win while an earlier dial is still pending', async () => {+ let releaseHomelab!: () => void++ const homelabGate = new Promise<void>(resolve => {+ releaseHomelab = resolve+ })++ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })+ ensureGatewayAgent.mockImplementationOnce(async () => {+ await homelabGate+ $connection.set({ connectionId: 'homelab', mode: 'remote' })+ })+ ensureGatewayAgent.mockImplementationOnce(async () => {+ await homelabGate+ $connection.set({ connectionId: 'local', mode: 'local' })+ })++ const openHomelab = selectConnection('homelab')+ await Promise.resolve()+ const stayLocal = selectConnection('local')++ releaseHomelab()+ await Promise.all([openHomelab, stayLocal])++ expect(ensureGatewayAgent.mock.calls).toEqual([+ ['homelab', 'default'],+ ['local', 'default']+ ])+ // Only the latest intent repaints the profile list.+ expect(refreshActiveProfile).toHaveBeenCalledTimes(1)+ expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)+ })++ it('restores the last profile used on each source', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local', profile: 'research', registryScoped: true })+ $activeGatewayProfile.set('research')+ $connection.set({ connectionId: 'homelab', mode: 'remote', registryScoped: true })+ $activeGatewayProfile.set('default')++ await selectConnection('local')++ expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'research')+ })++ it('does not remember a migrated v1 routing alias as a backend profile', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'homelab', mode: 'remote' })+ $activeGatewayProfile.set('legacy-homelab-alias')+ $connection.set({ connectionId: 'local', mode: 'local', registryScoped: true })++ await selectConnection('homelab')++ expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default')+ })++ it('does not remember a stale startup profile under the resolved source', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local', profile: 'default', registryScoped: true })+ $activeGatewayProfile.set('work-agent')+ $connection.set({ connectionId: 'homelab', mode: 'remote', profile: 'default', registryScoped: true })+ $activeGatewayProfile.set('default')++ await selectConnection('local')++ expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'default')+ })++ it('keeps the current source usable when a dial fails', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })+ ensureGatewayAgent.mockRejectedValueOnce(new Error('offline'))++ await expect(selectConnection('homelab')).rejects.toThrow('offline')++ expect(requestFreshSession).not.toHaveBeenCalled()+ expect(wipeSessionListsForGatewaySwitch).not.toHaveBeenCalled()+ expect($newChatProfile.get()).toBeNull()+ expect($pendingConnectionId.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsnew file mode 100644index 00000000000..24080a043a7--- /dev/null+++ b/apps/desktop/src/store/connections.ts@@ -0,0 +1,171 @@+import { atom, computed } from 'nanostores'++import type { DesktopConnectionsRegistry } from '@/global'+import { persistStringRecord, storedStringRecord } from '@/lib/storage'+import { wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'+import {+ $activeGatewayProfile,+ $newChatProfile,+ $showAllProfiles,+ ensureGatewayAgent,+ normalizeProfileKey,+ refreshActiveProfile,+ requestFreshSession+} from '@/store/profile'+import { $connection } from '@/store/session'++const LAST_PROFILE_STORAGE_KEY = 'hermes.desktop.lastProfileByConnection'++export const $connectionsRegistry = atom<DesktopConnectionsRegistry | null>(null)++// Use the resolved descriptor identity Electron publishes. The registry+// primary is only a compatibility fallback for older mains.+export const $activeConnectionId = computed(+ [$connectionsRegistry, $connection],+ (registry, connection) => connection?.connectionId ?? (connection ? (registry?.primary ?? null) : null)+)++export const $hasMultipleConnections = computed(+ $connectionsRegistry,+ registry => (registry?.connections.length ?? 0) > 1+)++const $lastProfileByConnection = atom<Record<string, string>>(storedStringRecord(LAST_PROFILE_STORAGE_KEY))+let pendingTarget: null | string = null+let switchRevision = 0++export const $pendingConnectionId = atom<null | string>(null)++$lastProfileByConnection.subscribe(value => persistStringRecord(LAST_PROFILE_STORAGE_KEY, value))++const $activeConnectionProfile = computed(+ [$activeConnectionId, $activeGatewayProfile, $connection],+ (connectionId, profile, connection) => ({+ connectionId,+ descriptorProfile: normalizeProfileKey(connection?.profile),+ profile: normalizeProfileKey(profile),+ registryScoped: connection?.registryScoped === true+ })+)++// Remember one profile per source, so switching machines is a re-home rather+// than a reset to `default`. The map is local UI preference only; Electron+// remains the authority for the connection registry and all secrets.+$activeConnectionProfile.subscribe(({ connectionId, descriptorProfile, profile, registryScoped }) => {+ // A migrated v1 per-profile remote may expose a client-side alias such as+ // "work" while the registered source's actual profile is "default". Only+ // remember a source/profile pair after Electron confirms that exact v2+ // descriptor. This also rejects the brief startup window where the profile+ // atom still carries the previous app run's alias.+ if (+ !connectionId ||+ !registryScoped ||+ descriptorProfile !== profile ||+ $lastProfileByConnection.get()[connectionId] === profile+ ) {+ return+ }++ $lastProfileByConnection.set({ ...$lastProfileByConnection.get(), [connectionId]: profile })+})++/** @internal Reset module-owned preferences and switch coordination for tests. */+export function _resetConnectionsForTests(): void {+ $lastProfileByConnection.set({})+ pendingTarget = null+ switchRevision = 0+ $pendingConnectionId.set(null)+}++export function setConnectionsRegistry(registry: DesktopConnectionsRegistry): void {+ $connectionsRegistry.set(registry)+}++/** Refresh the renderer cache from Electron's local registry. No backend is contacted. */+export async function refreshConnectionsRegistry(): Promise<DesktopConnectionsRegistry | null> {+ const bridge = window.hermesDesktop?.connections++ if (!bridge) {+ return null+ }++ const registry = await bridge.list()+ setConnectionsRegistry(registry)++ return registry+}++/**+ * Re-home Sessions to one registered source, restoring that source's last+ * profile. Only the selected source is dialed; merely rendering the switcher+ * never probes or opens remote gateways.+ */+export async function selectConnection(connectionId: string): Promise<void> {+ const registry = $connectionsRegistry.get()+ const targetConnection = registry?.connections.find(connection => connection.id === connectionId)++ if (!registry || !targetConnection) {+ return+ }++ const currentConnectionId = $activeConnectionId.get()+ const currentProfile = normalizeProfileKey($activeGatewayProfile.get())+ const targetProfile = normalizeProfileKey($lastProfileByConnection.get()[connectionId] ?? 'default')+ const targetKey = `${connectionId}::${targetProfile}`++ if (pendingTarget === targetKey) {+ return+ }++ const switching =+ pendingTarget !== null ||+ $showAllProfiles.get() ||+ currentConnectionId !== connectionId ||+ currentProfile !== targetProfile++ if (!switching) {+ return+ }++ if (pendingTarget === null && currentConnectionId === connectionId && currentProfile === targetProfile) {+ $showAllProfiles.set(false)+ $newChatProfile.set(targetProfile)+ requestFreshSession()++ return+ }++ const revision = ++switchRevision+ pendingTarget = targetKey+ $pendingConnectionId.set(connectionId)++ try {+ // Always use the explicit registry route. `local` must mean This device,+ // and a registry primary can differ from a legacy per-profile override.+ await ensureGatewayAgent(connectionId, targetProfile)++ if ($connection.get()?.connectionId !== connectionId) {+ throw new Error(`Connection "${targetConnection.label}" did not become active.`)+ }++ // A newer click owns the final refresh. Serialized gateway activation+ // already makes the latest source win; this guard also prevents an older+ // request from repainting its profile list after that newer activation.+ if (revision === switchRevision) {+ wipeSessionListsForGatewaySwitch()+ $showAllProfiles.set(false)+ $newChatProfile.set(targetProfile)+ requestFreshSession()+ await refreshActiveProfile()+ }+ } catch (error) {+ if (revision === switchRevision) {+ throw error+ }+ } finally {+ if (revision === switchRevision) {+ pendingTarget = null+ $pendingConnectionId.set(null)+ }+ }+}diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex ffa828c3776..fde23951a0a 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -46,6 +46,7 @@ vi.mock('@/store/session', () => ({vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))const {+ activeGateway,closeSecondaryGateways,configureGatewayRegistry,disposeSecondariesForConnection,@@ -87,6 +88,29 @@ afterEach(() => {})describe('disposeSecondariesForConnection', () => {+ it('keeps the previous source socket alive when another source becomes foreground', async () => {+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )++ installDesktop({ getConnectionFor })++ await ensureGatewayForAgent('homelab', 'default')+ const homelab = gatewayMocks.instances[0]++ await ensureGatewayForAgent('office', 'default')++ expect(gatewayMocks.instances).toHaveLength(2)+ expect(homelab.close).not.toHaveBeenCalled()+ expect(homelab.connectionState).toBe('open')++ // Returning to the first source reuses its live socket. A source switch is+ // only a foreground routing change; it must never interrupt backend work.+ await ensureGatewayForAgent('homelab', 'default')+ expect(gatewayMocks.instances).toHaveLength(2)+ expect(activeGateway()).toBe(homelab)+ })+it('closes and evicts every secondary scoped to the removed connection', async () => {const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>descriptorFor(connectionId, profile)diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.tsindex 1c93581c289..6bb3612aee4 100644--- a/apps/desktop/src/store/gateway-connection-scope.test.ts+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts@@ -42,6 +42,7 @@ vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() })const {closeSecondaryGateways,configureGatewayRegistry,+ ensureGatewayForAgent,openGatewayForAgent,pruneSecondaryGateways,setPrimaryGateway@@ -84,6 +85,15 @@ afterEach(() => {})describe('pruneSecondaryGateways with registry-scoped entries', () => {+ it('keeps the previous source socket open when Sessions switches backends', async () => {+ await ensureGatewayForAgent('work', 'default')+ await ensureGatewayForAgent('homelab', 'default')++ // Source switching only changes the foreground route. Retaining the first+ // socket lets its live turn continue and keeps receiving completion events.+ expect(gatewayMocks.closed).toEqual([])+ })+it("does not keep a registry socket alive off another source's same-named profile", async () => {// Gateway B's 'default' — the roster row (connectionId 'homelab', profile// 'default'). The keep-set carries the bare 'default' profile because the