The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a retired scope parks instead of redialing
Austin Pickett0fa67196b438
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex e76e5e14617..26c40861b59 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -39,6 +39,7 @@ import {gatewayActivationEpoch,isActivePrimary,liveSecondaryConnectionIds,+ parkSecondariesForRetiredBackend,pruneSecondaryGateways,reconnectSecondaryGateways,reportPrimaryGatewayState,@@ -1058,6 +1059,17 @@ export function useGatewayBoot({}})+ // Cooperative pool retirement: main is stopping a pooled backend so a+ // foreground open elsewhere gets its slot. Park the scopes riding it now,+ // before the socket drops, so neither the 'closed' state nor the next+ // focus/wake nudge redials into the slot it vacated. The tile keeps its+ // card; the next click on it re-arms the scope.+ const offPoolRetiring = desktop.onPoolBackendRetiring?.(payload => {+ if (payload && typeof payload.poolKey === 'string') {+ parkSecondariesForRetiredBackend(payload.poolKey)+ }+ })+const onOnline = () => void forceReconnectNow()const onVisible = () => {@@ -1390,6 +1402,7 @@ export function useGatewayBoot({offPowerResume?.()offConnectionApplied?.()offConnectionsChanged?.()+ offPoolRetiring?.()offGatewayReconnect()offActiveGatewayReauth()offActiveStateReauth()diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex 5eb5db4b1c5..9bc77685eb1 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -63,6 +63,7 @@ const {ensureGatewayForProfile,openGatewayForAgent,openGatewayForProfile,+ parkSecondariesForRetiredBackend,pruneSecondaryGateways,reconnectSecondaryGateways,retainGatewayForAgent,@@ -725,3 +726,71 @@ describe('secondary stalled-dial budget', () => {expect(getConnectionFor.mock.calls.length).toBe(parkedDials + 1)})})++describe('cooperative pool retirement (supersedes #104871)', () => {+ it('a retired scope parks: no reconnect on socket drop and no redial from the wake/focus nudge; an explicit open re-arms it', async () => {+ vi.useFakeTimers()++ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )++ installDesktop({ getConnectionFor })++ // A bot tile pinned this local child under the registry-local scope; main+ // pools that child under the bare profile key.+ await ensureGatewayForAgent('local', 'bot-a')+ await ensureGatewayForAgent('homelab', 'bot-b')+ expect(gatewayMocks.instances).toHaveLength(2)+ const dialsBefore = getConnectionFor.mock.calls.length++ // Main announces the retirement BEFORE it SIGTERMs the child.+ expect(parkSecondariesForRetiredBackend('bot-a')).toEqual(['conn:local::bot-a'])++ // Then the child exits and the socket drops.+ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }+ socket.connectionState = 'closed'++ // Neither the recovery nudge (focus / online / wake) nor time redials the+ // retired scope; the unrelated remote scope is untouched.+ reconnectSecondaryGateways()+ await vi.advanceTimersByTimeAsync(0)++ for (let index = 0; index < 20; index += 1) {+ await vi.advanceTimersByTimeAsync(20_000)+ }++ expect(getConnectionFor.mock.calls.filter(([args]) => args.profile === 'bot-a')).toHaveLength(+ getConnectionFor.mock.calls.slice(0, dialsBefore).filter(([args]) => args.profile === 'bot-a').length+ )++ // Parked ≠ evicted: the entry survives for its tile, and an explicit open+ // (a click on the bot) is the one thing that re-arms and redials it.+ const before = getConnectionFor.mock.calls.length+ await ensureGatewayForAgent('local', 'bot-a')+ expect(getConnectionFor.mock.calls.length).toBe(before + 1)+ expect(getConnectionFor.mock.calls.at(-1)?.[0]).toMatchObject({ connectionId: 'local', profile: 'bot-a' })++ // Once re-armed, the nudge treats it like any other scope again.+ ;(gatewayMocks.instances.at(-1) as unknown as { connectionState: string }).connectionState = 'closed'+ reconnectSecondaryGateways()+ await vi.advanceTimersByTimeAsync(0)+ expect(getConnectionFor.mock.calls.length).toBe(before + 2)+ })++ it('touch pings carry the scope turn lease so main can skip leased residents early', async () => {+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )++ const touchBackend = vi.fn(async () => ({ ok: true }))++ installDesktop({ getConnectionFor, touchBackend })++ await ensureGatewayForAgent('homelab', 'bot-a')+ touchBackend.mockClear()++ touchSecondaryGateways()+ expect(touchBackend).toHaveBeenCalledWith('conn:homelab::bot-a', { activeTurn: false })+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 942a4c21449..d8e3608418a 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -139,6 +139,14 @@ interface Secondary {// While true the entry auto-reconnects on drop; pruning flips it off so a// deliberate close doesn't trigger the backoff loop.wantOpen: boolean+ /**+ * Main retired this scope's pooled backend for a foreground open elsewhere+ * (electron/pool-retire.ts). A parked-by-stall entry re-arms on the+ * wake/focus nudge; a retired one must not — that nudge would redial into+ * the very slot the retirement freed. Only an explicit open of the scope+ * clears it (rearmSecondary).+ */+ retiredByPool: boolean/*** Epoch-ms deadline while an activation (prepare/ensure) is mid-dial. The* live-work pruner must not dispose an entry the user is switching to: a@@ -715,6 +723,7 @@ function isStalledDialError(error: unknown): boolean {function rearmSecondary(entry: Secondary): void {entry.wantOpen = trueentry.stalledDials = 0+ entry.retiredByPool = false}function scheduleReconnect(entry: Secondary): void {@@ -829,6 +838,7 @@ function createSecondary(profile: string, connectionId: null | string = null): Sretained: false,relayRetainCount: 0,wantOpen: true,+ retiredByPool: false,activationLeaseUntil: 0}@@ -1397,14 +1407,37 @@ export async function retainGatewayForSessionTurn(}cancelTurnLeaseRelease(key)+ // Another session on the same scope may still hold a lease; report the+ // scope's state, not this lease's.+ publishTurnLease(scope, scopeHasTurnLease(scope))releaseRoute()}g.turnLeases.set(key, release)+ publishTurnLease(scope, true)return release}+function scopeHasTurnLease(scope: string): boolean {+ const prefix = `${scope}\u0000`++ for (const key of g.turnLeases.keys()) {+ if (key.startsWith(prefix)) {+ return true+ }+ }++ return false+}++// Tell main whether a prompt turn leases this scope's pooled backend. An early+// skip for cooperative retirement (electron/pool-retire.ts), never the proof:+// main asks the backend itself before stopping anything. From #104871.+function publishTurnLease(scope: string, activeTurn: boolean): void {+ void window.hermesDesktop?.touchBackend?.(scope, { activeTurn }).catch(() => undefined)+}+function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {const sessionId = String(event.session_id || '').trim()@@ -1727,6 +1760,13 @@ const ACTIVE_GATEWAY_OPEN_WAIT_MS = 8_000// signals can force sockets that still report open to retire before redialing.export function reconnectSecondaryGateways({ forceOpenSockets = false }: { forceOpenSockets?: boolean } = {}): void {for (const entry of g.secondaries.values()) {+ // A backend main retired for a foreground open stays parked: redialing it+ // from a focus/wake nudge would queue a background spawn for the slot the+ // retirement just freed. Its tile still shows; the next click re-arms it.+ if (entry.retiredByPool) {+ continue+ }+// A parked entry (stall budget spent) is still pinned by its surface, or// the pruner would have removed it. This nudge is an explicit recovery// signal (online / focus / wake), so it re-arms with a fresh budget.@@ -1769,17 +1809,62 @@ export function openSecondaryCount(): number {// "Live" means the socket is OPEN: a wantOpen entry stuck in its reconnect// backoff has no consumer on that backend, and pinging it anyway kept a// tile-pinned backend keepalive-fresh forever, so LRU eviction and the idle-// reaper never freed its pool slot (#103375).+// reaper never freed its pool slot (#103375). Each ping also carries whether a+// prompt turn leases the scope, so a foreground dial that must retire a+// resident can skip leased ones early (the backend probe stays the proof).export function touchSecondaryGateways(): void {const desktop = window.hermesDesktopfor (const entry of g.secondaries.values()) {if (entry.wantOpen && isOpen(entry.gateway)) {- void desktop?.touchBackend?.(entry.scope).catch(() => undefined)+ void desktop?.touchBackend?.(entry.scope, { activeTurn: scopeHasTurnLease(entry.scope) }).catch(() => undefined)}}}+// A local child is pooled under the bare profile (legacy route) or+// `conn:local::<profile>`; both renderer scopes ride the same child, so a+// retirement of either key parks both.+function secondaryRidesPoolKey(entry: Secondary, poolKey: string): boolean {+ if (entry.scope === poolKey) {+ return true+ }++ const local = !entry.connectionId || entry.connectionId === 'local'+ const profile = normKey(entry.profile)++ return local && (profile === poolKey || `conn:local::${profile}` === poolKey)+}++// Main is retiring the pooled backend under `poolKey` for a foreground open+// (electron/pool-retire.ts). Park every scope riding it BEFORE the socket+// drops: the 'closed' state must not scheduleReconnect, and the focus/wake+// nudge must not re-arm it either — both would queue a background redial for+// the slot the retirement freed. The entry stays (bot tiles keep their card);+// the next explicit open of the scope re-arms it. Returns the parked scopes.+export function parkSecondariesForRetiredBackend(poolKey: string): string[] {+ const key = String(poolKey || '').trim()+ const parked: string[] = []++ if (!key) {+ return parked+ }++ for (const entry of g.secondaries.values()) {+ if (!secondaryRidesPoolKey(entry, key)) {+ continue+ }++ entry.wantOpen = false+ entry.retiredByPool = true+ entry.stalledDials = 0+ clearTimer(entry)+ parked.push(entry.scope)+ }++ return parked+}+// Tear a secondary down: stop its reconnect loop, detach listeners, close the// socket. Caller handles removal from the map.function disposeSecondary(entry: Secondary): void {