The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: re-ensure the canonical local gateway when its cached endpoint is dead
Teknium804719b6f02d
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex e1b62e11aa4..d2082fc2737 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -70,3 +70,34 @@ test('private dial credential is one-use and bound to the requesting native windexpect(headers['Sec-WebSocket-Protocol']).toBe('hermes-gateway-v1, hermes-gateway-ticket.private-ticket')expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()})++test('a dial against a replaced local gateway forgets the cached endpoint once and re-ensures', async () => {+ const { redialLocalGateway } = await import('./local-gateway')+ const endpoints = [{ instance_id: 'dead' }, { instance_id: 'alive' }]+ const forgotten: string[] = []+ let ensures = 0+ const result = await redialLocalGateway({+ ensure: async () => endpoints[Math.min(ensures++, 1)],+ forget: async () => { forgotten.push('primary') },+ use: async endpoint => {+ if (endpoint.instance_id === 'dead') {throw new Error('Gateway ticket bootstrap failed')}+ return `ticket-for-${endpoint.instance_id}`+ }+ })+ expect(result).toBe('ticket-for-alive')+ expect(forgotten).toEqual(['primary'])+ expect(ensures).toBe(2)+})++test('a dial that keeps failing after one re-ensure surfaces the error instead of looping', async () => {+ const { redialLocalGateway } = await import('./local-gateway')+ let ensures = 0+ let forgets = 0+ await expect(redialLocalGateway({+ ensure: async () => { ensures++; return { instance_id: 'still-dead' } },+ forget: async () => { forgets++ },+ use: async () => { throw new Error('Invalid gateway ticket response') }+ })).rejects.toThrow('Invalid gateway ticket response')+ expect(ensures).toBe(2)+ expect(forgets).toBe(1)+})diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex cc4cb7524a1..6388a42448d 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -54,6 +54,35 @@ export async function ensureLocalGateway(run: () => Promise<{ code: number; stdoreturn { baseUrl: endpoint.api_origin, wsUrl: `${endpoint.api_origin.replace(/^http/, 'ws')}/api/ws?native_dial=unminted`, mode: 'local', source: 'local', authMode: 'native', token: '', gatewayEndpoint: endpoint }}+// The cached connection descriptor pins the gateway instance that answered the+// first `gateway ensure`. When that owner is gone (crash, `gateway stop`,+// update restart) every ticket mint against the stale control socket fails and+// the renderer's reconnect backoff would loop on the dead descriptor forever.+// Forget the cached descriptor exactly once and re-run the canonical ensure;+// a second failure is a real error and surfaces to the caller.+export function isStaleLocalGatewayError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error ?? '')++ return message.startsWith('Gateway ticket') || message === 'Invalid gateway ticket response' || message === 'Unsafe gateway control path'+}++export async function redialLocalGateway<TEndpoint, TResult>(deps: {+ ensure: () => Promise<TEndpoint>+ forget: () => Promise<void> | void+ use: (endpoint: TEndpoint) => Promise<TResult>+}): Promise<TResult> {+ const first = await deps.ensure()++ try {+ return await deps.use(first)+ } catch (error) {+ if (!isStaleLocalGatewayError(error)) {throw error}+ await deps.forget()++ return deps.use(await deps.ensure())+ }+}+// A one-use ticket crosses private IPC, then leaves the URL before dialing.// Public descriptors and persisted connection state never contain credentials.export function createLocalGatewayDials() {diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 7ca0010db90..fcc91dc065f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -1,7 +1,7 @@import { execFileSync, spawn } from 'node:child_process'import type { GatewayEndpoint } from './local-gateway'-import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from './local-gateway'+import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'const localGatewayDials = createLocalGatewayDials()import crypto from 'node:crypto'import fs from 'node:fs'@@ -8293,9 +8293,15 @@ async function freshGatewayWsUrl(profile, webContentsId) {const connection = await ensureBackend(profile)if (connection.gatewayEndpoint) {- const ticket = await mintLocalGatewayTicket(connection.gatewayEndpoint)+ return redialLocalGateway({+ ensure: () => ensureBackend(profile),+ forget: () => forgetLocalGatewayDescriptor(profile),+ use: async current => {+ const ticket = await mintLocalGatewayTicket(current.gatewayEndpoint)- return localGatewayDials.prepare(connection.baseUrl, ticket, webContentsId)+ return localGatewayDials.prepare(current.baseUrl, ticket, webContentsId)+ }+ })}if (connection.authMode === 'oauth') {@@ -11453,6 +11459,31 @@ function profileRouteOptions(profile, request?) {// Resolve a backend connection for the given profile, per the routing table in// resolveProfileBackendRoute(). An empty / unknown profile resolves to the// primary, so legacy callers are unchanged.+// Drop the cached descriptor for a canonical local gateway whose owner is gone+// so the next ensureBackend() re-runs `gateway ensure` (attach or start) instead+// of minting tickets against a dead control socket. Nothing is killed: the+// descriptor never owned the runtime.+async function forgetLocalGatewayDescriptor(profile) {+ const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()+ const route = resolveProfileBackendRoute(key, profileRouteOptions(key))++ if (route.backend === 'primary') {+ const attempt = backendConnectionState.startAttempt()+ attempt.promise = backendConnectionState.getPromise()+ backendConnectionState.clearPromiseForAttempt(attempt)+ rememberLog(`[gateway] forgot stale canonical endpoint for primary "${key}"; re-ensuring`)++ return+ }++ const entry = backendPool.get(key)++ if (entry && !entry.process) {+ backendPool.delete(key)+ rememberLog(`[gateway] forgot stale canonical endpoint for profile "${key}"; re-ensuring`)+ }+}+async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPriority } = {}) {const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()const spawnPriority = spawnPriorityFrom(opts.spawnPriority)@@ -16286,13 +16317,24 @@ async function handleHermesApiRequest(request) {timeoutMs})}+ } else if (connection.gatewayEndpoint) {+ response = await redialLocalGateway({+ ensure: () => ensureBackend(routeProfile),+ forget: () => forgetLocalGatewayDescriptor(routeProfile),+ use: current => fetchJson(`${current.baseUrl}${apiRoute.requestPath}`, current.token, {+ method: request?.method,+ body: request?.body,+ upload: request?.upload,+ timeoutMs,+ gatewayDescriptor: current+ })+ })} else {response = await fetchJson(url, connection.token, {method: request?.method,body: request?.body,upload: request?.upload,- timeoutMs,- gatewayDescriptor: connection.gatewayEndpoint ? connection : undefined+ timeoutMs})}} catch (error) {