Skip to content

The agent that grows with you

fix(desktop): preserve gateway switch recovery ownership

Zeus-Deus559a56c36039
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 002d6293ac6..10856338c38 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
@@ -12,6 +12,7 @@ import {
import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'
import { reconnectGateway } from '@/store/gateway-reconnect'
import { $gatewaySwitching, beginGatewaySwitch, endGatewaySwitch } from '@/store/gateway-switch'
+import { notifyError } from '@/store/notifications'
import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'
import {
$activeSessionId,
@@ -19,6 +20,7 @@ import {
$currentCwd,
$gatewayState,
$selectedStoredSessionId,
+ $sessionsLoading,
setActiveSessionId,
setSelectedStoredSessionId
} from '@/store/session'
@@ -27,6 +29,11 @@ import { $sessionTiles } from '@/store/session-states'
import { takeGatewaySurvivor } from './gateway-hmr-survivor'
import { primaryRuntimeConnectionId, useGatewayBoot } from './use-gateway-boot'
+vi.mock(import('@/store/notifications'), async importOriginal => ({
+ ...(await importOriginal()),
+ notifyError: vi.fn()
+}))
+
// End-to-end-ish repro of the "remote VPS → stuck on CONNECTING, no Settings"
// bug that drives the REAL useGatewayBoot hook + REAL HermesGateway through a
// fake WebSocket we fully control. No Docker / no real port: from the desktop's
@@ -258,6 +265,7 @@ beforeEach(() => {
FakeWebSocket.pingMode = 'pong'
connectionApplied = null
powerResume = null
+ vi.mocked(notifyError).mockReset()
;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket
;(window as { hermesDesktop?: unknown }).hermesDesktop = fakeDesktop()
$gatewayState.set('idle')
@@ -371,6 +379,39 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($gatewayState.get()).toBe('open')
})
+ it('reports a Settings switch setup failure and does not disarm a newer switch started by recovery UI', async () => {
+ const failure = new Error('machine-context reset failed')
+ const beforeConnectionSwitch = vi.fn()
+ let newerToken: null | ReturnType<typeof beginGatewaySwitch> = null
+
+ beforeConnectionSwitch.mockImplementationOnce(() => {
+ throw failure
+ })
+ vi.mocked(notifyError).mockImplementationOnce((_error, fallback) => {
+ // A notification/recovery callback may synchronously start another
+ // switch. The failed Settings attempt never received a token and must
+ // not force this newer owner's barrier down from its finally block.
+ newerToken = beginGatewaySwitch()
+
+ return fallback
+ })
+
+ render(<Harness beforeConnectionSwitch={beforeConnectionSwitch} />)
+ await flushAsync()
+ expect($gatewayState.get()).toBe('open')
+
+ act(() => connectionApplied?.())
+ await flushAsync()
+
+ expect($desktopBoot.get().error).toBe(failure.message)
+ expect(notifyError).toHaveBeenCalledWith(failure, expect.any(String))
+ expect(newerToken).not.toBeNull()
+ expect($gatewaySwitching.get()).toBe(true)
+ expect($sessionsLoading.get()).toBe(true)
+
+ endGatewaySwitch(newerToken ?? undefined)
+ })
+
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} />)
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 ac903650190..c6950cadeaf 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -475,18 +475,22 @@ export function useGatewayBoot({
return
}
- // Barrier up + machine-context reset + session wipe, in one synchronous
- // step — the shared commit point of every connection switch.
- const switchToken = beginGatewaySwitch()
- clearReconnectTimer()
- clearBootRetryTimer()
- bootRetryAttempt = 0
- reconnectAttempt = 0
- reconnectFailingSince = null
- escalated = false
- reauthNotified = false
+ let switchToken: null | ReturnType<typeof beginGatewaySwitch> = null
try {
+ // Barrier up + machine-context reset + session wipe, in one synchronous
+ // step — the shared commit point of every connection switch. Keep this
+ // inside the error boundary: lifecycle/wipe setup can throw before a
+ // token is returned and must follow the normal boot-failure path.
+ switchToken = beginGatewaySwitch()
+ clearReconnectTimer()
+ clearBootRetryTimer()
+ bootRetryAttempt = 0
+ reconnectAttempt = 0
+ reconnectFailingSince = null
+ escalated = false
+ reauthNotified = false
+
gateway.close()
closeSecondaryGateways()
@@ -535,11 +539,19 @@ export function useGatewayBoot({
if (!cancelled) {
const message = err instanceof Error ? err.message : String(err)
failDesktopBoot(message)
- notifyError(err, translateNow('boot.errors.desktopBootFailed'))
+ // Disarm this failed attempt before notifying: recovery UI may
+ // synchronously begin a newer switch and re-arm loading under its own
+ // token, which this older catch must not lower afterwards.
setSessionsLoading(false)
+ notifyError(err, translateNow('boot.errors.desktopBootFailed'))
}
} finally {
- endGatewaySwitch(switchToken)
+ // beginGatewaySwitch cleans up internally when setup throws before
+ // returning. Never use token-less teardown here: it would force down a
+ // newer switch started synchronously by error recovery/notification UI.
+ if (switchToken !== null) {
+ endGatewaySwitch(switchToken)
+ }
}
}
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index e47e3f8057c..f9ca7de5b2f 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -371,7 +371,7 @@ export async function selectConnection(connectionId: string): Promise<void> {
// 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()
+ recoverActiveSourceAfterFailedGatewaySwitch(token)
requestFreshSession()
}
diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.ts
index fb891a7ab26..b3632a91938 100644
--- a/apps/desktop/src/store/gateway-switch.test.ts
+++ b/apps/desktop/src/store/gateway-switch.test.ts
@@ -156,9 +156,20 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poi
expect($gatewaySwitching.get()).toBe(false)
})
- it('recovers the active source and tears down its barrier when the wipe throws partway through', async () => {
+ it('does not disarm a newer switch while a partial-wipe recovery refresh is pending', async () => {
const failure = new Error('profile fetch invalidation failed')
- const refreshSessions = vi.fn(async () => undefined)
+ let finishRefresh: () => void = () => undefined
+ let refreshCompleted = false
+
+ const refreshPending = new Promise<void>(resolve => {
+ finishRefresh = resolve
+ })
+
+ const refreshSessions = vi.fn(async () => {
+ await refreshPending
+ refreshCompleted = true
+ })
+
const off = registerGatewaySwitchLifecycle({ beforeConnectionSwitch: () => undefined, refreshSessions })
vi.mocked(invalidateProfileListFetches).mockImplementationOnce(() => {
@@ -168,16 +179,49 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poi
expect(() => beginGatewaySwitch()).toThrow(failure)
expect($gatewaySwitching.get()).toBe(false)
await vi.waitFor(() => expect(refreshSessions).toHaveBeenCalledTimes(1))
- expect($sessionsLoading.get()).toBe(false)
- // The failed token cannot strand or lower ownership acquired afterwards.
+ // A newer switch takes ownership while the old source repaint is still in
+ // flight. Completing the old repaint must not lower the newer skeleton.
const next = beginGatewaySwitch()
expect($gatewaySwitching.get()).toBe(true)
+ expect($sessionsLoading.get()).toBe(true)
+
+ finishRefresh()
+ await vi.waitFor(() => expect(refreshCompleted).toBe(true))
+ await Promise.resolve()
+
+ expect($sessionsLoading.get()).toBe(true)
+ expect($gatewaySwitching.get()).toBe(true)
+
endGatewaySwitch(next)
expect($gatewaySwitching.get()).toBe(false)
off()
})
+ it('does not refresh through a newer route when recovery is superseded before it starts', async () => {
+ const failure = new Error('profile fetch invalidation failed')
+ const refreshSessions = vi.fn(async () => undefined)
+ const off = registerGatewaySwitchLifecycle({ beforeConnectionSwitch: () => undefined, refreshSessions })
+
+ vi.mocked(invalidateProfileListFetches).mockImplementationOnce(() => {
+ throw failure
+ })
+
+ expect(() => beginGatewaySwitch()).toThrow(failure)
+
+ // Recovery is queued on a microtask. A newer switch that starts first owns
+ // the active route, so the stale recovery must not issue a request through it.
+ const next = beginGatewaySwitch()
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(refreshSessions).not.toHaveBeenCalled()
+ expect($sessionsLoading.get()).toBe(true)
+
+ endGatewaySwitch(next)
+ off()
+ })
+
it('the barrier belongs to the LATEST switch: an older switch ending mid-commit of a newer one is a no-op', () => {
const older = beginGatewaySwitch()
const newer = beginGatewaySwitch()
@@ -263,11 +307,11 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poi
const refreshSessions = vi.fn(async () => undefined)
const off = registerGatewaySwitchLifecycle({ beforeConnectionSwitch: () => undefined, refreshSessions })
- beginGatewaySwitch()
+ const token = beginGatewaySwitch()
expect($sessionsLoading.get()).toBe(true)
- recoverActiveSourceAfterFailedGatewaySwitch()
- endGatewaySwitch()
+ recoverActiveSourceAfterFailedGatewaySwitch(token)
+ endGatewaySwitch(token)
await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
expect(refreshSessions).toHaveBeenCalledTimes(1)
@@ -283,14 +327,18 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poi
})
setSessionsLoading(true)
- recoverActiveSourceAfterFailedGatewaySwitch()
+ const failingToken = beginGatewaySwitch()
+ recoverActiveSourceAfterFailedGatewaySwitch(failingToken)
+ endGatewaySwitch(failingToken)
await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
off()
setSessionsLoading(true)
const debug = vi.spyOn(console, 'debug').mockImplementation(() => undefined)
+ const missingLifecycleToken = beginGatewaySwitch()
- recoverActiveSourceAfterFailedGatewaySwitch()
+ recoverActiveSourceAfterFailedGatewaySwitch(missingLifecycleToken)
+ endGatewaySwitch(missingLifecycleToken)
await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))
expect(debug).toHaveBeenCalledWith(
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index cd4556687dc..b351796e49c 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -101,7 +101,7 @@ export function beginGatewaySwitch(): GatewaySwitchToken {
// If a nested switch superseded this one, its owner is responsible instead.
if (wipeStarted && stillOwnsSwitch) {
try {
- recoverActiveSourceAfterFailedGatewaySwitch()
+ recoverActiveSourceAfterFailedGatewaySwitch(token)
} catch {
// Recovery must never replace the original commit failure.
}
@@ -129,23 +129,31 @@ export function endGatewaySwitch(token?: GatewaySwitchToken): void {
* 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.
+ * sidebar doesn't sit on the skeleton; the fetch is best-effort. Recovery
+ * retains the failed switch's token across the async refresh so it cannot
+ * request through, or disarm loading for, a newer route.
*/
-export function recoverActiveSourceAfterFailedGatewaySwitch(): void {
+export function recoverActiveSourceAfterFailedGatewaySwitch(token: GatewaySwitchToken): void {
const lifecycle = switchLifecycle
if (!lifecycle) {
console.debug('[gateway-switch] cannot repaint the active source because no switch lifecycle is registered')
- setSessionsLoading(false)
+
+ if (token === latestSwitchToken) {
+ setSessionsLoading(false)
+ }
return
}
void Promise.resolve()
- .then(() => lifecycle.refreshSessions())
+ .then(() => (token === latestSwitchToken ? lifecycle.refreshSessions() : undefined))
.catch(() => undefined)
- .finally(() => setSessionsLoading(false))
+ .finally(() => {
+ if (token === latestSwitchToken) {
+ setSessionsLoading(false)
+ }
+ })
}
/**