fix(desktop): self-heal dropped SSH/HTTP registered remote connections

A dropped registered remote connection (SSH or HTTP) never recovered on
its own: the next boot attempt failed with a transient transport error
("Could not verify the existing SSH backend", ERR_CONNECTION_RESET,
mint timeout), the failure was correctly NOT latched, but nothing ever
re-attempted the boot — the renderer's reconnect machinery only arms
after a completed boot. The app parked on "Desktop boot failed" until
the user manually deleted and re-entered the same connection details,
which merely forced the fresh bootstrap an automatic retry would have
performed (issue 82679, feature ask 80430).

Root causes and fixes:

- electron/backend-start-failure.ts: new isRetryableRemoteBootFailure()
  predicate — a remote, non-reauth boot failure is transient and may be
  retried; local failures and confirmed 401/403 rejections are not
  (a missing capability differs from a transient failure).
- electron/main.ts: the boot-failure progress broadcast now carries
  `retryable` (rides with `error` through updateBootProgress), and a
  failed reuse probe against a cached SSH master tears the stale
  master/tunnel down so the next attempt bootstraps fresh — exactly
  what manual re-entry did.
- use-gateway-boot.ts: bounded self-heal loop for a failed boot whose
  progress is marked retryable — up to 5 re-attempts with the same
  full-jitter backoff as the socket reconnect loop (2s base, 15s cap).
  Exhausted retries end in the real boot-failure recovery overlay,
  never an infinite spinner. Reset on success and on soft switch;
  timer cleared on unmount.
- store/boot.ts: resumeDesktopBootForRetry() re-arms the overlay with a
  retry status while an automatic retry is in flight.

Secondaries already had full-jitter backoff (store/gateway.ts); this
closes the same class for the PRIMARY/registered-connection path.

Tests: predicate matrix (retryable vs reauth-latch mutually exclusive),
plus renderer hook tests proving a transient SSH failure self-heals on
the next attempt, retries are bounded (6 total dials then the recovery
overlay, no further attempts), and non-retryable failures never enter
the loop. Sabotage-verified (disabling either half fails 4 tests).

Fixes #82679
Fixes #80430
This commit is contained in:
Teknium
2026-08-16 19:10:37 -07:00
parent ace85d63de
commit 2b7f49673f
13 changed files with 297 additions and 5 deletions
@@ -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`)
}
})
@@ -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
}
+28 -1
View File
@@ -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 }
@@ -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(<Harness />)
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(<Harness />)
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(<Harness />)
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)
})
})
@@ -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<typeof setTimeout> | 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<boolean> => {
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()
+7
View File
@@ -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
}
+1
View File
@@ -61,6 +61,7 @@ export const ar = defineLocale({
connectingGateway: 'جار الاتصال ببوابة سطح المكتب',
loadingSettings: 'جار تحميل إعدادات Hermes',
loadingSessions: 'جار تحميل الجلسات الأخيرة',
retryingRemoteBackend: 'جارٍ إعادة الاتصال بخادم Hermes البعيد…',
startingDesktopConnection: 'جار بدء اتصال سطح المكتب',
startingHermesDesktop: 'جار تشغيل Hermes Desktop...'
},
+1
View File
@@ -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…'
},
+1
View File
@@ -68,6 +68,7 @@ export const ja = defineLocale({
connectingGateway: 'ライブデスクトップゲートウェイに接続中',
loadingSettings: 'Hermes の設定を読み込み中',
loadingSessions: '最近のセッションを読み込み中',
retryingRemoteBackend: 'リモート Hermes バックエンドに再接続中…',
startingDesktopConnection: 'デスクトップ接続を開始中',
startingHermesDesktop: 'Hermes Desktop を起動中…'
},
+1
View File
@@ -114,6 +114,7 @@ export interface Translations {
connectingGateway: string
loadingSettings: string
loadingSessions: string
retryingRemoteBackend: string
startingDesktopConnection: string
startingHermesDesktop: string
}
+1
View File
@@ -68,6 +68,7 @@ export const zhHant = defineLocale({
connectingGateway: '正在連線桌面閘道',
loadingSettings: '正在載入 Hermes 設定',
loadingSessions: '正在載入最近工作階段',
retryingRemoteBackend: '正在重新連線遠端 Hermes 後端…',
startingDesktopConnection: '正在啟動桌面連線',
startingHermesDesktop: '正在啟動 Hermes Desktop…'
},
+1
View File
@@ -68,6 +68,7 @@ export const zh: Translations = {
connectingGateway: '正在连接桌面网关',
loadingSettings: '正在加载 Hermes 设置',
loadingSessions: '正在加载最近会话',
retryingRemoteBackend: '正在重新连接远程 Hermes 后端…',
startingDesktopConnection: '正在启动桌面连接',
startingHermesDesktop: '正在启动 Hermes 桌面版…'
},
+21
View File
@@ -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({