The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop transient remote ticket blips locking the chat
Andrew Fiebertf2c204d68934
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.tsindex 36a042c6d3f..058aa3e9de2 100644--- a/apps/desktop/electron/connection-config.test.ts+++ b/apps/desktop/electron/connection-config.test.ts@@ -49,7 +49,8 @@ import {RT_COOKIE_VARIANTS,savedProfileSsh,tokenPreview,- translateSelfProfileQuery+ translateSelfProfileQuery,+ withTransientRetries} from './connection-config'// --- connectionScopeKey / normAuthMode ---@@ -1134,6 +1135,54 @@ test('gateway ticket failures classify only explicit auth rejection statuses asassert.equal(serverFailure.needsOauthLogin, undefined)})+test('withTransientRetries retries transport blips but not auth rejections', async () => {+ const sleeps: number[] = []+ let transportAttempts = 0++ const ticket = await withTransientRetries(+ async () => {+ transportAttempts += 1++ if (transportAttempts < 3) {+ throw Object.assign(new Error('500: unavailable'), { statusCode: 500 })+ }++ return 'tkt-ok'+ },+ {+ delaysMs: [10, 10],+ sleep: async (ms: number) => {+ sleeps.push(ms)+ }+ }+ )++ assert.equal(ticket, 'tkt-ok')+ assert.equal(transportAttempts, 3)+ assert.deepEqual(sleeps, [10, 10])++ let authAttempts = 0+ await assert.rejects(+ () =>+ withTransientRetries(+ async () => {+ authAttempts += 1+ throw Object.assign(new Error('401: rejected'), { statusCode: 401 })+ },+ {+ delaysMs: [10],+ sleep: async () => undefined+ }+ ),+ (err: any) => {+ assert.equal(err.statusCode, 401)++ return true+ }+ )+ assert.equal(authAttempts, 1)+})+test('gateway WS URL IPC result serializes success and the auth-vs-transport matrix', async () => {assert.deepEqual(await gatewayWsUrlIpcResult(async () => 'wss://gateway.example.com/api/ws?ticket=fresh'), {ok: true,diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.tsindex 10cdd275b1f..47a2315324a 100644--- a/apps/desktop/electron/connection-config.ts+++ b/apps/desktop/electron/connection-config.ts@@ -151,6 +151,41 @@ function gatewayTicketFailure(error, authMessage, transportMessage) {return err}+/**+ * Retry a one-shot mint/fetch that can flap on brief network blips.+ * Auth rejections (401/403 / needsOauthLogin) fail immediately — retrying those+ * just hammers a dead session. Transport/server failures retry with short delays.+ */+async function withTransientRetries(run, options: any = {}) {+ const attempts = Number.isInteger(options.attempts) && options.attempts > 0 ? options.attempts : 3+ const delaysMs = Array.isArray(options.delaysMs) && options.delaysMs.length > 0 ? options.delaysMs : [250, 750]++ const sleep =+ typeof options.sleep === 'function' ? options.sleep : (ms: number) => new Promise(resolve => setTimeout(resolve, ms))++ const isRetryable =+ typeof options.isRetryable === 'function' ? options.isRetryable : (error: unknown) => !isGatewayAuthRejection(error)++ let lastError: unknown++ for (let attempt = 0; attempt < attempts; attempt += 1) {+ try {+ return await run()+ } catch (error) {+ lastError = error++ if (!isRetryable(error) || attempt >= attempts - 1) {+ throw error+ }++ const delay = delaysMs[Math.min(attempt, delaysMs.length - 1)]+ await sleep(delay)+ }+ }++ throw lastError+}+/** Serialize a fresh-WS-URL attempt across Electron's IPC boundary. */async function gatewayWsUrlIpcResult(resolveWsUrl: () => Promise<string>) {try {@@ -964,5 +999,6 @@ export {RT_COOKIE_VARIANTS,savedProfileSsh,tokenPreview,- translateSelfProfileQuery+ translateSelfProfileQuery,+ withTransientRetries}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 28af53a2524..04b1db74094 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -94,7 +94,8 @@ import {resolveTestWsUrl,savedProfileSsh,tokenPreview,- translateSelfProfileQuery+ translateSelfProfileQuery,+ withTransientRetries} from './connection-config'import {backendScopeKey,@@ -7591,15 +7592,34 @@ async function saveGatewayFileViaDataUrl(connection, profile, filePath, ctx: any// falling back to the OAuth cookie partition otherwise.// Throws (with statusCode 401) if the session cookie is missing/expired —// callers treat that as "needs re-login".+// Transient transport blips (brief host unreachable, 5xx, timeouts) are retried+// a few times before failing — those 1-3s flaps were promoting into the+// full-screen "couldn't start" lockout on reconnect.async function mintGatewayWsTicket(baseUrl, headers = {}) {- // Native flow: mint the ticket with the bearer token, no cookie involved.- const nativeAt = await ensureNativeAccessToken(baseUrl).catch(() => null)+ return withTransientRetries(async () => {+ // Native flow: mint the ticket with the bearer token, no cookie involved.+ const nativeAt = await ensureNativeAccessToken(baseUrl).catch(() => null)- if (nativeAt) {- const body = (await fetchJson(`${baseUrl}/api/auth/ws-ticket`, null, {+ if (nativeAt) {+ const body = (await fetchJson(`${baseUrl}/api/auth/ws-ticket`, null, {+ method: 'POST',+ timeoutMs: 8_000,+ bearer: nativeAt,+ headers+ })) as any++ const ticket = body?.ticket++ if (!ticket || typeof ticket !== 'string') {+ throw new Error('Gateway did not return a WS ticket.')+ }++ return ticket+ }++ const body = (await fetchJsonViaOauthSession(`${baseUrl}/api/auth/ws-ticket`, {method: 'POST',timeoutMs: 8_000,- bearer: nativeAt,headers})) as any@@ -7610,21 +7630,7 @@ async function mintGatewayWsTicket(baseUrl, headers = {}) {}return ticket- }-- const body = (await fetchJsonViaOauthSession(`${baseUrl}/api/auth/ws-ticket`, {- method: 'POST',- timeoutMs: 8_000,- headers- })) as any-- const ticket = body?.ticket-- if (!ticket || typeof ticket !== 'string') {- throw new Error('Gateway did not return a WS ticket.')- }-- return ticket+ })}// Build a fresh WS URL for the *current* connection. Critical for reconnects:@@ -12330,7 +12336,7 @@ ipcMain.handle('hermes:connection:revalidate', async () => {currentConnectionPromise: () => backendConnectionState.getPromise(),log: rememberLog,probe: fetchPublicJson,- resetConnection: resetHermesConnection,+ resetConnection: () => resetHermesConnection({ soft: true }),tracker: remoteLiveness}),revalidatePool()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 a208ae57d97..c2ef783e826 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@@ -96,6 +96,8 @@ const coderConn = {}function fakeDesktop() {+ let bootProgressHandler: ((payload: Record<string, unknown>) => void) | null = null+return {getConnection: vi.fn(async (profile?: null | string) => {const key = (profile ?? '').trim()@@ -113,7 +115,17 @@ function fakeDesktop() {running: true as boolean,timestamp: Date.now()})),- onBootProgress: vi.fn(() => () => undefined),+ onBootProgress: vi.fn(callback => {+ bootProgressHandler = callback++ return () => {+ bootProgressHandler = null+ }+ }),+ // Test helper: fire a post-boot progress event through the real subscription.+ emitBootProgress(payload: Record<string, unknown>) {+ bootProgressHandler?.(payload)+ },onBackendExit: vi.fn(() => () => undefined),onConnectionApplied: vi.fn(callback => {connectionApplied = callback@@ -340,11 +352,9 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>act(() => FakeWebSocket.instances[0].drop())await flushAsync()- // Burn a couple backoff cycles BEFORE the escalation threshold (<6 attempts,- // ~the first ~15s). This is the window where stock and fixed behave the- // same: socket down, hook retrying, gatewayState non-open, boot.error still- // null → CONNECTING covers the screen with no recovery surface. (Past ~45s- // the fix raises boot.error; that's asserted in the next test.)+ // Burn a couple backoff cycles BEFORE the escalation threshold. Socket+ // down, hook retrying, gatewayState non-open, boot.error still null so+ // chat stays usable (no CONNECTING / no couldn't-start overlay).await advanceBackoff()expect($gatewayState.get()).not.toBe('open')@@ -353,7 +363,7 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>expect(FakeWebSocket.instances.length).toBeGreaterThan(1)})- it('FIX: after the prolonged drop the hook raises a recoverable boot error (the escape hatch)', async () => {+ it('FIX: after a prolonged drop the chat stays unlocked (toast, not boot.error)', async () => {render(<Harness />)await flushAsync()expect($desktopBoot.get().error).toBeNull()@@ -362,17 +372,20 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>act(() => FakeWebSocket.instances[0].drop())await flushAsync()- // Walk the backoff past the >=6 attempt threshold (~45s of failures).+ // Walk the backoff past the ~45s escalation threshold.for (let i = 0; i < 8; i += 1) {await advanceBackoff()}- // The hook surfaced the recoverable error → BootFailureOverlay (Use local- // gateway / Sign in / Retry) becomes reachable instead of CONNECTING.- expect($desktopBoot.get().error).toBeTruthy()+ // Transport blips must NOT take the full-screen "couldn't start" overlay —+ // users were locked out of reading/drafting for the whole reconnect window.+ expect($desktopBoot.get().error).toBeNull()+ expect($gatewayState.get()).not.toBe('open')+ // Still retrying.+ expect(FakeWebSocket.instances.length).toBeGreaterThan(1)})- it('FIX: a successful reconnect clears the recoverable error', async () => {+ it('FIX: a successful reconnect after a prolonged drop restores the open gateway', async () => {render(<Harness />)await flushAsync()@@ -384,7 +397,7 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>await advanceBackoff()}- expect($desktopBoot.get().error).toBeTruthy()+ expect($desktopBoot.get().error).toBeNull()// The remote comes back: next reconnect attempt opens.FakeWebSocket.mode = 'open'@@ -423,6 +436,36 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>expect($gatewayState.get()).toBe('open')})+ it('FIX: post-boot ticket-mint boot-progress errors do not lock the UI', async () => {+ const desktop = fakeDesktop() as ReturnType<typeof fakeDesktop> & {+ emitBootProgress: (payload: Record<string, unknown>) => void+ }++ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop++ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ expect($desktopBoot.get().error).toBeNull()++ // Main re-emits the exact transient ticket error after a liveness rebuild.+ // That used to promote into BootFailureOverlay and lock reading/drafting.+ act(() => {+ desktop.emitBootProgress({+ error:+ 'Could not reach the remote Hermes gateway while refreshing its WebSocket ticket. Try reconnecting.',+ message: 'Desktop boot failed',+ phase: 'backend.error',+ progress: 94,+ running: false,+ timestamp: Date.now()+ })+ })++ expect($desktopBoot.get().error).toBeNull()+ expect($desktopBoot.get().visible).toBe(false)+ })+it('FIX: a failed session-list fetch during boot is non-fatal — the app still boots', async () => {// The version-skew report: gateway WS connects fine, but refreshSessions()// rejects (e.g. older backend 404s an endpoint the fallback didn't cover,diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 3d0e7e35b69..3550047f113 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -1,6 +1,7 @@import { isGatewayReauthRequired, resolveGatewayWsUrl } from '@hermes/shared'import { useEffect, useRef } from 'react'+import { shouldApplyPostBootProgressError } from '@/components/boot-failure-reauth'import type { HermesConnection } from '@/global'import { HermesGateway } from '@/hermes'import { translateNow } from '@/i18n'@@ -61,15 +62,12 @@ import type { RpcEvent } from '@/types/hermes'import { stashGatewaySurvivor, survivorIsStale, takeGatewaySurvivor } from './gateway-hmr-survivor'-// After the reconnect loop has been failing for this long, raise a recoverable-// boot error. Otherwise a dropped remote gateway loops the backoff forever-// behind the fullscreen CONNECTING overlay with no way to reach Settings /-// sign in / switch to local — the "lost connection breaks the app" dead end.-// The next successful reconnect clears it. Time-based (not attempt-count)-// because the full-jitter backoff makes attempt counts a meaningless clock:-// six jittered attempts can elapse in ~9s, while the old deterministic-// 1→15s ladder took ~45s to reach six failures — this threshold keeps that-// original ~45s calibration.+// After the reconnect loop has been failing for this long, raise a NON-blocking+// warning toast. Full-screen BootFailureOverlay used to lock the user out of+// reading/drafting for the whole 1–3 minute blip even though the transcript is+// still on screen underneath. Confirmed reauth still escalates to the overlay+// (Sign in is required). Time-based (not attempt-count) because full-jitter+// backoff makes attempt counts a meaningless clock.const RECONNECT_ESCALATE_AFTER_MS = 45_000// Bounded self-heal for a failed REMOTE boot (#82679): when the primary boot@@ -264,11 +262,14 @@ export function useGatewayBoot({await callbacksRef.current.refreshSessions().catch(() => undefined)} catch (err) {// OAuth session expired mid-reconnect: surface the actionable "sign in- // again" message once instead of silently looping the backoff against a- // ticket that can never succeed. Transport failures fall through to the- // backoff in the finally block below.+ // again" recovery overlay once instead of silently looping the backoff+ // against a ticket that can never succeed. Transport failures fall+ // through to the backoff in the finally block below — they must NOT+ // take the full-screen "couldn't start" path (locks reading/drafting).if (!cancelled && isGatewayReauthRequired(err) && !reauthNotified) {reauthNotified = true+ const message = err instanceof Error ? err.message : String(err)+ failDesktopBoot(message)notifyError(err, translateNow('boot.errors.gatewaySignInRequired'))}} finally {@@ -281,7 +282,14 @@ export function useGatewayBoot({if (Date.now() - reconnectFailingSince >= RECONNECT_ESCALATE_AFTER_MS && !escalated) {escalated = true- failDesktopBoot(translateNow('boot.errors.gatewayConnectionLost'))+ // Non-blocking: chat stays readable/draftable while we keep retrying.+ // Settings / Gateway menu remain reachable without a modal lockout.+ notify({+ kind: 'warning',+ title: translateNow('boot.errors.gatewayConnectionLost'),+ message: translateNow('boot.errors.gatewayConnectionLostDetail'),+ durationMs: 0+ })}scheduleReconnect()@@ -428,9 +436,12 @@ export function useGatewayBoot({const offBootProgress = desktop.onBootProgress(payload => {// Soft switch / post-boot startHermes re-emits progress — ignore so the- // cold-boot CONNECTING overlay stays down. Errors still surface.+ // cold-boot CONNECTING overlay stays down. Post-boot errors are gated:+ // only confirmed reauth takes the full-screen recovery surface. Transient+ // ticket-mint / host-unreachable failures must stay in the reconnect loop+ // (otherwise a 1–3 min blip bricks reading/drafting behind "couldn't start").if ($gatewaySwitching.get() || bootCompleted) {- if (payload.error) {+ if (payload.error && shouldApplyPostBootProgressError(payload.error)) {applyDesktopBootProgress(payload)}diff --git a/apps/desktop/src/components/boot-failure-reauth.test.ts b/apps/desktop/src/components/boot-failure-reauth.test.tsindex 202ecff0935..1cdd144820e 100644--- a/apps/desktop/src/components/boot-failure-reauth.test.ts+++ b/apps/desktop/src/components/boot-failure-reauth.test.ts@@ -7,6 +7,7 @@ import {isRemoteConfig,isRemoteReauthError,isRemoteReauthFailure,+ shouldApplyPostBootProgressError,signInLabel,sshFailureMessage} from './boot-failure-reauth'@@ -114,6 +115,19 @@ describe('isRemoteReauthError', () => {})})+describe('shouldApplyPostBootProgressError', () => {+ it('applies only confirmed reauth after a healthy boot — not transient ticket blips', () => {+ expect(shouldApplyPostBootProgressError('Your remote gateway session has expired.')).toBe(true)+ expect(+ shouldApplyPostBootProgressError(+ 'Could not reach the remote Hermes gateway while refreshing its WebSocket ticket. Try reconnecting.'+ )+ ).toBe(false)+ expect(shouldApplyPostBootProgressError('Lost connection to the gateway')).toBe(false)+ expect(shouldApplyPostBootProgressError(null)).toBe(false)+ })+})+describe('sshFailureMessage', () => {it('localizes SSH failures without changing non-SSH errors', () => {const copy = { sshErrAuth: 'localized auth', sshErrUnknown: 'localized unknown' }diff --git a/apps/desktop/src/components/boot-failure-reauth.ts b/apps/desktop/src/components/boot-failure-reauth.tsindex 703f3f74585..d84604b6f3f 100644--- a/apps/desktop/src/components/boot-failure-reauth.ts+++ b/apps/desktop/src/components/boot-failure-reauth.ts@@ -60,6 +60,18 @@ export function isRemoteReauthError(error: string | null | undefined): boolean {)}+/**+ * After a healthy cold boot, main may still re-emit boot-progress errors when a+ * post-boot startHermes()/ticket mint fails (liveness reset → rebuild, wake+ * recovery, etc.). Only CONFIRMED reauth should take over the full-screen+ * recovery overlay then — transient "could not reach … WebSocket ticket"+ * blips must stay in the reconnect loop so reading/drafting is not locked out+ * for 1–3 minutes while the socket self-heals.+ */+export function shouldApplyPostBootProgressError(error: string | null | undefined): boolean {+ return isRemoteReauthError(error)+}+// A remote, gated (oauth-bucket) gateway is a remote-reauth boot failure when the// session isn't connected OR the boot error is auth-shaped (connected-but-expired// — see isRemoteReauthError). Only re-establishing the remote session fixes it;diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 9328dfddb14..bb1e3d1bbdd 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -96,6 +96,8 @@ export const ar = defineLocale({backendStopped: 'توقف الخلفية',desktopBootFailed: 'فشل تشغيل سطح المكتب',gatewayConnectionLost: 'انقطع الاتصال بالبوابة',+ gatewayConnectionLostDetail:+ 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',gatewaySignInRequired: 'تسجيل الدخول للبوابة مطلوب',ipcBridgeUnavailable: 'جسر IPC لسطح المكتب غير متاح.'},diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex df70b466378..00bc7b6bc4e 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -81,6 +81,8 @@ export const en: Translations = {backendStopped: 'Backend stopped',desktopBootFailed: 'Desktop boot failed',gatewayConnectionLost: 'Lost connection to the gateway',+ gatewayConnectionLostDetail:+ 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',gatewaySignInRequired: 'Gateway sign-in required',ipcBridgeUnavailable: 'Desktop IPC bridge is unavailable.'},diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 0607f2260d8..c6c790c57ba 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -81,6 +81,8 @@ export const ja = defineLocale({backendStopped: 'バックエンドが停止しました',desktopBootFailed: 'デスクトップの起動に失敗しました',gatewayConnectionLost: 'ゲートウェイへの接続が切断されました',+ gatewayConnectionLostDetail:+ 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',gatewaySignInRequired: 'ゲートウェイへのサインインが必要です',ipcBridgeUnavailable: 'デスクトップ IPC ブリッジが利用できません。'},diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex ec1bd531440..a9e97b98c3d 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -127,6 +127,7 @@ export interface Translations {backendStopped: stringdesktopBootFailed: stringgatewayConnectionLost: string+ gatewayConnectionLostDetail: stringgatewaySignInRequired: stringipcBridgeUnavailable: string}diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex b9b55e0490f..9c16366bfd6 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -81,6 +81,8 @@ export const zhHant = defineLocale({backendStopped: '後端已停止',desktopBootFailed: '桌面啟動失敗',gatewayConnectionLost: '與閘道的連線已中斷',+ gatewayConnectionLostDetail:+ 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',gatewaySignInRequired: '需要閘道登入',ipcBridgeUnavailable: '桌面 IPC 橋接器不可用。'},diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex f4bf71a4f71..26e8d3ef836 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -81,6 +81,8 @@ export const zh: Translations = {backendStopped: '后端已停止',desktopBootFailed: '桌面启动失败',gatewayConnectionLost: '与网关的连接已断开',+ gatewayConnectionLostDetail:+ 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',gatewaySignInRequired: '需要登录网关',ipcBridgeUnavailable: '桌面 IPC 桥不可用。'},