The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): expose connection-aware plugin routing
addel27e4f0954093
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex faf8f3e5366..510275bda34 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -215,6 +215,7 @@ import {parentWatchdogEnv} from './parent-process-identity'import { selectPoolEvictions } from './pool-eviction'+import { buildOpaqueProfileRoutes, type EffectiveSshRoute, type ProfileRouteConfig } from './plugin-profile-routes'import { createKeepAwake } from './power-save'import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'import { rehomePrimaryConnection } from './primary-connection-rehome'@@ -8557,6 +8558,39 @@ function effectiveSshConfigFingerprint(sshConfig) {return crypto.createHash('sha256').update(output).digest('hex')}+function effectiveSshRouteForPlugin(config: ProfileRouteConfig): Promise<EffectiveSshRoute> {+ const ssh =+ process.platform === 'win32'+ ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')+ : 'ssh'++ const args = ['-G']++ if (config.sshPort) {+ args.push('-p', String(config.sshPort))+ }++ args.push('--', config.sshUser ? `${config.sshUser}@${config.sshHost}` : config.sshHost)++ return new Promise((resolve, reject) => {+ execFile(ssh, args, { encoding: 'utf8', timeout: 10_000, windowsHide: true }, (error, stdout) => {+ if (error) {+ reject(new Error('Could not resolve SSH route for profile.'))++ return+ }++ const resolved = parseSshGOutput(stdout)++ resolve({+ hostname: resolved.hostname || config.sshHost,+ port: resolved.port || config.sshPort || 22,+ user: resolved.user || config.sshUser+ })+ })+ })+}+async function bootstrapSshConnection(profile, sshConfig, reuseToken, source) {const scope = sshScopeKey(profile)const effectiveConfigFingerprint = effectiveSshConfigFingerprint(sshConfig)@@ -11948,6 +11982,27 @@ ipcMain.handle('hermes:bootstrap:get', async () => getBootstrapState())ipcMain.handle('hermes:connection-config:get', async (_event, profile) =>sanitizeDesktopConnectionConfig(readDesktopConnectionConfig(), profile))+ipcMain.handle('hermes:plugin-profile-routes', async (_event, rawProfileNames) => {+ const profileNames = Array.isArray(rawProfileNames)+ ? rawProfileNames+ .filter(name => typeof name === 'string')+ .map(name => name.trim())+ .filter(Boolean)+ .slice(0, 256)+ : []++ const config = readDesktopConnectionConfig()+ const globalConfig = (await sanitizeDesktopConnectionConfig(config, null)) as ProfileRouteConfig++ return buildOpaqueProfileRoutes({+ getProfileConfig: async profile => (await sanitizeDesktopConnectionConfig(config, profile)) as ProfileRouteConfig,+ globalConfig,+ installationId: desktopInstallationId,+ primaryProfile: primaryProfileKey(),+ profileNames,+ resolveSsh: effectiveSshRouteForPlugin+ })+})ipcMain.handle('hermes:ssh-config:hosts', async () => ({ hosts: collectSshConfigHosts() }))ipcMain.handle('hermes:ssh-config:resolve', async (_event, host) => {const value = String(host || '').trim()diff --git a/apps/desktop/electron/plugin-profile-routes.test.ts b/apps/desktop/electron/plugin-profile-routes.test.tsnew file mode 100644index 00000000000..3d507099ee0--- /dev/null+++ b/apps/desktop/electron/plugin-profile-routes.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from 'vitest'++import { buildOpaqueProfileRoutes, type ProfileRouteConfig } from './plugin-profile-routes'++function config(overrides: Partial<ProfileRouteConfig> = {}): ProfileRouteConfig {+ return {+ cloudOrg: '',+ mode: 'local',+ remoteUrl: '',+ sshHost: '',+ sshPort: null,+ sshRemoteHermesPath: '',+ sshRemoteProfile: '',+ sshUser: '',+ ...overrides+ }+}++describe('buildOpaqueProfileRoutes', () => {+ it('groups SSH aliases by their effective route without exposing endpoint data', async () => {+ const configs = new Map([+ [+ 'research',+ config({+ mode: 'ssh',+ sshHost: 'lab-a',+ sshRemoteHermesPath: '~/.hermes',+ sshRemoteProfile: 'remote-research'+ })+ ],+ [+ 'writing',+ config({+ mode: 'ssh',+ sshHost: 'lab-b',+ sshRemoteHermesPath: '~/.hermes',+ sshRemoteProfile: 'remote-writing'+ })+ ]+ ])++ const resolveSsh = vi.fn(async () => ({ hostname: 'gateway.example', port: 22, user: 'hermes' }))++ const routes = await buildOpaqueProfileRoutes({+ getProfileConfig: profile => configs.get(profile) ?? config(),+ globalConfig: config(),+ installationId: 'install-a-secret',+ primaryProfile: 'default',+ profileNames: ['default', 'research', 'writing'],+ resolveSsh+ })++ expect(routes.map(route => ({ mode: route.mode, profile: route.profile, targetProfile: route.targetProfile }))).toEqual([+ { mode: 'local', profile: 'default', targetProfile: 'default' },+ { mode: 'remote', profile: 'research', targetProfile: 'remote-research' },+ { mode: 'remote', profile: 'writing', targetProfile: 'remote-writing' }+ ])+ expect(routes[1].connectionId).toBe(routes[2].connectionId)+ expect(routes[0].connectionId).not.toBe(routes[1].connectionId)+ expect(JSON.stringify(routes)).not.toContain('gateway.example')+ expect(JSON.stringify(routes)).not.toContain('lab-a')+ expect(JSON.stringify(routes)).not.toContain('.hermes')+ })++ it('changes opaque IDs when the effective SSH destination changes', async () => {+ const options = {+ getProfileConfig: () => config({ mode: 'ssh', sshHost: 'lab', sshRemoteHermesPath: '~/.hermes' }),+ globalConfig: config(),+ installationId: 'install-a-secret',+ primaryProfile: 'default',+ profileNames: ['default', 'worker']+ }++ const before = await buildOpaqueProfileRoutes({+ ...options,+ resolveSsh: async () => ({ hostname: 'old.example', port: 22, user: 'hermes' })+ })++ const after = await buildOpaqueProfileRoutes({+ ...options,+ resolveSsh: async () => ({ hostname: 'new.example', port: 22, user: 'hermes' })+ })++ expect(before[1].connectionId).not.toBe(after[1].connectionId)+ })++ it('keys IDs to the Desktop installation', async () => {+ const options = {+ getProfileConfig: () => config({ mode: 'remote', remoteUrl: 'https://gateway.example' }),+ globalConfig: config(),+ primaryProfile: 'default',+ profileNames: ['default', 'worker'],+ resolveSsh: vi.fn()+ }++ const first = await buildOpaqueProfileRoutes({ ...options, installationId: 'install-a-secret' })+ const second = await buildOpaqueProfileRoutes({ ...options, installationId: 'install-b-secret' })++ expect(first[1].connectionId).not.toBe(second[1].connectionId)+ })++ it('inherits the global remote gateway and deduplicates profile names', async () => {+ const routes = await buildOpaqueProfileRoutes({+ getProfileConfig: () => config(),+ globalConfig: config({ mode: 'remote', remoteUrl: 'https://gateway.example/' }),+ installationId: 'install-a-secret',+ primaryProfile: 'default',+ profileNames: ['default', 'alpha', 'beta', 'alpha'],+ resolveSsh: vi.fn()+ })++ expect(routes.map(route => route.profile)).toEqual(['default', 'alpha', 'beta'])+ expect(routes.map(route => route.targetProfile)).toEqual(['default', 'alpha', 'beta'])+ expect(routes.every(route => route.mode === 'remote')).toBe(true)+ expect(new Set(routes.map(route => route.connectionId))).toHaveLength(1)+ })++ it('keeps cloud organizations on one service URL in distinct groups', async () => {+ const routes = await buildOpaqueProfileRoutes({+ getProfileConfig: profile =>+ profile === 'org-a' || profile === 'org-b'+ ? config({ cloudOrg: profile, mode: 'cloud', remoteUrl: 'https://cloud.example' })+ : config(),+ globalConfig: config(),+ installationId: 'install-a-secret',+ primaryProfile: 'default',+ profileNames: ['default', 'org-a', 'org-b'],+ resolveSsh: vi.fn()+ })++ expect(new Set(routes.map(route => route.connectionId))).toHaveLength(3)+ expect(JSON.stringify(routes.map(({ connectionId, mode }) => ({ connectionId, mode })))).not.toContain('org-a')+ })+})diff --git a/apps/desktop/electron/plugin-profile-routes.ts b/apps/desktop/electron/plugin-profile-routes.tsnew file mode 100644index 00000000000..69582f06545--- /dev/null+++ b/apps/desktop/electron/plugin-profile-routes.ts@@ -0,0 +1,140 @@+import crypto from 'node:crypto'++export interface ProfileRouteConfig {+ cloudOrg: string+ mode: 'cloud' | 'local' | 'remote' | 'ssh'+ remoteUrl: string+ sshHost: string+ sshPort: null | number+ sshRemoteHermesPath: string+ sshRemoteProfile: string+ sshUser: string+}++export interface EffectiveSshRoute {+ hostname: string+ port: null | number+ user: string+}++export interface OpaqueProfileRoute {+ connectionId: string+ mode: 'local' | 'remote'+ profile: string+ targetProfile: string+}++interface BuildOpaqueProfileRoutesOptions {+ getProfileConfig: (profile: string) => ProfileRouteConfig | Promise<ProfileRouteConfig>+ globalConfig: ProfileRouteConfig+ installationId: string+ primaryProfile: string+ profileNames: string[]+ resolveSsh: (config: ProfileRouteConfig) => Promise<EffectiveSshRoute>+}++function normalizeProfile(name: null | string | undefined): string {+ return String(name ?? '').trim() || 'default'+}++function normalizeRemoteUrl(raw: string): string {+ const value = String(raw || '').trim()++ try {+ const url = new URL(value)+ url.username = ''+ url.password = ''+ url.search = ''+ url.hash = ''+ url.pathname = url.pathname.replace(/\/+$/, '') || '/'++ return url.toString().replace(/\/$/, '')+ } catch {+ return value.toLowerCase().replace(/\/+$/, '')+ }+}++async function connectionScope(+ config: ProfileRouteConfig,+ resolveSsh: BuildOpaqueProfileRoutesOptions['resolveSsh']+): Promise<{ key: string; mode: 'local' | 'remote' }> {+ if (config.mode === 'ssh') {+ const effective = await resolveSsh(config)++ // Remote profile is intentionally excluded: profiles mapped into the same+ // remote Hermes home form one interaction scope. Key/identity-file paths are+ // credentials and likewise stay out of the scope material.+ return {+ key: [+ 'ssh',+ effective.user.trim(),+ effective.hostname.trim().toLowerCase(),+ effective.port ?? 22,+ config.sshRemoteHermesPath.trim()+ ].join('\0'),+ mode: 'remote'+ }+ }++ if (config.mode === 'cloud') {+ return {+ key: `cloud\0${normalizeRemoteUrl(config.remoteUrl)}\0${config.cloudOrg.trim()}`,+ mode: 'remote'+ }+ }++ if (config.mode === 'remote') {+ return { key: `remote\0${normalizeRemoteUrl(config.remoteUrl)}`, mode: 'remote' }+ }++ return { key: 'local', mode: 'local' }+}++function opaqueConnectionId(scope: string, installationId: string): string {+ const digest = crypto.createHmac('sha256', installationId).update(scope).digest('hex')++ return `connection-${digest.slice(0, 24)}`+}++/**+ * Resolve Desktop routing profiles at the Electron boundary and return only+ * keyed, credential-free descriptors to the renderer/plugin runtime.+ */+export async function buildOpaqueProfileRoutes({+ getProfileConfig,+ globalConfig,+ installationId,+ primaryProfile,+ profileNames,+ resolveSsh+}: BuildOpaqueProfileRoutesOptions): Promise<OpaqueProfileRoute[]> {+ const primary = normalizeProfile(primaryProfile)+ const names: string[] = []+ const seen = new Set<string>()++ for (const raw of [primary, ...profileNames]) {+ const name = normalizeProfile(raw)++ if (!seen.has(name)) {+ seen.add(name)+ names.push(name)+ }+ }++ const globalScope = await connectionScope(globalConfig, resolveSsh)++ return Promise.all(+ names.map(async profile => {+ const scoped = await getProfileConfig(profile)+ const scope = scoped.mode === 'local' ? globalScope : await connectionScope(scoped, resolveSsh)++ return {+ connectionId: opaqueConnectionId(scope.key, installationId),+ mode: scope.mode,+ profile,+ targetProfile:+ scoped.mode === 'ssh' ? normalizeProfile(scoped.sshRemoteProfile || profile) : profile+ }+ })+ )+}diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 96c76d4822c..f573ca24d4f 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {getConnection: profile => ipcRenderer.invoke('hermes:connection', profile),// Registry-scoped backend resolution: { connectionId, profile } → descriptor.getConnectionFor: payload => ipcRenderer.invoke('hermes:connection:for', payload),+ getProfileRoutes: profiles => ipcRenderer.invoke('hermes:plugin-profile-routes', profiles),revalidateConnection: () => ipcRenderer.invoke('hermes:connection:revalidate'),touchBackend: profile => ipcRenderer.invoke('hermes:backend:touch', profile),getGatewayWsUrl: profile => ipcRenderer.invoke('hermes:gateway:ws-url', profile),diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 9f3fd353408..507f3710663 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -31,6 +31,9 @@ declare global {}) => Promise<GatewayWsUrlResult>// Union agent roster across every registered connection.getAgentRoster?: () => Promise<DesktopAgentRoster>+ // Credential-free, installation-keyed route identities for Desktop+ // plugins. Endpoint and auth material never crosses the IPC boundary.+ getProfileRoutes: (profiles: string[]) => Promise<DesktopPluginProfileRoute[]>// Reconnect-after-wake recovery: liveness-probe the cached PRIMARY backend// and drop it if a remote one has gone unreachable, so the next// getConnection() rebuilds a reachable descriptor instead of the renderer@@ -578,6 +581,13 @@ export interface DesktopUpdateProgress {at: number}+export interface DesktopPluginProfileRoute {+ connectionId: string+ mode: 'local' | 'remote'+ profile: string+ targetProfile: string+}+export interface HermesConnection {baseUrl: stringdarwinMajor?: numberdiff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex bf6bf770d0f..19734385024 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -26,14 +26,21 @@ import type { ClientSessionState } from '@/app/types'import { $narrowViewport } from '@/components/pane-shell/tree/store'import { onGatewayEvent } from '@/contrib/events'import { deleteProfile, getLogs, getStatus, type HermesGateway } from '@/hermes'-import { $gateway, openGatewayForAgent, openGatewayForProfile } from '@/store/gateway'+import {+ $gateway,+ openGatewayForAgent,+ openGatewayForProfile,+ requestGatewayForProfile+} from '@/store/gateway'import { notify, notifyError } from '@/store/notifications'import {$activeGatewayProfile,+ $profiles,ensureGatewayAgent,ensureGatewayProfile,newSessionInProfile,normalizeProfileKey,+ refreshProfiles,selectProfile,setActiveProfile,setShowAllProfiles@@ -76,6 +83,15 @@ const $focusedAwaitingResponse = focusedTurnFlag(PRIMARY_SESSION_VIEW.$awaitingResponse)+export interface PluginProfileRoute {+ connectionId: string+ mode: 'local' | 'remote'+ /** Desktop profile used to select the connection route. */+ profile: string+ /** Backend Hermes profile served by that route. */+ targetProfile: string+}+/** Window geometry + the app's responsive posture, one readonly rect. */export interface ViewportRect {width: number@@ -319,6 +335,33 @@ export const host = {/** One-shot system status snapshot (platforms, versions, …). */status: async () => getStatus(),+ /** Credential-free Desktop profile routes for connection-aware plugin UI.+ * Profiles sharing one execution gateway receive the same opaque id. */+ profileRoutes: async () => {+ const desktop = window.hermesDesktop+ const getProfileRoutes = desktop?.getProfileRoutes++ if (!getProfileRoutes) {+ throw new Error('Hermes Desktop connection routing unavailable')+ }++ let profiles = $profiles.get()++ try {+ profiles = await refreshProfiles()+ } catch {+ // Route inventory is a read: a transient backend failure falls back to+ // the last cache. Electron always adds the primary Desktop profile.+ }++ return getProfileRoutes(profiles.map(profile => profile.name))+ },++ /** Gateway JSON-RPC through a named Desktop profile without foregrounding+ * that profile or changing the active chat/gateway. */+ requestProfile: async <T>(profile: string, method: string, params: Record<string, unknown> = {}): Promise<T> =>+ requestGatewayForProfile<T>(profile, method, params),+/** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything* the app itself uses. Lazy: resolves the LIVE socket per call. */request: async <T>(method: string, params: Record<string, unknown> = {}): Promise<T> => {diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.tsnew file mode 100644index 00000000000..d9c2eabe5db--- /dev/null+++ b/apps/desktop/src/store/gateway-profile-request.test.ts@@ -0,0 +1,182 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const secondaryGateways: Array<{+ close: ReturnType<typeof vi.fn>+ connect: ReturnType<typeof vi.fn>+ connectionState: string+ request: ReturnType<typeof vi.fn>+}> = []++let connectGate: Promise<void> | null = null++vi.mock('@/hermes', () => ({+ HermesGateway: class {+ connectionState = 'closed'+ connect = vi.fn(async () => {+ if (this.connectionState === 'connecting') {+ return+ }++ this.connectionState = 'connecting'++ if (connectGate) {+ await connectGate+ }++ this.connectionState = 'open'+ })+ request = vi.fn(async (method: string, params: Record<string, unknown>) => {+ if (this.connectionState !== 'open') {+ throw new Error('gateway is not connected')+ }++ return { method, params }+ })+ close = vi.fn()+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})++ constructor() {+ secondaryGateways.push(this)+ }+ }+}))+vi.mock('@/store/session', () => ({ setGatewayState: vi.fn() }))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const {+ $gateway,+ closeSecondaryGateways,+ configureGatewayRegistry,+ ensureGatewayForProfile,+ pruneSecondaryGateways,+ requestGatewayForProfile,+ setPrimaryGateway+} = await import('./gateway')++function installDesktop(getConnection: ReturnType<typeof vi.fn>): void {+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {+ getConnection,+ touchBackend: vi.fn(async () => undefined)+ }+}++function makePrimary() {+ return {+ connectionState: 'open',+ request: vi.fn(async (method: string, params: Record<string, unknown>) => ({ method, params }))+ }+}++beforeEach(async () => {+ secondaryGateways.length = 0+ connectGate = null+ configureGatewayRegistry({ onEvent: vi.fn() })+ closeSecondaryGateways()+})++afterEach(() => {+ closeSecondaryGateways()+ vi.clearAllMocks()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('requestGatewayForProfile', () => {+ it('requests through a pooled profile gateway without changing the active gateway', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop(+ vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ )+ )+ await ensureGatewayForProfile('default')++ const result = await requestGatewayForProfile('worker', 'profiles.list', { include_sessions: true })++ expect(result).toEqual({ method: 'profiles.list', params: { include_sessions: true } })+ expect(secondaryGateways).toHaveLength(1)+ expect(secondaryGateways[0].request).toHaveBeenCalledWith('profiles.list', { include_sessions: true })+ expect($gateway.get()).toBe(primary)+ })++ it('uses the primary socket and adds profile scope for a shared global remote route', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop(+ vi.fn(async (profile: null | string) => ({+ port: 4242,+ ...(profile ? { profile, sharedPrimary: true } : {}),+ token: 'primary-token'+ }))+ )+ await ensureGatewayForProfile('default')++ const result = await requestGatewayForProfile('venture', 'session.list', { limit: 20, profile: 'wrong' })++ expect(result).toEqual({ method: 'session.list', params: { limit: 20, profile: 'venture' } })+ expect(primary.request).toHaveBeenCalledWith('session.list', { limit: 20, profile: 'venture' })+ expect(secondaryGateways).toHaveLength(0)+ expect($gateway.get()).toBe(primary)+ })++ it('serializes concurrent requests while a secondary gateway is connecting', async () => {+ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })++ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop(+ vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ )+ )+ await ensureGatewayForProfile('default')++ const first = requestGatewayForProfile('worker', 'profiles.list')+ await vi.waitFor(() => expect(secondaryGateways[0]?.connect).toHaveBeenCalledOnce())+ const second = requestGatewayForProfile('worker', 'profiles.list')+ const guardedSecond = second.catch(error => error)++ await Promise.resolve()+ releaseConnect()++ const [firstResult, secondResult] = await Promise.all([first, guardedSecond])++ expect(firstResult).toEqual({ method: 'profiles.list', params: {} })+ expect(secondResult).toEqual({ method: 'profiles.list', params: {} })+ expect(secondaryGateways[0].connect).toHaveBeenCalledOnce()+ expect(secondaryGateways[0].request).toHaveBeenCalledTimes(2)+ expect($gateway.get()).toBe(primary)+ })++ it('prevents pruning while a background request is connecting or in flight', async () => {+ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })++ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop(+ vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ )+ )+ await ensureGatewayForProfile('default')++ const request = requestGatewayForProfile('worker', 'profiles.list')+ await vi.waitFor(() => expect(secondaryGateways[0]?.connect).toHaveBeenCalledOnce())++ pruneSecondaryGateways(new Set())+ releaseConnect()++ await expect(request).resolves.toEqual({ method: 'profiles.list', params: {} })+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 2cdcc8b6b01..0fa9349dfc4 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -34,6 +34,8 @@ interface Secondary {/** Registry connection serving this socket; null = the local/legacy path. */connectionId: null | stringgateway: HermesGateway+ activeRequests: number+ connectPromise: Promise<void> | nulloffEvent: () => voidoffState: () => voidreconnectTimer: ReturnType<typeof setTimeout> | null@@ -204,31 +206,54 @@ async function openSecondary(entry: Secondary): Promise<void> {return}- // Registry-scoped entries dial through getConnectionFor when the bridge has- // it (feature-detected: an older Electron main lacks the door and those- // entries simply can't exist yet — createSecondary guards creation).- const conn =- entry.connectionId && desktop.getConnectionFor- ? await desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile })- : await desktop.getConnection(entry.profile)-- const wsUrl = await resolveGatewayWsUrl(- entry.connectionId && desktop.getGatewayWsUrlFor- ? {- getGatewayWsUrl: () =>- desktop.getGatewayWsUrlFor!({ connectionId: entry.connectionId, profile: entry.profile })- }- : desktop,- conn- )-- await entry.gateway.connect(wsUrl)+ if (entry.connectPromise) {+ await entry.connectPromise- if (g.activeKey === entry.scope) {- setConnection(conn)+ return}- void desktop.touchBackend?.(entry.scope).catch(() => undefined)+ const pending = (async () => {+ // Registry-scoped entries dial through getConnectionFor when the bridge has+ // it. Local/legacy entries retain the existing getConnection path.+ const conn =+ entry.connectionId && desktop.getConnectionFor+ ? await desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile })+ : await desktop.getConnection(entry.profile)++ const wsUrl = await resolveGatewayWsUrl(+ entry.connectionId && desktop.getGatewayWsUrlFor+ ? {+ getGatewayWsUrl: () =>+ desktop.getGatewayWsUrlFor!({ connectionId: entry.connectionId, profile: entry.profile })+ }+ : desktop,+ conn+ )++ await entry.gateway.connect(wsUrl)++ if (!entry.wantOpen) {+ entry.gateway.close()++ return+ }++ if (g.activeKey === entry.scope) {+ setConnection(conn)+ }++ void desktop.touchBackend?.(entry.scope).catch(() => undefined)+ })()++ entry.connectPromise = pending++ try {+ await pending+ } finally {+ if (entry.connectPromise === pending) {+ entry.connectPromise = null+ }+ }}function scheduleReconnect(entry: Secondary): void {@@ -295,6 +320,8 @@ function createSecondary(profile: string, connectionId: null | string = null): Sprofile,connectionId,gateway,+ activeRequests: 0,+ connectPromise: null,offEvent: () => {},offState: () => {},reconnectTimer: null,@@ -349,30 +376,91 @@ async function sharedPrimaryRoute(profile: string): Promise<boolean> {}}-// Open `profile`'s socket WITHOUT making it active — the hover-intent pre-warm-// (store/profile). Runs the same spawn + connect chain as a real switch, so by-// click time ensureGatewayForProfile finds an open socket and just activates-// it. No scheduleReconnect on failure: a hover is speculative, so a dead-// backend must not start a background retry loop — the real switch owns retry-// and error UX. An already-open (or primary) profile is a no-op.-export async function openGatewayForProfile(profile: string): Promise<void> {+// Resolve and open `profile`'s socket WITHOUT changing the active gateway.+// Shared global-remote profiles intentionally return the primary socket plus a+// request-scope flag; dedicated local/remote profiles use their pooled socket.+async function gatewayForProfile(+ profile: string,+ leaseRequest = false+): Promise<{ gateway: HermesGateway | null; key: string; release: () => void; scopeProfile: boolean }> {const key = normKey(profile)+ const noRelease = () => undefinedif (key === g.primaryProfile) {- return+ return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }}if (await sharedPrimaryRoute(key)) {- // Served by the primary backend — there is no per-profile socket to warm.- return+ return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }}const entry = g.secondaries.get(key) ?? createSecondary(key)++ // Existing dev-HMR entries predate the request lease field.+ if (!Number.isFinite(entry.activeRequests)) {+ entry.activeRequests = 0+ }+entry.wantOpen = true- if (!isOpen(entry.gateway)) {- await openSecondary(entry)+ if (leaseRequest) {+ entry.activeRequests += 1}++ let released = false++ const release = () => {+ if (!released && leaseRequest) {+ released = true+ entry.activeRequests = Math.max(0, entry.activeRequests - 1)+ }+ }++ try {+ if (!isOpen(entry.gateway)) {+ await openSecondary(entry)+ }+ } catch (error) {+ release()+ throw error+ }++ return { gateway: entry.gateway, key, release, scopeProfile: false }+}++/**+ * Send a gateway RPC through a named Desktop profile without foregrounding it.+ * Global-remote routes share the primary socket and need an explicit profile+ * param; dedicated pooled backends are already scoped by their descriptor.+ */+export async function requestGatewayForProfile<T>(+ profile: string,+ method: string,+ params: Record<string, unknown> = {}+): Promise<T> {+ const route = await gatewayForProfile(profile, true)++ try {+ if (!route.gateway) {+ throw new Error(`Hermes gateway unavailable for profile "${route.key}"`)+ }++ const routedParams = route.scopeProfile ? { ...params, profile: route.key } : params++ return await route.gateway.request<T>(method, routedParams)+ } finally {+ route.release()+ }+}++// Open `profile`'s socket WITHOUT making it active — the hover-intent pre-warm+// (store/profile). Runs the same spawn + connect chain as a real switch, so by+// click time ensureGatewayForProfile finds an open socket and just activates+// it. No scheduleReconnect on failure: a hover is speculative, so a dead+// backend must not start a background retry loop — the real switch owns retry+// and error UX. An already-open (or primary) profile is a no-op.+export async function openGatewayForProfile(profile: string): Promise<void> {+ await gatewayForProfile(profile)}// ── Connection-scoped agents (multi-source roster) ─────────────────────────@@ -555,7 +643,12 @@ function restoreActiveToPrimaryIfEvicted(): void {// 'default' activity (and vice versa) — cross-connection attribution.export function pruneSecondaryGateways(keep: Set<string>): void {for (const [key, entry] of [...g.secondaries]) {- if (key === g.activeKey || keep.has(key) || (!entry.connectionId && keep.has(entry.profile))) {+ if (+ key === g.activeKey ||+ keep.has(key) ||+ (!entry.connectionId && keep.has(entry.profile)) ||+ entry.activeRequests > 0+ ) {continue}diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex d0c4892277f..542160f626b 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -411,11 +411,25 @@ host.onEvent(type, fn) // gateway event stream ('*' = all);host.logs(...) // tail an app log filehost.status() // one-shot system status snapshothost.restartGateway() // restart the backend gateway-host.request<T>(method, params?) // gateway JSON-RPC — the real power+host.profileRoutes() // [{ profile, targetProfile, connectionId, mode }]+host.requestProfile<T>(profile, method, params?) // routed RPC; no foreground swap+host.request<T>(method, params?) // active-gateway JSON-RPC — the real power````host.request` is the same JSON-RPC the app itself uses (sessions, config, skills,-cron, kanban, …). Profile-shaped plugins get first-class methods too:+cron, kanban, …). `host.requestProfile` routes that RPC through a named Desktop+profile's local/SSH/URL/cloud backend without changing the active chat or gateway.+Use `host.profileRoutes()` for connection-aware UI: `connectionId` is stable,+installation-scoped, and derived inside Electron with installation-keyed hashing;+profiles sharing one execution gateway receive the same id, while endpoint or+credential fields never cross the plugin IPC boundary. Key persisted identity by+`connectionId + targetProfile`, not by profile name alone. `profile` is the Desktop+route to pass to `host.requestProfile()` or `host.openSession()`; `targetProfile` is+the backend Hermes profile served by that route. They differ only when a Desktop+route explicitly maps to another backend profile (for example an SSH+`remoteProfile` override); profile names are bot identity, not connection secrets.++Profile-shaped plugins get first-class methods too:`profiles.list` (each profile + its most recent conversation as`last_session`; pass `include_sessions: false` to skip the per-profile DBprobe) and `profiles.create` (`name`, `description`, `clone_from`,