Skip to content

The agent that grows with you

fix(desktop): commit gateway switches before publishing the new source (#93937)

Zeus-Deus5472d1d66c09
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.tsx
index 4b4a044f469..002d6293ac6 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
@@ -1,11 +1,27 @@
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { DesktopConnectionsRegistry } from '@/global'
import { $desktopBoot } from '@/store/boot'
+import {
+ $connectionsRegistry,
+ _resetConnectionsForTests,
+ selectConnection,
+ setConnectionsRegistry
+} from '@/store/connections'
import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'
import { reconnectGateway } from '@/store/gateway-reconnect'
+import { $gatewaySwitching, beginGatewaySwitch, endGatewaySwitch } from '@/store/gateway-switch'
import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'
-import { $connection, $currentCwd, $gatewayState } from '@/store/session'
+import {
+ $activeSessionId,
+ $connection,
+ $currentCwd,
+ $gatewayState,
+ $selectedStoredSessionId,
+ setActiveSessionId,
+ setSelectedStoredSessionId
+} from '@/store/session'
import { $sessionTiles } from '@/store/session-states'
import { takeGatewaySurvivor } from './gateway-hmr-survivor'
@@ -277,6 +293,11 @@ afterEach(() => {
$connection.set(null)
$profiles.set([])
$sessionTiles.set([])
+ _resetConnectionsForTests()
+ $connectionsRegistry.set(null)
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ endGatewaySwitch()
vi.useRealTimers()
;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket
delete (window as { hermesDesktop?: unknown }).hermesDesktop
@@ -350,6 +371,107 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($gatewayState.get()).toBe('open')
})
+ it('a store-driven switch (Sessions switcher) runs the same machine-context reset as a Settings apply (#93937)', async () => {
+ const beforeConnectionSwitch = vi.fn()
+ const { unmount } = render(<Harness beforeConnectionSwitch={beforeConnectionSwitch} />)
+ await flushAsync()
+
+ act(() => beginGatewaySwitch())
+ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
+ expect($gatewaySwitching.get()).toBe(true)
+ act(() => endGatewaySwitch())
+ expect($gatewaySwitching.get()).toBe(false)
+
+ // Teardown unregisters: a switch after unmount must not call a dead host.
+ unmount()
+ beginGatewaySwitch()
+ endGatewaySwitch()
+ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
+ })
+
+ it("#93937: the Sessions switcher never publishes the new source while the previous backend's runtime id is still bound", async () => {
+ // Real stores end to end: real useGatewayBoot, real gateway registry, real
+ // selectConnection, fake sockets. Boot on the primary VPS with a transcript
+ // open (its runtime id was minted by THAT backend), then switch sources
+ // through the sidebar door. Before the fix that door activated the new
+ // socket first and wiped the bindings after an IPC round-trip, so the
+ // renderer sat on "gateway B + runtime id from A" and B answered every
+ // session RPC with "session not found".
+ const registryConnections: DesktopConnectionsRegistry = {
+ connections: [
+ { id: 'primary-vps', kind: 'remote', label: 'VPS', tokenPreview: '...t', tokenSet: true },
+ { id: 'coder-remote', kind: 'remote', label: 'Coder', tokenPreview: '...c', tokenSet: true }
+ ],
+ primary: 'primary-vps',
+ secureTokenStorage: true,
+ version: 2
+ }
+
+ const desktop = fakeDesktop() as ReturnType<typeof fakeDesktop> & Record<string, unknown>
+ const setLastUsed = vi.fn(async (id: string) => ({ ok: true, registry: { ...registryConnections, lastUsed: id } }))
+ let bindingAtDial: null | string = null
+
+ desktop.api = vi.fn(async ({ path }: { path: string }) =>
+ path === '/api/profiles/active' ? { active: 'default', current: 'default' } : { profiles: [] }
+ )
+ desktop.getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
+ ...coderConn,
+ connectionId,
+ profile,
+ registryScoped: true
+ }))
+ desktop.getGatewayWsUrlFor = vi.fn(async () => {
+ // Phase 1 (the dial) runs with the previous source still fully bound.
+ bindingAtDial = $activeSessionId.get()
+
+ return coderConn.wsUrl
+ })
+ desktop.connections = { list: vi.fn(async () => registryConnections), setLastUsed }
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+
+ const beforeConnectionSwitch = vi.fn()
+ render(<Harness beforeConnectionSwitch={beforeConnectionSwitch} />)
+ await flushAsync()
+ expect($gatewayState.get()).toBe('open')
+ expect($connection.get()?.connectionId).toBe('primary-vps')
+
+ setConnectionsRegistry(registryConnections)
+ setSelectedStoredSessionId('stored-on-vps')
+ setActiveSessionId('a93bb39d')
+
+ // Every instant the new source is visible, with what a session-scoped
+ // effect would read right then.
+ const published: Array<{ activeSessionId: null | string; switching: boolean }> = []
+
+ const off = $connection.listen(next => {
+ if (next?.connectionId === 'coder-remote') {
+ published.push({ activeSessionId: $activeSessionId.get(), switching: $gatewaySwitching.get() })
+ }
+ })
+
+ const switching = selectConnection('coder-remote')
+ await flushAsync()
+ await flushAsync()
+ await flushAsync()
+ await switching
+ off()
+
+ // The previous backend's runtime id was already gone — and the barrier up —
+ // at every publication of the new source. (Pre-fix: the first publication
+ // carried activeSessionId 'a93bb39d' with the barrier down.)
+ expect(published.length).toBeGreaterThan(0)
+ expect(published).toEqual(published.map(() => ({ activeSessionId: null, switching: true })))
+ expect(bindingAtDial).toBe('a93bb39d')
+ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
+ expect($connection.get()?.connectionId).toBe('coder-remote')
+ expect(isActivePrimary()).toBe(false)
+ expect($activeSessionId.get()).toBeNull()
+ expect($selectedStoredSessionId.get()).toBeNull()
+ expect($gatewaySwitching.get()).toBe(false)
+ // The switch committed: the registry remembers the new source as last-used.
+ expect(setLastUsed).toHaveBeenCalledWith('coder-remote')
+ })
+
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
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index 8c0e88643aa..a27318d6c43 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -31,7 +31,12 @@ import {
touchSecondaryGateways
} from '@/store/gateway'
import { registerGatewayReconnect } from '@/store/gateway-reconnect'
-import { $gatewaySwitching, wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'
+import {
+ $gatewaySwitching,
+ beginGatewaySwitch,
+ endGatewaySwitch,
+ registerGatewaySwitchLifecycle
+} from '@/store/gateway-switch'
import { notify, notifyError } from '@/store/notifications'
import {
$activeGatewayProfile,
@@ -190,6 +195,15 @@ export function useGatewayBoot({
return () => void (cancelled = true)
}
+ // Store-driven switches (Sessions switcher → selectConnection) commit
+ // through beginGatewaySwitch(), which runs this window's machine-context
+ // reset — the same one a Settings apply (softSwitch below) runs. One owner,
+ // one reset, so the two doors can't drift apart again (#93937).
+ const offSwitchLifecycle = registerGatewaySwitchLifecycle({
+ beforeConnectionSwitch: () => callbacksRef.current.beforeConnectionSwitch(),
+ refreshSessions: () => callbacksRef.current.refreshSessions()
+ })
+
// --- Reconnect-after-sleep machinery -------------------------------------
// macOS sleep silently drops the renderer's WebSocket. The backend Python
// process keeps running, but nothing re-opened the socket on wake, so the
@@ -477,7 +491,9 @@ export function useGatewayBoot({
return
}
- $gatewaySwitching.set(true)
+ // Barrier up + machine-context reset + session wipe, in one synchronous
+ // step — the shared commit point of every connection switch.
+ beginGatewaySwitch()
clearReconnectTimer()
clearBootRetryTimer()
bootRetryAttempt = 0
@@ -485,8 +501,6 @@ export function useGatewayBoot({
reconnectFailingSince = null
escalated = false
reauthNotified = false
- callbacksRef.current.beforeConnectionSwitch()
- wipeSessionListsForGatewaySwitch()
try {
gateway.close()
@@ -541,7 +555,7 @@ export function useGatewayBoot({
setSessionsLoading(false)
}
} finally {
- $gatewaySwitching.set(false)
+ endGatewaySwitch()
}
}
@@ -923,7 +937,8 @@ export function useGatewayBoot({
return () => {
cancelled = true
- $gatewaySwitching.set(false)
+ offSwitchLifecycle()
+ endGatewaySwitch()
clearReconnectTimer()
clearBootRetryTimer()
clearInterval(keepaliveTimer)
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 59e840f16dd..5ff10c748fd 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -14,19 +14,45 @@ const $connection = atom<null | {
registryScoped?: boolean
}>(null)
+// The runtime session id minted by the CURRENT backend — the binding a switch
+// must sever before the next source is published (#93937).
+const $activeSessionId = atom<null | string>(null)
+const $gatewaySwitching = atom(false)
+
const ensureGatewayAgent = vi.fn(async (_connectionId: null | string, _profile: string): Promise<void> => undefined)
+const openGatewayAgent = vi.fn(async (_connectionId: string, _profile: string): Promise<void> => undefined)
const refreshActiveProfile = vi.fn(async () => undefined)
const requestFreshSession = vi.fn()
-const wipeSessionListsForGatewaySwitch = vi.fn()
+const beforeConnectionSwitch = vi.fn()
+const wipeSessionListsForGatewaySwitch = vi.fn(() => $activeSessionId.set(null))
+
+// Test double for the store's commit point with the real one's contract
+// (barrier → machine-context reset → wipe, synchronously); the real
+// implementation is covered by gateway-switch.test.ts.
+const beginGatewaySwitch = vi.fn(() => {
+ $gatewaySwitching.set(true)
+ beforeConnectionSwitch()
+ wipeSessionListsForGatewaySwitch()
+})
+
+const endGatewaySwitch = vi.fn(() => $gatewaySwitching.set(false))
+const recoverActiveSourceAfterFailedGatewaySwitch = vi.fn()
vi.mock('@/store/session', () => ({ $connection }))
-vi.mock('@/store/gateway-switch', () => ({ wipeSessionListsForGatewaySwitch }))
+vi.mock('@/store/gateway-switch', () => ({
+ $gatewaySwitching,
+ beginGatewaySwitch,
+ endGatewaySwitch,
+ recoverActiveSourceAfterFailedGatewaySwitch,
+ wipeSessionListsForGatewaySwitch
+}))
vi.mock('@/store/profile', () => ({
$activeGatewayProfile,
$newChatProfile,
$showAllProfiles,
ensureGatewayAgent,
normalizeProfileKey: (name: null | string | undefined) => (name ?? '').trim() || 'default',
+ openGatewayAgent,
refreshActiveProfile,
requestFreshSession
}))
@@ -73,9 +99,17 @@ beforeEach(() => {
registryScoped: true
})
})
+ openGatewayAgent.mockReset()
+ openGatewayAgent.mockResolvedValue(undefined)
refreshActiveProfile.mockClear()
requestFreshSession.mockClear()
+ beforeConnectionSwitch.mockClear()
+ beginGatewaySwitch.mockClear()
+ endGatewaySwitch.mockClear()
+ recoverActiveSourceAfterFailedGatewaySwitch.mockClear()
wipeSessionListsForGatewaySwitch.mockClear()
+ $activeSessionId.set(null)
+ $gatewaySwitching.set(false)
list.mockClear()
setLastUsed.mockClear()
vi.stubGlobal('window', { hermesDesktop: { connections: { list, setLastUsed } }, localStorage })
@@ -144,7 +178,9 @@ describe('selectConnection', () => {
await selectConnection('homelab')
+ expect(openGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
+ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
expect(requestFreshSession).toHaveBeenCalledTimes(1)
expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
expect($newChatProfile.get()).toBe('default')
@@ -172,37 +208,38 @@ describe('selectConnection', () => {
})
it('lets a later source choice win while an earlier dial is still pending', async () => {
- let releaseHomelab!: () => void
+ let releaseDials!: () => void
- const homelabGate = new Promise<void>(resolve => {
- releaseHomelab = resolve
+ const dialGate = new Promise<void>(resolve => {
+ releaseDials = resolve
})
setConnectionsRegistry(registry)
$connection.set({ connectionId: 'local', mode: 'local' })
- ensureGatewayAgent.mockImplementationOnce(async () => {
- await homelabGate
- $connection.set({ connectionId: 'homelab', mode: 'remote' })
- })
- ensureGatewayAgent.mockImplementationOnce(async () => {
- await homelabGate
- $connection.set({ connectionId: 'local', mode: 'local' })
+ openGatewayAgent.mockImplementation(async () => {
+ await dialGate
})
const openHomelab = selectConnection('homelab')
await Promise.resolve()
const stayLocal = selectConnection('local')
- releaseHomelab()
+ releaseDials()
await Promise.all([openHomelab, stayLocal])
- expect(ensureGatewayAgent.mock.calls).toEqual([
+ expect(openGatewayAgent.mock.calls).toEqual([
['homelab', 'default'],
['local', 'default']
])
+ // The superseded dial never activates: the user doesn't flip through
+ // homelab on the way back to local, and only the winner commits.
+ expect(ensureGatewayAgent.mock.calls).toEqual([['local', 'default']])
+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
// Only the latest intent repaints the profile list.
expect(refreshActiveProfile).toHaveBeenCalledTimes(1)
- expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect($connection.get()?.connectionId).toBe('local')
+ expect($gatewaySwitching.get()).toBe(false)
})
it('restores the last profile used on each source', async () => {
@@ -240,18 +277,90 @@ describe('selectConnection', () => {
expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'default')
})
- it('keeps the current source usable when a dial fails', async () => {
+ it('keeps the current source usable when a dial fails: nothing is severed before the target is reachable', async () => {
setConnectionsRegistry(registry)
$connection.set({ connectionId: 'local', mode: 'local' })
- ensureGatewayAgent.mockRejectedValueOnce(new Error('offline'))
+ $activeSessionId.set('a93bb39d')
+ openGatewayAgent.mockRejectedValueOnce(new Error('offline'))
await expect(selectConnection('homelab')).rejects.toThrow('offline')
- expect(requestFreshSession).not.toHaveBeenCalled()
+ // The dial failed in phase 1 — the switch never committed, so the open
+ // transcript, its runtime binding and the session lists are all intact.
+ expect(ensureGatewayAgent).not.toHaveBeenCalled()
+ expect(beginGatewaySwitch).not.toHaveBeenCalled()
+ expect(beforeConnectionSwitch).not.toHaveBeenCalled()
expect(wipeSessionListsForGatewaySwitch).not.toHaveBeenCalled()
+ expect($activeSessionId.get()).toBe('a93bb39d')
+ expect($gatewaySwitching.get()).toBe(false)
+ expect(requestFreshSession).not.toHaveBeenCalled()
expect($newChatProfile.get()).toBeNull()
expect($pendingConnectionId.get()).toBeNull()
expect(setLastUsed).not.toHaveBeenCalled()
+ expect($connection.get()?.connectionId).toBe('local')
+ })
+
+ it('an activation that does not land after the wipe lowers the barrier and repaints the still-active source', async () => {
+ setConnectionsRegistry(registry)
+ $connection.set({ connectionId: 'local', mode: 'local' })
+ // The dial opened the socket but the activation was declined (source
+ // edited/removed mid-switch): $connection never moves to homelab.
+ ensureGatewayAgent.mockImplementationOnce(async () => undefined)
+
+ await expect(selectConnection('homelab')).rejects.toThrow('did not become active')
+
+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect(endGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect($gatewaySwitching.get()).toBe(false)
+ // The lists were wiped for a commit that never happened; the source that
+ // is still active gets repainted and the user lands on a fresh draft there.
+ expect(recoverActiveSourceAfterFailedGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect(requestFreshSession).toHaveBeenCalledTimes(1)
+ expect(setLastUsed).not.toHaveBeenCalled()
+ expect($newChatProfile.get()).toBeNull()
+ expect($pendingConnectionId.get()).toBeNull()
+ expect($connection.get()?.connectionId).toBe('local')
+ })
+
+ it("#93937: severs the previous source's runtime session binding BEFORE the new source is published, behind the barrier", async () => {
+ setConnectionsRegistry(registry)
+ $connection.set({ connectionId: 'local', mode: 'local' })
+ // Runtime id minted by the local backend; only local has ever heard of it.
+ $activeSessionId.set('a93bb39d')
+
+ // Phase 1 (the dial) must not touch the current workspace at all.
+ openGatewayAgent.mockImplementationOnce(async () => {
+ expect($activeSessionId.get()).toBe('a93bb39d')
+ expect($gatewaySwitching.get()).toBe(false)
+ expect(wipeSessionListsForGatewaySwitch).not.toHaveBeenCalled()
+ })
+
+ // Every publication of the new source, with what a session-scoped effect
+ // would read at that instant.
+ const published: Array<{ activeSessionId: null | string; connectionId?: string; switching: boolean }> = []
+
+ const off = $connection.listen(next => {
+ published.push({
+ activeSessionId: $activeSessionId.get(),
+ connectionId: next?.connectionId,
+ switching: $gatewaySwitching.get()
+ })
+ })
+
+ await selectConnection('homelab')
+ off()
+
+ // The old runtime id was already gone when homelab became visible, and
+ // the barrier was up — nothing could pair 'a93bb39d' with the new backend.
+ expect(published).toEqual([{ activeSessionId: null, connectionId: 'homelab', switching: true }])
+ // dial → commit (barrier + reset + wipe) → activate, in that order.
+ expect(openGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
+ expect(openGatewayAgent.mock.invocationCallOrder[0]).toBeLessThan(beginGatewaySwitch.mock.invocationCallOrder[0])
+ expect(beginGatewaySwitch.mock.invocationCallOrder[0]).toBeLessThan(ensureGatewayAgent.mock.invocationCallOrder[0])
+ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
+ expect(endGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect($gatewaySwitching.get()).toBe(false)
+ expect($activeSessionId.get()).toBeNull()
})
it('boot-time restore leaves "All profiles" browse mode on (#93197)', async () => {
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index 472f5b59ec5..d8a1c0e6cd4 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -2,13 +2,18 @@ import { atom, computed } from 'nanostores'
import type { DesktopConnectionsRegistry } from '@/global'
import { persistStringRecord, storedStringRecord } from '@/lib/storage'
-import { wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'
+import {
+ beginGatewaySwitch,
+ endGatewaySwitch,
+ recoverActiveSourceAfterFailedGatewaySwitch
+} from '@/store/gateway-switch'
import {
$activeGatewayProfile,
$newChatProfile,
$showAllProfiles,
ensureGatewayAgent,
normalizeProfileKey,
+ openGatewayAgent,
refreshActiveProfile,
requestFreshSession
} from '@/store/profile'
@@ -160,6 +165,17 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection
* Re-home Sessions to one registered source, restoring that source's last
* profile. Only the selected source is dialed; merely rendering the switcher
* never probes or opens remote gateways.
+ *
+ * Two phases, same commit contract as a Settings → Gateway apply (softSwitch):
+ * 1. Dial the target WITHOUT activating it. The previous source stays fully
+ * bound and painted, so a dead target fails with nothing lost.
+ * 2. beginGatewaySwitch() — barrier up, machine-context reset, session
+ * bindings wiped — then activate the already-open socket. Nothing awaits
+ * between the wipe and the publication, so no route/session effect can
+ * observe the new source while $activeSessionId still names the previous
+ * backend's runtime. Activating first and wiping after (across an IPC
+ * round-trip) is exactly how that id leaked to the new backend and came
+ * back as "session not found" (#93937).
*/
export async function selectConnection(connectionId: string): Promise<void> {
const registry = $connectionsRegistry.get()
@@ -210,12 +226,39 @@ export async function selectConnection(connectionId: string): Promise<void> {
$pendingConnectionId.set(connectionId)
try {
+ // Phase 1 — open the target's socket; the active route is untouched.
// Always use the explicit registry route. `local` must mean This device,
// and a registry primary can differ from a legacy per-profile override.
- await ensureGatewayAgent(connectionId, targetProfile)
+ await openGatewayAgent(connectionId, targetProfile)
+
+ // A newer click owns the switch from here on. The superseded dial never
+ // activates, so the user doesn't flip through it on the way to the source
+ // they picked last; its socket stays warm for that click or idles out.
+ if (revision !== switchRevision) {
+ return
+ }
+
+ // Phase 2 — commit: sever the previous backend's bindings FIRST, then
+ // activate. Synchronous from the wipe to the publication (the socket is
+ // already open), and behind the barrier until the descriptor lands.
+ beginGatewaySwitch()
- if ($connection.get()?.connectionId !== connectionId) {
- throw new Error(`Connection "${targetConnection.label}" did not become active.`)
+ try {
+ await ensureGatewayAgent(connectionId, targetProfile)
+
+ if ($connection.get()?.connectionId !== connectionId) {
+ throw new Error(`Connection "${targetConnection.label}" did not become active.`)
+ }
+ } catch (error) {
+ // The wipe already happened but the previous source is still the active
+ // one, and nothing reactive re-pulls its lists (no scope moved). Repaint
+ // it and land on a fresh draft there, matching what a failed Settings
+ // apply leaves behind.
+ recoverActiveSourceAfterFailedGatewaySwitch()
+ requestFreshSession()
+ throw error
+ } finally {
+ endGatewaySwitch()
}
// A newer click owns the final refresh. Serialized gateway activation
@@ -223,7 +266,6 @@ export async function selectConnection(connectionId: string): Promise<void> {
// request from repainting its profile list after that newer activation.
if (revision === switchRevision) {
await rememberConnection(connectionId)
- wipeSessionListsForGatewaySwitch()
if (!restoreOnBoot) {
$showAllProfiles.set(false)
diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.ts
index 6bb3612aee4..c1a29540710 100644
--- a/apps/desktop/src/store/gateway-connection-scope.test.ts
+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts
@@ -105,6 +105,18 @@ describe('pruneSecondaryGateways with registry-scoped entries', () => {
expect(gatewayMocks.closed).toEqual(['wss://homelab.invalid/api/ws?profile=default'])
})
+ it('a switch-phase dial (activationLease) survives a live-work recompute until its activation lands', async () => {
+ // Phase one of the Sessions-switcher source switch: the target is opened
+ // but not yet active and has no live work of its own. Another source's
+ // streaming turn recomputes the keep-set mid-dial — that must not dispose
+ // the socket the switch is about to activate (#89622 via #93937).
+ await openGatewayForAgent('homelab', 'default', { activationLease: true })
+
+ pruneSecondaryGateways(new Set(['default']))
+
+ expect(gatewayMocks.closed).toEqual([])
+ })
+
it('keeps a registry socket whose composite scope has live work', async () => {
await openGatewayForAgent('homelab', 'default')
diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.ts
index 7610d3a8c22..e08adcc1ea2 100644
--- a/apps/desktop/src/store/gateway-switch.test.ts
+++ b/apps/desktop/src/store/gateway-switch.test.ts
@@ -2,12 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { $sessionsLimit, resetSessionsLimit, SIDEBAR_SESSIONS_PAGE_SIZE } from '@/store/layout'
import {
+ $activeSessionId,
$cronSessions,
$freshDraftReady,
$messagingSessions,
$sessionProfilesTruncated,
$sessions,
$sessionsLoading,
+ setActiveSessionId,
setCronSessions,
setFreshDraftReady,
setMessagingSessions,
@@ -17,7 +19,14 @@ import {
} from '@/store/session'
import { $stalledSessionIds } from '@/store/session-states'
-import { $gatewaySwitching, wipeSessionListsForGatewaySwitch } from './gateway-switch'
+import {
+ $gatewaySwitching,
+ beginGatewaySwitch,
+ endGatewaySwitch,
+ recoverActiveSourceAfterFailedGatewaySwitch,
+ registerGatewaySwitchLifecycle,
+ wipeSessionListsForGatewaySwitch
+} from './gateway-switch'
vi.mock('@/lib/query-client', () => ({
invalidateProfileScopedQueries: vi.fn()
@@ -79,3 +88,120 @@ describe('wipeSessionListsForGatewaySwitch', () => {
expect(invalidateProfileListFetches).toHaveBeenCalled()
})
})
+
+describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit point (#93937)', () => {
+ beforeEach(() => {
+ $gatewaySwitching.set(false)
+ setSessions([{ id: 's1', title: 'old', profile: 'default' } as never])
+ setActiveSessionId('a93bb39d')
+ setSessionsLoading(false)
+ })
+
+ afterEach(() => {
+ setSessions([])
+ setActiveSessionId(null)
+ setSessionsLoading(true)
+ $gatewaySwitching.set(false)
+ })
+
+ it('raises the barrier, runs the registered machine-context reset, then wipes — synchronously, in that order', () => {
+ const seen: string[] = []
+
+ const off = registerGatewaySwitchLifecycle({
+ beforeConnectionSwitch: () => {
+ // The reset runs behind the barrier and BEFORE the wipe: it may still
+ // read the outgoing session (to fresh-draft it), never a half-wiped one.
+ seen.push(
+ `switching=${$gatewaySwitching.get()} active=${$activeSessionId.get()} rows=${$sessions.get().length}`
+ )
+ },
+ refreshSessions: async () => undefined
+ })
+
+ beginGatewaySwitch()
+
+ expect(seen).toEqual(['switching=true active=a93bb39d rows=1'])
+ expect($gatewaySwitching.get()).toBe(true)
+ // The previous backend's runtime binding is gone before anything can dial.
+ expect($activeSessionId.get()).toBeNull()
+ expect($sessions.get()).toEqual([])
+ expect($sessionsLoading.get()).toBe(true)
+
+ endGatewaySwitch()
+ expect($gatewaySwitching.get()).toBe(false)
+ off()
+ })
+
+ it('still severs the bindings when no lifecycle is registered (windows that never mount the boot hook)', () => {
+ beginGatewaySwitch()
+
+ expect($gatewaySwitching.get()).toBe(true)
+ expect($activeSessionId.get()).toBeNull()
+ expect($sessions.get()).toEqual([])
+
+ endGatewaySwitch()
+ expect($gatewaySwitching.get()).toBe(false)
+ })
+
+ it('an unregistered lifecycle no longer runs, and a stale unregister cannot evict a newer one', () => {
+ const first = vi.fn()
+ const second = vi.fn()
+
+ const offFirst = registerGatewaySwitchLifecycle({
+ beforeConnectionSwitch: first,
+ refreshSessions: async () => undefined
+ })
+
+ const offSecond = registerGatewaySwitchLifecycle({
+ beforeConnectionSwitch: second,
+ refreshSessions: async () => undefined
+ })
+
+ // Stale unregister from the older host: the newer registration stays.
+ offFirst()
+ beginGatewaySwitch()
+ endGatewaySwitch()
+
+ expect(first).not.toHaveBeenCalled()
+ expect(second).toHaveBeenCalledTimes(1)
+
+ offSecond()
+ beginGatewaySwitch()
+ endGatewaySwitch()
+
+ expect(second).toHaveBeenCalledTimes(1)
+ })
+
+ it('recoverActiveSourceAfterFailedGatewaySwitch re-pulls the still-active source and disarms the skeleton', async () => {
+ const refreshSessions = vi.fn(async () => undefined)
+ const off = registerGatewaySwitchLifecycle({ beforeConnectionSwitch: () => undefined, refreshSessions })
+
+ beginGatewaySwitch()
+ expect($sessionsLoading.get()).toBe(true)
+
+ recoverActiveSourceAfterFailedGatewaySwitch()
+ endGatewaySwitch()
+ await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
+
+ expect(refreshSessions).toHaveBeenCalledTimes(1)
+ off()
+ })
+
+ it('a failing repaint (or none registered) still disarms the skeleton', async () => {
+ const off = registerGatewaySwitchLifecycle({
+ beforeConnectionSwitch: () => undefined,
+ refreshSessions: async () => {
+ throw new Error('backend busy')
+ }
+ })
+
+ setSessionsLoading(true)
+ recoverActiveSourceAfterFailedGatewaySwitch()
+ await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
+ off()
+
+ setSessionsLoading(true)
+ recoverActiveSourceAfterFailedGatewaySwitch()
+ await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
+ })
+})
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index d166071f791..681445f1d71 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -27,11 +27,75 @@ import { resetSessionPinMirror } from '@/store/session-pin-sync'
import { clearAllSessionStates } from '@/store/session-states'
import { clearTranscriptTails } from '@/store/transcript-tail-cache'
-// True while a soft gateway-mode apply is mid-flight (wipe → re-dial). Lets the
-// boot hook suppress the backend-exit toast and keeps the cold-boot CONNECTING
-// overlay from resurrecting when startHermes re-emits boot progress.
+// True while a connection switch is mid-flight — a Settings → Gateway apply
+// (wipe → re-dial, use-gateway-boot softSwitch) or a Sessions-switcher source
+// change (store/connections selectConnection). Lets the boot hook suppress the
+// backend-exit toast, keeps the cold-boot CONNECTING overlay from resurrecting
+// when startHermes re-emits boot progress, and tells the resume path that a
+// "session not found" mid-switch means "retry once things settle", not "gone".
export const $gatewaySwitching = atom(false)
+/**
+ * Renderer-side cleanup a connection switch must run before the next gateway
+ * is activated or published: fresh-draft the open transcript, drop the overlay
+ * return route, reset the project tree, close terminals — everything bound to
+ * the OUTGOING backend that lives outside the session store. Registered by
+ * useGatewayBoot (whose host owns those React callbacks) so store-driven
+ * switches run the exact same reset as a Settings → Gateway apply.
+ */
+export interface GatewaySwitchLifecycle {
+ beforeConnectionSwitch: () => void
+ /** Re-pull the session lists from whichever backend is active NOW. */
+ refreshSessions: () => Promise<void>
+}
+
+let switchLifecycle: GatewaySwitchLifecycle | null = null
+
+export function registerGatewaySwitchLifecycle(lifecycle: GatewaySwitchLifecycle): () => void {
+ switchLifecycle = lifecycle
+
+ return () => {
+ if (switchLifecycle === lifecycle) {
+ switchLifecycle = null
+ }
+ }
+}
+
+/**
+ * Commit point of every connection switch: raise the barrier and sever every
+ * binding to the outgoing backend in ONE synchronous step. Both switch doors —
+ * Settings apply (softSwitch) and the Sessions switcher (selectConnection) —
+ * must call this BEFORE the next gateway is activated or its descriptor
+ * published. The sidebar door used to activate first and wipe afterwards
+ * (across an IPC round-trip), so route/session effects saw the new source while
+ * $activeSessionId still named the previous backend's runtime and sent that id
+ * to a backend that had never minted it — "session not found" (#93937).
+ */
+export function beginGatewaySwitch(): void {
+ $gatewaySwitching.set(true)
+ switchLifecycle?.beforeConnectionSwitch()
+ wipeSessionListsForGatewaySwitch()
+}
+
+/** Lower the barrier once the switch has committed (or failed). */
+export function endGatewaySwitch(): void {
+ $gatewaySwitching.set(false)
+}
+
+/**
+ * A commit that fails AFTER beginGatewaySwitch leaves the still-active source
+ * with its lists wiped and the sidebar skeleton armed, and nothing reactive
+ * re-pulls them (no source/profile scope moved). Repaint it explicitly so the
+ * sidebar doesn't sit on the skeleton; the fetch is best-effort, the skeleton
+ * always disarms.
+ */
+export function recoverActiveSourceAfterFailedGatewaySwitch(): void {
+ void Promise.resolve()
+ .then(() => switchLifecycle?.refreshSessions())
+ .catch(() => undefined)
+ .finally(() => setSessionsLoading(false))
+}
+
/**
* Clear gateway-bound session UI so sidebar skeletons retrigger.
*
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 1f578ecd609..efb72c7a9e4 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -865,7 +865,18 @@ export async function openGatewayForProfile(profile: string): Promise<void> {
// routing. Feature-detected: without the Electron getConnectionFor door these
// throw, and roster surfaces disable non-local rows instead.
-export async function openGatewayForAgent(connectionId: null | string, profile: string): Promise<void> {
+// `activationLease`: hold the same prune lease ensureGatewayForAgent holds for
+// the whole dial. Phase one of the two-phase source switch (store/connections
+// selectConnection) opens the target here and activates it right after; without
+// the lease a live-work recompute during the cold spawn would dispose the entry
+// mid-dial and the click would die (#89622). Plain pre-warms stay prunable —
+// a hovered-but-never-activated socket must not be pinned off another source's
+// live work.
+export async function openGatewayForAgent(
+ connectionId: null | string,
+ profile: string,
+ { activationLease = false }: { activationLease?: boolean } = {}
+): Promise<void> {
const scope = registryBackendScopeKey(connectionId, profile)
if (scope === normKey(profile)) {
@@ -880,8 +891,24 @@ export async function openGatewayForAgent(connectionId: null | string, profile:
entry.retained = true
entry.wantOpen = true
- if (!isOpen(entry.gateway)) {
+ if (activationLease) {
+ // Stays held after a successful open: the activation that follows releases
+ // it (applyActive path), and one that never comes lets it expire.
+ entry.activationLeaseUntil = Date.now() + ACTIVATION_LEASE_MS
+ }
+
+ if (isOpen(entry.gateway)) {
+ return
+ }
+
+ try {
await openSecondary(entry)
+ } catch (error) {
+ if (activationLease) {
+ entry.activationLeaseUntil = 0
+ }
+
+ throw error
}
}
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index 4ad397744f0..4d78df0397c 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -18,6 +18,7 @@ import {
activeGatewayConnectionId,
ensureGatewayForAgent,
ensureGatewayForProfile,
+ openGatewayForAgent,
openGatewayForProfile
} from '@/store/gateway'
import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override'
@@ -408,6 +409,25 @@ async function resolveConnectionForAgent(connectionId: string, profile: string):
}
}
+// Phase one of the two-phase source switch (store/connections
+// selectConnection): dial the (connectionId, profile) socket WITHOUT activating
+// it. The active route, $activeGatewayProfile and $connection are untouched, so
+// the previous backend stays fully bound and painted while the target
+// spawns/connects — a dead target fails HERE and the current source loses
+// nothing. The follow-up ensureGatewayAgent then finds the socket open and
+// activates it synchronously, which lets the caller sever the previous
+// backend's session bindings and publish the new source in the same tick
+// (#93937). An already-open target is a no-op.
+export async function openGatewayAgent(connectionId: string, profile: string): Promise<void> {
+ const connection = connectionId.trim()
+
+ if (!connection) {
+ return
+ }
+
+ await openGatewayForAgent(connection, normalizeProfileKey(profile), { activationLease: true })
+}
+
// Activate a connection-scoped agent's gateway — the (connectionId, profile)
// analogue of ensureGatewayProfile, and the door the SDK's ensureAgent goes
// through. Two invariants the raw store call (ensureGatewayForAgent) does not