The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): tear down renderer secondaries when a registry connection is removed
Teknium28c729e68f6f
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 0b2017a42c5..e1e22a07309 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -9144,6 +9144,21 @@ function sendConnectionApplied() {webContents.send('hermes:connection:applied')}+// Registry lifecycle push: a connection was removed or materially edited, so+// every window must tear down (and, for edits, re-dial) its secondary sockets+// scoped to that connection. Without this, a removed remote/cloud source keeps+// its renderer WebSocket open and streaming as a ghost, and an edited one+// keeps talking to the OLD endpoint until idle-reap.+function broadcastConnectionsChanged(payload: { connectionId: string; reason: 'removed' | 'updated' }) {+ for (const win of BrowserWindow.getAllWindows()) {+ const { webContents } = win++ if (webContents && !webContents.isDestroyed()) {+ webContents.send('hermes:connections:changed', payload)+ }+ }+}+async function waitForBackendExit(child, timeoutMs = 5000) {if (!child || child.exitCode !== null || child.signalCode !== null) {return@@ -11907,6 +11922,10 @@ ipcMain.handle('hermes:connections:remove', async (_event, id) => {// Tear down anything the removed connection still had running: pooled// backends under its composite keys and any ssh tunnel scopes it owned.stopRegistryConnectionBackends(key)+ // And the renderer side: without this push, secondaries scoped to the+ // removed connection keep their WebSocket open (remote/cloud have no local+ // process to kill) and stream ghost events until page reload.+ broadcastConnectionsChanged({ connectionId: key, reason: 'removed' })return { ok: true, registry: sanitizeConnectionsRegistry(registry) }})diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 3c9f2ab1eb3..96c76d4822c 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -138,7 +138,16 @@ contextBridge.exposeInMainWorld('hermesDesktop', {setPrimary: id => ipcRenderer.invoke('hermes:connections:set-primary', id),test: id => ipcRenderer.invoke('hermes:connections:test', id),// Fan out `hermes update` to every eligible registered connection.- updateAll: () => ipcRenderer.invoke('hermes:connections:update-all')+ updateAll: () => ipcRenderer.invoke('hermes:connections:update-all'),+ // Registry lifecycle push (main → renderer): a connection was removed or+ // materially edited, so secondaries scoped to it must be disposed (and,+ // for edits, re-dialed at the new target).+ onChanged: callback => {+ const listener = (_event, payload) => callback(payload)+ ipcRenderer.on('hermes:connections:changed', listener)++ return () => ipcRenderer.removeListener('hermes:connections:changed', listener)+ }},sshConfigHosts: () => ipcRenderer.invoke('hermes:ssh-config:hosts'),sshResolveHost: host => ipcRenderer.invoke('hermes:ssh-config:resolve', host),diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 334ea4e604d..dc988eb0899 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -17,6 +17,7 @@ import {$gateway,closeSecondaryGateways,configureGatewayRegistry,+ disposeSecondariesForConnection,ensureGatewayForProfile,pruneSecondaryGateways,reconnectSecondaryGateways,@@ -434,6 +435,18 @@ export function useGatewayBoot({const offPowerResume = desktop.onPowerResume?.(() => reconnectNow())const offConnectionApplied = desktop.onConnectionApplied?.(() => void softSwitch())+ // Registry lifecycle: a removed connection's secondaries must close NOW+ // (remote/cloud have no local process whose death would drop the socket —+ // they'd keep streaming ghost events); a materially edited one is+ // disposed AND re-dialed so its sockets target the new endpoint.+ const offConnectionsChanged = desktop.connections?.onChanged?.(payload => {+ if (!payload || typeof payload.connectionId !== 'string') {+ return+ }++ disposeSecondariesForConnection(payload.connectionId, { redial: payload.reason === 'updated' })+ })+const onOnline = () => reconnectNow()const onVisible = () => {@@ -636,6 +649,7 @@ export function useGatewayBoot({document.removeEventListener('visibilitychange', onVisible)offPowerResume?.()offConnectionApplied?.()+ offConnectionsChanged?.()offState()offEvent()offExit()diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 14f73a061e0..b7486a5c59f 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -143,6 +143,13 @@ declare global {// Fan out `hermes update` to every eligible registered connection;// cloud entries are skipped (platform-managed), each row independent.updateAll?: () => Promise<{ ok: boolean; results: DesktopConnectionUpdateResult[] }>+ // Registry lifecycle push: fired when a connection is removed or+ // materially edited so the renderer can dispose (and re-dial) the+ // secondary gateways scoped to it. Optional: older Electron mains+ // don't emit it.+ onChanged?: (+ callback: (payload: { connectionId: string; reason: 'removed' | 'updated' }) => void+ ) => () => void}sshConfigHosts: () => Promise<DesktopSshHostsResult>sshResolveHost: (host: string) => Promise<DesktopSshResolveResult>diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsnew file mode 100644index 00000000000..846ee3501ed--- /dev/null+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -0,0 +1,195 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Connection lifecycle for registry-scoped secondary gateways:+//+// 1. Removing a connection must dispose its secondaries — remote/cloud+// sources have no local process whose death would drop the socket, so+// without an explicit dispose the WebSocket stays open and streams ghost+// events until page reload.+// 2. A materially edited connection re-dials so fresh sockets target the+// NEW endpoint.+// 3. When the Electron main reports the connection no longer exists+// (`No connection with id`), the reconnect loop fail-stops and evicts+// the entry instead of retrying forever.++const gatewayMocks = vi.hoisted(() => {+ const instances: { close: ReturnType<typeof vi.fn>; connectionState: string }[] = []++ return {+ connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined),+ instances+ }+})++vi.mock('@/hermes', () => ({+ HermesGateway: class {+ connectionState = 'closed'+ close = vi.fn(() => {+ this.connectionState = 'closed'+ })+ connect = async (wsUrl: string): Promise<void> => {+ await gatewayMocks.connect(wsUrl)+ this.connectionState = 'open'+ }+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})+ constructor() {+ gatewayMocks.instances.push(this as never)+ }+ }+}))+vi.mock('@/store/session', () => ({+ setConnection: vi.fn(),+ setGatewayState: vi.fn()+}))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const {+ closeSecondaryGateways,+ configureGatewayRegistry,+ disposeSecondariesForConnection,+ ensureActiveGatewayOpen,+ ensureGatewayForAgent,+ setPrimaryGateway+} = await import('./gateway')++function installDesktop(stub: Record<string, unknown>): void {+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = stub+}++function descriptorFor(connectionId: string, profile: string) {+ return {+ authMode: 'token',+ baseUrl: `https://${connectionId}.invalid`,+ mode: 'remote',+ profile,+ token: 'fake-test-token',+ wsUrl: `wss://${connectionId}.invalid/api/ws?profile=${profile}`+ }+}++beforeEach(() => {+ configureGatewayRegistry({ onEvent: vi.fn() } as never)+ setPrimaryGateway({ connectionState: 'open' } as never, 'default')+})++afterEach(() => {+ closeSecondaryGateways()+ gatewayMocks.instances.length = 0+ vi.clearAllMocks()+ vi.useRealTimers()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('disposeSecondariesForConnection', () => {+ it('closes and evicts every secondary scoped to the removed connection', async () => {+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )++ installDesktop({ getConnectionFor })++ await ensureGatewayForAgent('homelab', 'default')+ await ensureGatewayForAgent('homelab', 'work')+ await ensureGatewayForAgent('office', 'default')++ expect(gatewayMocks.instances).toHaveLength(3)++ disposeSecondariesForConnection('homelab')++ // Both homelab sockets closed; the office socket untouched.+ expect(gatewayMocks.instances[0].close).toHaveBeenCalledOnce()+ expect(gatewayMocks.instances[1].close).toHaveBeenCalledOnce()+ expect(gatewayMocks.instances[2].close).not.toHaveBeenCalled()++ // No redial for a removal.+ expect(getConnectionFor).toHaveBeenCalledTimes(3)+ })++ it('re-dials disposed secondaries when redial is requested (material edit)', async () => {+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )++ installDesktop({ getConnectionFor })++ await ensureGatewayForAgent('homelab', 'default')+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(1)++ disposeSecondariesForConnection('homelab', { redial: true })++ // The redial runs async through the normal open path — flush it.+ await vi.waitFor(() => {+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(2)+ })++ // Old socket closed, fresh descriptor fetched (would carry the new URL).+ expect(gatewayMocks.instances[0].close).toHaveBeenCalledOnce()+ expect(getConnectionFor).toHaveBeenCalledTimes(2)+ })++ it('is a no-op for blank or unknown connection ids', async () => {+ installDesktop({+ getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>+ descriptorFor(connectionId, profile)+ )+ })++ await ensureGatewayForAgent('homelab', 'default')++ disposeSecondariesForConnection('')+ disposeSecondariesForConnection('ghost')++ expect(gatewayMocks.instances[0].close).not.toHaveBeenCalled()+ })+})++describe('reconnect fail-stop on a removed connection', () => {+ it('evicts the entry instead of retrying when the registry no longer knows the id', async () => {+ const getConnectionFor = vi+ .fn()+ .mockResolvedValueOnce(descriptorFor('homelab', 'default'))+ .mockRejectedValue(new Error('No connection with id "homelab".'))++ installDesktop({ getConnectionFor })++ await ensureGatewayForAgent('homelab', 'default')+ expect(gatewayMocks.instances).toHaveLength(1)++ // Simulate the socket dropping after the connection was removed.+ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }+ socket.connectionState = 'closed'++ // ensureActiveGatewayOpen drives reconnectSecondary for the active scope.+ const result = await ensureActiveGatewayOpen()++ expect(result).toBeNull()+ // Fail-stop: the entry was disposed + evicted, so a second drive finds+ // nothing to retry (no further getConnectionFor calls).+ const callsAfterFailStop = getConnectionFor.mock.calls.length+ await ensureActiveGatewayOpen()+ expect(getConnectionFor.mock.calls.length).toBe(callsAfterFailStop)+ })++ it('keeps retrying on ordinary transport failures', async () => {+ const getConnectionFor = vi+ .fn()+ .mockResolvedValueOnce(descriptorFor('homelab', 'default'))+ .mockRejectedValueOnce(new Error('ECONNREFUSED'))+ .mockResolvedValue(descriptorFor('homelab', 'default'))++ installDesktop({ getConnectionFor })++ await ensureGatewayForAgent('homelab', 'default')++ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }+ socket.connectionState = 'closed'++ // First drive fails with a transport error → entry survives.+ await ensureActiveGatewayOpen()+ // Second drive succeeds against the surviving entry.+ const reopened = await ensureActiveGatewayOpen()++ expect(reopened).not.toBeNull()+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 52b34a11331..1c2173b56c8 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -235,8 +235,18 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {try {await openSecondary(entry)entry.reconnectAttempt = 0- } catch {- // Transport failure → fall through to the backoff below.+ } catch (error) {+ // The registry no longer knows this connection (removed while we were+ // backing off). Retrying forever can never succeed — fail-stop: dispose+ // the entry and evict it instead of an infinite 15s-cap retry loop.+ if (entry.connectionId && isMissingConnectionError(error)) {+ entry.reconnecting = false+ disposeSecondary(entry)+ g.secondaries.delete(entry.scope)++ return+ }+ // Other transport failure → fall through to the backoff below.} finally {entry.reconnecting = false@@ -246,6 +256,15 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {}}+// Electron's getConnectionFor rejects with `No connection with id "…"` when+// the registry entry is gone. That is a permanent condition for the scoped+// socket, unlike transient transport errors.+function isMissingConnectionError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error ?? '')++ return message.includes('No connection with id')+}+function createSecondary(profile: string, connectionId: null | string = null): Secondary {const gateway = new HermesGateway()const scope = backendScopeKey(connectionId, profile)@@ -533,6 +552,39 @@ export function closeSecondaryGateways(): void {restoreActiveToPrimaryIfEvicted()}+// Registry lifecycle: a connection was removed or materially edited. Dispose+// every secondary scoped to it (a removed remote/cloud source has no local+// process to die, so without this its WebSocket stays open streaming ghost+// events). With `redial` (the edit case) each disposed profile is re-dialed+// through the normal open path so the fresh socket targets the NEW endpoint;+// the active scope re-activates so the foreground keeps painting.+export function disposeSecondariesForConnection(connectionId: string, opts: { redial?: boolean } = {}): void {+ const id = String(connectionId || '').trim()++ if (!id) {+ return+ }++ for (const [key, entry] of [...g.secondaries]) {+ if (entry.connectionId !== id) {+ continue+ }++ const wasActive = key === g.activeKey++ disposeSecondary(entry)+ g.secondaries.delete(key)++ if (opts.redial) {+ const reopen = wasActive+ ? ensureGatewayForAgent(entry.connectionId, entry.profile)+ : openGatewayForAgent(entry.connectionId, entry.profile)++ void reopen.catch(() => undefined)+ }+ }+}+// Self-accept so editing this module (or a fan-out that lands here) is an// in-place hot update instead of a full page reload — the live sockets in `g`// survive the swap. Dev-only: production strips import.meta.hot.