The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop reconnecting rejected gateway sessions
Robin Fernandes6c5764cddcf6
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 65192a94129..8feb88f73cd 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@@ -614,8 +614,11 @@ describe('primary failure foreground isolation', () => {expect($desktopBoot.get().error).toContain(error)desktop.getGatewayWsUrl.mockImplementation(async conn => conn?.wsUrl ?? primaryConn.wsUrl)- act(() => FakeWebSocket.instances[0].drop())- await advanceBackoff()+ // A rejected session waits for explicit recovery, even after credentials change.+ let recovery!: Promise<void>+ act(() => { recovery = reconnectGateway() })+ await flushAsync()+ await recoveryexpect($gatewayState.get()).toBe('open')expect($desktopBoot.get().error).toBeNull()expect(overlay.queryByRole('heading')).toBeNull()@@ -629,6 +632,32 @@ describe('primary failure foreground isolation', () => {})describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () => {+ it('parks rejected primary auth across timers and wake signals until explicit recovery', async () => {+ const desktop = fakeDesktop()+ desktop.getConnection.mockResolvedValue({ ...primaryConn, authMode: 'oauth' })+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop+ render(<Harness />)+ await flushAsync()+ desktop.getGatewayWsUrl.mockRejectedValue(Object.assign(new Error('Sign in again'), { needsOauthLogin: true }))+ act(() => FakeWebSocket.instances[0].drop())+ await advanceBackoff()+ expect($desktopBoot.get().error).toContain('session has expired')+ const calls = desktop.getGatewayWsUrl.mock.calls.length+ await advanceBackoff()+ act(() => {+ powerResume?.()+ window.dispatchEvent(new Event('focus'))+ window.dispatchEvent(new Event('online'))+ })+ await advanceBackoff()+ expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(calls)+ desktop.getGatewayWsUrl.mockResolvedValue(primaryConn.wsUrl)+ act(() => { connectionApplied?.() })+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ expect($desktopBoot.get().error).toBeNull()+ })+it('INITIAL boot against a dead VPS: getConnection hangs (waitForHermes) → app sits in the connecting combo, then fails', async () => {// The report's actual path: a fresh launch pointed at an unreachable VPS.// startHermes()'s remote branch awaits waitForHermes() for 45s before itdiff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 26c40861b59..c84ee518fd2 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -358,7 +358,7 @@ export function useGatewayBoot({}const attemptReconnect = async (manual?: { profile: string; activationEpoch: number }) => {- if (cancelled || reconnecting || gatewayOpen() || $gatewaySwitching.get()) {+ if (cancelled || primaryReauthError || reconnecting || gatewayOpen() || $gatewaySwitching.get()) {return}@@ -481,7 +481,7 @@ export function useGatewayBoot({} finally {reconnecting = false- if (!cancelled && !gatewayOpen() && !$gatewaySwitching.get()) {+ if (!cancelled && !primaryReauthError && !gatewayOpen() && !$gatewaySwitching.get()) {if (reconnectFailingSince === null) {reconnectFailingSince = Date.now()}@@ -509,7 +509,7 @@ export function useGatewayBoot({}function scheduleReconnect(manual?: { profile: string; activationEpoch: number }) {- if (cancelled || reconnecting || reconnectTimer !== null || gatewayOpen() || $gatewaySwitching.get()) {+ if (cancelled || primaryReauthError || reconnecting || reconnectTimer !== null || gatewayOpen() || $gatewaySwitching.get()) {return}@@ -1021,6 +1021,9 @@ export function useGatewayBoot({return}+ // Only explicit recovery may retry a credential that requires sign-in.+ primaryReauthError = null+ reauthNotified = falsegateway.close()clearReconnectTimer()reconnectAttempt = 0diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex f5f595d5db9..5ee803192cd 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -802,3 +802,34 @@ describe('cooperative pool retirement (supersedes #104871)', () => {expect(touchBackend).toHaveBeenCalledWith('conn:homelab::bot-a', { activeTurn: false })})})+++describe('rejected secondary authentication', () => {+ it('parks only the rejected source across automatic nudges and recovers on explicit selection', async () => {+ vi.useFakeTimers()+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({+ ...descriptorFor(connectionId, profile), authMode: 'oauth'+ }))+ const getGatewayWsUrlFor = vi.fn(async () => ({ ok: true, wsUrl: 'wss://cloud.invalid/api/ws?ticket=fresh' }))+ installDesktop({ getConnectionFor, getGatewayWsUrlFor })+ await ensureGatewayForAgent('cloud', 'default')+ gatewayMocks.instances[0].connectionState = 'closed'+ getGatewayWsUrlFor.mockResolvedValue({ ok: false, needsOauthLogin: true, error: 'Sign in again' } as never)+ const rejected = ensureActiveGatewayOpen()+ await vi.advanceTimersByTimeAsync(8_000)+ expect(await rejected).toBeNull()+ const calls = getGatewayWsUrlFor.mock.calls.length+ reconnectSecondaryGateways({ forceOpenSockets: true })+ await vi.advanceTimersByTimeAsync(60_000)+ const nudged = ensureActiveGatewayOpen()+ await vi.advanceTimersByTimeAsync(8_000)+ expect(await nudged).toBeNull()+ expect(getGatewayWsUrlFor).toHaveBeenCalledTimes(calls)+ getGatewayWsUrlFor.mockResolvedValue({ ok: true, wsUrl: 'wss://cloud.invalid/api/ws?ticket=new' })+ await ensureGatewayForAgent('healthy', 'default')+ expect(activeGateway()?.connectionState).toBe('open')+ await ensureGatewayForAgent('cloud', 'default')+ expect(activeGateway()?.connectionState).toBe('open')+ expect(getGatewayWsUrlFor).toHaveBeenCalledTimes(calls + 2)+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex ca134c5b902..aeb250d0bcb 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -1,6 +1,7 @@import {type ConnectionState,type GatewayEvent,+ isGatewayReauthRequired,reconnectBackoffDelayMs,registryBackendScopeKey,resolveGatewayWsUrl,@@ -10,7 +11,9 @@ import { atom } from 'nanostores'import type { HermesConnection } from '@/global'import { HermesGateway, setApiRequestConnection } from '@/hermes'+import { translateNow } from '@/i18n'import { isTimeoutError, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'+import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'import { markNativeNotifyBaseline } from '@/store/notify-baseline'import { setConnection, setGatewayState } from '@/store/session'import { stampSecondaryProfileOwner } from '@/store/session-event-provenance'@@ -112,6 +115,8 @@ interface Secondary {/** Consecutive automatic dials that stalled (slot wait / dial timeout)* rather than failing fast; see SECONDARY_STALLED_DIAL_BUDGET. */stalledDials: number+ // Wake, polling and relay retention cannot revive a rejected credential.+ reauthError: Error | nullreconnecting: boolean/** A material connection edit is waiting for live owners to drain. */pendingConnectionRedial: boolean@@ -600,6 +605,10 @@ function clearTimer(entry: Secondary): void {async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'background'): Promise<void> {const desktop = window.hermesDesktop+ if (entry.reauthError) {+ throw entry.reauthError+ }+if (!desktop) {return}@@ -735,6 +744,13 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'btry {await pending+ } catch (error) {+ if (isGatewayReauthRequired(error)) {+ entry.reauthError = error+ entry.wantOpen = false+ clearTimer(entry)+ }+ throw error} finally {if (entry.connectPromise === pending) {entry.connectPromise = null@@ -765,6 +781,11 @@ function isStalledDialError(error: unknown): boolean {}function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'): void {+ if (entry.reauthError && priority !== 'foreground') {+ throw entry.reauthError+ }+ entry.reauthError = null+if (entry.retiredByPool && priority !== 'foreground') {throw new Error(`Backend for "${entry.profile}" was retired; open it explicitly to reconnect.`)}@@ -800,6 +821,11 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {await openSecondary(entry)entry.reconnectAttempt = 0} catch (error) {+ if (isGatewayReauthRequired(error)) {+ notifyError(error, translateNow('boot.errors.gatewaySignInRequired'), { action: RECOVERY_ACTIONS.openGateways() })+ return+ }+// The registry no longer knows this connection (removed while we were// backing off), or Electron's deletion guard reports the profile itself// gone/mid-delete. Both are permanent for this scoped socket — retrying@@ -881,6 +907,7 @@ function createSecondary(profile: string, connectionId: null | string = null): SreconnectTimer: null,reconnectAttempt: 0,stalledDials: 0,+ reauthError: null,reconnecting: false,pendingConnectionRedial: false,retained: false,@@ -1256,7 +1283,9 @@ export function retainGatewayForRelay(connectionId: null | string, profile: stri}entry.relayRetainCount += 1- rearmSecondary(entry)+ if (!entry.reauthError) {+ rearmSecondary(entry)+ }let released = false@@ -1772,7 +1801,7 @@ export async function ensureActiveGatewayOpen(): Promise<HermesGateway | null> {const entry = g.secondaries.get(g.activeKey)- if (!entry) {+ if (!entry || entry.reauthError) {return null}@@ -1814,7 +1843,7 @@ export function reconnectSecondaryGateways({ forceOpenSockets = false }: { force// A backend main retired for a foreground open stays parked: redialing it// from a focus/wake nudge would queue a background spawn for the slot the// retirement just freed. Its tile still shows; the next click re-arms it.- if (entry.retiredByPool) {+ if (entry.retiredByPool || entry.reauthError) {continue}