The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): drop the renderer half of the retired backend pool
Teknium6b4d57c97da0
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 6c63b816857..8b4869aeb73 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -593,15 +593,6 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:backend-exit', listener)},- // Cooperative pool retirement (main → renderer): the pooled backend under- // `poolKey` is being stopped for a foreground open. Park that scope; do not- // redial into the slot it vacated.- onPoolBackendRetiring: callback => {- const listener = (_event, payload) => callback(payload)- ipcRenderer.on('hermes:pool:retiring', listener)-- return () => ipcRenderer.removeListener('hermes:pool:retiring', listener)- },// Soft gateway-mode apply finished tearing down the primary backend. Renderer// should wipe session lists + re-dial without a window reload.onConnectionApplied: callback => {diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsxindex 766ee10091f..e7b15ea6aa2 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsx+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsx@@ -66,7 +66,6 @@ function fakeDesktop() {onPowerResume: vi.fn(unsubscribe),revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),onWindowStateChanged: vi.fn(unsubscribe),- touchBackend: vi.fn(async () => undefined),profile: { get: vi.fn(async () => ({ profile: 'default' })) }}}diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex c5ff8082bac..ea2f536b97d 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -48,7 +48,6 @@ import {gatewayActivationEpoch,isActivePrimary,liveSecondaryConnectionIds,- parkSecondariesForRetiredBackend,pruneSecondaryGateways,reconnectSecondaryGateways,reportPrimaryGatewayState,@@ -1308,17 +1307,6 @@ 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 = () => {@@ -1690,7 +1678,6 @@ export function useGatewayBoot({offPowerResume?.()offConnectionApplied?.()offConnectionsChanged?.()- offPoolRetiring?.()offGatewayReconnect()offActiveGatewayReauth()offActiveStateReauth()diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 68902d6c32a..e2520a503f0 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -593,9 +593,6 @@ declare global {) => () => voidonPreviewFileChanged: (callback: (payload: HermesPreviewFileChanged) => void) => () => voidonBackendExit: (callback: (payload: BackendExit) => void) => () => void- // Cooperative pool retirement: main is stopping the pooled backend under- // `poolKey` for a foreground open. The renderer parks that scope.- onPoolBackendRetiring?: (callback: (payload: { poolKey: string }) => void) => () => void// Soft gateway-mode apply: primary backend was torn down without a window// reload. Wipe session lists (skeletons) and re-dial.onConnectionApplied?: (callback: () => void) => () => voiddiff --git a/apps/desktop/src/plugins/hermes-bots/group-activity.ts b/apps/desktop/src/plugins/hermes-bots/group-activity.tsindex 55d1a41d7e7..71b6346f230 100644--- a/apps/desktop/src/plugins/hermes-bots/group-activity.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-activity.ts@@ -76,9 +76,9 @@ export function currentGroupActivity(group: string) {* must keep classifying it as transient (never a roster badge). */export const GROUP_SLOT_WAIT_REASON = 'slot_wait_timeout'-/** Stable coordinator phrase (`pool-spawn-coordinator.ts`), the- * cross-process discriminator — same shape as `isLocalBackendSlotWaitTimeout`- * in `store/pool-limits.ts`, kept local because the plugin fence cannot+/** Stable phrase older Desktop hosts' local backend pool raised on a slot-wait+ * timeout (a renderer can still be served by one across an upgrade); same+ * shape as the store's classifier, kept local because the plugin fence cannot* import the store. Match narrowly so other backend failures keep their path. */export function isGroupSlotWaitTimeoutText(text: unknown): boolean {return typeof text === 'string' && text.includes('timed out while waiting for a free slot')diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 5812c3d76ab..88b4d394677 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1520,11 +1520,11 @@ export const host = {options?: PluginProfileRequestOptions): Promise<T> => requestPluginProfile<T>(route, method, params, timeoutMs, options),- /** Pin a route's pooled gateway socket open across repeated `requestProfile`+ /** Pin a route's gateway socket open across repeated `requestProfile`* calls (#93594: the bot-relay drain loop was dialing and tearing down a* fresh WebSocket per registered connection per tick). Returns a once-only- * release. Local routes are exempt (no-op release) so the idle reaper can- * still reclaim spawned local backends. Feature-detect on older desktops+ * release. Local routes are exempt (no-op release): the host gateway's+ * lifetime does not depend on renderer pins. Feature-detect on older desktops* (`typeof host.retainProfileSocket === 'function'`). */retainProfileSocket: (route: PluginProfileRoute | string): (() => void) => {if (typeof route === 'string' || !route) {diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex 2c6cca56688..07d261c5abf 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -67,7 +67,6 @@ vi.mock('@/store/session-states', () => reconnectStateMocks)const {activeGateway,- touchSecondaryGateways,closeLegacySecondaryGateways,closeSecondaryGateways,configureGatewayRegistry,@@ -77,7 +76,6 @@ const {ensureGatewayForProfile,openGatewayForAgent,openGatewayForProfile,- parkSecondariesForRetiredBackend,pruneSecondaryGateways,reconnectSecondaryGateways,requestGatewayForAgent,@@ -734,38 +732,6 @@ describe('reconnect fail-stop on a removed connection', () => {})})-describe('touchSecondaryGateways', () => {- it('pings only secondaries whose socket is open, so a backend nobody reaches can idle-reap (#103375)', 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', 'default')- await ensureGatewayForAgent('office', 'default')- // openSecondary pings once per successful dial; only the keepalive sweep- // is under test here.- touchBackend.mockClear()-- touchSecondaryGateways()- expect(touchBackend).toHaveBeenCalledTimes(2)-- // The office socket drops and sits in reconnect backoff: still wantOpen,- // but nothing on this window uses that backend until it reopens.- const office = gatewayMocks.instances[1] as unknown as { connectionState: string }- office.connectionState = 'closed'- touchBackend.mockClear()-- touchSecondaryGateways()-- expect(touchBackend).toHaveBeenCalledTimes(1)- expect(touchBackend).not.toHaveBeenCalledWith(expect.stringContaining('office'))- })-})-describe('secondary stalled-dial budget', () => {it('parks a scope after repeated stalled dials instead of redialing forever, and a user action re-arms it (#103375)', async () => {vi.useFakeTimers()@@ -999,66 +965,6 @@ describe('secondary stalled-dial budget', () => {})})-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- )-- // Ambient hydration and relay/status RPCs must not undo the park either.- const { requestGatewayForAgent } = await import('./gateway')- const parkedDials = getConnectionFor.mock.calls.length- await expect(openGatewayForAgent('local', 'bot-a')).rejects.toThrow(/retired/i)- await expect(requestGatewayForAgent('local', 'bot-a', 'session.list')).rejects.toThrow(/retired/i)- await expect(retainGatewayForAgent('local', 'bot-a')).rejects.toThrow(/retired/i)- expect(getConnectionFor.mock.calls.length).toBe(parkedDials)-- // 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)- })-})-describe('rejected secondary authentication', () => {it('parks only the rejected source across automatic nudges and recovers on explicit selection', async () => {vi.useFakeTimers()diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.tsindex 563e01f5b6e..b03dd356a5e 100644--- a/apps/desktop/src/store/gateway-profile-request.test.ts+++ b/apps/desktop/src/store/gateway-profile-request.test.ts@@ -760,8 +760,7 @@ describe('attached shared-remote group turns (#96493)', () => {getConnectionFor: vi.fn(async () => {throw new Error('Timed out connecting to profile "sean"')}),- getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'ws://local/sean' })),- touchBackend: vi.fn(async () => undefined)+ getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'ws://local/sean' }))}await ensureGatewayForProfile('default')@@ -840,8 +839,7 @@ describe('session-owner calls for a profile on the shared local host backend (#1getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({ok: true as const,wsUrl: `ws://${connectionId}/${profile}`- })),- touchBackend: vi.fn(async () => undefined)+ }))}return getConnectionFordiff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex dea73e8b416..0bd7b718a1f 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -169,14 +169,6 @@ 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@@ -462,19 +454,9 @@ function isPrimaryRegistryRoute(connectionId: null | string, profile: string): b* the chat's transport fan-out and the renderer receives every event twice* (garbled streaming text + a duplicate interim bubble, #120005). Isolated* SSH/pooled backends (neither flag) still get their own secondary. */-async function ridesPrimaryBackend(- connectionId: null | string,- profile: string,- spawnPriority: SpawnPriority = 'background'-): Promise<boolean> {+async function ridesPrimaryBackend(connectionId: null | string, profile: string): Promise<boolean> {const id = String(connectionId ?? '').trim()const key = normKey(profile)- const parked = g.secondaries.get(registryBackendScopeKey(connectionId, key))-- if (parked?.retiredByPool) {- rearmSecondary(parked, spawnPriority)- }-if (!id || !g.primaryConnectionId || id !== g.primaryConnectionId) {return false}@@ -561,11 +543,11 @@ export function activeGateway(): HermesGateway | null {/** Passive ordering barrier for a runtime's transcript reads. Inspect only* existing sockets: waiting must never dial, activate, or retain a backend.* Each client names its own replaying runtime IDs; no ambient route is used- * to decide which session's events are safe to paint over. A pruned or- * pool-retired secondary keeps its closed socket's watermarks but will never- * reopen to replay them, so it must not veto reads forever. */+ * to decide which session's events are safe to paint over. A pruned+ * secondary keeps its closed socket's watermarks but will never reopen to+ * replay them, so it must not veto reads forever. */export function pendingSessionReplay(runtimeId: string): Promise<boolean> | undefined {- const reconnectable = [...g.secondaries.values()].filter(entry => entry.wantOpen && !entry.retiredByPool)+ const reconnectable = [...g.secondaries.values()].filter(entry => entry.wantOpen)const clients = new Set([g.primaryGateway, ...reconnectable.map(entry => entry.gateway)])// A closed socket's false means only that IT cannot replay yet. When another@@ -898,13 +880,8 @@ function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'g.dialFailures.delete(entry.scope)}- if (entry.retiredByPool && priority !== 'foreground') {- throw new Error(`Backend for "${entry.profile}" was retired; open it explicitly to reconnect.`)- }-entry.wantOpen = trueentry.stalledDials = 0- entry.retiredByPool = false}function recordDialFailure(entry: Secondary, error?: unknown): void {@@ -1081,7 +1058,6 @@ function createSecondary(profile: string, connectionId: null | string = null): Sretained: false,relayRetainCount: 0,wantOpen: true,- retiredByPool: false,activationLeaseUntil: 0}@@ -1172,12 +1148,6 @@ async function gatewayForProfile(): Promise<{ gateway: HermesGateway | null; key: string; release: () => void; scopeProfile: boolean }> {const key = normKey(profile)const noRelease = () => undefined- const parked = g.secondaries.get(key)-- if (parked?.retiredByPool) {- rearmSecondary(parked, spawnPriority)- }-if (key === g.primaryProfile) {return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }}@@ -1328,7 +1298,7 @@ export async function requestGatewayForAgent<T>(return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal, { spawnPriority })}- if (await ridesPrimaryBackend(connectionId, key, spawnPriority)) {+ if (await ridesPrimaryBackend(connectionId, key)) {traceAgentRoute(scope, 'primary-shared')return requestOnPrimaryGateway<T>(method, { ...params, profile: key }, timeoutMs, signal)@@ -1550,7 +1520,7 @@ export async function retainGatewayForAgent(return route.release}- if (isPrimaryRegistryRoute(connectionId, key) || (await ridesPrimaryBackend(connectionId, key, spawnPriority))) {+ if (isPrimaryRegistryRoute(connectionId, key) || (await ridesPrimaryBackend(connectionId, key))) {// Primary socket stays open for the window lifetime — no secondary to hold.return () => undefined}@@ -1722,43 +1692,14 @@ 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 {- // Older Desktop hosts own pooled children. Canonical hosts expose no touch- // capability: their gateway lifetime is independent of renderer leases.- const desktop = window.hermesDesktop as (typeof window.hermesDesktop & {- touchBackend?: (scope: string, options?: { activeTurn?: boolean }) => Promise<unknown>- })-- void desktop?.touchBackend?.(scope, { activeTurn }).catch(() => undefined)-}-function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {const sessionId = String(event.session_id || '').trim()@@ -1841,7 +1782,7 @@ export async function openGatewayForAgent(return openGatewayForProfile(profile, { spawnPriority })}- if (await ridesPrimaryBackend(connectionId, profile, spawnPriority)) {+ if (await ridesPrimaryBackend(connectionId, profile)) {if (!isOpen(g.primaryGateway)) {throw new Error('Hermes gateway unavailable')}@@ -1897,7 +1838,7 @@ export async function ensureGatewayForAgent(const activationEpoch = beginGatewayActivation()- if (await ridesPrimaryBackend(connectionId, profile, 'foreground')) {+ if (await ridesPrimaryBackend(connectionId, profile)) {// A retained primary can be open while the foreground still points at a// different source. Reusing its socket must also move the active route.return Boolean(isOpen(g.primaryGateway) && !signal?.aborted && applyActive(g.primaryProfile, activationEpoch))@@ -2183,7 +2124,7 @@ export function reconnectSecondaryGateways({ forceOpenSockets = false }: { force// 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 || g.reauthFailures.has(entry.scope)) {+ if (g.reauthFailures.has(entry.scope)) {continue}@@ -2239,71 +2180,6 @@ export function openSecondaryCount(): number {return count}-// Keep the idle reaper from killing a backend we still need: ping every live-// secondary. The active one is pinged separately (touchActiveGatewayBackend).-// "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). 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 {- // Older Desktop hosts own pooled children. Canonical hosts expose no touch- // capability: their gateway lifetime is independent of renderer keepalives.- const desktop = window.hermesDesktop as (typeof window.hermesDesktop & {- touchBackend?: (scope: string, options?: { activeTurn?: boolean }) => Promise<unknown>- })-- for (const entry of g.secondaries.values()) {- if (entry.wantOpen && isOpen(entry.gateway)) {- 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 {diff --git a/apps/desktop/src/store/kanban-connection-scope.test.ts b/apps/desktop/src/store/kanban-connection-scope.test.tsindex 83015cedd83..772d22431a2 100644--- a/apps/desktop/src/store/kanban-connection-scope.test.ts+++ b/apps/desktop/src/store/kanban-connection-scope.test.ts@@ -83,8 +83,7 @@ describe('connection-switch query invalidation', () => {})),getGatewayWsUrl: vi.fn(async () => 'wss://pool.invalid/api/ws?ticket=fake'),- getGatewayWsUrlFor: vi.fn(async () => 'wss://spark.invalid/api/ws?ticket=fake'),- touchBackend: vi.fn(async () => ({ ok: true }))+ getGatewayWsUrlFor: vi.fn(async () => 'wss://spark.invalid/api/ws?ticket=fake')},localStorage: new Map<string, string>() as unknown as Storage})