The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): secondary sockets judge a stable open by their own openedAt, not the persistent lastOpenedAt
kshitijk4poor80814b94842f
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 39f8815ea94..cc370f687e3 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -312,6 +312,12 @@ export function useGatewayBoot({// Reset together with the backoff counters: on a STABLE open (isStableOpen)// or a manual/wake-driven reconnect — never on a bare 'open' that dies.let escalated = false+ const resetReconnectBackoff = () => {+ reconnectAttempt = 0+ reconnectFailingSince = null+ escalated = false+ }+// Bounded automatic boot retry for transient REMOTE failures (#82679).let bootRetryAttempt = 0let bootRetryTimer: ReturnType<typeof setTimeout> | null = null@@ -544,9 +550,7 @@ export function useGatewayBoot({}clearReconnectTimer()- reconnectAttempt = 0- reconnectFailingSince = null- escalated = false+ resetReconnectBackoff()reconnectSecondaryGateways({ forceOpenSockets: forceOpenSocket })// Browser WebSocket state can remain OPEN after sleep even though the OS@@ -624,7 +628,6 @@ export function useGatewayBoot({async function getWindowBackend(startup = false): Promise<HermesConnection> {const profile = windowProfileOverride()const peer = isPeerInstanceWindow()-const route = profile? { profile, connectionId: peer ? new URLSearchParams(window.location.search).get('connectionId') : null }: startup && !peer@@ -708,9 +711,7 @@ export function useGatewayBoot({clearLivenessReprobeTimer()livenessProbeFailures = 0bootRetryAttempt = 0- reconnectAttempt = 0- reconnectFailingSince = null- escalated = false+ resetReconnectBackoff()reauthNotified = falseprimaryReauthError = nullbootFailed = false@@ -989,9 +990,7 @@ export function useGatewayBoot({}} else if (st === 'closed' || st === 'error') {if (isStableOpen(openedAt)) {- reconnectAttempt = 0- reconnectFailingSince = null- escalated = false+ resetReconnectBackoff()}openedAt = null@@ -1085,9 +1084,7 @@ export function useGatewayBoot({reauthNotified = falsegateway.close()clearReconnectTimer()- reconnectAttempt = 0- reconnectFailingSince = null- escalated = false+ resetReconnectBackoff()await attemptReconnect({profile: normalizeProfileKey($activeGatewayProfile.get()),activationEpoch: gatewayActivationEpoch()diff --git a/apps/desktop/src/store/gateway.test.ts b/apps/desktop/src/store/gateway.test.tsindex 9d5d11c41f8..90557dd8b49 100644--- a/apps/desktop/src/store/gateway.test.ts+++ b/apps/desktop/src/store/gateway.test.ts@@ -13,7 +13,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'// the entry instead of retrying forever.const gatewayMocks = vi.hoisted(() => {- const instances: { close: ReturnType<typeof vi.fn>; connectionState: string }[] = []+ const instances: {+ close: ReturnType<typeof vi.fn>+ connectionState: string+ emitState: (state: string) => void+ }[] = []return {connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined),@@ -28,12 +32,29 @@ vi.mock('@/hermes', () => ({close = vi.fn(() => {this.connectionState = 'closed'})+ stateListener: ((state: string) => void) | null = null+ emitState = (state: string): void => {+ this.connectionState = state+ this.stateListener?.(state)+ }+ // Mirrors json-rpc-gateway: 'connecting' → 'open' on success, → 'error' on a refused dial.connect = async (wsUrl: string): Promise<void> => {- await gatewayMocks.connect(wsUrl)- this.connectionState = 'open'+ this.emitState('connecting')+ try {+ await gatewayMocks.connect(wsUrl)+ } catch (error) {+ this.emitState('error')+ throw error+ }+ this.emitState('open')}onEvent = vi.fn(() => () => {})- onState = vi.fn(() => () => {})+ onState = vi.fn((listener: (state: string) => void) => {+ this.stateListener = listener+ return () => {+ this.stateListener = null+ }+ })constructor() {gatewayMocks.instances.push(this as never)}@@ -377,3 +398,56 @@ describe('server→client request routing without a registry handler (#112791)',expect(onServerRequest).toHaveBeenCalledWith(expect.objectContaining({ id: 'srq-1', method: 'clarify', profile: 'work' }))})})++describe('secondary reconnect backoff (#83134)', () => {+ const installWork = (): void =>+ installDesktop({+ getConnection: vi.fn(async ({ profile }: { profile: string }) => ({+ authMode: 'token',+ baseUrl: `https://${profile}.invalid`,+ mode: 'local',+ profile,+ token: 'fake-test-token',+ wsUrl: `wss://${profile}.invalid/ws`+ }))+ })++ it('climbs the ladder while the backend stays down after a stable session', async () => {+ vi.useFakeTimers()+ installWork()++ await ensureGatewayForProfile('work')+ const socket = gatewayMocks.instances[0]++ // A session that lived well past the stable-open window, then the backend dies.+ await vi.advanceTimersByTimeAsync(6_000)+ gatewayMocks.connect.mockRejectedValue(new Error('connection refused'))+ socket.emitState('closed')++ // Every redial is refused ('connecting' → 'error'). A refused dial never+ // opened, so it must not look like a stable session and reset the ladder.+ await vi.advanceTimersByTimeAsync(12_000)++ // Ladder from attempt 0: ≤ ~8 dials in 12 s; a reset-per-failure loop makes ~40+.+ expect(gatewayMocks.connect.mock.calls.length).toBeLessThanOrEqual(10)+ })++ it('treats an accept-then-close socket as a failed attempt', async () => {+ vi.useFakeTimers()+ installWork()+ gatewayMocks.connect.mockResolvedValue(undefined)++ await ensureGatewayForProfile('work')++ // Each redial "succeeds" and the socket dies 100 ms later, forever.+ gatewayMocks.connect.mockImplementation(async () => {+ const socket = gatewayMocks.instances.at(-1)!+ setTimeout(() => socket.emitState('closed'), 100)+ })+ gatewayMocks.instances[0].emitState('closed')++ await vi.advanceTimersByTimeAsync(12_000)++ expect(gatewayMocks.connect.mock.calls.length).toBeLessThanOrEqual(10)+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 922f1a313a9..961a328d1e7 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -126,6 +126,10 @@ interface Secondary {* remount loop (#94769). 0 = never opened.*/lastOpenedAt: number+ /** Date.now() of the CURRENT socket's 'open'; null while not open. Stability+ * clock for the backoff reset (#83134) — `lastOpenedAt` persists across+ * closes and would make every failed redial look like a stable session. */+ openedAt: null | numberactiveRequests: numberconnectPromise: Promise<void> | nulloffEvent: () => void@@ -643,7 +647,6 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bconst desktop = window.hermesDesktopconst reauthError = g.reauthFailures.get(entry.scope)?.error-if (reauthError) {throw reauthError}@@ -792,7 +795,6 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bentry.wantOpen = falseclearTimer(entry)}-throw error} finally {if (entry.connectPromise === pending) {@@ -825,11 +827,9 @@ function isStalledDialError(error: unknown): boolean {function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'): void {const reauthError = g.reauthFailures.get(entry.scope)?.error-if (reauthError && priority !== 'foreground') {throw reauthError}-g.reauthFailures.delete(entry.scope)if (entry.retiredByPool && priority !== 'foreground') {@@ -868,7 +868,6 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {} catch (error) {if (isGatewayReauthRequired(error)) {notifyError(error, translateNow('boot.errors.gatewaySignInRequired'), { action: RECOVERY_ACTIONS.openGateways() })-return}@@ -945,6 +944,7 @@ function createSecondary(profile: string, connectionId: null | string = null): Sconnection: null,gateway,lastOpenedAt: 0,+ openedAt: null,activeRequests: 0,connectPromise: null,offEvent: () => {},@@ -981,14 +981,17 @@ function createSecondary(profile: string, connectionId: null | string = null): Sif (state === 'open') {entry.stalledDials = 0+ entry.openedAt = Date.now()clearTimer(entry)} else if (state === 'closed' || state === 'error') {// Same stable-open rule as the primary (#83134): an accept-then-close socket// is a failed attempt, so the ladder resets only after a socket that lived.- if (entry.lastOpenedAt > 0 && isStableOpen(entry.lastOpenedAt)) {+ if (isStableOpen(entry.openedAt)) {entry.reconnectAttempt = 0}+ entry.openedAt = null+// A dead socket cannot emit the terminal event that normally releases// its turn lease. Drop the orphaned lease before deciding whether this// route is still retained/active enough to reconnect.@@ -1354,7 +1357,6 @@ export function retainGatewayForRelay(connectionId: null | string, profile: stri}entry.relayRetainCount += 1-if (!g.reauthFailures.has(entry.scope)) {rearmSecondary(entry)}@@ -1994,7 +1996,6 @@ function probeSecondaryLiveness(entry: Secondary): void {// before the turn ends, so a foreground turn mid tool call shows// activeRequests 0. The registry's live-scope hook supplies the turn.const liveScopes = g.config?.liveScopes?.()-const turnInFlight =liveScopes && (liveScopes.has(entry.scope) || (!entry.connectionId && liveScopes.has(entry.profile))) ? 1 : 0@@ -2298,7 +2299,6 @@ export function closeLegacySecondaryGateways(): void {g.reauthFailures.delete(scope)}}-closeSecondariesWhere(isLegacySecondary)}