The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): redial the local gateway after a normal stop removed its control socket
teknium17865569ec1b6
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex 5d219fde21b..09e638fb215 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -106,3 +106,85 @@ test('a dial that keeps failing after one re-ensure surfaces the error instead oexpect(ensures).toBe(2)expect(forgets).toBe(1)})++test.skipIf(process.platform === 'win32')('a stopped gateway that unlinked its control socket is a stale owner, not a raw filesystem error', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { mintLocalGatewayTicket, redialLocalGateway } = await import('./local-gateway')+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-redial-'))+ const socketPath = path.join(home, 'gateway.sock')+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }++ const serve = async (ticket: string) => {+ const server = net.createServer(socket => socket.once('data', () => {+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket } }) + '\n')+ }))++ await new Promise<void>(resolve => server.listen(socketPath, resolve))+ await fs.chmod(socketPath, 0o600)++ return server+ }++ const stop = async (server: ReturnType<typeof net.createServer>) => {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(socketPath, { force: true })+ }++ let replacement: ReturnType<typeof net.createServer> | null = null+ const original = await serve('grant-original')++ try {+ expect(await mintLocalGatewayTicket(endpoint)).toBe('grant-original')+ await stop(original)++ let ensures = 0+ let forgets = 0++ const result = await redialLocalGateway({+ ensure: async () => {+ ensures += 1++ if (ensures === 2) {replacement = await serve('grant-replacement')}++ return endpoint+ },+ forget: () => { forgets += 1 },+ use: e => mintLocalGatewayTicket(e)+ })++ expect(result).toBe('grant-replacement')+ expect(forgets).toBe(1)+ expect(ensures).toBe(2)+ } finally {+ if (replacement) {await stop(replacement)}+ await fs.rm(home, { recursive: true, force: true })+ }+})++test.skipIf(process.platform === 'win32')('a group-accessible control socket is refused as unsafe, and unrelated errors are never stale', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-unsafe-'))+ const socketPath = path.join(home, 'gateway.sock')+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }+ const server = net.createServer(socket => socket.end())+ await new Promise<void>(resolve => server.listen(socketPath, resolve))+ await fs.chmod(socketPath, 0o660)++ try {+ const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)+ expect(failure).toBeInstanceOf(Error)+ expect(failure.message).toBe('Unsafe gateway control path')+ expect(isStaleLocalGatewayError(failure)).toBe(true)+ expect(isStaleLocalGatewayError(new Error('EACCES: permission denied'))).toBe(false)+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(home, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex b752ef23648..b7ef133e9c8 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -135,17 +135,14 @@ export function configureWindowsGatewayTicketClient(client: NonNullable<typeof wwindowsTicketClient = client}-export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {- if (process.platform === 'win32') {- if (!windowsTicketClient) {throw new Error('Gateway ticket client is not configured')}+function isMissingNodeError(error: unknown): boolean {+ const code = (error as NodeJS.ErrnoException)?.code- return windowsTicketClient(endpoint, purpose)- }- const home = endpoint.profile_id+ return code === 'ENOENT' || code === 'ENOTDIR'+}- if (await fs.realpath(home) !== home) {throw new Error('Noncanonical gateway profile')}- await privateNode(home, 'directory')- let socketPath = path.join(home, 'gateway.sock')+async function resolveControlSocket(home: string): Promise<string> {+ const socketPath = path.join(home, 'gateway.sock')try { await privateNode(socketPath, 'socket') } catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {throw error}@@ -157,7 +154,31 @@ export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose:if (!path.isAbsolute(target) || path.basename(path.dirname(target)) !== `hermes-gw-${hash}` || path.basename(target) !== 'control.sock') {throw new Error('Invalid gateway control pointer')}await privateNode(path.dirname(target), 'directory')await privateNode(target, 'socket')- socketPath = target++ return target+ }++ return socketPath+}++export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {+ if (process.platform === 'win32') {+ if (!windowsTicketClient) {throw new Error('Gateway ticket client is not configured')}++ return windowsTicketClient(endpoint, purpose)+ }++ const home = endpoint.profile_id++ if (await fs.realpath(home) !== home) {throw new Error('Noncanonical gateway profile')}+ await privateNode(home, 'directory')+ let socketPath: string++ try { socketPath = await resolveControlSocket(home) } catch (error) {+ // `gateway stop` unlinks both the socket and its pointer: the owner is gone,+ // which the redial must treat as stale rather than as a raw filesystem error.+ if (isMissingNodeError(error)) {throw new Error('Gateway ticket control socket missing')}+ throw error}return new Promise((resolve, reject) => {diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 09632bae537..f559f9fbd47 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -11179,6 +11179,26 @@ async function forgetLocalGatewayDescriptor(profile) {}}+// Registry twin of forgetLocalGatewayDescriptor: a 'local' registry connection+// either delegates to the v1 profile route or pools a forced-local child under+// its composite key, so the stale descriptor lives wherever ensureRegistryBackend+// put it.+async function forgetRegistryLocalGatewayDescriptor(connectionId, profile) {+ const profileKey = String(profile ?? '').trim() || 'default'+ const localRoute = resolveRegistryLocalRoute(profileKey, {+ globalRemote: globalRemoteActive(),+ profileRemoteOverride: Boolean(profileHasRemoteOverride(profileKey))+ })++ if (localRoute.delegate) {+ return forgetLocalGatewayDescriptor(profile)+ }++ if (backendPool.delete(localRoute.poolKey)) {+ rememberLog(`[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`)+ }+}+async function ensureBackend(profile, opts: { passive?: boolean } = {}) {const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()const passive = Boolean(opts.passive)@@ -14940,9 +14960,15 @@ ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {const connection = await ensureRegistryBackend(payload?.connectionId, payload?.profile)if (connection.gatewayEndpoint) {- const ticket = await mintLocalGatewayTicket(connection.gatewayEndpoint)+ return redialLocalGateway({+ ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile),+ forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile),+ use: async (current: typeof connection) => {+ const ticket = await mintLocalGatewayTicket(current.gatewayEndpoint)- return localGatewayDials.prepare(connection.baseUrl, ticket, _event.sender.id)+ return localGatewayDials.prepare(current.baseUrl, ticket, _event.sender.id)+ }+ })}return registryGatewayWsUrlHandler(payload)