The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): single-owner backend dial claim in Electron main (#90812)
Tekniumbb3421bf2584
diff --git a/apps/desktop/electron/backend-dial-claim.test.ts b/apps/desktop/electron/backend-dial-claim.test.tsnew file mode 100644index 00000000000..6d13d7b261f--- /dev/null+++ b/apps/desktop/electron/backend-dial-claim.test.ts@@ -0,0 +1,143 @@+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import { describe, expect, it, vi } from 'vitest'++import { BackendDialClaims } from './backend-dial-claim'+import { parseBackendScopeKey } from './connection-registry'++const here = path.dirname(fileURLToPath(import.meta.url))+const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')++describe('BackendDialClaims (#90812)', () => {+ it('coalesces two concurrent dials for the same (connectionId, profile) onto ONE backend spawn', async () => {+ const claims = new BackendDialClaims()+ let spawns = 0+ let resolveSpawn: ((value: { baseUrl: string }) => void) | undefined++ const dial = vi.fn(() => {+ spawns += 1++ return new Promise<{ baseUrl: string }>(resolve => {+ resolveSpawn = resolve+ })+ })++ // Two renderer windows race the same reconnect: reconnectGateway()'s+ // in-flight lock is per-renderer, so BOTH invoke the main-process dial.+ const first = claims.run('conn:office-ssh::default', dial)+ const second = claims.run('conn:office-ssh::default', dial)++ expect(spawns).toBe(1)++ resolveSpawn?.({ baseUrl: 'http://127.0.0.1:53150' })++ const [firstResult, secondResult] = await Promise.all([first, second])++ // The second caller receives the FIRST dial's result, not its own spawn.+ expect(firstResult).toBe(secondResult)+ expect(firstResult).toEqual({ baseUrl: 'http://127.0.0.1:53150' })+ expect(dial).toHaveBeenCalledTimes(1)+ })++ it('scopes claims by key: different (connectionId, profile) pairs dial independently', async () => {+ const claims = new BackendDialClaims()+ const dialA = vi.fn(async () => 'a')+ const dialB = vi.fn(async () => 'b')++ const [a, b] = await Promise.all([+ claims.run('conn:office-ssh::default', dialA),+ claims.run('conn:office-ssh::work', dialB)+ ])++ expect(a).toBe('a')+ expect(b).toBe('b')+ expect(dialA).toHaveBeenCalledTimes(1)+ expect(dialB).toHaveBeenCalledTimes(1)+ })++ it('releases the claim once the dial settles so a later reconnect can dial again (bounded, not latched)', async () => {+ const claims = new BackendDialClaims()+ const dial = vi.fn(async () => 'fresh')++ await claims.run('default', dial)+ expect(claims.inFlight('default')).toBe(false)++ await claims.run('default', dial)+ expect(dial).toHaveBeenCalledTimes(2)+ })++ it('propagates a failed dial to every coalesced waiter and never caches the rejection', async () => {+ const claims = new BackendDialClaims()+ let rejectSpawn: ((error: Error) => void) | undefined++ const failingDial = vi.fn(+ () =>+ new Promise<never>((_resolve, reject) => {+ rejectSpawn = reject+ })+ )++ const first = claims.run('conn:office-ssh::default', failingDial)+ const second = claims.run('conn:office-ssh::default', failingDial)+ expect(failingDial).toHaveBeenCalledTimes(1)++ rejectSpawn?.(new Error('ssh dial failed'))++ await expect(first).rejects.toThrow('ssh dial failed')+ await expect(second).rejects.toThrow('ssh dial failed')++ // Fail closed but not latched: the NEXT dial attempt runs fresh.+ const recovered = vi.fn(async () => 'recovered')+ await expect(claims.run('conn:office-ssh::default', recovered)).resolves.toBe('recovered')+ expect(recovered).toHaveBeenCalledTimes(1)+ })++ it('a synchronously-throwing dial rejects the claim instead of escaping the coalescing seam', async () => {+ const claims = new BackendDialClaims()++ await expect(+ claims.run('default', () => {+ throw new Error('spawn refused')+ })+ ).rejects.toThrow('spawn refused')++ expect(claims.inFlight('default')).toBe(false)+ })+})++describe('parseBackendScopeKey (#90812/#93910)', () => {+ it('round-trips the composite pool key back to (connectionId, profile)', () => {+ expect(parseBackendScopeKey('conn:office-ssh::default')).toEqual({+ connectionId: 'office-ssh',+ profile: 'default'+ })+ expect(parseBackendScopeKey('conn:office-ssh::work')).toEqual({ connectionId: 'office-ssh', profile: 'work' })+ })++ it('treats a bare profile key as the local/primary scope', () => {+ expect(parseBackendScopeKey('default')).toEqual({ connectionId: null, profile: 'default' })+ expect(parseBackendScopeKey('work')).toEqual({ connectionId: null, profile: 'work' })+ })+})++describe('main.ts wiring for #90812', () => {+ it('routes the profile-scoped dial IPC through the single-owner claim', () => {+ const handlerStart = mainSource.indexOf("ipcMain.handle('hermes:connection', ")+ expect(handlerStart).toBeGreaterThan(-1)+ const body = mainSource.slice(handlerStart, handlerStart + 900)++ expect(body).toContain('backendDialClaims.run(')+ expect(body).toContain('ensureBackend(profile)')+ })++ it('routes the registry-scoped dial IPC through the claim keyed by backendScopeKey(connectionId, profile)', () => {+ const handlerStart = mainSource.indexOf("ipcMain.handle('hermes:connection:for', ")+ expect(handlerStart).toBeGreaterThan(-1)+ const body = mainSource.slice(handlerStart, handlerStart + 1_200)++ expect(body).toContain('backendDialClaims.run(backendScopeKey(id, profile)')+ expect(body).toContain('ensureRegistryBackend(id, profile)')+ })+})diff --git a/apps/desktop/electron/backend-dial-claim.ts b/apps/desktop/electron/backend-dial-claim.tsnew file mode 100644index 00000000000..e71ffe5f4ea--- /dev/null+++ b/apps/desktop/electron/backend-dial-claim.ts@@ -0,0 +1,58 @@+/**+ * backend-dial-claim.ts+ *+ * Single-owner reconnect/dial claim for backend spawns, keyed by the pool+ * scope key from backendScopeKey(connectionId, profile) (#90812).+ *+ * Why this exists: reconnectGateway()'s in-flight lock lives at renderer+ * module scope, so it only dedupes reconnects INSIDE one window. Two windows+ * (main + a session pop-out) racing the same wake both invoke the main-process+ * dial IPC, and for a pooled SSH connection the loser of the pool-entry race+ * could bootstrap a duplicate remote backend. Electron main is the single+ * owner of backend lifecycles, so the claim belongs here: the first dial for a+ * (connectionId, profile) key runs; every concurrent caller for the same key+ * awaits and receives that first dial's result.+ *+ * Bounded by construction: a claim exists only while its dial promise is+ * unsettled — both outcomes release it, so a failed dial is never cached and+ * the next reconnect attempt runs fresh (fail closed, not latched).+ */+export class BackendDialClaims {+ readonly #inflightByKey = new Map<string, Promise<unknown>>()++ /** Whether a dial for this key is currently in flight (test/diagnostic seam). */+ inFlight(key: string): boolean {+ return this.#inflightByKey.has(key)+ }++ run<T>(key: string, dial: () => Promise<T> | T): Promise<T> {+ const existing = this.#inflightByKey.get(key) as Promise<T> | undefined++ if (existing) {+ return existing+ }++ // Start the dial eagerly so the first caller's spawn is already in flight+ // when a concurrent caller arrives; a synchronously-throwing dial is+ // converted into a rejection of THIS claim so it cannot bypass the seam.+ let pending: Promise<T>++ try {+ pending = Promise.resolve(dial())+ } catch (error) {+ pending = Promise.reject(error)+ }++ const release = () => {+ if (this.#inflightByKey.get(key) === pending) {+ this.#inflightByKey.delete(key)+ }+ }++ this.#inflightByKey.set(key, pending)+ // Release on both outcomes without creating an unhandled rejected branch.+ void pending.then(release, release)++ return pending+ }+}diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.tsindex 309ac2070f1..582d599532d 100644--- a/apps/desktop/electron/connection-registry.ts+++ b/apps/desktop/electron/connection-registry.ts@@ -171,6 +171,24 @@ export function backendScopeKey(connectionId: null | string | undefined, profilereturn `conn:${connection}::${profileKey}`}+/**+ * Inverse of backendScopeKey(): recover (connectionId, profile) from a pool+ * key. A bare profile key (the local/primary scope) maps to a null+ * connectionId. Used by the post-resume rebuild path (#93910) to re-dial a+ * retired pool entry through the same claim-guarded ensure path a renderer+ * would use.+ */+export function parseBackendScopeKey(key: string): { connectionId: null | string; profile: string } {+ const value = String(key ?? '').trim()+ const match = /^conn:(.+?)::(.+)$/.exec(value)++ if (!match) {+ return { connectionId: null, profile: value || 'default' }+ }++ return { connectionId: match[1], profile: match[2] }+}+/** All pool keys owned by a connection share this prefix (used to stop them on remove). */export function backendScopePrefix(connectionId: string): string {return `conn:${String(connectionId).trim()}::`diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex b0db64b3f0c..87bc3930de9 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -45,6 +45,7 @@ import {} from './backend-claim'import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'+import { BackendDialClaims } from './backend-dial-claim'import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'import {isReauthRequiredError,@@ -131,6 +132,7 @@ import {migrateV1ToRegistry,normalizeConnectionInput,normalizeRegistry,+ parseBackendScopeKey,reconcileAppliedGlobalConnection,reconcileRegistryDrift,registrySourceOwnsPrimaryBackend,@@ -288,11 +290,13 @@ import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySetimport { type ActiveWork, mergeActiveWork, normalizeActiveWork, quitPromptFor } from './quit-guard'import * as remoteLifecycle from './remote-lifecycle'import {+ attachPowerResumeRemoteRevalidation,ensureHealthyPooledRemoteBackendForDispatch,RemoteLivenessTracker,RemoteRevalidationCoordinator,revalidatePooledRemoteBackends,- revalidateRemoteConnection+ revalidateRemoteConnection,+ revalidateSuspectPooledRemoteBackends} from './remote-liveness'import {applyRemoteRequestHeaders,@@ -1342,6 +1346,12 @@ const backendConnectionState = createBackendConnectionState<ReturnType<typeof spconst remoteLiveness = new RemoteLivenessTracker()const remoteRevalidation = new RemoteRevalidationCoordinator()const registryDispatchRevalidation = new RemoteRevalidationCoordinator()+// Single-owner reconnect/dial claim (#90812): reconnectGateway()'s in-flight+// lock is per-renderer, so two windows racing one wake can both invoke the+// backend ensure IPC and double-dial a pooled SSH backend. Main owns backend+// lifecycles, so concurrent dials for one (connectionId, profile) scope+// coalesce here — the second caller awaits the first spawn's result.+const backendDialClaims = new BackendDialClaims()// True while connection-config:apply soft-rehomes the primary — suppresses the// backend-exit toast so an intentional kill doesn't look like a crash.let softRehomeInProgress = false@@ -6356,6 +6366,15 @@ function registerPowerResumeListeners() {powerMonitor.on('on-battery', () => broadcastBatteryState(true))powerMonitor.on('on-ac', () => broadcastBatteryState(false))onBatteryPower = powerMonitor.isOnBatteryPower()+ // Pooled remote/SSH backends are also suspect after a wake (#93910): the+ // renderer nudge above only re-drives the PRIMARY socket, while pooled+ // tunnels have no renderer loop of their own. Bounded + coalesced inside;+ // never a hot loop.+ attachPowerResumeRemoteRevalidation({+ log: rememberLog,+ powerMonitor,+ revalidate: () => revalidateSuspectPoolAfterResume()+ })} catch {// powerMonitor is unavailable before app 'ready' on some platforms; the// caller registers after 'ready', so this should not normally throw.@@ -13079,7 +13098,12 @@ function createWindow() {}ipcMain.handle('hermes:connection', async (_event, profile) => {- const connection = await ensureBackend(profile)+ // Coalesce concurrent renderer dials for one profile scope (#90812): the+ // renderer-side reconnect lock is per-window, so two windows waking at once+ // both land here. The claim key mirrors ensureBackend()'s own profile+ // normalization so every spelling of the primary coalesces onto one dial.+ const profileKey = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()+ const connection = await backendDialClaims.run(backendScopeKey(null, profileKey), () => ensureBackend(profile))const connectionId = resolvedConnectionId(readDesktopConnectionsRegistry(), connection)return connectionId ? { ...connection, connectionId } : connection@@ -13093,7 +13117,10 @@ ipcMain.handle('hermes:connection:for', async (_event, payload) => {const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)const registry = readDesktopConnectionsRegistry()const id = String(connectionId || '').trim() || registry.primary- const connection = await ensureRegistryBackend(id, profile)+ // Same single-owner claim as 'hermes:connection', keyed by the composite+ // (connectionId, profile) scope (#90812): concurrent registry dials for one+ // scope share the first spawn instead of bootstrapping duplicate remotes.+ const connection = await backendDialClaims.run(backendScopeKey(id, profile), () => ensureRegistryBackend(id, profile))return { ...connection, connectionId: id, registryScoped: true }})@@ -13186,6 +13213,50 @@ function revalidatePool() {})}+// Re-dial one retired pool key through the SAME claim-guarded ensure path a+// renderer dial takes (#90812), so a resume-driven rebuild and a concurrent+// renderer reconnect coalesce onto one spawn instead of racing.+function redialPoolBackendAfterResume(poolKey: string) {+ const { connectionId, profile } = parseBackendScopeKey(poolKey)++ return backendDialClaims.run(poolKey, () =>+ connectionId ? ensureRegistryBackend(connectionId, profile) : ensureBackend(profile)+ )+}++// Identity for coalescing post-resume sweeps in the shared revalidation+// coordinator: overlapping resume/unlock/network-restore kicks join the one+// in-flight sweep instead of stacking probes.+const suspectPoolSweepScope = {}++// Sleep/wake recovery for POOLED remote/SSH backends (#93910). The primary+// renderer socket already has wake-path probe/reconnect nudges, but pooled+// descriptors (Bots pane, secondary connections) kept serving dead SSH+// tunnels after macOS resume: no child 'exit' fires for a remote, and the+// background failure-streak policy takes several rounds to drop one. On+// resume every pooled remote is suspect — probe each once (bounded), tear+// down the dead ones (pool entry + SSH bootstrap + tunnel/master) and rebuild+// them through the claim-guarded dial path.+function revalidateSuspectPoolAfterResume() {+ return remoteRevalidation.run(suspectPoolSweepScope, () =>+ revalidateSuspectPooledRemoteBackends({+ entries: backendPool.entries(),+ log: rememberLog,+ probe: (connection, path, options) => fetchJsonForBackend(connection, path, options),+ rebuild: poolKey => redialPoolBackendAfterResume(poolKey),+ retire: async poolKey => {+ await stopPoolBackend(poolKey)+ // The pool key doubles as the SSH scope for registry SSH backends and+ // resolves through sshScopeKey() for bare-profile remotes; both+ // teardown calls no-op when the scope holds no SSH state.+ await sshBootstrapCoordinator.cancelAndWait(poolKey)+ await teardownSshConnection(poolKey)+ },+ tracker: remoteLiveness+ })+ )+}+ipcMain.handle('hermes:backend:touch', async (_event, profile) => {touchPoolBackend(profile)