From 2228bc7d88f7bfef408371053d89fecdf067af26 Mon Sep 17 00:00:00 2001 From: David Dudok de Wit <5354424+dokterdok@users.noreply.github.com> Date: Mon, 17 Aug 2026 14:00:47 +0200 Subject: [PATCH] feat(desktop): remember the last used source --- .../electron/connection-registry.test.ts | 39 ++++++++++++- apps/desktop/electron/connection-registry.ts | 38 +++++++++++-- apps/desktop/electron/main.ts | 16 ++++++ apps/desktop/electron/preload.ts | 2 + .../chat/sidebar/connection-switcher.test.tsx | 48 +++++++++++++++- .../app/chat/sidebar/connection-switcher.tsx | 13 +++++ .../settings/connections-registry.test.tsx | 22 +++++++- .../src/app/settings/connections-registry.tsx | 40 ++++++++++++++ apps/desktop/src/global.d.ts | 10 ++++ apps/desktop/src/i18n/en.ts | 4 ++ apps/desktop/src/i18n/types.ts | 4 ++ apps/desktop/src/i18n/zh.ts | 4 ++ apps/desktop/src/store/connections.test.ts | 28 +++++++++- apps/desktop/src/store/connections.ts | 55 +++++++++++++++++++ website/docs/user-guide/desktop.md | 1 + .../user-guide/multi-connection-desktop.md | 10 ++++ 16 files changed, 326 insertions(+), 8 deletions(-) diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts index c97e0bb44a..c5ff57c9df 100644 --- a/apps/desktop/electron/connection-registry.test.ts +++ b/apps/desktop/electron/connection-registry.test.ts @@ -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) diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts index 9c497e997f..012743bc09 100644 --- a/apps/desktop/electron/connection-registry.ts +++ b/apps/desktop/electron/connection-registry.ts @@ -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 } +} diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 6a2f6dc780..8e35bbefd9 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -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 || '')) diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index a87ab15f3a..7e2e52a319 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -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'), diff --git a/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx b/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx index cd347bb4f3..fd245f58db 100644 --- a/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx +++ b/apps/desktop/src/app/chat/sidebar/connection-switcher.test.tsx @@ -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('local'), $connectionsRegistry: atom(null), $pendingConnectionId: atom(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> 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() + + 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() diff --git a/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx index ae3b6aed26..c3ec15b002 100644 --- a/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx +++ b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx @@ -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) { diff --git a/apps/desktop/src/app/settings/connections-registry.test.tsx b/apps/desktop/src/app/settings/connections-registry.test.tsx index 53ea1d5098..4b4852dc50 100644 --- a/apps/desktop/src/app/settings/connections-registry.test.tsx +++ b/apps/desktop/src/app/settings/connections-registry.test.tsx @@ -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() + + 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() + + await waitFor(() => expect(list).toHaveBeenCalledTimes(1)) + expect(screen.queryByText('Open on launch')).toBeNull() + }) + it('tests a connection through the bridge', async () => { render() diff --git a/apps/desktop/src/app/settings/connections-registry.tsx b/apps/desktop/src/app/settings/connections-registry.tsx index 8b38518879..c7ec2fbb15 100644 --- a/apps/desktop/src/app/settings/connections-registry.tsx +++ b/apps/desktop/src/app/settings/connections-registry.tsx @@ -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) const [removeTarget, setRemoveTarget] = useState(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}

+ {!loading && registry && registry.connections.length > 1 && ( + 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 ? (
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts index bc53598dd0..db4eb8d15f 100644 --- a/apps/desktop/src/global.d.ts +++ b/apps/desktop/src/global.d.ts @@ -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 // 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 diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index fdd61711c2..6013a244ae 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -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', diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts index 429bb57451..5f8a32a480 100644 --- a/apps/desktop/src/i18n/types.ts +++ b/apps/desktop/src/i18n/types.ts @@ -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 diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index b6cba0cfc3..d5e7831c0f 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -910,6 +910,10 @@ export const zh: Translations = { intro: '注册你的智能体所在的每个位置——本机、局域网中的远程网关、Hermes Cloud 实例——全部保存在这里。', stagedNote: '可在“会话”侧边栏切换来源。配置档案、聊天、消息和定时任务始终限定在所选来源;“主连接”是注册表的默认值,不会切换当前工作区。', + launchModeTitle: '启动时打开', + launchModeDesc: '始终打开主连接,或恢复上次成功连接的来源。', + launchPrimary: '主连接', + launchLastUsed: '上次使用', loadFailed: '无法加载连接', currentPill: '当前', primaryPill: '主连接', diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts index 0fce2649f1..ec92be722a 100644 --- a/apps/desktop/src/store/connections.test.ts +++ b/apps/desktop/src/store/connections.test.ts @@ -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() }) }) diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts index 076ecf14dc..c97c07ce11 100644 --- a/apps/desktop/src/store/connections.ts +++ b/apps/desktop/src/store/connections.ts @@ -31,6 +31,7 @@ export const $hasMultipleConnections = computed( const $lastProfileByConnection = atom>(storedStringRecord(LAST_PROFILE_STORAGE_KEY)) let pendingTarget: null | string = null +let restoreAttempted = false let switchRevision = 0 export const $pendingConnectionId = atom(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 { + 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 { + 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 { currentProfile !== targetProfile if (!switching) { + await rememberConnection(connectionId) + return } @@ -130,6 +183,7 @@ export async function selectConnection(connectionId: string): Promise { $showAllProfiles.set(false) $newChatProfile.set(targetProfile) requestFreshSession() + await rememberConnection(connectionId) return } @@ -151,6 +205,7 @@ export async function selectConnection(connectionId: string): Promise { // 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) diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md index a7857e7c86..813df33188 100644 --- a/website/docs/user-guide/desktop.md +++ b/website/docs/user-guide/desktop.md @@ -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. diff --git a/website/docs/user-guide/multi-connection-desktop.md b/website/docs/user-guide/multi-connection-desktop.md index 0b34a4135c..444a021779 100644 --- a/website/docs/user-guide/multi-connection-desktop.md +++ b/website/docs/user-guide/multi-connection-desktop.md @@ -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.