Skip to content

The agent that grows with you

fix(desktop): preserve switch loading ownership

Zeus-Deusf23b3c805c7d
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 10856338c38..d5c533be7a8 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
@@ -379,6 +379,63 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($gatewayState.get()).toBe('open')
})
+ it('a stale failed Settings switch cannot disarm the newer switch loading owner', async () => {
+ const desktop = fakeDesktop()
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+
+ render(<Harness />)
+ await flushAsync()
+ expect($gatewayState.get()).toBe('open')
+
+ const failureA = new Error('switch A failed')
+ const failureB = new Error('switch B failed')
+ let rejectA: (error: Error) => void = () => undefined
+ let rejectB: (error: Error) => void = () => undefined
+
+ desktop.getConnection
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectA = reject
+ })
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectB = reject
+ })
+ )
+
+ act(() => connectionApplied?.())
+ expect($gatewaySwitching.get()).toBe(true)
+ expect($sessionsLoading.get()).toBe(true)
+
+ act(() => connectionApplied?.())
+ expect($gatewaySwitching.get()).toBe(true)
+ expect($sessionsLoading.get()).toBe(true)
+
+ await act(async () => {
+ rejectA(failureA)
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ expect(notifyError).toHaveBeenCalledWith(failureA, expect.any(String))
+ expect($desktopBoot.get().error).toBe(failureA.message)
+ expect($gatewaySwitching.get()).toBe(true)
+ expect($sessionsLoading.get()).toBe(true)
+
+ await act(async () => {
+ rejectB(failureB)
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ expect(notifyError).toHaveBeenCalledWith(failureB, expect.any(String))
+ expect($desktopBoot.get().error).toBe(failureB.message)
+ expect($gatewaySwitching.get()).toBe(false)
+ expect($sessionsLoading.get()).toBe(false)
+ })
+
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()
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 c6950cadeaf..e62ff6cb5ca 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -36,6 +36,7 @@ import {
$gatewaySwitching,
beginGatewaySwitch,
endGatewaySwitch,
+ isCurrentGatewaySwitch,
registerGatewaySwitchLifecycle
} from '@/store/gateway-switch'
import { notify, notifyError } from '@/store/notifications'
@@ -539,10 +540,14 @@ export function useGatewayBoot({
if (!cancelled) {
const message = err instanceof Error ? err.message : String(err)
failDesktopBoot(message)
- // 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)
+
+ // Only the current owner may lower loading. A failed begin returns no
+ // token and cleans its own barrier internally; lower loading only when
+ // that cleanup did not preserve a recursively-started newer switch.
+ if (switchToken === null ? !$gatewaySwitching.get() : isCurrentGatewaySwitch(switchToken)) {
+ setSessionsLoading(false)
+ }
+
notifyError(err, translateNow('boot.errors.desktopBootFailed'))
}
} finally {
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index b351796e49c..cad23cf5af6 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -56,6 +56,11 @@ export type GatewaySwitchToken = number
let latestSwitchToken = 0
+/** True only while token owns the latest connection-switch lifecycle. */
+export function isCurrentGatewaySwitch(token: GatewaySwitchToken): boolean {
+ return token === latestSwitchToken
+}
+
export function registerGatewaySwitchLifecycle(lifecycle: GatewaySwitchLifecycle): () => void {
switchLifecycle = lifecycle
@@ -91,7 +96,7 @@ export function beginGatewaySwitch(): GatewaySwitchToken {
} catch (error) {
// No caller received this token, so begin owns cleanup. Token-aware teardown
// preserves a newer recursively-started switch, if lifecycle code began one.
- const stillOwnsSwitch = token === latestSwitchToken
+ const stillOwnsSwitch = isCurrentGatewaySwitch(token)
endGatewaySwitch(token)
@@ -118,7 +123,7 @@ export function beginGatewaySwitch(): GatewaySwitchToken {
* newer one is still in flight. No token = force down (host teardown).
*/
export function endGatewaySwitch(token?: GatewaySwitchToken): void {
- if (token !== undefined && token !== latestSwitchToken) {
+ if (token !== undefined && !isCurrentGatewaySwitch(token)) {
return
}
@@ -139,7 +144,7 @@ export function recoverActiveSourceAfterFailedGatewaySwitch(token: GatewaySwitch
if (!lifecycle) {
console.debug('[gateway-switch] cannot repaint the active source because no switch lifecycle is registered')
- if (token === latestSwitchToken) {
+ if (isCurrentGatewaySwitch(token)) {
setSessionsLoading(false)
}
@@ -147,10 +152,10 @@ export function recoverActiveSourceAfterFailedGatewaySwitch(token: GatewaySwitch
}
void Promise.resolve()
- .then(() => (token === latestSwitchToken ? lifecycle.refreshSessions() : undefined))
+ .then(() => (isCurrentGatewaySwitch(token) ? lifecycle.refreshSessions() : undefined))
.catch(() => undefined)
.finally(() => {
- if (token === latestSwitchToken) {
+ if (isCurrentGatewaySwitch(token)) {
setSessionsLoading(false)
}
})