The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep profile rail alive across remote/Cloud connection switches
Teknium5f8d488830a8
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsxindex 3c507cec5f4..5603d70219a 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $desktopBoot } from '@/store/boot'import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'-import { $activeGatewayProfile, ensureGatewayProfile } from '@/store/profile'+import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'import { $connection, $currentCwd, $gatewayState } from '@/store/session'import { takeGatewaySurvivor } from './gateway-hmr-survivor'@@ -160,6 +160,7 @@ beforeEach(() => {closeSecondaryGateways()$activeGatewayProfile.set('default')$connection.set(null)+ $profiles.set([])vi.useFakeTimers()FakeWebSocket.mode = 'open'FakeWebSocket.instances = []@@ -197,6 +198,7 @@ afterEach(() => {closeSecondaryGateways()$activeGatewayProfile.set('default')$connection.set(null)+ $profiles.set([])vi.useRealTimers();(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocketdelete (window as { hermesDesktop?: unknown }).hermesDesktop@@ -270,6 +272,56 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>expect($gatewayState.get()).toBe('open')})+ it('re-fetches the profile rail from the NEW backend after a connection apply (#85731)', async () => {+ // The reported repro: connected to backend A, the rail shows A's named+ // profiles; the user applies a different remote/Cloud connection (soft+ // re-home). The rail must repopulate from backend B — before the fix+ // nothing deterministically re-pulled /api/profiles on the soft switch,+ // so the rail kept (or, with a stale in-flight response, collapsed to)+ // the previous backend's list.+ const desktop = fakeDesktop() as ReturnType<typeof fakeDesktop> & {+ api: ReturnType<typeof vi.fn>+ }++ desktop.api = vi.fn(async ({ path }: { path: string }) => {+ if (path === '/api/profiles/active') {+ return { active: 'default', current: 'default' }+ }++ if (path === '/api/profiles') {+ return {+ profiles: [+ { is_default: true, name: 'default' },+ { is_default: false, name: 'cloud-eric' }+ ]+ }+ }++ throw new Error(`unexpected api call: ${path}`)+ })+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop++ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')++ // The rail currently mirrors backend A's profile universe.+ $profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'eric' }+ ] as never)++ // Settings → Gateway apply lands: main tears down softly and notifies.+ act(() => connectionApplied?.())+ await flushAsync()+ await flushAsync()++ expect($gatewayState.get()).toBe('open')+ // Backend B's list replaced A's — the rail survives the switch instead of+ // painting the previous backend's (or an empty) universe.+ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'cloud-eric'])+ })+it('a remote that drops post-boot keeps looping with NO boot.error (the dead-end CONNECTING combo)', async () => {render(<Harness />)await flushAsync()diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex e6b4e26f3db..9c69c0e2fcc 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -29,7 +29,7 @@ import {} from '@/store/gateway'import { $gatewaySwitching, wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'import { notify, notifyError } from '@/store/notifications'-import { $activeGatewayProfile, normalizeProfileKey, touchActiveGatewayBackend } from '@/store/profile'+import { $activeGatewayProfile, normalizeProfileKey, refreshActiveProfile, touchActiveGatewayBackend } from '@/store/profile'import {$activeSessionId,$connection,@@ -344,10 +344,17 @@ export function useGatewayBoot({}// Same shape as boot(): profile first (session scope depends on it),- // then the independent fetches concurrently.+ // then the independent fetches concurrently. refreshActiveProfile is+ // explicit here: the rail's $profiles still shows the PREVIOUS+ // backend's list after a connection/mode apply, and nothing else+ // re-pulls /api/profiles deterministically post-switch — leaving the+ // rail stale or (if a stale in-flight response landed) collapsed+ // (#85731). Best-effort like the rest: a failure keeps the cached+ // list rather than blanking the rail.await adoptPrimaryProfile()await Promise.all([seedDefaultCwd(),+ refreshActiveProfile().catch(() => undefined),callbacksRef.current.refreshHermesConfig().catch(() => undefined),callbacksRef.current.refreshSessions().catch(() => undefined)])diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.tsindex 93f004834f8..7610d3a8c22 100644--- a/apps/desktop/src/store/gateway-switch.test.ts+++ b/apps/desktop/src/store/gateway-switch.test.ts@@ -23,6 +23,17 @@ vi.mock('@/lib/query-client', () => ({invalidateProfileScopedQueries: vi.fn()}))+vi.mock(import('@/store/profile'), async importOriginal => {+ const actual = await importOriginal()++ return {+ ...actual,+ invalidateProfileListFetches: vi.fn()+ }+})++const { invalidateProfileListFetches } = await import('@/store/profile')+describe('wipeSessionListsForGatewaySwitch', () => {beforeEach(() => {$gatewaySwitching.set(false)@@ -58,4 +69,13 @@ describe('wipeSessionListsForGatewaySwitch', () => {expect($sessionsLimit.get()).toBe(SIDEBAR_SESSIONS_PAGE_SIZE)expect($freshDraftReady.get()).toBe(true)})++ it('strands in-flight profile-list fetches so the old backend cannot repaint the rail (#85731)', () => {+ // The soft re-home moves /api/profiles routing to the NEW backend; a+ // response still in flight from the previous one must be invalidated+ // here, in the same wipe every connection/mode apply funnels through.+ wipeSessionListsForGatewaySwitch()++ expect(invalidateProfileListFetches).toHaveBeenCalled()+ })})diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.tsindex 3003be4b32e..6c08cec5352 100644--- a/apps/desktop/src/store/gateway-switch.ts+++ b/apps/desktop/src/store/gateway-switch.ts@@ -6,6 +6,7 @@ import { invalidateProfileScopedQueries } from '@/lib/query-client'import { clearArtifactRegistry } from '@/store/artifacts'import { resetSessionsLimit } from '@/store/layout'import { resetLiveSync } from '@/store/live-sync'+import { invalidateProfileListFetches } from '@/store/profile'import {$unreadFinishedSessionIds,setActiveSessionId,@@ -45,6 +46,12 @@ export function wipeSessionListsForGatewaySwitch(): void {// The next backend is a different runtime — don't carry the old one's// "batched sidebar endpoint missing" capability verdict across the switch.resetSidebarBatchCapability()+ // Strand any in-flight /api/profiles fetch from the PREVIOUS backend. The+ // rail's $profiles cache is deliberately NOT wiped (an empty list flickers+ // the rail away), but a late response from the old backend must not+ // overwrite what the new backend reports — that stale write is how a+ // remote/Cloud connection apply made the profile rail vanish (#85731).+ invalidateProfileListFetches()// Pins are mirrored per-backend. The next gateway has its own state.db and// has never seen them, so drop the "already pushed" bookkeeping and let the// next reconcile re-assert the whole set against the new backend.diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.tsindex fbf99396436..14d6de5f0a2 100644--- a/apps/desktop/src/store/profile.test.ts+++ b/apps/desktop/src/store/profile.test.ts@@ -20,7 +20,7 @@ vi.mock('@/hermes', () => ({vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))-const { $activeGatewayProfile, $profiles, ensureGatewayProfile, prewarmProfileBackend, refreshProfiles } =+const { $activeGatewayProfile, $profiles, ensureGatewayProfile, invalidateProfileListFetches, prewarmProfileBackend, refreshProfiles } =await import('./profile')const { $connection } = await import('./session')@@ -173,3 +173,67 @@ describe('refreshProfiles shared rail list (#49289)', () => {expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'test1'])})})++describe('stale profile-list fetches across a backend switch (#85731)', () => {+ it('a late response from the previous backend cannot clobber the new backend list', async () => {+ // The disappearing-rail mechanism: /api/profiles is in flight against+ // backend A when the user applies a different remote/Cloud connection.+ // The soft re-home fetches backend B's list, then A's late (often empty /+ // default-only) response lands LAST and collapses the rail.+ let resolveOld: (value: { profiles: ProfileInfo[] }) => void = () => undefined+ vi.mocked(getProfiles).mockImplementationOnce(+ () => new Promise(resolve => (resolveOld = resolve))+ )++ const oldFetch = refreshProfiles() // in flight against backend A++ // Connection apply → soft re-home strands in-flight fetches...+ invalidateProfileListFetches()++ // ...and the new backend's list arrives.+ vi.mocked(getProfiles).mockResolvedValueOnce({+ profiles: [profile('default', true), profile('eric'), profile('coder')]+ })+ await refreshProfiles()+ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'eric', 'coder'])++ // Backend A's stale response finally lands: it must NOT overwrite $profiles.+ resolveOld({ profiles: [profile('default', true)] })+ await oldFetch++ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'eric', 'coder'])+ })++ it('a normal refresh still writes the cache after prior invalidations', async () => {+ invalidateProfileListFetches()+ vi.mocked(getProfiles).mockResolvedValueOnce({ profiles: [profile('default', true), profile('solo')] })++ await refreshProfiles()++ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'solo'])+ })++ it('strands in-flight fetches when the active gateway profile swaps backends', async () => {+ // Sibling site of the same class: a live profile swap moves /api/profiles+ // routing to another backend mid-fetch. The $activeGatewayProfile+ // subscriber must bump the epoch exactly like the connection-apply wipe.+ let resolveOld: (value: { profiles: ProfileInfo[] }) => void = () => undefined+ vi.mocked(getProfiles).mockImplementationOnce(+ () => new Promise(resolve => (resolveOld = resolve))+ )++ const oldFetch = refreshProfiles() // in flight against the old profile's backend++ $activeGatewayProfile.set('coder') // swap → subscriber invalidates++ vi.mocked(getProfiles).mockResolvedValueOnce({+ profiles: [profile('default', true), profile('coder')]+ })+ await refreshProfiles()++ resolveOld({ profiles: [] })+ await oldFetch++ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'coder'])+ })+})diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex a844598be49..99fd3dd7054 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -39,9 +39,29 @@ export function setActiveProfile(name: string): void {$activeProfile.set(name || 'default')}+// ── Stale-fetch invalidation across backend switches ───────────────────────+// $profiles mirrors the ACTIVE backend's /api/profiles. A connection/mode+// apply (the soft re-home) or a profile/agent activation changes which backend+// that is while a fetch may still be in flight — and a late response from the+// PREVIOUS backend must not clobber the list the new backend just served.+// That was #85731's disappearing rail: applying a different remote/Cloud+// connection let the old (often dying, profile-less) backend's response land+// last, collapsing $profiles and hiding the rail. Bumping the epoch strands+// every in-flight fetch: the response still resolves for its caller, but it+// no longer writes the shared cache ("guard against the past").+let profileListEpoch = 0++export function invalidateProfileListFetches(): void {+ profileListEpoch += 1+}+export async function refreshProfiles(): Promise<ProfileInfo[]> {+ const epoch = profileListEpochconst { profiles } = await getProfiles()- $profiles.set(profiles)++ if (epoch === profileListEpoch) {+ $profiles.set(profiles)+ }return profiles}@@ -110,13 +130,19 @@ interface ActiveProfileResponse {// Pull the running backend's current profile + the available profile list.// Best-effort: failures (backend not up yet) leave the prior values intact.export async function refreshActiveProfile(): Promise<void> {+ const epoch = profileListEpoch+try {const res = await window.hermesDesktop.api<ActiveProfileResponse>({path: '/api/profiles/active',timeoutMs: STARTUP_REQUEST_TIMEOUT_MS})- setActiveProfile(res.current || 'default')+ // Same stale-response guard as refreshProfiles: a backend switch mid-fetch+ // means this answer describes the PREVIOUS backend.+ if (epoch === profileListEpoch) {+ setActiveProfile(res.current || 'default')+ }} catch {// Backend may not be ready; keep the last known value.}@@ -183,6 +209,10 @@ $activeGatewayProfile.subscribe(value => {// every profile switch.invalidateProfileScopedQueries()resetStarmapGraph()+ // /api/profiles now routes to a different backend: strand any in-flight+ // profile-list fetch so the previous backend's late answer can't clobber+ // the rail (the #85731 class — same guard as the connection-apply wipe).+ invalidateProfileListFetches()}_lastRoutedProfile = key