The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): persist composer model/provider per remote connection and profile
Brooklyn Nicholsonf08666d42a76
diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.tsindex c8838b39ce2..10695abcb79 100644--- a/apps/desktop/src/store/profile-agent-activation.test.ts+++ b/apps/desktop/src/store/profile-agent-activation.test.ts@@ -36,7 +36,16 @@ vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))const { $activeGatewayProfile, ensureGatewayAgent, ensureGatewayProfile } = await import('./profile')-const { $connection } = await import('./session')++const {+ $connection,+ $currentModel,+ $currentProvider,+ setComposerSelectionOwner,+ setCurrentModel,+ setCurrentModelSource,+ setCurrentProvider+} = await import('./session')const agentConn = (over: Partial<HermesConnection> = {}): HermesConnection =>({ baseUrl: 'https://homelab.invalid', mode: 'remote', profile: 'research', ...over }) as HermesConnection@@ -50,6 +59,9 @@ const getConnectionFor =vi.fn<(payload: { connectionId?: null | string; profile?: null | string }) => Promise<HermesConnection>>()beforeEach(() => {+ const localStorage = window.localStorage++ localStorage.clear()getConnection.mockReset()getConnectionFor.mockReset()ensureGatewayForAgent.mockClear()@@ -57,7 +69,8 @@ beforeEach(() => {$gateway.set({ id: 'live-socket' })$activeGatewayProfile.set('default')$connection.set(localConn())- vi.stubGlobal('window', { hermesDesktop: { getConnection, getConnectionFor } })+ vi.stubGlobal('window', { hermesDesktop: { getConnection, getConnectionFor }, localStorage })+ setComposerSelectionOwner('homelab', 'default')})afterEach(() => {@@ -90,6 +103,67 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =expect($connection.get()?.mode).toBe('local')})+ it('reseeds and persists under the activated owner when its descriptor fetch fails', async () => {+ setComposerSelectionOwner('homelab', 'default')+ setCurrentModel('grok-4')+ setCurrentProvider('xai-oauth')+ setCurrentModelSource('manual')+ getConnectionFor.mockRejectedValue(new Error('source unreachable'))++ // Mirrors ContribWiring's gateway-scope effect: the active-profile+ // publication forces the target profile's model/provider defaults.+ const unbind = $activeGatewayProfile.subscribe(profile => {+ if (profile === 'research') {+ setCurrentModel('local/model')+ setCurrentProvider('custom:local')+ setCurrentModelSource('default')+ }+ })++ await ensureGatewayAgent('homelab', 'research')+ unbind()++ expect($connection.get()?.mode).toBe('local')+ expect($currentModel.get()).toBe('local/model')+ expect($currentProvider.get()).toBe('custom:local')++ setComposerSelectionOwner('homelab', 'default')+ expect($currentModel.get()).toBe('grok-4')+ expect($currentProvider.get()).toBe('xai-oauth')++ setComposerSelectionOwner('homelab', 'research')+ expect($currentModel.get()).toBe('local/model')+ expect($currentProvider.get()).toBe('custom:local')+ })++ it('does not persist a legacy profile reseed when its owner descriptor is unresolved', async () => {+ setComposerSelectionOwner('homelab', 'default')+ setCurrentModel('grok-4')+ setCurrentProvider('xai-oauth')+ setCurrentModelSource('manual')+ getConnection.mockRejectedValue(new Error('source unreachable'))++ const unbind = $activeGatewayProfile.subscribe(profile => {+ if (profile === 'research') {+ setCurrentModel('unresolved-model')+ setCurrentProvider('unresolved-provider')+ setCurrentModelSource('default')+ }+ })++ await ensureGatewayProfile('research')+ unbind()++ setComposerSelectionOwner('homelab', 'default')+ expect($currentModel.get()).toBe('grok-4')+ expect($currentProvider.get()).toBe('xai-oauth')+ expect(+ [...Array(window.localStorage.length)].map((_, index) =>+ window.localStorage.getItem(window.localStorage.key(index) || '')+ )+ ).not.toContain('unresolved-model')+ })+it('does not republish a registry identity invalidated during activation', async () => {ensureGatewayForAgent.mockResolvedValueOnce(false)diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex 71380bbafb9..09ab31619f9 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -25,7 +25,7 @@ import {} from '@/store/gateway'import { notifyError } from '@/store/notifications'import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override'-import { setConnection } from '@/store/session'+import { clearComposerSelectionOwner, setComposerSelectionOwner, setConnection } from '@/store/session'import type { SessionOwnerRoute } from '@/store/session-request-router'import { resetStarmapGraph } from '@/store/starmap'import type { ProfileInfo } from '@/types/hermes'@@ -523,11 +523,13 @@ export async function ensureGatewayProfile(profile: string | null | undefined):// descriptor become visible together; a null descriptor (no bridge, or a// failed best-effort lookup) keeps the previous one — fail open.batch(() => {- $activeGatewayProfile.set(target)-if (connection) {setConnection(connection)+ } else {+ clearComposerSelectionOwner()}++ $activeGatewayProfile.set(target)})})()@@ -710,11 +712,15 @@ export async function ensureGatewayAgent(// descriptor keeps the previous one — fail open, resynced by// boot/reconnect later.batch(() => {- $activeGatewayProfile.set(target)-if (descriptor) {setConnection(descriptor)}++ // The activated registry coordinate is authoritative even when the+ // best-effort descriptor lookup failed. Publish it before the profile+ // atom wakes forced model reseeds or a picker can persist a selection.+ setComposerSelectionOwner(connection, target)+ $activeGatewayProfile.set(target)})})()diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex 18449c77dbd..22253f6f205 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -22,6 +22,8 @@ import {$activeSessionId,$connection,$currentCwd,+ $currentModel,+ $currentProvider,$selectedStoredSessionId,$sessions,$unreadFinishedSessionIds,@@ -46,8 +48,13 @@ import {sessionBelongsToProfile,sessionOwnerRouteFromRow,sessionPinId,+ setComposerSelectionOwner,+ setConnection,setCurrentCwd,setCurrentCwdTransient,+ setCurrentModel,+ setCurrentModelSource,+ setCurrentProvider,setRememberedRoute,setRememberedSessionId,setSelectedStoredSessionId,@@ -66,6 +73,83 @@ import {const session = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ id: 'live', ...over })+describe('composer model persistence scope', () => {+ const local = { baseUrl: '', connectionId: 'local', mode: 'local' } as never++ beforeEach(() => {+ window.localStorage.clear()+ setConnection(local)+ setCurrentModel('')+ setCurrentProvider('')+ setCurrentModelSource('')+ })++ afterEach(() => {+ setConnection(local)+ window.localStorage.clear()+ })++ it('keeps manual model selections isolated by remote connection and profile', () => {+ const remote = (profile: string) =>+ ({ baseUrl: 'https://aibox.example', connectionId: 'aibox', mode: 'remote', profile }) as never++ setConnection(remote('fred'))+ setCurrentModel('grok-4')+ setCurrentProvider('xai-oauth')+ setCurrentModelSource('manual')++ setConnection(remote('fred-work'))+ expect($currentModel.get()).toBe('')+ expect($currentProvider.get()).toBe('')++ setCurrentModel('local/model')+ setCurrentProvider('custom:local')+ setConnection(remote('fred'))++ expect($currentModel.get()).toBe('grok-4')+ expect($currentProvider.get()).toBe('xai-oauth')+ })++ it('keeps inferred local-primary connections on the historical bare keys', () => {+ setComposerSelectionOwner('remote', 'default')+ window.localStorage.setItem('hermes.desktop.composer.model', 'legacy-model')+ window.localStorage.setItem('hermes.desktop.composer.provider', 'legacy-provider')++ setConnection({ baseUrl: '', connectionId: 'local', mode: 'local', profile: 'default' } as never)++ expect($currentModel.get()).toBe('legacy-model')+ expect($currentProvider.get()).toBe('legacy-provider')+ setCurrentModel('next-model')+ expect(window.localStorage.getItem('hermes.desktop.composer.model')).toBe('next-model')+ expect(window.localStorage.getItem('hermes.desktop.composer.model.registry.local.default')).toBeNull()+ })++ it('uses the live registry owner when the connection descriptor is stale', () => {+ const remote = (profile: string) =>+ ({ baseUrl: 'https://aibox.example', connectionId: 'aibox', mode: 'remote', profile }) as never++ setConnection(remote('fred'))+ setCurrentModel('grok-4')+ setCurrentProvider('xai-oauth')+ setCurrentModelSource('manual')++ // ensureGatewayAgent publishes this coordinate even if getConnectionFor+ // fails and $connection therefore still describes fred.+ setComposerSelectionOwner('aibox', 'fred-work')+ setCurrentModel('local/model')+ setCurrentProvider('custom:local')+ setCurrentModelSource('default')++ setComposerSelectionOwner('aibox', 'fred')+ expect($currentModel.get()).toBe('grok-4')+ expect($currentProvider.get()).toBe('xai-oauth')++ setComposerSelectionOwner('aibox', 'fred-work')+ expect($currentModel.get()).toBe('local/model')+ expect($currentProvider.get()).toBe('custom:local')+ })+})+describe('session owner hints', () => {afterEach(() => {_resetSessionOwnerHintsForTests({ storage: true })diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 620db95cf74..029fa90acbb 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -5,7 +5,7 @@ import { lastVisibleMessageIsUser } from '@/app/chat/thread-loading'import type { ContextSuggestion } from '@/app/types'import type { HermesConnection } from '@/global'import type { ChatMessage } from '@/lib/chat-messages'-import { activeConnectionScopeSuffix, rescopeConnectionScopedStores } from '@/lib/connection-scoped'+import { activeConnectionScopeSuffix, connectionScopeSuffix, rescopeConnectionScopedStores } from '@/lib/connection-scoped'import { persistBoolean, persistString, readJson, storedBoolean, storedString, writeJson } from '@/lib/storage'import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope'import type { SessionInfo, UsageStats } from '@/types/hermes'@@ -21,14 +21,50 @@ const WORKSPACE_CWD_KEY = 'hermes.desktop.workspace-cwd'// The composer's model/effort/fast is sticky UI state, NOT the profile default// (that lives in Settings → Model). Persisting it in localStorage makes a pick// follow across Cmd+N and app restarts instead of snapping back to the default.-// It's deliberately global (not per-profile): a profile switch force-reseeds to-// that profile's default, while within a profile new chats keep your last pick.+// Model/provider/source are scoped to the remote (connection, profile) owner so+// a provider authenticated on one profile cannot contaminate another profile's+// session.create. Local/single-backend users retain the historical bare keys.const COMPOSER_MODEL_KEY = 'hermes.desktop.composer.model'const COMPOSER_PROVIDER_KEY = 'hermes.desktop.composer.provider'const COMPOSER_MODEL_SOURCE_KEY = 'hermes.desktop.composer.model-source'const COMPOSER_EFFORT_KEY = 'hermes.desktop.composer.reasoning-effort'const COMPOSER_FAST_KEY = 'hermes.desktop.composer.fast'+// Unlike presentation-oriented $connection, this scope is published from the+// gateway activation coordinate before profile-change effects can reseed the+// composer. null means the exact owner is temporarily unknown: values may still+// paint, but must not be written through the previous backend's storage key.+let composerSelectionScope: string | null = ''++function composerScopeForConnection(connection: HermesConnection | null): string | null {+ if (!connection) {+ return null+ }++ // Electron may infer the sole `local` registry id onto the ordinary primary+ // descriptor. That remains the legacy single-backend path: only an explicit+ // registry-scoped route earns a new namespace.+ if (connection.mode !== 'remote' && !connection.registryScoped) {+ return ''+ }++ if (connection.connectionId) {+ return `.registry.${encodeURIComponent(connection.connectionId)}.${encodeURIComponent(connection.profile || 'default')}`+ }++ return connectionScopeSuffix(connection)+}++function composerSelectionKey(base: string): string | null {+ return composerSelectionScope === null ? null : `${base}${composerSelectionScope}`+}++function storedComposerString(base: string): string | null {+ const key = composerSelectionKey(base)++ return key === null ? null : storedString(key)+}+// The last chat the user had open, so a relaunch lands back on it instead of an// empty new-chat. Stored (not runtime) id — the route is keyed by stored id.//@@ -948,8 +984,8 @@ export function getSessionOwnerHint(// clears it and resets the retry counter. Null whenever the active route has a// healthy, in-flight, or still-auto-retrying resume.export const $resumeExhaustedSessionId = atom<string | null>(null)-export const $currentModel = atom(storedString(COMPOSER_MODEL_KEY) ?? '')-export const $currentProvider = atom(storedString(COMPOSER_PROVIDER_KEY) ?? '')+export const $currentModel = atom(storedComposerString(COMPOSER_MODEL_KEY) ?? '')+export const $currentProvider = atom(storedComposerString(COMPOSER_PROVIDER_KEY) ?? '')export const $currentReasoningEffort = atom(storedString(COMPOSER_EFFORT_KEY) ?? '')export const $currentServiceTier = atom('')export const $currentFastMode = atom(storedBoolean(COMPOSER_FAST_KEY, false))@@ -1005,6 +1041,31 @@ export const $contextSuggestions = atom<ContextSuggestion[]>([])export const $modelPickerOpen = atom(false)export const $sessionPickerOpen = atom(false)+function rescopeComposerSelection(nextScope: string | null): void {+ if (nextScope === composerSelectionScope) {+ return+ }++ composerSelectionScope = nextScope+ $currentModel.set(storedComposerString(COMPOSER_MODEL_KEY) ?? '')+ $currentProvider.set(storedComposerString(COMPOSER_PROVIDER_KEY) ?? '')+ $currentModelSource.set(getCurrentModelSource())+}++/** Publish an exact registry route before active-profile effects can persist a+ * forced default. A registry id is authority even while its descriptive+ * HermesConnection lookup is unavailable. */+export function setComposerSelectionOwner(connectionId: string, profile: string): void {+ rescopeComposerSelection(+ `.registry.${encodeURIComponent(connectionId)}.${encodeURIComponent(profile.trim() || 'default')}`+ )+}++/** Fail closed while a successful legacy profile activation has no descriptor. */+export function clearComposerSelectionOwner(): void {+ rescopeComposerSelection(null)+}+export const setConnection = (next: Updater<HermesConnection | null>) => {updateAtom($connection, next)// Repoint connection-scoped persistence (pins, manual session order,@@ -1013,6 +1074,7 @@ export const setConnection = (next: Updater<HermesConnection | null>) => {// keeps the current scope.rescopeConnectionScopedStores($connection.get())syncCronModelImpactConnection($connection.get())+ rescopeComposerSelection(composerScopeForConnection($connection.get()))}export const setGatewayState = (next: Updater<ConnectionState>) => updateAtom($gatewayState, next)@@ -1137,16 +1199,24 @@ export const setAwaitingResponse = (next: Updater<boolean>) => updateAtom($awaitexport const setCurrentModel = (next: Updater<string>) => {updateAtom($currentModel, next)- persistString(COMPOSER_MODEL_KEY, $currentModel.get() || null)+ const key = composerSelectionKey(COMPOSER_MODEL_KEY)++ if (key !== null) {+ persistString(key, $currentModel.get() || null)+ }}export const setCurrentProvider = (next: Updater<string>) => {updateAtom($currentProvider, next)- persistString(COMPOSER_PROVIDER_KEY, $currentProvider.get() || null)+ const key = composerSelectionKey(COMPOSER_PROVIDER_KEY)++ if (key !== null) {+ persistString(key, $currentProvider.get() || null)+ }}export const getCurrentModelSource = (): ComposerModelSource => {- const source = storedString(COMPOSER_MODEL_SOURCE_KEY)+ const source = storedComposerString(COMPOSER_MODEL_SOURCE_KEY)return source === 'default' || source === 'manual' ? source : ''}@@ -1157,7 +1227,12 @@ export const getCurrentModelSource = (): ComposerModelSource => {export const $currentModelSource = atom<ComposerModelSource>(getCurrentModelSource())export const setCurrentModelSource = (source: ComposerModelSource) => {- persistString(COMPOSER_MODEL_SOURCE_KEY, source || null)+ const key = composerSelectionKey(COMPOSER_MODEL_SOURCE_KEY)++ if (key !== null) {+ persistString(key, source || null)+ }+$currentModelSource.set(source)}