The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop failing a source switch that is still dialing
psam5a41f9e8a8a1
diff --git a/apps/desktop/src/lib/with-timeout.ts b/apps/desktop/src/lib/with-timeout.tsindex 9197aaa8fed..a1605b4e521 100644--- a/apps/desktop/src/lib/with-timeout.ts+++ b/apps/desktop/src/lib/with-timeout.ts@@ -19,6 +19,25 @@ export const BACKEND_BOOT_WAIT_TIMEOUT_MS = 180_000// caller forever. Every caller of these bounds them with this shared budget.export const RECONNECT_ATTEMPT_TIMEOUT_MS = 20_000+/** Budget for the phase-1 dial of a source switch (store/connections+ * selectConnection). Unlike the two above this await is not one IPC: it is the+ * main process's whole remote bring-up chain — one ssh connect+ * (DEFAULT_CONNECT_TIMEOUT_MS 15 s in electron/ssh-connection.ts), the+ * sequential ssh execs that probe platform, locate the runtime and read its+ * version (DEFAULT_EXEC_TIMEOUT_MS 20 s each), the spawned backend's ready+ * sentinel (DEFAULT_READY_TIMEOUT_MS 45 s in electron/remote-lifecycle.ts) and+ * the port forward (DEFAULT_FORWARD_TIMEOUT_MS 15 s). Their sum is ~135 s, and+ * a *healthy* cold dial lands far inside it — measured 37-64 s against a 2 GB+ * VPS over Windows ssh (no mux: every stage is a fresh ssh process plus a cold+ * `serve` boot).+ *+ * Bounding that chain with RECONNECT_ATTEMPT_TIMEOUT_MS reported+ * "Could not connect to <source>" for switches that were still dialing, and+ * then connected anyway (withTimeout does not cancel the dial), which read as a+ * failure the user had to retry. The per-IPC budget still catches the #93454+ * class from inside the dial; this one only has to outlast a legitimate dial. */+export const SOURCE_SWITCH_DIAL_TIMEOUT_MS = 135_000+/** Rejection raised by withTimeout. The bounded work is NOT cancelled — the* caller decides what a straggler that settles later means. */export class TimeoutError extends Error {diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.tsindex 8010b3fa053..496c9d0fa6b 100644--- a/apps/desktop/src/store/connections.test.ts+++ b/apps/desktop/src/store/connections.test.ts@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'import type { DesktopConnectionsRegistry } from '@/global'-import { BACKEND_BOOT_WAIT_TIMEOUT_MS } from '@/lib/with-timeout'+import { BACKEND_BOOT_WAIT_TIMEOUT_MS, SOURCE_SWITCH_DIAL_TIMEOUT_MS } from '@/lib/with-timeout'import { deferred } from '../test/deferred'@@ -643,6 +643,47 @@ describe('selectConnection', () => {}})+ it('a slow-but-healthy dial is not a failed switch: the source caps only past the ssh layer budget, and the click lands', async () => {+ vi.useFakeTimers()++ try {+ const dial = deferred<void>()++ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })+ openGatewayAgent.mockImplementationOnce(() => dial.promise)++ let outcome = 'pending'++ const attempt = selectConnection('homelab').then(+ () => {+ outcome = 'resolved'+ },+ (error: Error) => {+ outcome = error.message+ }+ )++ // A cold remote dial is a chain of main-process stages (ssh connect, the+ // platform/locate/version execs, the spawned backend's ready sentinel, the+ // forward) that routinely outruns the 20 s reconnect-class budget: measured+ // 37-64 s against a small VPS. The switch must keep waiting instead of+ // toasting "Could not connect to <source>" for a source that is arriving.+ await vi.advanceTimersByTimeAsync(60_000)+ expect(outcome).toBe('pending')+ expect($pendingConnectionId.get()).toBe('homelab')++ dial.resolve()+ await attempt++ expect(outcome).toBe('resolved')+ expect($connection.get()?.connectionId).toBe('homelab')+ expect($gatewaySwitching.get()).toBe(false)+ } finally {+ vi.useRealTimers()+ }+ })+it('a dial that never answers times out: nothing severed, the click fails visibly, and the source can be retried', async () => {vi.useFakeTimers()@@ -657,7 +698,7 @@ describe('selectConnection', () => {(error: Error) => error.message)- await vi.advanceTimersByTimeAsync(20_000)+ await vi.advanceTimersByTimeAsync(SOURCE_SWITCH_DIAL_TIMEOUT_MS)expect(await outcome).toMatch(/Timed out connecting to "Homelab"/)expect(ensureGatewayAgent).not.toHaveBeenCalled()diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 5e72929dc90..0462e1d1bf1 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -4,7 +4,12 @@ import { getProfiles } from '@/api/profiles'import type { DesktopConnectionsRegistry } from '@/global'import { invalidateProfileScopedQueries } from '@/lib/query-client'import { persistStringRecord, storedStringRecord } from '@/lib/storage'-import { BACKEND_BOOT_WAIT_TIMEOUT_MS, isTimeoutError, withTimeout } from '@/lib/with-timeout'+import {+ BACKEND_BOOT_WAIT_TIMEOUT_MS,+ isTimeoutError,+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,+ withTimeout+} from '@/lib/with-timeout'import { $connectionsRegistry } from '@/store/connection-registry-state'import { $defaultProfileRoute, refreshDefaultProfile } from '@/store/default-profile'import {@@ -34,7 +39,12 @@ const LAST_PROFILE_STORAGE_KEY = 'hermes.desktop.lastProfileByConnection'// handshake or IPC (the #93454 class) must surface as a failed click — not a// spinner that also swallows every later click on the same source, and never// a barrier left up or a wipe left unpainted.-const SWITCH_DIAL_TIMEOUT_MS = 20_000+//+// The dial and the commit are different work and so carry different budgets.+// The commit is local (sever the old bindings, activate, publish) and stays at+// the reconnect-class 20 s. The dial is the main process's whole remote+// bring-up chain, which the renderer cannot time from here — see+// SOURCE_SWITCH_DIAL_TIMEOUT_MS in lib/with-timeout.ts for its composition.const SWITCH_COMMIT_TIMEOUT_MS = 20_000const SWITCH_REMEMBER_TIMEOUT_MS = 5_000// Matches the primary spawn budget: a healthy cold boot publishes well within@@ -411,7 +421,7 @@ export async function selectConnection(connectionId: string, options: SelectConn// and a registry primary can differ from a legacy per-profile override.await withTimeout(openGatewayAgent(connectionId, targetProfile),- SWITCH_DIAL_TIMEOUT_MS,+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,`Timed out connecting to "${targetConnection.label}".`)@@ -431,7 +441,7 @@ export async function selectConnection(connectionId: string, options: SelectConn// the exact failure for caller UX (network failures are not sign-in errors).await withTimeout(getProfiles({ connectionId, profile: targetProfile }),- SWITCH_DIAL_TIMEOUT_MS,+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,`Timed out connecting to "${targetConnection.label}".`)diff --git a/apps/desktop/src/store/gateway.test.ts b/apps/desktop/src/store/gateway.test.tsindex 34b42a520df..14758741bb4 100644--- a/apps/desktop/src/store/gateway.test.ts+++ b/apps/desktop/src/store/gateway.test.ts@@ -358,6 +358,61 @@ describe('secondary connection timeout (#93454)', () => {expect(callCount).toBe(2)expect(activeGateway()).toBe(gatewayMocks.instances[0])})++ it('waits out a slow registry bring-up instead of failing the dial at the reconnect budget', async () => {+ // A registry route is not one IPC: it is a backend coming up on ANOTHER+ // machine — ssh connect, the platform/locate/version probes, the remote+ // spawn and its ready sentinel. Cold bring-ups measured 37-64 s against a+ // small VPS, so the reconnect-class budget rejected a dial that was still+ // arriving (~20 s later it landed anyway, and the user read the toast as a+ // failure).+ vi.useFakeTimers()++ try {+ let release: () => void = () => undefined++ const getConnectionFor = vi.fn(+ () =>+ new Promise(resolve => {+ release = () =>+ resolve({+ authMode: 'token',+ connectionId: 'homelab',+ profile: 'default',+ wsUrl: 'wss://homelab.invalid/ws'+ })+ })+ )++ installDesktop({ getConnectionFor })++ // The #92434 pin above leaves gatewayMocks.connect latched on a+ // never-resolving mockImplementation; restore the resolving dial.+ gatewayMocks.connect.mockImplementation(async () => undefined)++ let outcome = 'pending'++ const dial = openGatewayForAgent('homelab', 'default').then(+ () => {+ outcome = 'resolved'+ },+ (error: Error) => {+ outcome = error.message+ }+ )++ await vi.advanceTimersByTimeAsync(60_000)+ expect(outcome).toBe('pending')++ release()+ await dial++ expect(outcome).toBe('resolved')+ expect(gatewayMocks.instances[0].connectionState).toBe('open')+ } finally {+ vi.useRealTimers()+ }+ })})describe('server→client request routing without a registry handler (#112791)', () => {diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 302e8e78324..7d40c0b3928 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -19,7 +19,12 @@ import {LIVENESS_REPROBE_DELAY_MS} from '@/lib/gateway-liveness-policy'import { isMissingRpcMethod } from '@/lib/gateway-rpc'-import { isTimeoutError, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'+import {+ isTimeoutError,+ RECONNECT_ATTEMPT_TIMEOUT_MS,+ SOURCE_SWITCH_DIAL_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'@@ -777,6 +782,12 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b// this secondary (SSH terminal, messaging DELETE, session send, …) never// settles either. Bound the same way use-gateway-boot.ts bounds the// primary's equivalent awaits.+ //+ // Two bring-ups with different legitimate worst cases: a registry route is a+ // backend coming up on ANOTHER machine (ssh connect + probes + remote spawn ++ // ready sentinel), which is the SOURCE_SWITCH_DIAL budget, while a local+ // profile's pooled child spawns on this machine (measured ~9 s; the+ // reconnect-class budget is not the binding constraint there).const conn =entry.connectionId && desktop.getConnectionFor? await withTimeout(@@ -785,7 +796,7 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bprofile: entry.profile,...dialPriority(spawnPriority)}),- RECONNECT_ATTEMPT_TIMEOUT_MS,+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,`Timed out connecting to profile "${entry.profile}"`): await withTimeout(