feat(desktop): remember the last used source

This commit is contained in:
David Dudok de Wit
2026-08-17 14:00:47 +02:00
committed by Teknium
parent ccd30f955c
commit 2228bc7d88
16 changed files with 326 additions and 8 deletions
@@ -30,6 +30,8 @@ import {
removeConnection,
resolvedConnectionId,
resolveRegistryLocalRoute,
setConnectionLaunchMode,
setLastUsedConnection,
setPrimaryConnection,
shouldDeferLocalEnumeration,
shouldRetrySshInventory,
@@ -688,6 +690,8 @@ test('normalizeRegistry degrades junk to a local-only registry', () => {
assert.equal(registry.version, REGISTRY_VERSION)
assert.equal(registry.primary, LOCAL_CONNECTION_ID)
assert.equal(registry.launchMode, 'primary')
assert.equal(registry.lastUsed, LOCAL_CONNECTION_ID)
assert.equal(registry.connections.length, 1)
assert.equal(registry.connections[0].kind, 'local')
}
@@ -719,6 +723,8 @@ test('normalizeRegistry round-trips a valid registry unchanged in shape', () =>
const input = {
version: 2,
primary: 'homelab',
launchMode: 'last-used',
lastUsed: 'homelab',
connections: [
{ id: 'local', kind: 'local', label: 'This device' },
{
@@ -744,6 +750,8 @@ test('normalizeRegistry round-trips a valid registry unchanged in shape', () =>
const registry = normalizeRegistry(input)
assert.equal(registry.primary, 'homelab')
assert.equal(registry.launchMode, 'last-used')
assert.equal(registry.lastUsed, 'homelab')
assert.equal(registry.connections.length, 4)
assert.deepEqual(
registry.connections.map(c => c.id),
@@ -753,6 +761,22 @@ test('normalizeRegistry round-trips a valid registry unchanged in shape', () =>
assert.equal(registry.connections[3].port, 2222)
})
test('normalizeRegistry falls back to Primary when the last-used source is missing', () => {
const registry = normalizeRegistry({
version: 2,
primary: 'homelab',
launchMode: 'last-used',
lastUsed: 'retired-host',
connections: [
{ id: 'local', kind: 'local', label: 'This device' },
{ id: 'homelab', kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }
]
})
assert.equal(registry.launchMode, 'last-used')
assert.equal(registry.lastUsed, 'homelab')
})
// --- v1 → v2 migration ---
test('migrate: v1 local-only config → local-only registry', () => {
@@ -837,17 +861,19 @@ test('migrate: duplicate host labels are suffixed, not dropped', () => {
// --- registry operations ---
test('removeConnection: local refuses, primary retargets to local', () => {
test('removeConnection: local refuses, primary and last-used retarget safely', () => {
let registry = emptyRegistry()
const entry = normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)
registry = upsertConnection(registry, entry)
registry = setPrimaryConnection(registry, entry.id)
registry = setLastUsedConnection(registry, entry.id)
assert.throws(() => removeConnection(registry, LOCAL_CONNECTION_ID), /cannot be removed/)
const after = removeConnection(registry, entry.id)
assert.equal(after.primary, LOCAL_CONNECTION_ID)
assert.equal(after.lastUsed, LOCAL_CONNECTION_ID)
assert.equal(after.connections.length, 1)
// Removing an unknown id is a no-op, not an error.
assert.equal(removeConnection(after, 'ghost'), after)
@@ -860,6 +886,17 @@ test('setPrimaryConnection validates the target id', () => {
assert.equal(setPrimaryConnection(registry, LOCAL_CONNECTION_ID).primary, LOCAL_CONNECTION_ID)
})
test('last-used source and launch mode validate their persisted values', () => {
let registry = emptyRegistry()
const entry = normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)
registry = upsertConnection(registry, entry)
assert.throws(() => setLastUsedConnection(registry, 'ghost'), /No connection/)
assert.equal(setLastUsedConnection(registry, entry.id).lastUsed, entry.id)
assert.equal(setConnectionLaunchMode(registry, 'last-used').launchMode, 'last-used')
assert.throws(() => setConnectionLaunchMode(registry, 'sometimes'), /Unknown connection launch mode/)
})
test('upsertConnection replaces by id and appends new ids', () => {
let registry = emptyRegistry()
const a = normalizeConnectionInput({ kind: 'remote', label: 'A', url: 'http://a:1' }, registry)
+34 -4
View File
@@ -76,6 +76,11 @@ export interface ConnectionRegistry {
version: typeof REGISTRY_VERSION
/** id of the connection that owns the window/primary backend. */
primary: string
/** Which saved source Sessions should restore when the app launches. */
launchMode: 'last-used' | 'primary'
/** Last source the Sessions workspace successfully opened. Additive in v2
* so registries written before multi-source switching still normalize. */
lastUsed: string
connections: RegistryConnection[]
}
@@ -891,11 +896,15 @@ export function normalizeRegistry(raw: unknown): ConnectionRegistry {
connections.unshift(localEntry())
}
const primary = String(parsed.primary || '').trim()
const storedPrimary = String(parsed.primary || '').trim()
const primary = connections.some(c => c.id === storedPrimary) ? storedPrimary : LOCAL_CONNECTION_ID
const storedLastUsed = String(parsed.lastUsed || '').trim()
return {
version: REGISTRY_VERSION,
primary: connections.some(c => c.id === primary) ? primary : LOCAL_CONNECTION_ID,
primary,
launchMode: parsed.launchMode === 'last-used' ? 'last-used' : 'primary',
lastUsed: connections.some(c => c.id === storedLastUsed) ? storedLastUsed : primary,
connections
}
}
@@ -1040,7 +1049,7 @@ export function migrateV1ToRegistry(v1: unknown): ConnectionRegistry {
}
}
return { version: REGISTRY_VERSION, primary, connections }
return { version: REGISTRY_VERSION, primary, launchMode: 'primary', lastUsed: primary, connections }
}
/** Insert or replace by id. Input must already be normalized/validated. */
@@ -1067,9 +1076,12 @@ export function removeConnection(registry: ConnectionRegistry, id: string): Conn
throw new Error('The local connection cannot be removed.')
}
const primary = registry.primary === id ? LOCAL_CONNECTION_ID : registry.primary
return {
...registry,
primary: registry.primary === id ? LOCAL_CONNECTION_ID : registry.primary,
primary,
lastUsed: registry.lastUsed === id ? primary : registry.lastUsed,
connections: registry.connections.filter(c => c.id !== id)
}
}
@@ -1082,3 +1094,21 @@ export function setPrimaryConnection(registry: ConnectionRegistry, id: string):
return { ...registry, primary: id }
}
/** Remember the last source the Sessions workspace opened successfully. */
export function setLastUsedConnection(registry: ConnectionRegistry, id: string): ConnectionRegistry {
if (!registry.connections.some(c => c.id === id)) {
throw new Error(`No connection with id "${id}".`)
}
return { ...registry, lastUsed: id }
}
/** Choose whether launch restores the explicit primary or the last-used source. */
export function setConnectionLaunchMode(registry: ConnectionRegistry, launchMode: string): ConnectionRegistry {
if (launchMode !== 'last-used' && launchMode !== 'primary') {
throw new Error(`Unknown connection launch mode "${String(launchMode)}".`)
}
return { ...registry, launchMode }
}
+16
View File
@@ -108,6 +108,8 @@ import {
removeConnection,
resolvedConnectionId,
resolveRegistryLocalRoute,
setConnectionLaunchMode,
setLastUsedConnection,
setPrimaryConnection,
shouldDeferLocalEnumeration,
shouldRetrySshInventory,
@@ -8366,6 +8368,8 @@ function sanitizeConnectionsRegistry(registry = readDesktopConnectionsRegistry()
return {
version: registry.version,
primary: registry.primary,
launchMode: registry.launchMode,
lastUsed: registry.lastUsed,
secureTokenStorage,
connections: registry.connections.map(sanitizeRegistryConnection)
}
@@ -12594,6 +12598,18 @@ ipcMain.handle('hermes:connections:set-primary', async (_event, id) => {
return { ok: true, registry: sanitizeConnectionsRegistry(registry) }
})
ipcMain.handle('hermes:connections:set-launch-mode', async (_event, mode) => {
const registry = setConnectionLaunchMode(readDesktopConnectionsRegistry(), String(mode || ''))
writeDesktopConnectionsRegistry(registry)
return { ok: true, registry: sanitizeConnectionsRegistry(registry) }
})
ipcMain.handle('hermes:connections:set-last-used', async (_event, id) => {
const registry = setLastUsedConnection(readDesktopConnectionsRegistry(), String(id || ''))
writeDesktopConnectionsRegistry(registry)
return { ok: true, registry: sanitizeConnectionsRegistry(registry) }
})
ipcMain.handle('hermes:connections:test', async (_event, id) => {
const registry = readDesktopConnectionsRegistry()
const entry = registry.connections.find(c => c.id === String(id || ''))
+2
View File
@@ -137,6 +137,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
save: payload => ipcRenderer.invoke('hermes:connections:save', payload),
remove: id => ipcRenderer.invoke('hermes:connections:remove', id),
setPrimary: id => ipcRenderer.invoke('hermes:connections:set-primary', id),
setLaunchMode: mode => ipcRenderer.invoke('hermes:connections:set-launch-mode', mode),
setLastUsed: id => ipcRenderer.invoke('hermes:connections:set-last-used', id),
test: id => ipcRenderer.invoke('hermes:connections:test', id),
// Fan out `hermes update` to every eligible registered connection.
updateAll: () => ipcRenderer.invoke('hermes:connections:update-all'),
@@ -1,4 +1,4 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { atom } from 'nanostores'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -15,10 +15,24 @@ vi.mock('@/store/connections', () => ({
$activeConnectionId: atom<null | string>('local'),
$connectionsRegistry: atom<DesktopConnectionsRegistry | null>(null),
$pendingConnectionId: atom<null | string>(null),
initializeConnectionsRegistry: vi.fn(async () => null),
refreshConnectionsRegistry: vi.fn(async () => null),
selectConnection: vi.fn(async () => undefined)
}))
vi.mock('@/store/boot', () => ({
$desktopBoot: atom({
error: null,
fakeMode: false,
message: 'Starting',
phase: 'renderer.init',
progress: 2,
running: true,
timestamp: 0,
visible: true
})
}))
vi.mock('@/i18n', () => ({
useI18n: () => ({
t: {
@@ -33,9 +47,13 @@ vi.mock('@/i18n', () => ({
}))
const connectionStore = await import('@/store/connections')
const bootStore = await import('@/store/boot')
const $activeConnectionId = connectionStore.$activeConnectionId as ReturnType<typeof atom<null | string>>
const $connectionsRegistry = connectionStore.$connectionsRegistry
const $desktopBoot = bootStore.$desktopBoot
const $pendingConnectionId = connectionStore.$pendingConnectionId
const initializeConnectionsRegistry = vi.mocked(connectionStore.initializeConnectionsRegistry)
const refreshConnectionsRegistry = vi.mocked(connectionStore.refreshConnectionsRegistry)
const selectConnection = vi.mocked(connectionStore.selectConnection)
const onConnect = vi.fn()
@@ -59,10 +77,38 @@ afterEach(() => {
vi.clearAllMocks()
$connectionsRegistry.set(null)
$activeConnectionId.set('local')
$desktopBoot.set({
error: null,
fakeMode: false,
message: 'Starting',
phase: 'renderer.init',
progress: 2,
running: true,
timestamp: 0,
visible: true
})
$pendingConnectionId.set(null)
})
describe('ConnectionSwitcher', () => {
it('waits for primary boot fetches before restoring the launch source', async () => {
$connectionsRegistry.set(registry([connection('local', 'This device', 'local'), connection('homelab', 'Homelab')]))
render(<ConnectionSwitcher onConnect={onConnect} />)
expect(refreshConnectionsRegistry).toHaveBeenCalledTimes(1)
expect(initializeConnectionsRegistry).not.toHaveBeenCalled()
$desktopBoot.set({
...$desktopBoot.get(),
phase: 'renderer.ready',
progress: 100,
running: false,
visible: false
})
await waitFor(() => expect(initializeConnectionsRegistry).toHaveBeenCalledTimes(1))
})
it('adds no source chrome for a local-only setup', () => {
$connectionsRegistry.set(registry([connection('local', 'This device', 'local')]))
render(<ConnectionSwitcher onConnect={onConnect} />)
@@ -16,10 +16,12 @@ import type { DesktopRegistryConnection } from '@/global'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
import { Cloud, Loader2, Monitor, Network, Terminal } from '@/lib/icons'
import { $desktopBoot } from '@/store/boot'
import {
$activeConnectionId,
$connectionsRegistry,
$pendingConnectionId,
initializeConnectionsRegistry,
refreshConnectionsRegistry,
selectConnection
} from '@/store/connections'
@@ -29,6 +31,7 @@ export function ConnectionSwitcher({ onConnect }: { onConnect: () => void }) {
const { t } = useI18n()
const registry = useStore($connectionsRegistry)
const activeConnectionId = useStore($activeConnectionId)
const boot = useStore($desktopBoot)
const pendingConnectionId = useStore($pendingConnectionId)
useEffect(() => {
@@ -43,6 +46,16 @@ export function ConnectionSwitcher({ onConnect }: { onConnect: () => void }) {
return off
}, [])
useEffect(() => {
// The primary boot owns its initial config/session fetches. Restoring a
// different source before those settle lets a late primary response repaint
// the sidebar under the new source label. Switch only after boot completes,
// then the normal source reset/refetch remains the final writer.
if (!boot.running) {
void initializeConnectionsRegistry().catch(() => undefined)
}
}, [boot.running])
const connections = registry?.connections ?? []
if (connections.length <= 1) {
@@ -15,6 +15,7 @@ import {
const list = vi.fn()
const save = vi.fn()
const remove = vi.fn()
const setLaunchMode = vi.fn()
const setPrimary = vi.fn()
const test = vi.fn()
@@ -51,11 +52,12 @@ beforeEach(() => {
list.mockResolvedValue(registry)
save.mockResolvedValue({ connection: registry.connections[1], ok: true, registry })
remove.mockResolvedValue({ ok: true, registry: { ...registry, connections: [registry.connections[0]] } })
setLaunchMode.mockResolvedValue({ ok: true, registry: { ...registry, launchMode: 'last-used' } })
setPrimary.mockResolvedValue({ ok: true, registry: { ...registry, primary: 'homelab' } })
test.mockResolvedValue({ ok: true, reachable: true })
Object.defineProperty(window, 'hermesDesktop', {
configurable: true,
value: { connections: { list, remove, save, setPrimary, test } }
value: { connections: { list, remove, save, setLaunchMode, setPrimary, test } }
})
})
@@ -143,6 +145,24 @@ describe('ConnectionsRegistrySection', () => {
await waitFor(() => expect(setPrimary).toHaveBeenCalledWith('homelab'))
})
it('lets users opt into restoring the last-used source', async () => {
render(<ConnectionsRegistrySection />)
await waitFor(() => expect(screen.getByText('Open on launch')).toBeTruthy())
fireEvent.click(screen.getByText('Last used'))
await waitFor(() => expect(setLaunchMode).toHaveBeenCalledWith('last-used'))
})
it('keeps the launch preference out of the way for a single source', async () => {
list.mockResolvedValueOnce({ ...registry, connections: [registry.connections[0]] })
render(<ConnectionsRegistrySection />)
await waitFor(() => expect(list).toHaveBeenCalledTimes(1))
expect(screen.queryByText('Open on launch')).toBeNull()
})
it('tests a connection through the bridge', async () => {
render(<ConnectionsRegistrySection />)
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { Input } from '@/components/ui/input'
import { SegmentedControl } from '@/components/ui/segmented-control'
import type {
DesktopConnectionKind,
DesktopConnectionsRegistry,
@@ -211,6 +212,7 @@ export function ConnectionsRegistrySection() {
const [testingId, setTestingId] = useState<null | string>(null)
const [removeTarget, setRemoveTarget] = useState<DesktopRegistryConnection | null>(null)
const [plainTextConfirm, setPlainTextConfirm] = useState(false)
const [launchModeBusy, setLaunchModeBusy] = useState(false)
const [updatingAll, setUpdatingAll] = useState(false)
// Inline duplicate rejection from the save path (dedupe is also enforced in
// the main process, so a crafted payload can't slip past the UI check).
@@ -384,6 +386,26 @@ export function ConnectionsRegistrySection() {
[bridge, publishRegistry, s.saveFailed]
)
const setLaunchMode = useCallback(
async (mode: 'last-used' | 'primary') => {
if (!bridge?.setLaunchMode) {
return
}
setLaunchModeBusy(true)
try {
const result = await bridge.setLaunchMode(mode)
publishRegistry(result.registry)
} catch (err) {
notifyError(err, s.saveFailed)
} finally {
setLaunchModeBusy(false)
}
},
[bridge, publishRegistry, s.saveFailed]
)
const test = useCallback(
async (conn: DesktopRegistryConnection) => {
if (!bridge) {
@@ -459,6 +481,24 @@ export function ConnectionsRegistrySection() {
{s.stagedNote}
</p>
{!loading && registry && registry.connections.length > 1 && (
<ListRow
action={
<SegmentedControl
disabled={launchModeBusy || !bridge?.setLaunchMode}
onChange={mode => void setLaunchMode(mode)}
options={[
{ id: 'primary', label: s.launchPrimary },
{ id: 'last-used', label: s.launchLastUsed }
]}
value={registry.launchMode ?? 'primary'}
/>
}
description={s.launchModeDesc}
title={s.launchModeTitle}
/>
)}
{loading ? (
<div className="flex items-center gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
<Loader2 className="size-4 animate-spin" />
+10
View File
@@ -144,6 +144,10 @@ declare global {
) => Promise<{ ok: boolean; connection: DesktopRegistryConnection; registry: DesktopConnectionsRegistry }>
remove: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
setPrimary: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
setLaunchMode?: (
mode: 'last-used' | 'primary'
) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
setLastUsed?: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
test: (id: string) => Promise<DesktopConnectionTestResult>
// Fan out `hermes update` to every eligible registered connection;
// cloud entries are skipped (platform-managed), each row independent.
@@ -819,6 +823,12 @@ export interface DesktopConnectionsRegistry {
version: number
// id of the connection that owns the window/primary backend.
primary: string
// Preserve old installs by defaulting to the explicit primary; users may
// instead resume the last successfully opened source.
launchMode?: 'last-used' | 'primary'
// Last source the Sessions workspace opened successfully. Optional for
// compatibility with an older Electron main during a rolling app update.
lastUsed?: string
// Whether OS-keychain-backed encryption (Electron safeStorage) is available;
// false drives the plain-text token opt-in on keyring-less Linux.
secureTokenStorage: boolean
+4
View File
@@ -706,6 +706,10 @@ export const en: Translations = {
'Register every place your agents live — this device, remote gateways on your network, and Hermes Cloud instances. All of them are stored here.',
stagedNote:
'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.',
launchModeTitle: 'Open on launch',
launchModeDesc: 'Always open the Primary source, or resume the last source that connected successfully.',
launchPrimary: 'Primary source',
launchLastUsed: 'Last used',
loadFailed: 'Could not load connections',
currentPill: 'Current',
primaryPill: 'Primary',
+4
View File
@@ -592,6 +592,10 @@ export interface Translations {
title: string
intro: string
stagedNote: string
launchModeTitle: string
launchModeDesc: string
launchPrimary: string
launchLastUsed: string
loadFailed: string
currentPill: string
primaryPill: string
+4
View File
@@ -910,6 +910,10 @@ export const zh: Translations = {
intro: '注册你的智能体所在的每个位置——本机、局域网中的远程网关、Hermes Cloud 实例——全部保存在这里。',
stagedNote:
'可在“会话”侧边栏切换来源。配置档案、聊天、消息和定时任务始终限定在所选来源;“主连接”是注册表的默认值,不会切换当前工作区。',
launchModeTitle: '启动时打开',
launchModeDesc: '始终打开主连接,或恢复上次成功连接的来源。',
launchPrimary: '主连接',
launchLastUsed: '上次使用',
loadFailed: '无法加载连接',
currentPill: '当前',
primaryPill: '主连接',
+27 -1
View File
@@ -35,6 +35,7 @@ const {
$activeConnectionId,
$connectionsRegistry,
$pendingConnectionId,
initializeConnectionsRegistry,
refreshConnectionsRegistry,
_resetConnectionsForTests,
selectConnection,
@@ -53,6 +54,7 @@ const registry: DesktopConnectionsRegistry = {
}
const list = vi.fn(async () => registry)
const setLastUsed = vi.fn(async (id: string) => ({ ok: true, registry: { ...registry, lastUsed: id } }))
beforeEach(() => {
localStorage.clear()
@@ -75,7 +77,8 @@ beforeEach(() => {
requestFreshSession.mockClear()
wipeSessionListsForGatewaySwitch.mockClear()
list.mockClear()
vi.stubGlobal('window', { hermesDesktop: { connections: { list } }, localStorage })
setLastUsed.mockClear()
vi.stubGlobal('window', { hermesDesktop: { connections: { list, setLastUsed } }, localStorage })
})
afterEach(() => vi.unstubAllGlobals())
@@ -89,6 +92,27 @@ describe('connection registry cache', () => {
expect($activeConnectionId.get()).toBeNull()
})
it('restores the last-used source once when that launch mode is enabled', async () => {
list.mockResolvedValueOnce({ ...registry, lastUsed: 'homelab', launchMode: 'last-used' })
$connection.set({ connectionId: 'local', mode: 'local' })
await initializeConnectionsRegistry()
await initializeConnectionsRegistry()
expect(ensureGatewayAgent).toHaveBeenCalledTimes(1)
expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
expect(setLastUsed).toHaveBeenCalledWith('homelab')
})
it('preserves the established Primary-source launch behavior by default', async () => {
list.mockResolvedValueOnce({ ...registry, lastUsed: 'homelab', launchMode: 'primary' })
$connection.set({ connectionId: 'local', mode: 'local' })
await initializeConnectionsRegistry()
expect(ensureGatewayAgent).not.toHaveBeenCalled()
})
it('uses only the resolved descriptor identity for the active gateway', () => {
setConnectionsRegistry({ ...registry, primary: 'homelab' })
$connection.set({ connectionId: 'work-vps', mode: 'remote' })
@@ -114,6 +138,7 @@ describe('selectConnection', () => {
expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
expect($newChatProfile.get()).toBe('default')
expect(refreshActiveProfile).toHaveBeenCalledTimes(1)
expect(setLastUsed).toHaveBeenCalledWith('homelab')
})
it('does not reset or dial when the active source/profile is selected again', async () => {
@@ -215,5 +240,6 @@ describe('selectConnection', () => {
expect(wipeSessionListsForGatewaySwitch).not.toHaveBeenCalled()
expect($newChatProfile.get()).toBeNull()
expect($pendingConnectionId.get()).toBeNull()
expect(setLastUsed).not.toHaveBeenCalled()
})
})
+55
View File
@@ -31,6 +31,7 @@ export const $hasMultipleConnections = computed(
const $lastProfileByConnection = atom<Record<string, string>>(storedStringRecord(LAST_PROFILE_STORAGE_KEY))
let pendingTarget: null | string = null
let restoreAttempted = false
let switchRevision = 0
export const $pendingConnectionId = atom<null | string>(null)
@@ -72,6 +73,7 @@ $activeConnectionProfile.subscribe(({ connectionId, descriptorProfile, profile,
export function _resetConnectionsForTests(): void {
$lastProfileByConnection.set({})
pendingTarget = null
restoreAttempted = false
switchRevision = 0
$pendingConnectionId.set(null)
}
@@ -94,6 +96,55 @@ export async function refreshConnectionsRegistry(): Promise<DesktopConnectionsRe
return registry
}
async function rememberConnection(connectionId: string): Promise<void> {
const setLastUsed = window.hermesDesktop?.connections?.setLastUsed
if (!setLastUsed) {
return
}
try {
const result = await setLastUsed(connectionId)
setConnectionsRegistry(result.registry)
} catch {
// The source is already usable. A read-only/full userData directory must
// not turn a successful backend switch into a false connection failure.
}
}
/**
* Load the registry once for Sessions and restore the last successfully used
* source. Later registry refreshes stay side-effect free, so editing Settings
* in another window never changes the active workspace.
*/
export async function initializeConnectionsRegistry(): Promise<DesktopConnectionsRegistry | null> {
const registry = await refreshConnectionsRegistry()
if (!registry || restoreAttempted) {
return registry
}
restoreAttempted = true
const lastUsed = registry.connections.some(connection => connection.id === registry.lastUsed)
? registry.lastUsed
: registry.primary
const preferredId = registry.launchMode === 'last-used' ? lastUsed : registry.primary
if (!preferredId) {
return registry
}
if ($activeConnectionId.get() === preferredId) {
await rememberConnection(preferredId)
} else {
await selectConnection(preferredId)
}
return $connectionsRegistry.get() ?? registry
}
/**
* Re-home Sessions to one registered source, restoring that source's last
* profile. Only the selected source is dialed; merely rendering the switcher
@@ -123,6 +174,8 @@ export async function selectConnection(connectionId: string): Promise<void> {
currentProfile !== targetProfile
if (!switching) {
await rememberConnection(connectionId)
return
}
@@ -130,6 +183,7 @@ export async function selectConnection(connectionId: string): Promise<void> {
$showAllProfiles.set(false)
$newChatProfile.set(targetProfile)
requestFreshSession()
await rememberConnection(connectionId)
return
}
@@ -151,6 +205,7 @@ export async function selectConnection(connectionId: string): Promise<void> {
// 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) {
await rememberConnection(connectionId)
wipeSessionListsForGatewaySwitch()
$showAllProfiles.set(false)
$newChatProfile.set(targetProfile)
+1
View File
@@ -303,6 +303,7 @@ Further down the same **Settings → Gateways** page, the connections registry m
- **Every connection needs a unique name** (a device name such as "Homelab" or "Work laptop"). When the same profile name exists on several registered sources, surfaces disambiguate it as `@profile-device` (e.g. `@research-homelab`).
- **Switch sources from the Sessions sidebar.** A named source selector appears when more than one source is registered and handles any registry size without making gateways look like profiles. The adjacent profile rail then shows only that source's agents and remembers the last profile used there; large profile sets condense independently.
- **Choose what opens after a restart.** **Open on launch** keeps the backward-compatible **Primary source** default, or can resume the **Last used** source after it connects successfully. This preference is stored outside the application bundle and survives Desktop updates.
- **Add / edit / remove / test** connections from the panel. The **Add** flow offers all four kinds — **Local**, **Hermes Cloud**, **Remote gateway**, and **SSH** (the Local button is disabled while the app-managed local entry exists, and a hint points cloud adds at the sign-in/discovery flow above). The local entry is managed by the app and cannot be removed. **Test** probes the connection's own HTTP and WebSocket legs directly.
- **Duplicates are rejected at save time**: only one **local** entry ever; remote and cloud entries are deduplicated on the normalized URL (trimmed, trailing slashes stripped, lowercased — across both kinds); SSH entries on the normalized `user@host:port` plus remote profile.
- Existing settings are **imported automatically** the first time you run a build with the registry: your current global connection and any legacy per-profile overrides become named entries. The legacy settings file is left untouched, so older builds keep working.
@@ -59,6 +59,12 @@ Rules worth knowing:
registry fallback for multi-source calls that do not name a source.
**Make primary** does not switch the current Sessions workspace; removing
the primary falls back to the local entry.
- **Open on launch** controls which source Sessions opens after a full app
restart. **Primary source** preserves the established Desktop behavior and
remains the default for existing and new installs. Choose **Last used** to
resume the most recent source that connected successfully. A failed switch
is never remembered, and a removed or unavailable saved source falls back
to Primary.
- **Test** probes the connection's own HTTP *and* WebSocket legs, so a pass
(the *"Reachable"* toast) means chat will actually work — not just that the
host pinged.
@@ -170,6 +176,10 @@ that live on one source.
then shows only that source's profiles; the home pill returns to its default
profile and the layers pill shows **All profiles on this source**.
**Cmd/Ctrl+1–9** continue to switch profiles within the active source.
- The selected source survives a quit and relaunch only when **Settings →
Connections → Open on launch** is set to **Last used**. The preference and
source id live in the app's user-data registry, so replacing or updating the
application bundle does not reset them.
- With more than thirteen profiles on the active source, their avatar strip
condenses into a named profile selector. Large source and profile sets can
therefore coexist without changing the **source → profile → sessions** model.