diff --git a/apps/desktop/electron/backend-start-failure.test.ts b/apps/desktop/electron/backend-start-failure.test.ts index 36d352d66c..d164813180 100644 --- a/apps/desktop/electron/backend-start-failure.test.ts +++ b/apps/desktop/electron/backend-start-failure.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { test } from 'vitest' -import { shouldLatchBackendStartFailure, shouldLatchRemoteReauthFailure } from './backend-start-failure' +import { isRetryableRemoteBootFailure, shouldLatchBackendStartFailure, shouldLatchRemoteReauthFailure } from './backend-start-failure' test('latches a LOCAL backend failure so the install-retry loop is broken', () => { assert.equal(shouldLatchBackendStartFailure({ attemptedRemote: false }), true) @@ -50,3 +50,30 @@ test('the two latches never fire for the same failure', () => { } } }) + +test('FIX #82679: a transient remote failure is retryable so a dropped SSH/HTTP connection self-heals', () => { + // The dropped-registered-connection class: "Could not verify the existing + // SSH backend", ERR_CONNECTION_RESET on an HTTP remote, mint timeouts. All + // surface as non-reauth remote boot failures and must enter the bounded + // renderer retry loop instead of parking on "Desktop boot failed". + assert.equal(isRetryableRemoteBootFailure({ attemptedRemote: true, isReauth: false }), true) +}) + +test('a CONFIRMED reauth rejection is never auto-retried (missing capability, not transient failure)', () => { + assert.equal(isRetryableRemoteBootFailure({ attemptedRemote: true, isReauth: true }), false) +}) + +test('local failures are never auto-retried by the remote self-heal loop', () => { + assert.equal(isRetryableRemoteBootFailure({ attemptedRemote: false, isReauth: false }), false) + assert.equal(isRetryableRemoteBootFailure({ attemptedRemote: false, isReauth: true }), false) +}) + +test('retryable and reauth-latch are mutually exclusive for remote failures', () => { + // Every remote failure either self-heals (transient) or latches for sign-in + // (confirmed reauth) — never both, never neither. + for (const isReauth of [true, false]) { + const retry = isRetryableRemoteBootFailure({ attemptedRemote: true, isReauth }) + const latch = shouldLatchRemoteReauthFailure({ attemptedRemote: true, isReauth }) + assert.equal(retry !== latch, true, `remote failure with reauth=${isReauth} must pick exactly one path`) + } +}) diff --git a/apps/desktop/electron/backend-start-failure.ts b/apps/desktop/electron/backend-start-failure.ts index 3c5ffdbcad..efc4361637 100644 --- a/apps/desktop/electron/backend-start-failure.ts +++ b/apps/desktop/electron/backend-start-failure.ts @@ -70,3 +70,32 @@ export interface RemoteReauthFailureContext { export function shouldLatchRemoteReauthFailure(context: RemoteReauthFailureContext): boolean { return context.attemptedRemote && context.isReauth } + +export interface RemoteBootRetryContext { + /** True when the boot that just failed was dialing a REMOTE (or cloud/SSH) backend. */ + attemptedRemote: boolean + /** + * True when the failure was a CONFIRMED auth rejection (401/403), which can + * never self-heal without the user signing in again. + */ + isReauth: boolean +} + +/** + * Whether a failed primary-backend boot is a TRANSIENT remote failure the + * renderer may retry automatically (bounded, with backoff). + * + * This closes the self-heal gap of issue #82679: a dropped SSH/HTTP remote + * connection surfaces at the next boot as a transient transport failure + * ("Could not verify the existing SSH backend", ERR_CONNECTION_RESET, mint + * timeouts). Those never latch (see shouldLatchBackendStartFailure), but + * nothing ever RE-ATTEMPTED the boot either — the renderer's reconnect loop + * only arms after a completed boot, so the app sat on "Desktop boot failed" + * until the user manually re-entered the same connection details (which just + * forced a fresh bootstrap). A missing capability differs from a transient + * failure: confirmed reauth rejections and local failures stay out of the + * retry path; everything else remote is connectivity and should retry. + */ +export function isRetryableRemoteBootFailure(context: RemoteBootRetryContext): boolean { + return context.attemptedRemote && !context.isReauth +} diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 848165f279..913e877f27 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -45,7 +45,7 @@ import { verifyHermesCli } from './backend-probes' import { waitForDashboardPortAnnouncement } from './backend-ready' -import { shouldLatchBackendStartFailure, shouldLatchRemoteReauthFailure } from './backend-start-failure' +import { isRetryableRemoteBootFailure, shouldLatchBackendStartFailure, shouldLatchRemoteReauthFailure } from './backend-start-failure' import { detectRemoteDisplay, isWindowsBinaryPathInWsl, @@ -1246,6 +1246,7 @@ let bootProgressState = { message: 'Waiting to start Hermes backend', phase: 'idle', progress: 0, + retryable: false, running: false, timestamp: Date.now() } @@ -1812,6 +1813,12 @@ function updateBootProgress(update, options: { allowDecrease?: boolean } = {}) { error: update.error === undefined ? bootProgressState.error : update.error, fakeMode: BOOT_FAKE_MODE || Boolean(update.fakeMode), progress: nextProgress, + // `retryable` rides with `error`: it survives updates that preserve the + // error and resets alongside a new/cleared error unless explicitly set. + retryable: + update.retryable === undefined + ? update.error === undefined && Boolean(bootProgressState.retryable) + : Boolean(update.retryable), timestamp: Date.now() } @@ -8643,6 +8650,20 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc } catch { void 0 } + } else { + // The cached master was reused but the lifecycle probe against it + // failed ("Could not verify the existing SSH backend"). Keeping the + // stale entry means every subsequent boot re-attempts through the same + // wedged master/tunnel and fails identically until the user re-enters + // the connection details (whose changed fingerprint forces a teardown). + // Tear it down now so the next attempt — automatic retry included — + // bootstraps a fresh master, which is exactly what manual re-entry + // did (#82679). + try { + await teardownSshConnection(profile) + } catch { + void 0 + } } const err = new Error(error.message) as any @@ -10192,6 +10213,12 @@ async function startHermes() { error: message, message: `Desktop boot failed: ${message}`, phase: 'backend.error', + // Renderer contract for the self-heal loop (#82679): a transient + // REMOTE failure (dropped SSH/HTTP registered connection, mint + // timeout) is retryable — the renderer re-attempts the boot with + // bounded backoff. Local failures and confirmed reauth rejections + // are not: those end in the recovery overlay / sign-in affordance. + retryable: isRetryableRemoteBootFailure({ attemptedRemote, isReauth: isReauthRequiredError(error) }), running: false }, { allowDecrease: true } 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 c0ca28cde4..a208ae57d9 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 @@ -104,12 +104,13 @@ function fakeDesktop() { }), getGatewayWsUrl: vi.fn(async (conn?: { wsUrl?: string }) => conn?.wsUrl ?? primaryConn.wsUrl), getBootProgress: vi.fn(async () => ({ - error: null, + error: null as null | string, fakeMode: false, message: '', phase: 'init', progress: 0, - running: true, + retryable: false as boolean, + running: true as boolean, timestamp: Date.now() })), onBootProgress: vi.fn(() => () => undefined), @@ -412,7 +413,11 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () => }) expect(desktop.revalidateConnection).toHaveBeenCalledOnce() - expect(desktop.getConnection).toHaveBeenLastCalledWith('default') + // The manual reconnect dials the WINDOW-owned primary backend (no profile + // arg) — same contract as the sleep/wake reconnect: passing the active + // profile would retarget the primary socket after a live profile swap. + const lastCall = desktop.getConnection.mock.calls.at(-1) ?? [] + expect(lastCall.length === 0 || lastCall[0] == null || lastCall[0] === '').toBe(true) expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(2) expect(FakeWebSocket.instances).toHaveLength(2) expect($gatewayState.get()).toBe('open') @@ -525,4 +530,109 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () => expect($connection.get()?.profile).toBe('coder') expect($connection.get()?.baseUrl).toBe(coderConn.baseUrl) }) + + it('FIX #82679: a transient remote boot failure self-heals — the next attempt rebuilds the dropped connection', async () => { + // The reported class: the app relaunches (or wakes) against a registered + // SSH/HTTP remote whose transport dropped. startHermes() rejects with a + // transient transport error ("Could not verify the existing SSH backend"), + // main tags the boot progress `retryable`, and — before the fix — the app + // parked on "Desktop boot failed" until the user re-entered the exact same + // connection details. Now the renderer retries the boot with backoff and + // the second attempt (fresh bootstrap, same details) succeeds. + const desktop = fakeDesktop() + desktop.getConnection = vi + .fn() + .mockRejectedValueOnce(new Error('Could not verify the existing SSH backend.')) + .mockImplementation(async () => primaryConn) + desktop.getBootProgress = vi.fn(async () => ({ + error: 'Could not verify the existing SSH backend.', + fakeMode: false, + message: 'Desktop boot failed: Could not verify the existing SSH backend.', + phase: 'backend.error', + progress: 24, + retryable: true, + running: false, + timestamp: Date.now() + })) + ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop + + render() + await flushAsync() + + // First attempt failed but the failure is retryable: no terminal error, + // the overlay shows the retry status instead of the dead-end failure. + expect($desktopBoot.get().error).toBeNull() + expect($gatewayState.get()).not.toBe('open') + + // Walk past the first backoff delay (2s base, 15s cap, full jitter). + await advanceBackoff() + + // Second boot attempt rebuilt the connection — no manual re-entry. + expect(desktop.getConnection.mock.calls.length).toBeGreaterThan(1) + expect($gatewayState.get()).toBe('open') + expect($desktopBoot.get().error).toBeNull() + }) + + it('FIX #82679: boot retries are BOUNDED — a persistently dead remote ends in the recovery overlay, not a spinner', async () => { + const desktop = fakeDesktop() + desktop.getConnection = vi.fn(async () => { + throw new Error('Could not verify the existing SSH backend.') + }) + desktop.getBootProgress = vi.fn(async () => ({ + error: 'Could not verify the existing SSH backend.', + fakeMode: false, + message: 'Desktop boot failed: Could not verify the existing SSH backend.', + phase: 'backend.error', + progress: 24, + retryable: true, + running: false, + timestamp: Date.now() + })) + ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop + + render() + await flushAsync() + + // Exhaust the bounded retry budget (5 attempts, ≤15s jittered delay each). + for (let i = 0; i < 7; i += 1) { + await advanceBackoff() + } + + // 1 initial + 5 bounded retries; the loop then STOPS retrying and the + // terminal boot error surfaces the real recovery affordance. + expect(desktop.getConnection).toHaveBeenCalledTimes(6) + expect($desktopBoot.get().error).toBeTruthy() + + // No further attempts after the budget is spent — bounded, not infinite. + await advanceBackoff() + expect(desktop.getConnection).toHaveBeenCalledTimes(6) + }) + + it('FIX #82679: a NON-retryable boot failure (local / confirmed reauth) fails immediately without auto-retry', async () => { + const desktop = fakeDesktop() + desktop.getConnection = vi.fn(async () => { + throw new Error('401: gateway session expired') + }) + desktop.getBootProgress = vi.fn(async () => ({ + error: '401: gateway session expired', + fakeMode: false, + message: 'Desktop boot failed: 401: gateway session expired', + phase: 'backend.error', + progress: 24, + retryable: false, + running: false, + timestamp: Date.now() + })) + ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop + + render() + await flushAsync() + + expect($desktopBoot.get().error).toBeTruthy() + expect(desktop.getConnection).toHaveBeenCalledTimes(1) + + // Still no retry later: a missing capability is not a transient failure. + await advanceBackoff() + expect(desktop.getConnection).toHaveBeenCalledTimes(1) + }) }) 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 73981edcb7..0af663741b 100644 --- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts +++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts @@ -11,6 +11,7 @@ import { applyDesktopBootProgress, completeDesktopBoot, failDesktopBoot, + resumeDesktopBootForRetry, setDesktopBootStep } from '@/store/boot' import { @@ -70,6 +71,20 @@ import { stashGatewaySurvivor, survivorIsStale, takeGatewaySurvivor } from './ga // original ~45s calibration. const RECONNECT_ESCALATE_AFTER_MS = 45_000 +// Bounded self-heal for a failed REMOTE boot (#82679): when the primary boot +// fails on a transient remote fault (dropped SSH/HTTP registered connection, +// mint timeout — main tags those `retryable` on the boot progress), the +// renderer re-attempts the whole boot with the same full-jitter backoff the +// post-boot reconnect loop uses, up to this many attempts. Retries are +// bounded and end in the real recovery affordance (the boot-failure overlay +// with Retry / Settings), never an infinite spinner. Local failures and +// confirmed reauth rejections never enter this loop — a missing capability +// differs from a transient failure. +const BOOT_RETRY_MAX_ATTEMPTS = 5 +// Base delay for boot retries. Deliberately slower than the socket reconnect +// loop's 300ms: each attempt may rebuild an SSH master + remote dashboard. +const BOOT_RETRY_BASE_DELAY_MS = 2_000 + interface GatewayBootOptions { beforeConnectionSwitch: () => void handleGatewayEvent: (event: RpcEvent) => void @@ -148,6 +163,30 @@ export function useGatewayBoot({ // dead-end CONNECTING screen. Reset on a clean open or a manual/ // wake-driven reconnect. let escalated = false + // Bounded automatic boot retry for transient REMOTE failures (#82679). + let bootRetryAttempt = 0 + let bootRetryTimer: ReturnType | null = null + + const clearBootRetryTimer = () => { + if (bootRetryTimer !== null) { + clearTimeout(bootRetryTimer) + bootRetryTimer = null + } + } + + // Whether the failed boot is a TRANSIENT remote fault main marked as + // retryable (dropped SSH/HTTP registered connection, mint timeout). + // Local failures and confirmed reauth rejections come back false and go + // straight to the recovery overlay. + const bootFailureIsRetryable = async (): Promise => { + try { + const snapshot = await desktop.getBootProgress() + + return snapshot?.retryable === true + } catch { + return false + } + } // Wrap the live getter in a call so TS control-flow analysis doesn't narrow // `connectionState` to a constant across the early-return guards (the state @@ -322,6 +361,8 @@ export function useGatewayBoot({ $gatewaySwitching.set(true) clearReconnectTimer() + clearBootRetryTimer() + bootRetryAttempt = 0 reconnectAttempt = 0 reconnectFailingSince = null escalated = false @@ -650,9 +691,32 @@ export function useGatewayBoot({ completeDesktopBoot() bootCompleted = true + bootRetryAttempt = 0 } catch (err) { if (!cancelled) { const message = err instanceof Error ? err.message : String(err) + + // Transient remote failure (dropped SSH/HTTP registered connection, + // mint timeout): self-heal with bounded, jittered retries instead of + // parking on "Desktop boot failed" until the user re-enters the same + // connection details (#82679). Main already cleared the failed cached + // descriptor, so the next getConnection() rebuilds the connection — + // exactly what manual re-entry forced. Exhausted retries, local + // failures, and confirmed reauth rejections end in the real recovery + // affordance (the boot-failure overlay), never an infinite spinner. + if (bootRetryAttempt < BOOT_RETRY_MAX_ATTEMPTS && (await bootFailureIsRetryable()) && !cancelled) { + const delay = reconnectBackoffDelayMs(bootRetryAttempt, { baseDelayMs: BOOT_RETRY_BASE_DELAY_MS }) + bootRetryAttempt += 1 + resumeDesktopBootForRetry(translateNow('boot.steps.retryingRemoteBackend')) + clearBootRetryTimer() + bootRetryTimer = setTimeout(() => { + bootRetryTimer = null + void boot() + }, delay) + + return + } + failDesktopBoot(message) notifyError(err, translateNow('boot.errors.desktopBootFailed')) setSessionsLoading(false) @@ -701,6 +765,7 @@ export function useGatewayBoot({ cancelled = true $gatewaySwitching.set(false) clearReconnectTimer() + clearBootRetryTimer() clearInterval(keepaliveTimer) offWorking() offAttention() diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts index 39d32b4120..14968e3490 100644 --- a/apps/desktop/src/global.d.ts +++ b/apps/desktop/src/global.d.ts @@ -914,6 +914,13 @@ export interface DesktopBootProgress { message: string phase: string progress: number + /** + * True when the boot failure carried by `error` was a TRANSIENT remote + * failure (dropped SSH/HTTP registered connection, mint timeout) that the + * renderer may retry automatically. Absent/false on success updates, + * local failures, and confirmed reauth rejections. + */ + retryable?: boolean running: boolean timestamp: number } diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts index e6a1840cf5..63a3fc21a1 100644 --- a/apps/desktop/src/i18n/ar.ts +++ b/apps/desktop/src/i18n/ar.ts @@ -61,6 +61,7 @@ export const ar = defineLocale({ connectingGateway: 'جار الاتصال ببوابة سطح المكتب', loadingSettings: 'جار تحميل إعدادات Hermes', loadingSessions: 'جار تحميل الجلسات الأخيرة', + retryingRemoteBackend: 'جارٍ إعادة الاتصال بخادم Hermes البعيد…', startingDesktopConnection: 'جار بدء اتصال سطح المكتب', startingHermesDesktop: 'جار تشغيل Hermes Desktop...' }, diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index f9d2e73992..66fef81950 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -68,6 +68,7 @@ export const en: Translations = { connectingGateway: 'Connecting live desktop gateway', loadingSettings: 'Loading Hermes settings', loadingSessions: 'Loading recent sessions', + retryingRemoteBackend: 'Reconnecting to the remote Hermes backend…', startingDesktopConnection: 'Starting desktop connection', startingHermesDesktop: 'Starting Hermes Desktop…' }, diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts index 0f188bcad5..b867991316 100644 --- a/apps/desktop/src/i18n/ja.ts +++ b/apps/desktop/src/i18n/ja.ts @@ -68,6 +68,7 @@ export const ja = defineLocale({ connectingGateway: 'ライブデスクトップゲートウェイに接続中', loadingSettings: 'Hermes の設定を読み込み中', loadingSessions: '最近のセッションを読み込み中', + retryingRemoteBackend: 'リモート Hermes バックエンドに再接続中…', startingDesktopConnection: 'デスクトップ接続を開始中', startingHermesDesktop: 'Hermes Desktop を起動中…' }, diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts index d016106f2b..9ad887c970 100644 --- a/apps/desktop/src/i18n/types.ts +++ b/apps/desktop/src/i18n/types.ts @@ -114,6 +114,7 @@ export interface Translations { connectingGateway: string loadingSettings: string loadingSessions: string + retryingRemoteBackend: string startingDesktopConnection: string startingHermesDesktop: string } diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts index 08eab1e78c..6ffb40f36d 100644 --- a/apps/desktop/src/i18n/zh-hant.ts +++ b/apps/desktop/src/i18n/zh-hant.ts @@ -68,6 +68,7 @@ export const zhHant = defineLocale({ connectingGateway: '正在連線桌面閘道', loadingSettings: '正在載入 Hermes 設定', loadingSessions: '正在載入最近工作階段', + retryingRemoteBackend: '正在重新連線遠端 Hermes 後端…', startingDesktopConnection: '正在啟動桌面連線', startingHermesDesktop: '正在啟動 Hermes Desktop…' }, diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index cdb668d480..a0abb9a861 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -68,6 +68,7 @@ export const zh: Translations = { connectingGateway: '正在连接桌面网关', loadingSettings: '正在加载 Hermes 设置', loadingSessions: '正在加载最近会话', + retryingRemoteBackend: '正在重新连接远程 Hermes 后端…', startingDesktopConnection: '正在启动桌面连接', startingHermesDesktop: '正在启动 Hermes 桌面版…' }, diff --git a/apps/desktop/src/store/boot.ts b/apps/desktop/src/store/boot.ts index 5300bdfc7d..c8937fe0dc 100644 --- a/apps/desktop/src/store/boot.ts +++ b/apps/desktop/src/store/boot.ts @@ -66,6 +66,27 @@ export function setDesktopBootStep(step: { }) } +/** + * Re-arm the boot overlay for an automatic bounded retry of a failed REMOTE + * boot (#82679). Unlike setDesktopBootStep — whose null `error` intentionally + * cannot clear a latched failure — this explicitly lifts the error so the + * overlay shows the retry status instead of the terminal failure surface + * while the retry is in flight. failDesktopBoot() re-latches when the + * bounded retries are exhausted. + */ +export function resumeDesktopBootForRetry(message: string) { + const current = $desktopBoot.get() + $desktopBoot.set({ + ...current, + error: null, + message, + phase: 'renderer.boot.retry', + running: true, + timestamp: Date.now(), + visible: true + }) +} + export function completeDesktopBoot(message = translateNow('boot.ready')) { const current = $desktopBoot.get() $desktopBoot.set({