The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): keep plugin sockets retrying through a gateway restart
unsupportedpastels4f097f66473d
diff --git a/apps/desktop/electron/plugin-ws-url.test.ts b/apps/desktop/electron/plugin-ws-url.test.tsindex 4f6ede66e49..c7ca76fe28c 100644--- a/apps/desktop/electron/plugin-ws-url.test.ts+++ b/apps/desktop/electron/plugin-ws-url.test.ts@@ -81,6 +81,36 @@ test('mints a native-http grant for a local gateway and null elsewhere', async (expect(mint).toHaveBeenCalledTimes(1)})+// The renderer cannot tell a refused upgrade from a gateway that is away. Main can name the one case it+// knows is not transient, a grant mint refused for a permission reason, and answers it as plain data.+test('a mint refused for a permission reason is a named reply, any other failure stays an error', async () => {+ const unsafe = new Error('Unsafe gateway control path: \'/home/u/.hermes\' is accessible to other users (mode 755): run chmod go-rwx \'/home/u/.hermes\'')+ const groupWritable = new Error('Profile home is writable by a group other accounts share: run chmod g-w \'/home/u/.hermes\'')+ const bridged = Object.assign(new Error('Gateway ticket bootstrap failed'), { reason: 'unsafe_control_permissions' })+ const mint = vi.fn(async (): Promise<string> => { throw unsafe })++ const handler = createPluginWsUrlHandler({+ ensureBackend: vi.fn(async () => ({ baseUrl: 'http://127.0.0.1:9', gatewayEndpoint: endpoint })),+ ensureRegistryBackend: vi.fn(),+ forgetLocalGatewayDescriptor: vi.fn(),+ forgetRegistryLocalGatewayDescriptor: vi.fn(),+ launchHome: '/home/u/.hermes',+ mint,+ prepare: vi.fn(() => 'unused')+ })++ const request = { path: '/events', pluginId: 'kanban', profile: 'default' }++ for (const error of [unsafe, groupWritable, bridged]) {+ mint.mockRejectedValueOnce(error)+ await expect(handler(request, 3)).resolves.toEqual({ refused: 'permission' })+ }++ // An owner that is gone (redialed once, then still gone) is a connection failure: the renderer retries.+ mint.mockRejectedValue(new Error('Gateway ticket control socket missing'))+ await expect(handler(request, 3)).rejects.toThrow('Gateway ticket control socket missing')+})+test('the shared local dial keeps the gateway socket on an interactive grant', async () => {const { localGatewayDial } = await import('./local-gateway')const mint = vi.fn(async () => 'interactive-2')diff --git a/apps/desktop/electron/plugin-ws-url.ts b/apps/desktop/electron/plugin-ws-url.tsindex adfc108b946..1ceed2ea904 100644--- a/apps/desktop/electron/plugin-ws-url.ts+++ b/apps/desktop/electron/plugin-ws-url.ts@@ -10,6 +10,21 @@ export interface PluginWsUrlRequest {profile?: unknown}+/** `hermes:plugin:ws-url`'s reply: a one-use URL, null to stay on polling (not a local gateway), or+ * the one refusal main can name, which the renderer stops on. Any other failure rejects, and the+ * renderer keeps its capped retry: it cannot tell a refusal from a gateway that is away. */+export type PluginWsUrlReply = null | string | { refused: 'permission' }++/** A grant mint refused for a permission reason: an unsafe control path or a group-writable home+ * (this Desktop's own checks, or the runtime bridge's `unsafe_control_permissions`). Unlike an+ * owner that is restarting, draining or being re-ensured, it does not clear by itself. */+export function isMintPermissionRefusal(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error ?? '')++ return message.startsWith('Unsafe gateway control path') || message.startsWith('Profile home is writable by a group')+ || (error as { reason?: unknown })?.reason === 'unsafe_control_permissions'+}+interface ResolvedBackend {baseUrl: stringgatewayEndpoint?: GatewayEndpoint@@ -65,7 +80,7 @@ export function createPluginWsUrlHandler(deps: {mint?: typeof mintLocalGatewayTicketprepare: (origin: string, path: string, ticket: string, webContentsId: number) => string}) {- return async (request: PluginWsUrlRequest, webContentsId: number): Promise<null | string> => {+ return async (request: PluginWsUrlRequest, webContentsId: number): Promise<PluginWsUrlReply> => {const path = pluginWsPath(request?.pluginId, request?.path)const { connectionId, profile } = requestconst ensure = () => (connectionId ? deps.ensureRegistryBackend(connectionId, profile) : deps.ensureBackend(profile))@@ -74,14 +89,19 @@ export function createPluginWsUrlHandler(deps: {return null}- return localGatewayDial({- ensure,- forget: () => (connectionId ? deps.forgetRegistryLocalGatewayDescriptor(connectionId, profile) : deps.forgetLocalGatewayDescriptor(profile)),- launchHome: deps.launchHome,- mint: deps.mint,- prepare: (baseUrl, ticket) => deps.prepare(baseUrl, path, ticket, webContentsId),- profile: typeof profile === 'string' ? profile : '',- purpose: 'native-http'- })+ try {+ return await localGatewayDial({+ ensure,+ forget: () => (connectionId ? deps.forgetRegistryLocalGatewayDescriptor(connectionId, profile) : deps.forgetLocalGatewayDescriptor(profile)),+ launchHome: deps.launchHome,+ mint: deps.mint,+ prepare: (baseUrl, ticket) => deps.prepare(baseUrl, path, ticket, webContentsId),+ profile: typeof profile === 'string' ? profile : '',+ purpose: 'native-http'+ })+ } catch (error) {+ if (isMintPermissionRefusal(error)) {return { refused: 'permission' }}+ throw error+ }}}diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 3fb2c6bc886..dc1f6d587e4 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -46,7 +46,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {// Registry-scoped fresh WS URL: { connectionId, profile } → result shape of// getGatewayWsUrl, minted against that connection's backend.getGatewayWsUrlFor: payload => ipcRenderer.invoke('hermes:gateway:ws-url-for', payload),- // { connectionId, profile, pluginId, path } → one-use local plugin socket URL, or null.+ // { connectionId, profile, pluginId, path } → one-use local plugin socket URL, null, or { refused: 'permission' }.getPluginWsUrl: payload => ipcRenderer.invoke('hermes:plugin:ws-url', payload),// Union agent roster across every registered connection.getAgentRoster: () => ipcRenderer.invoke('hermes:agents:roster'),diff --git a/apps/desktop/src/api/plugins.test.ts b/apps/desktop/src/api/plugins.test.tsindex 4e2573c18a4..a0968e15908 100644--- a/apps/desktop/src/api/plugins.test.ts+++ b/apps/desktop/src/api/plugins.test.ts@@ -68,8 +68,8 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {}}- const desktop = (connection: Record<string, unknown>, minted: null | string = 'ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=n') => {- const getPluginWsUrl = vi.fn(async () => minted)+ const desktop = (connection: Record<string, unknown>, minted: unknown = 'ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=n') => {+ const getPluginWsUrl = vi.fn(async (): Promise<unknown> => minted)Object.defineProperty(window, 'hermesDesktop', {configurable: true,value: { getConnection: vi.fn(async () => connection), getPluginWsUrl }@@ -90,6 +90,7 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {FakeSocket.all = []vi.restoreAllMocks()vi.unstubAllGlobals()+ setApiRequestConnection(null)setApiRequestProfile(null)Reflect.deleteProperty(window, 'hermesDesktop')vi.useRealTimers()@@ -121,23 +122,78 @@ describe('pluginSocket credentials and refusals (PLG-1)', () => {dispose()})- it('stops re-dialing after repeated refusals', async () => {+ // The browser cannot tell a refused upgrade from a gateway that is restarting, draining or being+ // re-ensured: those dials keep the capped retry, however long the outage lasts.+ it('keeps retrying through a restart-length outage and reconnects', async () => {vi.useFakeTimers()vi.stubGlobal('WebSocket', FakeSocket)const mint = desktop(local)+ const frames: unknown[] = []- const dispose = pluginSocket('kanban', '/events', () => undefined)+ const dispose = pluginSocket('kanban', '/events', frame => frames.push(frame))await vi.advanceTimersByTimeAsync(0)for (let i = 0; i < 20; i += 1) {await refuseLatest()}- expect(FakeSocket.all).toHaveLength(5)+ // The mint itself failing while the owner is away is a connection failure too.+ mint.mockRejectedValueOnce(new Error('Gateway ticket control socket missing'))+ await refuseLatest()+ await vi.advanceTimersByTimeAsync(31_000)++ expect(FakeSocket.all).toHaveLength(22)+ expect(mint).toHaveBeenCalledTimes(23)+ const socket = FakeSocket.all.at(-1)!+ socket.onopen?.()+ socket.onmessage?.({ data: '{"ok":1}' })+ expect(frames).toEqual([{ ok: 1 }])+ dispose()+ })++ // Main names the one refusal it can identify: a grant mint refused for a permission reason.+ it('stops after repeated permission refusals from main', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ const mint = desktop(local, { refused: 'permission' })++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(600_000)+expect(mint).toHaveBeenCalledTimes(5)+ expect(FakeSocket.all).toHaveLength(0)dispose()})+ it('a profile or connection change resets the refusal count and dials again', async () => {+ vi.useFakeTimers()+ vi.stubGlobal('WebSocket', FakeSocket)+ setApiRequestProfile('coder')+ const mint = desktop(local, { refused: 'permission' })++ const dispose = pluginSocket('kanban', '/events', () => undefined)+ await vi.advanceTimersByTimeAsync(600_000)+ expect(mint).toHaveBeenCalledTimes(5)++ // Still refused under the new profile: a fresh budget of five, then stop again.+ setApiRequestProfile('research')+ await vi.advanceTimersByTimeAsync(600_000)+ expect(mint).toHaveBeenCalledTimes(10)+ expect(mint).toHaveBeenLastCalledWith(expect.objectContaining({ profile: 'research' }))++ mint.mockResolvedValue('ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=m')+ setApiRequestConnection('homelab')+ await vi.advanceTimersByTimeAsync(0)+ expect(mint).toHaveBeenCalledTimes(11)+ expect(FakeSocket.all.map(socket => socket.url)).toEqual(['ws://127.0.0.1:9/api/plugins/kanban/events?native_dial=m'])+ dispose()++ // A disposed socket no longer follows the scope.+ setApiRequestProfile('coder')+ await vi.advanceTimersByTimeAsync(600_000)+ expect(mint).toHaveBeenCalledTimes(11)+ })+it('keeps reconnecting a socket that stayed open before it dropped', async () => {vi.useFakeTimers()vi.stubGlobal('WebSocket', FakeSocket)diff --git a/apps/desktop/src/api/plugins.ts b/apps/desktop/src/api/plugins.tsindex 5b873e9d2c3..363c5635077 100644--- a/apps/desktop/src/api/plugins.ts+++ b/apps/desktop/src/api/plugins.ts@@ -3,7 +3,7 @@ import { isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'import type { HermesConnection } from '@/global'import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'-import { getApiRequestConnection, getApiRequestProfile, hermesApi, profileScoped } from './client'+import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile, hermesApi, profileScoped } from './client'/** Resolve the ACTIVE backend's connection descriptor, (connectionId,* profile)-scoped — mirroring how store/profile resolves $connection: a@@ -86,14 +86,17 @@ export async function pluginRest<T>(pluginId: string, path: string, opts: Plugin})}-/** Consecutive dials that never stayed open before the socket gives up for good.- * Every attempt is gateway traffic that keeps an idle-exit gateway awake. */+/** Refusals in a row that do not clear by themselves before the socket stops for its current+ * (connection, profile) scope. Every attempt is gateway traffic that keeps an idle-exit gateway awake. */const MAX_REFUSED_PLUGIN_DIALS = 5+/** What a plugin socket dials: a URL, null to stay on polling, or main's named refusal. */+type PluginSocketTarget = null | string | { refused: 'permission' }+/** The URL a plugin socket dials, or null to stay on polling. A local gateway* (`authMode: 'native'`, no static token) gets a fresh one-use URL from main:* its native grant rides a request header main attaches to that one dial. */-async function pluginSocketUrl(connection: HermesConnection, pluginId: string, suffix: string): Promise<null | string> {+async function pluginSocketUrl(connection: HermesConnection, pluginId: string, suffix: string): Promise<PluginSocketTarget> {if (connection.authMode === 'native') {const mint = window.hermesDesktop.getPluginWsUrl@@ -113,26 +116,42 @@ async function pluginSocketUrl(connection: HermesConnection, pluginId: string, sreturn `${base}/api/plugins/${pluginId}${suffix}${join}token=${encodeURIComponent(connection.token)}`}+const requestScopeKey = () => `${getApiRequestConnection() ?? ''}\n${getApiRequestProfile() ?? ''}`+/** The plugin WebSocket door — the live twin of `pluginRest`, scoped the same* way: `path` is relative to `/api/plugins/<pluginId>` ('/events' → the* plugin's own event stream). Token-mode backends auth via the same query* credential the app's own sockets use, a local gateway via the native grant* its REST twin uses; OAuth remotes resolve null (callers keep their polling* fallback — every consumer must have one anyway, since a socket can drop).- * Auto-reconnects with backoff until disposed, and gives up after- * MAX_REFUSED_PLUGIN_DIALS dials in a row that never stayed open. */+ *+ * Auto-reconnects with capped backoff until disposed. A dial that never opens+ * keeps retrying: the browser cannot tell a refused upgrade from a gateway that+ * is restarting, draining or being re-ensured. It stops after+ * MAX_REFUSED_PLUGIN_DIALS refusals in a row that do not clear by themselves:+ * main refusing the grant mint for a permission reason, or a server that+ * accepts and closes at once. A connection or profile change resets the count+ * and dials again. */export function pluginSocket(pluginId: string, path: string, onMessage: (data: unknown) => void): () => void {const suffix = pluginPathSuffix('pluginSocket', path)let socket: null | WebSocket = nulllet disposed = false+ let stopped = falselet attempt = 0let refused = 0+ let scope = requestScopeKey()- const retry = () => {- refused += 1+ const retry = (refusal: boolean) => {+ refused = refusal ? refused + 1 : refused++ if (disposed) {+ return+ }++ if (refused >= MAX_REFUSED_PLUGIN_DIALS) {+ stopped = true- if (disposed || refused >= MAX_REFUSED_PLUGIN_DIALS) {return}@@ -153,19 +172,23 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: ureturn}- let url: null | string+ let url: PluginSocketTargettry {url = await pluginSocketUrl(connection, pluginId, suffix)} catch {- // The local mint failed (gateway gone or refusing): a refused dial.- return retry()+ // The local mint failed or timed out (owner away, re-ensuring): a connection failure.+ return retry(false)}if (disposed || !url) {return}+ if (typeof url !== 'string') {+ return retry(true)+ }+socket = new WebSocket(url)let openedAt: null | number = null@@ -186,21 +209,41 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: usocket.onclose = () => {socket = null- // Only a socket that stayed up resets the ladder: an accept-then-close server- // (Kanban on an archived board) counts as a refused dial.+ // Only a socket that stayed up resets the ladder. An accept-then-close server+ // (Kanban on an archived board) is up and answering, so it counts as a refusal.if (isStableOpen(openedAt)) {attempt = 0refused = 0}- retry()+ retry(openedAt !== null && !isStableOpen(openedAt))}}+ // Another connection or profile is another gateway or another consent: a fresh count, and a+ // stopped socket dials again.+ const unlisten = $apiRequestScope.listen(() => {+ const next = requestScopeKey()++ if (next === scope) {+ return+ }++ scope = next+ attempt = 0+ refused = 0++ if (stopped && !disposed) {+ stopped = false+ void connect()+ }+ })+void connect()return () => {disposed = true+ unlisten()socket?.close()}}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex baef20e90be..55886217543 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -49,13 +49,15 @@ declare global {profile?: null | string}) => Promise<GatewayWsUrlResult>// One-use plugin socket URL for a local gateway (its native grant rides- // a header main attaches to that dial); null for every other backend.+ // a header main attaches to that dial); null for every other backend;+ // { refused: 'permission' } when main refused the grant mint for a+ // permission reason. Any other failure rejects.getPluginWsUrl?: (payload: {connectionId?: null | stringpath: stringpluginId: stringprofile?: null | string- }) => Promise<null | string>+ }) => Promise<null | string | { refused: 'permission' }>// Union agent roster across every registered connection.getAgentRoster?: () => Promise<DesktopAgentRoster>// Credential-free routes across the union connection registry. The