Skip to content

The agent that grows with you

fix(desktop): harden plugin route lifecycle

addelc76b7e634371
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 2fc06ce4731..0b7de9d5624 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -214,15 +214,16 @@ import {
electronProcessStartMarker,
parentWatchdogEnv
} from './parent-process-identity'
-import { selectPoolEvictions } from './pool-eviction'
import {
buildOpaqueProfileRoutes,
buildRegistryProfileRoutes,
type EffectiveSshRoute,
localRouteFallbackProfiles,
type ProfileRouteConfig,
- registryGatewayWsUrl
+ registryGatewayWsUrl,
+ undialedSshRouteSeeds
} from './plugin-profile-routes'
+import { selectPoolEvictions } from './pool-eviction'
import { createKeepAwake } from './power-save'
import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'
import { rehomePrimaryConnection } from './primary-connection-rehome'
@@ -8048,7 +8049,7 @@ function sanitizeConnectionsRegistry(registry = readDesktopConnectionsRegistry()
* stored envelope on edit; switching auth away from 'token' clears it
* (normalizeConnectionInput drops tokens on non-token entries).
*/
-function saveRegistryConnection(input: any = {}) {
+async function saveRegistryConnection(input: any = {}) {
const registry = readDesktopConnectionsRegistry()
const existing = input.id ? registry.connections.find(c => c.id === input.id) : null
const incomingToken = typeof input.token === 'string' ? input.token.trim() : ''
@@ -8078,7 +8079,7 @@ function saveRegistryConnection(input: any = {}) {
// connection's pooled backends/tunnels and tell renderers to dispose+redial
// their secondaries for this connection id.
if (existing && connectionDialFieldsChanged(existing, entry)) {
- stopRegistryConnectionBackends(entry.id)
+ await stopRegistryConnectionBackends(entry.id)
broadcastConnectionsChanged({ connectionId: entry.id, reason: 'updated' })
}
@@ -8646,7 +8647,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
}
)
removeForceCleanup = lease.onForceCleanup(() => ssh.close())
- await ssh.open()
+ await ssh.open({ signal: lease.signal })
}
let result
@@ -9511,7 +9512,7 @@ async function connectRegistryBackend(source, profile, key, poolEntry) {
// Stop every pooled backend and ssh scope owned by a registry connection —
// called when the connection is removed from the registry.
-function stopRegistryConnectionBackends(connectionId) {
+async function stopRegistryConnectionBackends(connectionId) {
const prefix = backendScopePrefix(connectionId)
for (const key of [...backendPool.keys()]) {
@@ -9520,11 +9521,19 @@ function stopRegistryConnectionBackends(connectionId) {
}
}
- for (const scope of [...sshConnections.keys()]) {
- if (String(scope).startsWith(prefix)) {
- void teardownSshConnection(scope)
- }
- }
+ const sshScopes = new Set([
+ ...[...sshConnections.keys()].filter(scope => String(scope).startsWith(prefix)),
+ ...[...sshBootstrapCoordinator.active]
+ .map(entry => entry.scope)
+ .filter(scope => String(scope).startsWith(prefix))
+ ])
+
+ await Promise.all(
+ [...sshScopes].map(async scope => {
+ await sshBootstrapCoordinator.cancelAndWait(scope)
+ await teardownSshConnection(scope)
+ })
+ )
}
// Mark a pool profile as recently used so the idle reaper spares it. The
@@ -12002,13 +12011,37 @@ ipcMain.handle('hermes:plugin-profile-routes', async (_event, rawProfileNames) =
const enumerations = await enumerateRegistryAgentSources(registry)
let agents = buildAgentRoster(enumerations)
+ // Roster enumeration deliberately does not dial connect-on-demand SSH
+ // sources. Publish one credential-free seed route so a plugin can be the
+ // first caller that opens the tunnel.
+ const sshSeeds = undialedSshRouteSeeds(agents, registry.connections)
+
+ if (sshSeeds.length > 0) {
+ agents = [
+ ...agents,
+ ...sshSeeds.map(seed => {
+ const source = registry.connections.find(connection => connection.id === seed.connectionId)!
+
+ return {
+ connectionId: source.id,
+ connectionKind: source.kind,
+ connectionLabel: source.label,
+ handle: seed.profile,
+ profile: seed.profile
+ }
+ })
+ ]
+ }
+
// A local enumeration can fail while remote/cloud sources succeed. Preserve
// cached v1 profile names as explicitly-local rows so those valid routes do
// not disappear and duplicate names remain source-qualified.
const localSource = registry.connections.find(source => source.kind === 'local')
+
const localEnumeration = localSource
? enumerations.find(({ connection }) => connection.id === localSource.id)
: undefined
+
const localFallbackProfiles = localSource
? localRouteFallbackProfiles(agents, localSource.id, fallbackProfileNames, Boolean(localEnumeration?.error))
: []
@@ -12093,7 +12126,7 @@ ipcMain.handle('hermes:connection-config:test', async (_event, payload) => testD
// list, so they are safe to ship ahead of the switchover.
ipcMain.handle('hermes:connections:list', async () => sanitizeConnectionsRegistry())
ipcMain.handle('hermes:connections:save', async (_event, payload) => {
- const saved = saveRegistryConnection(payload)
+ const saved = await saveRegistryConnection(payload)
return { ok: true, connection: saved, registry: sanitizeConnectionsRegistry() }
})
@@ -12103,7 +12136,7 @@ ipcMain.handle('hermes:connections:remove', async (_event, id) => {
writeDesktopConnectionsRegistry(registry)
// Tear down anything the removed connection still had running: pooled
// backends under its composite keys and any ssh tunnel scopes it owned.
- stopRegistryConnectionBackends(key)
+ await 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.
diff --git a/apps/desktop/electron/plugin-profile-routes.test.ts b/apps/desktop/electron/plugin-profile-routes.test.ts
index 3fee32f824e..1f40e9d847d 100644
--- a/apps/desktop/electron/plugin-profile-routes.test.ts
+++ b/apps/desktop/electron/plugin-profile-routes.test.ts
@@ -5,7 +5,8 @@ import {
buildRegistryProfileRoutes,
localRouteFallbackProfiles,
type ProfileRouteConfig,
- registryGatewayWsUrl
+ registryGatewayWsUrl,
+ undialedSshRouteSeeds
} from './plugin-profile-routes'
function config(overrides: Partial<ProfileRouteConfig> = {}): ProfileRouteConfig {
@@ -105,6 +106,33 @@ describe('buildOpaqueProfileRoutes', () => {
expect(first[1].connectionId).not.toBe(second[1].connectionId)
})
+ it('isolates an SSH resolution failure to its configured route', async () => {
+ const options = {
+ getProfileConfig: (profile: string) =>
+ profile === 'broken'
+ ? config({ mode: 'ssh', sshHost: 'unreachable', sshPort: 2222, sshUser: 'hermes' })
+ : config(),
+ globalConfig: config(),
+ installationId: 'install-a-secret',
+ primaryProfile: 'default',
+ profileNames: ['default', 'broken']
+ }
+
+ const routes = await buildOpaqueProfileRoutes({
+ ...options,
+ resolveSsh: async route => {
+ if (route.sshHost === 'unreachable') {
+ throw new Error('ssh -G timed out')
+ }
+
+ return { hostname: route.sshHost, port: route.sshPort, user: route.sshUser }
+ }
+ })
+
+ expect(routes).toHaveLength(2)
+ expect(routes.find(route => route.profile === 'broken')).toMatchObject({ mode: 'remote', profile: 'broken' })
+ })
+
it('inherits the global remote gateway and deduplicates profile names', async () => {
const routes = await buildOpaqueProfileRoutes({
getProfileConfig: () => config(),
@@ -248,3 +276,23 @@ describe('localRouteFallbackProfiles', () => {
expect(localRouteFallbackProfiles([], 'local', ['default'], false)).toEqual([])
})
})
+
+describe('undialedSshRouteSeeds', () => {
+ it('keeps a stable default route while retaining the configured backend target', () => {
+ expect(
+ undialedSshRouteSeeds([], [
+ { id: 'homelab', kind: 'ssh', remoteProfile: 'venture' },
+ { id: 'cloud-prod', kind: 'cloud' }
+ ])
+ ).toEqual([{ connectionId: 'homelab', profile: 'default' }])
+ })
+
+ it('does not add a speculative seed after the source has roster agents', () => {
+ expect(
+ undialedSshRouteSeeds(
+ [{ connectionId: 'homelab', profile: 'research' }],
+ [{ id: 'homelab', kind: 'ssh', remoteProfile: 'venture' }]
+ )
+ ).toEqual([])
+ })
+})
diff --git a/apps/desktop/electron/plugin-profile-routes.ts b/apps/desktop/electron/plugin-profile-routes.ts
index 8b7e45a30bd..3f1a1d0468c 100644
--- a/apps/desktop/electron/plugin-profile-routes.ts
+++ b/apps/desktop/electron/plugin-profile-routes.ts
@@ -67,6 +67,7 @@ export function localRouteFallbackProfiles(
.filter(agent => agent.connectionId === localConnectionId)
.map(agent => normalizeProfile(agent.profile))
)
+
const fallback: string[] = []
for (const raw of profileNames) {
@@ -81,6 +82,25 @@ export function localRouteFallbackProfiles(
return fallback
}
+/** Credential-free seed routes let a plugin be the first caller to lazily dial
+ * an SSH source. Once a source has roster agents, those live profiles are the
+ * inventory and no speculative seed is needed. */
+export function undialedSshRouteSeeds(
+ agents: RegistryProfileRouteAgent[],
+ sources: RegistryProfileRouteSource[]
+): Array<{ connectionId: string; profile: string }> {
+ const dialed = new Set(agents.map(agent => agent.connectionId))
+
+ return sources
+ .filter(source => source.kind === 'ssh' && !dialed.has(source.id))
+ .map(source => ({
+ connectionId: source.id,
+ // remoteProfile is the backend target, not the source-local route. Keep
+ // identity stable when the first lazy dial later inventories `default`.
+ profile: 'default'
+ }))
+}
+
function normalizeProfile(name: null | string | undefined): string {
return String(name ?? '').trim() || 'default'
}
@@ -107,7 +127,20 @@ async function connectionScope(
resolveSsh: BuildOpaqueProfileRoutesOptions['resolveSsh']
): Promise<{ key: string; mode: 'local' | 'remote' }> {
if (config.mode === 'ssh') {
- const effective = await resolveSsh(config)
+ let effective: EffectiveSshRoute
+
+ try {
+ effective = await resolveSsh(config)
+ } catch {
+ // `ssh -G` may time out or fail for one stale alias. Keep route inventory
+ // available for every other profile and derive this opaque id from the
+ // configured target; the actual lazy dial will still surface its error.
+ effective = {
+ hostname: config.sshHost,
+ port: config.sshPort,
+ user: config.sshUser
+ }
+ }
// Remote profile is intentionally excluded: profiles mapped into the same
// remote Hermes home form one interaction scope. Key/identity-file paths are
diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
index d3ffb99e0ee..557df7a1861 100644
--- a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
@@ -163,6 +163,28 @@ test('cancelAndWait drains only the requested scope', async () => {
assert.equal(await second, 'second')
})
+test('cancelAndWait force-cleans pending resources before awaiting rollback', async () => {
+ const coordinator = createBootstrapCoordinator()
+ const gate = deferred()
+ let cleaned = 0
+
+ const pending = coordinator.start('scope', 'x', async lease => {
+ lease.onForceCleanup(async () => {
+ cleaned++
+ })
+ await gate.promise
+ lease.assertCurrent()
+ })
+
+ await Promise.resolve()
+ const drain = coordinator.cancelAndWait('scope')
+ await Promise.resolve()
+ gate.resolve()
+ await drain
+ await assert.rejects(pending, (error: any) => error.kind === 'superseded')
+ assert.equal(cleaned, 1)
+})
+
test('a generation started during cancelAndWait cannot run before the drain completes', async () => {
const coordinator = createBootstrapCoordinator()
const oldGate = deferred()
diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.ts
index c38e0473aae..7badbcb594b 100644
--- a/apps/desktop/electron/ssh-bootstrap-coordinator.ts
+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.ts
@@ -100,6 +100,11 @@ function createBootstrapCoordinator() {
}
try {
+ // Cancellation alone only invalidates the lease; it does not interrupt a
+ // child process currently blocked in SSH connect/config resolution. Close
+ // registered resources first so rollback can settle promptly while the
+ // drain barrier still prevents stale resurrection.
+ await Promise.allSettled(entries.flatMap(entry => [...entry.forceCleanups]).map(cleanup => cleanup()))
await Promise.allSettled(entries.map(entry => entry.promise))
} finally {
if (drains.get(scope) === barrier) {
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index a3d6d731bd5..5fcba400acc 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -260,6 +260,24 @@ test('open() establishes the master when not already alive', async () => {
assert.deepEqual(ops, ['check', 'master'], 'probes liveness first, then opens the master')
})
+test('open() abort kills an in-flight SSH child instead of waiting for timeout', async () => {
+ const child = fakeChild({ hang: true })
+
+ const conn = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn: () => child, controlDir: '/tmp/d', connectTimeoutMs: 1000 }
+ )
+
+ const controller = new AbortController()
+ const opening = conn.open({ signal: controller.signal })
+
+ await Promise.resolve()
+ controller.abort()
+
+ await assert.rejects(opening, (error: any) => error.kind === 'superseded')
+ assert.equal(child._killed, true)
+})
+
test('open() is a no-op when the master is already alive and execs verify', async () => {
const ops: string[] = []
diff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.ts
index 9b535c69c5b..26aac621132 100644
--- a/apps/desktop/electron/ssh-connection.ts
+++ b/apps/desktop/electron/ssh-connection.ts
@@ -351,8 +351,16 @@ function sshErrorMessage(kind, conn, stderr?) {
// Resolves { code, stdout, stderr }. On timeout the child is SIGKILLed and the
// promise rejects with err.kind = TIMEOUT. `spawnFn` is injectable for tests.
-function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData }: any = {}) {
+function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData, signal }: any = {}) {
return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ const error: any = new Error('SSH operation was cancelled.')
+ error.kind = 'superseded'
+ reject(error)
+
+ return
+ }
+
const useStdinPipe = stdinData != null || stdin !== 'ignore'
let child
@@ -387,9 +395,35 @@ function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData
const err: any = new Error(`ssh timed out after ${timeoutMs}ms`)
err.kind = SSH_ERROR.TIMEOUT
+ signal?.removeEventListener('abort', onAbort)
reject(err)
}, timeoutMs)
+ const onAbort = () => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ clearTimeout(timer)
+
+ try {
+ child.kill('SIGKILL')
+ } catch {
+ // already gone
+ }
+
+ const error: any = new Error('SSH operation was cancelled.')
+ error.kind = 'superseded'
+ reject(error)
+ }
+
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ if (signal?.aborted) {
+ onAbort()
+ }
+
child.stdout?.on('data', d => {
stdout += d.toString()
})
@@ -403,6 +437,7 @@ function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData
settled = true
clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
reject(error)
})
child.on('close', code => {
@@ -412,6 +447,7 @@ function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData
settled = true
clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
resolve({ code, stdout, stderr })
})
})
@@ -516,6 +552,10 @@ class SshConnection {
}
_fail(stderrOrErr, fallbackKind = SSH_ERROR.UNKNOWN) {
+ if (stderrOrErr?.kind === 'superseded') {
+ return stderrOrErr
+ }
+
if (stderrOrErr && stderrOrErr.kind === SSH_ERROR.TIMEOUT) {
const err: any = new Error(sshErrorMessage(SSH_ERROR.TIMEOUT, this))
err.kind = SSH_ERROR.TIMEOUT
@@ -534,13 +574,13 @@ class SshConnection {
// Open the connection. Mux: start the persistent ControlMaster (idempotent —
// a live master is a no-op). No-mux: there is no master; validate auth +
// reachability with a one-shot `ssh true` so failures classify identically.
- async open() {
- if (await this.isAlive()) {
+ async open({ signal }: any = {}) {
+ if (await this.isAlive({ signal })) {
// -O check passing is not proof the master works: a ControlPersist master
// can survive a failed teardown with wedged channels (observed on macOS
// after a mode switch — check succeeds, every exec times out). Verify with
// a real exec before trusting it; on failure, evict and dial fresh.
- if (!this._mux || (await this._verifyMuxChannel())) {
+ if (!this._mux || (await this._verifyMuxChannel({ signal }))) {
this._opened = true
return
@@ -557,7 +597,8 @@ class SshConnection {
try {
result = await runSsh(buildExecArgs(this, 'exit 0', this._connectTimeoutMs), {
timeoutMs: this._connectTimeoutMs,
- spawnFn: this._spawnFn
+ spawnFn: this._spawnFn,
+ signal
})
} catch (error) {
throw this._fail(error, SSH_ERROR.UNREACHABLE)
@@ -606,7 +647,7 @@ class SshConnection {
let result
try {
- result = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn })
+ result = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn, signal })
} catch (error) {
throw this._fail(error, SSH_ERROR.UNREACHABLE)
}
@@ -621,7 +662,7 @@ class SshConnection {
// Liveness. Mux: `-O check` against the master socket. No-mux: a cheap
// one-shot exec — "alive" means "we can still authenticate and run".
- async isAlive() {
+ async isAlive({ signal }: any = {}) {
if ([...this._tunnels.values()].some(tunnel => tunnel.alive === false)) {
return false
}
@@ -631,25 +672,34 @@ class SshConnection {
: buildExecArgs(this, 'exit 0', this._connectTimeoutMs)
try {
- const result: any = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn })
+ const result: any = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn, signal })
return result.code === 0
- } catch {
+ } catch (error: any) {
+ if (error?.kind === 'superseded') {
+ throw error
+ }
+
return false
}
}
// A real exec through the master (`exit 0` works under POSIX shells and
// cmd.exe); a wedged mux hangs to the timeout.
- async _verifyMuxChannel() {
+ async _verifyMuxChannel({ signal }: any = {}) {
try {
const result: any = await runSsh(buildExecArgs(this, 'exit 0', this._connectTimeoutMs), {
timeoutMs: this._connectTimeoutMs,
- spawnFn: this._spawnFn
+ spawnFn: this._spawnFn,
+ signal
})
return result.code === 0
- } catch {
+ } catch (error: any) {
+ if (error?.kind === 'superseded') {
+ throw error
+ }
+
return false
}
}
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index 3fd2d74c19b..aacc0b0f73d 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -20,6 +20,7 @@ import {
disposeSecondariesForConnection,
ensureGatewayForProfile,
isActivePrimary,
+ gatewayActivationEpoch,
pruneSecondaryGateways,
reconnectSecondaryGateways,
reportPrimaryGatewayState,
@@ -416,9 +417,25 @@ export function useGatewayBoot({
// (connectionId, profile) keep-set so two sources exposing the same
// profile name (every source has a 'default') can't collide.
configureGatewayRegistry({
+ onActiveConnectionChanged: publish,
onEvent: event => {
recordSessionEventScope(event)
callbacksRef.current.handleGatewayEvent(event)
+ },
+ onActiveConnectionInvalidated: (fallbackProfile, invalidationEpoch) => {
+ $activeGatewayProfile.set(fallbackProfile)
+ void desktop
+ .getConnection(fallbackProfile)
+ .then(connection => {
+ if (!cancelled && gatewayActivationEpoch() === invalidationEpoch) {
+ publish(connection)
+ }
+ })
+ .catch(() => {
+ if (!cancelled && gatewayActivationEpoch() === invalidationEpoch) {
+ publish(null)
+ }
+ })
}
})
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 671e5706b3b..032a58bd4d4 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -137,9 +137,13 @@ async function requestPluginProfile<T>(
const roster = await getAgentRoster()
const profile = route.trim() || 'default'
- const matches = roster.agents.filter(agent => agent.profile === profile)
+ const soleLocalSource = roster.sources.length === 1 && roster.sources[0]?.kind === 'local'
- if (matches.length === 1 && matches[0].connectionId === 'local') {
+ // The string overload is compatibility-only. A sole local registry is the
+ // one topology where a profile name is intrinsically unambiguous, even when
+ // its live enumeration transiently failed. Any additional source requires a
+ // descriptor because an undialed/unreachable source may expose the same name.
+ if (soleLocalSource) {
return requestGatewayForProfile<T>(profile, method, params)
}
diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.ts
new file mode 100644
index 00000000000..ffcace23f20
--- /dev/null
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@ -0,0 +1,240 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { ProfileInfo } from '@/types/hermes'
+
+vi.mock('@/app/chat/session-view', async () => {
+ const { atom } = await import('nanostores')
+
+ return { PRIMARY_SESSION_VIEW: { $awaitingResponse: atom(false), $busy: atom(false) } }
+})
+vi.mock('@/app/open-session', () => ({ openSession: vi.fn() }))
+vi.mock('@/components/pane-shell/tree/store', async () => {
+ const { atom } = await import('nanostores')
+
+ return { $narrowViewport: atom(false) }
+})
+vi.mock('@/contrib/events', () => ({ onGatewayEvent: vi.fn() }))
+vi.mock('@/hermes', () => ({ deleteProfile: vi.fn(), getLogs: vi.fn(), getStatus: vi.fn() }))
+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))
+vi.mock('@/store/system-actions', () => ({ runGatewayRestart: vi.fn() }))
+vi.mock('@/store/session', async () => {
+ const { atom } = await import('nanostores')
+
+ return {
+ $activeSessionId: atom(null),
+ $currentCwd: atom(''),
+ $currentModel: atom(''),
+ $gatewayState: atom('open'),
+ $selectedStoredSessionId: atom(null)
+ }
+})
+vi.mock('@/store/session-states', async () => {
+ const { atom } = await import('nanostores')
+
+ return {
+ $focusedRuntimeId: atom(null),
+ $focusedSessionState: atom(null),
+ $focusedStoredSessionId: atom(null),
+ $sessionStates: atom({})
+ }
+})
+vi.mock('@/store/profile', async () => {
+ const { atom } = await import('nanostores')
+
+ const profiles = atom([
+ {
+ has_env: false,
+ is_default: false,
+ model: null,
+ name: 'cached-only',
+ path: '/profiles/cached-only',
+ provider: null,
+ skill_count: 0
+ }
+ ])
+
+ return {
+ $activeGatewayProfile: atom('remote-worker'),
+ $profiles: profiles,
+ ensureGatewayAgent: vi.fn(),
+ ensureGatewayProfile: vi.fn(),
+ newSessionInProfile: vi.fn(),
+ normalizeProfileKey: (value: null | string | undefined) => (value ?? '').trim() || 'default',
+ refreshProfiles: vi.fn(async () => profiles.get()),
+ selectProfile: vi.fn(),
+ setActiveProfile: vi.fn(),
+ setShowAllProfiles: vi.fn()
+ }
+})
+vi.mock('@/store/gateway', async () => {
+ const { atom } = await import('nanostores')
+
+ return {
+ $gateway: atom(null),
+ ensureGatewayForAgent: vi.fn(),
+ openGatewayForAgent: vi.fn(),
+ openGatewayForProfile: vi.fn(),
+ requestGatewayForAgent: vi.fn(
+ async (connectionId: string, profile: string, method: string, params: Record<string, unknown>) => ({
+ connectionId,
+ method,
+ params,
+ profile
+ })
+ ),
+ requestGatewayForProfile: vi.fn(async (profile: string, method: string, params: Record<string, unknown>) => ({
+ method,
+ params,
+ profile
+ }))
+ }
+})
+
+const { host } = await import('./index')
+const { requestGatewayForAgent, requestGatewayForProfile } = await import('@/store/gateway')
+const { $profiles, refreshProfiles } = await import('@/store/profile')
+
+const profile = (name: string): ProfileInfo => ({
+ has_env: false,
+ is_default: name === 'default',
+ model: null,
+ name,
+ path: `/profiles/${name}`,
+ provider: null,
+ skill_count: 0
+})
+
+afterEach(() => {
+ vi.clearAllMocks()
+ $profiles.set([profile('cached-only')])
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+describe('connection-aware plugin host APIs', () => {
+ it('refreshes the profile inventory before asking Electron for routes', async () => {
+ const getProfileRoutes = vi.fn(async () => [
+ { connectionId: 'connection-local', mode: 'local', profile: 'desktop-primary', targetProfile: 'desktop-primary' },
+ {
+ connectionId: 'connection-remote',
+ mode: 'remote',
+ profile: 'remote-worker',
+ targetProfile: 'backend-worker'
+ }
+ ])
+
+ vi.mocked(refreshProfiles).mockResolvedValueOnce([profile('desktop-primary'), profile('remote-worker')])
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { getProfileRoutes }
+
+ const routes = await host.profileRoutes()
+
+ expect(routes).toEqual([
+ { connectionId: 'connection-local', mode: 'local', profile: 'desktop-primary', targetProfile: 'desktop-primary' },
+ {
+ connectionId: 'connection-remote',
+ mode: 'remote',
+ profile: 'remote-worker',
+ targetProfile: 'backend-worker'
+ }
+ ])
+ expect(refreshProfiles).toHaveBeenCalledOnce()
+ expect(getProfileRoutes).toHaveBeenCalledWith(['desktop-primary', 'remote-worker'])
+ })
+
+ it('falls back to the cached profile inventory when refresh fails', async () => {
+ const getProfileRoutes = vi.fn(async () => [
+ { connectionId: 'connection-cached', mode: 'remote', profile: 'cached-worker', targetProfile: 'cached-worker' }
+ ])
+
+ $profiles.set([profile('cached-worker')])
+ vi.mocked(refreshProfiles).mockRejectedValueOnce(new Error('profile backend unavailable'))
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { getProfileRoutes }
+
+ await expect(host.profileRoutes()).resolves.toEqual([
+ { connectionId: 'connection-cached', mode: 'remote', profile: 'cached-worker', targetProfile: 'cached-worker' }
+ ])
+ expect(getProfileRoutes).toHaveBeenCalledWith(['cached-worker'])
+ })
+
+ it('forwards a targeted request without changing foreground state', async () => {
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote' as const,
+ profile: 'remote-worker',
+ targetProfile: 'backend-worker'
+ }
+
+ const result = await host.requestProfile(route, 'profiles.list', { include_sessions: true })
+
+ expect(result).toEqual({
+ connectionId: 'source-a',
+ method: 'profiles.list',
+ params: { include_sessions: true },
+ profile: 'remote-worker'
+ })
+ expect(requestGatewayForAgent).toHaveBeenCalledWith('source-a', 'remote-worker', 'profiles.list', {
+ include_sessions: true
+ })
+ expect(requestGatewayForProfile).not.toHaveBeenCalled()
+ })
+
+ it('keeps the profile-only request overload as a legacy fallback', async () => {
+ const result = await host.requestProfile('legacy-worker', 'profiles.list', { include_sessions: true })
+
+ expect(result).toEqual({
+ method: 'profiles.list',
+ params: { include_sessions: true },
+ profile: 'legacy-worker'
+ })
+ expect(requestGatewayForProfile).toHaveBeenCalledWith('legacy-worker', 'profiles.list', {
+ include_sessions: true
+ })
+ })
+
+ it('rejects a profile-only request when the current registry makes it ambiguous', async () => {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getAgentRoster: vi.fn(async () => ({
+ agents: [
+ { connectionId: 'source-a', profile: 'research' },
+ { connectionId: 'source-b', profile: 'research' }
+ ],
+ sources: [
+ { connectionId: 'source-a', kind: 'remote', label: 'A' },
+ { connectionId: 'source-b', kind: 'remote', label: 'B' }
+ ]
+ }))
+ }
+
+ await expect(host.requestProfile('research', 'profiles.list')).rejects.toThrow(/route descriptor/i)
+ expect(requestGatewayForProfile).not.toHaveBeenCalled()
+ })
+
+ it('keeps profile-only compatibility when sole-local enumeration fails', async () => {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getAgentRoster: vi.fn(async () => ({
+ agents: [],
+ sources: [{ connectionId: 'local', kind: 'local', label: 'This device' }]
+ }))
+ }
+
+ await expect(host.requestProfile('research', 'profiles.list')).resolves.toEqual({
+ method: 'profiles.list',
+ params: {},
+ profile: 'research'
+ })
+ })
+
+ it('rejects profile-only routing when another source is undialed', async () => {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getAgentRoster: vi.fn(async () => ({
+ agents: [{ connectionId: 'local', profile: 'research' }],
+ sources: [
+ { connectionId: 'local', kind: 'local', label: 'This device' },
+ { connectionId: 'homelab', kind: 'ssh', label: 'Homelab' }
+ ]
+ }))
+ }
+
+ await expect(host.requestProfile('research', 'profiles.list')).rejects.toThrow(/route descriptor/i)
+ expect(requestGatewayForProfile).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.ts
index 61f0db42cd8..2a59d304067 100644
--- a/apps/desktop/src/store/gateway-profile-request.test.ts
+++ b/apps/desktop/src/store/gateway-profile-request.test.ts
@@ -48,7 +48,11 @@ const {
$gateway,
closeSecondaryGateways,
configureGatewayRegistry,
+ ensureGatewayForAgent,
ensureGatewayForProfile,
+ gatewayActivationEpoch,
+ disposeSecondariesForConnection,
+ openGatewayForAgent,
pruneSecondaryGateways,
requestGatewayForAgent,
requestGatewayForProfile,
@@ -98,6 +102,7 @@ describe('requestGatewayForProfile', () => {
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(secondaryGateways[0].close).toHaveBeenCalledOnce()
expect($gateway.get()).toBe(primary)
})
@@ -150,6 +155,7 @@ describe('requestGatewayForProfile', () => {
expect(secondResult).toEqual({ method: 'profiles.list', params: {} })
expect(secondaryGateways[0].connect).toHaveBeenCalledOnce()
expect(secondaryGateways[0].request).toHaveBeenCalledTimes(2)
+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
expect($gateway.get()).toBe(primary)
})
@@ -175,7 +181,7 @@ describe('requestGatewayForProfile', () => {
releaseConnect()
await expect(request).resolves.toEqual({ method: 'profiles.list', params: {} })
- expect(secondaryGateways[0].close).not.toHaveBeenCalled()
+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
pruneSecondaryGateways(new Set())
expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
@@ -221,6 +227,8 @@ describe('requestGatewayForAgent', () => {
expect(getGatewayWsUrlFor).toHaveBeenCalledWith({ connectionId: 'source-b', profile: 'research' })
expect(getConnection).not.toHaveBeenCalled()
expect(secondaryGateways).toHaveLength(2)
+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
+ expect(secondaryGateways[1].close).toHaveBeenCalledOnce()
expect($gateway.get()).toBe(primary)
})
@@ -245,4 +253,104 @@ describe('requestGatewayForAgent', () => {
expect(getConnectionFor).not.toHaveBeenCalled()
expect($gateway.get()).toBe(primary)
})
+
+ it('evicts registry sockets when their source is edited or removed', async () => {
+ const primary = makePrimary()
+ const getConnectionFor = vi.fn(async ({ connectionId, profile }) => ({ connectionId, port: 5151, profile }))
+ const onActiveConnectionInvalidated = vi.fn()
+
+ setPrimaryGateway(primary as never, 'default')
+ configureGatewayRegistry({ onActiveConnectionInvalidated, onEvent: vi.fn() })
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: vi.fn(),
+ getConnectionFor,
+ getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
+ ok: true as const,
+ wsUrl: `ws://${connectionId}/${profile}`
+ })),
+ touchBackend: vi.fn(async () => undefined)
+ }
+
+ await openGatewayForAgent('source-a', 'research')
+ await requestGatewayForAgent('source-a', 'research', 'session.list')
+ disposeSecondariesForConnection('source-a')
+
+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
+ expect(onActiveConnectionInvalidated).not.toHaveBeenCalled()
+
+ await requestGatewayForAgent('source-a', 'research', 'session.list')
+ expect(secondaryGateways).toHaveLength(2)
+ expect(getConnectionFor).toHaveBeenCalledTimes(2)
+ })
+
+ it('invalidates an active pinned source with its window profile and a route epoch', async () => {
+ const primary = makePrimary()
+ const onActiveConnectionChanged = vi.fn()
+ const onActiveConnectionInvalidated = vi.fn()
+
+ setPrimaryGateway(primary as never, 'pinned')
+ configureGatewayRegistry({ onActiveConnectionChanged, onActiveConnectionInvalidated, onEvent: vi.fn() })
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: vi.fn(),
+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => ({ connectionId, port: 5151, profile })),
+ getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
+ ok: true as const,
+ wsUrl: `ws://${connectionId}/${profile}`
+ })),
+ touchBackend: vi.fn(async () => undefined)
+ }
+
+ await ensureGatewayForAgent('source-a', 'pinned')
+ disposeSecondariesForConnection('source-a')
+
+ const invalidationEpoch = gatewayActivationEpoch()
+ expect(onActiveConnectionInvalidated).toHaveBeenCalledWith('pinned', invalidationEpoch)
+ expect($gateway.get()).toBe(primary)
+
+ // Same profile, different source advances the guard as soon as activation
+ // starts, before its deferred socket connect can finish.
+ let releaseConnect: () => void = () => undefined
+ connectGate = new Promise<void>(resolve => {
+ releaseConnect = resolve
+ })
+ const sourceBActivation = ensureGatewayForAgent('source-b', 'pinned')
+ await vi.waitFor(() => expect(secondaryGateways[1]?.connect).toHaveBeenCalledOnce())
+ expect(gatewayActivationEpoch()).toBeGreaterThan(invalidationEpoch)
+ releaseConnect()
+ await sourceBActivation
+ expect(onActiveConnectionChanged).toHaveBeenLastCalledWith(expect.objectContaining({ connectionId: 'source-b' }))
+ })
+
+ it('does not activate or publish a source invalidated while its dial is pending', async () => {
+ const primary = makePrimary()
+ const onActiveConnectionChanged = vi.fn()
+
+ setPrimaryGateway(primary as never, 'default')
+ configureGatewayRegistry({ onActiveConnectionChanged, onEvent: vi.fn() })
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: vi.fn(async profile => ({ port: 4242, profile })),
+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => ({ connectionId, port: 5151, profile })),
+ getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
+ ok: true as const,
+ wsUrl: `ws://${connectionId}/${profile}`
+ })),
+ touchBackend: vi.fn(async () => undefined)
+ }
+ await ensureGatewayForProfile('default')
+
+ let releaseConnect: () => void = () => undefined
+ connectGate = new Promise<void>(resolve => {
+ releaseConnect = resolve
+ })
+ const pendingActivation = ensureGatewayForAgent('source-b', 'default')
+ await vi.waitFor(() => expect(secondaryGateways[0]?.connect).toHaveBeenCalledOnce())
+
+ disposeSecondariesForConnection('source-b')
+ releaseConnect()
+ await pendingActivation
+
+ expect(secondaryGateways[0].close).toHaveBeenCalled()
+ expect(onActiveConnectionChanged).not.toHaveBeenCalled()
+ expect($gateway.get()).toBe(primary)
+ })
})
diff --git a/apps/desktop/src/store/gateway-shared-remote.test.ts b/apps/desktop/src/store/gateway-shared-remote.test.ts
index 35df2160d19..690b9667436 100644
--- a/apps/desktop/src/store/gateway-shared-remote.test.ts
+++ b/apps/desktop/src/store/gateway-shared-remote.test.ts
@@ -132,11 +132,12 @@ describe('ensureGatewayForProfile under a shared global remote', () => {
await ensureGatewayForProfile('worker')
- expect(gatewayMocks.setConnection).not.toHaveBeenCalled()
+ expect(gatewayMocks.setConnection).toHaveBeenCalledOnce()
+ expect(gatewayMocks.setConnection).toHaveBeenLastCalledWith(connection)
await ensureActiveGatewayOpen()
- expect(gatewayMocks.setConnection).toHaveBeenCalledOnce()
- expect(gatewayMocks.setConnection).toHaveBeenCalledWith(connection)
+ expect(gatewayMocks.setConnection).toHaveBeenCalledTimes(2)
+ expect(gatewayMocks.setConnection).toHaveBeenLastCalledWith(connection)
})
})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 6d4ad28a21a..f54467c0b05 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -2,6 +2,7 @@ import { backendScopeKey, type ConnectionState, type GatewayEvent, resolveGatewa
import { atom } from 'nanostores'
import { HermesGateway, setApiRequestConnection } from '@/hermes'
+import type { HermesConnection } from '@/global'
import { reconnectBackoffDelayMs } from '@/lib/reconnect-backoff'
import { markNativeNotifyBaseline } from '@/store/notify-baseline'
import { setConnection, setGatewayState } from '@/store/session'
@@ -24,6 +25,8 @@ const isOpen = (gateway: HermesGateway | null): boolean => gateway?.connectionSt
interface RegistryConfig {
onEvent: (event: GatewayEvent) => void
+ onActiveConnectionInvalidated?: (fallbackProfile: string, activationEpoch: number) => void
+ onActiveConnectionChanged?: (connection: HermesConnection) => void
}
// ── Secondary (pool) backends ──────────────────────────────────────────────
@@ -33,6 +36,7 @@ interface Secondary {
profile: string
/** Registry connection serving this socket; null = the local/legacy path. */
connectionId: null | string
+ connection: HermesConnection | null
gateway: HermesGateway
activeRequests: number
connectPromise: Promise<void> | null
@@ -41,6 +45,8 @@ interface Secondary {
reconnectTimer: ReturnType<typeof setTimeout> | null
reconnectAttempt: number
reconnecting: boolean
+ /** True when a foreground/prewarmed consumer owns this entry beyond one RPC. */
+ retained: boolean
// While true the entry auto-reconnects on drop; pruning flips it off so a
// deliberate close doesn't trigger the backoff loop.
wantOpen: boolean
@@ -62,6 +68,7 @@ interface GatewayRegistryState {
primaryGateway: HermesGateway | null
primaryProfile: string
activeKey: string
+ activationEpoch: number
secondaries: Map<string, Secondary>
$gateway: ReturnType<typeof atom<HermesGateway | null>>
}
@@ -74,6 +81,7 @@ function createRegistryState(): GatewayRegistryState {
primaryGateway: null,
primaryProfile: 'default',
activeKey: 'default',
+ activationEpoch: 0,
secondaries: new Map<string, Secondary>(),
// The active gateway instance, exposed for inline message-stream
// components (inline ClarifyTool, model overlays) that call gateway
@@ -131,6 +139,11 @@ export function isActivePrimary(): boolean {
return g.activeKey === g.primaryProfile
}
+/** Changes on every active route selection, including same-profile source swaps. */
+export function gatewayActivationEpoch(): number {
+ return Number.isFinite(g.activationEpoch) ? g.activationEpoch : 0
+}
+
export function activeGateway(): HermesGateway | null {
if (g.activeKey === g.primaryProfile) {
return g.primaryGateway
@@ -181,6 +194,21 @@ export function reportPrimaryGatewayState(state: ConnectionState): void {
}
function setActive(profile: string): void {
+ const activationEpoch = beginGatewayActivation()
+ applyActive(profile, activationEpoch)
+}
+
+function beginGatewayActivation(): number {
+ g.activationEpoch = gatewayActivationEpoch() + 1
+
+ return g.activationEpoch
+}
+
+function applyActive(profile: string, activationEpoch: number): boolean {
+ if (gatewayActivationEpoch() !== activationEpoch) {
+ return false
+ }
+
g.activeKey = normKey(profile)
const gateway = activeGateway()
g.$gateway.set(gateway)
@@ -190,6 +218,16 @@ function setActive(profile: string): void {
// through the same source of truth every activation path maintains here —
// registry-agent activations included, not just profile switches.
setApiRequestConnection(activeGatewayConnectionId())
+
+ return true
+}
+
+function publishActiveConnection(connection: HermesConnection): void {
+ if (g.config?.onActiveConnectionChanged) {
+ g.config.onActiveConnectionChanged(connection)
+ } else {
+ setConnection(connection)
+ }
}
function clearTimer(entry: Secondary): void {
@@ -220,6 +258,8 @@ async function openSecondary(entry: Secondary): Promise<void> {
? await desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile })
: await desktop.getConnection(entry.profile)
+ entry.connection = conn
+
const wsDeps =
entry.connectionId && desktop.getGatewayWsUrlFor
? {
@@ -241,7 +281,7 @@ async function openSecondary(entry: Secondary): Promise<void> {
}
if (g.activeKey === entry.scope) {
- setConnection(conn)
+ publishActiveConnection(conn)
}
void desktop.touchBackend?.(entry.scope).catch(() => undefined)
@@ -321,6 +361,7 @@ function createSecondary(profile: string, connectionId: null | string = null): S
scope,
profile,
connectionId,
+ connection: null,
gateway,
activeRequests: 0,
connectPromise: null,
@@ -329,6 +370,7 @@ function createSecondary(profile: string, connectionId: null | string = null): S
reconnectTimer: null,
reconnectAttempt: 0,
reconnecting: false,
+ retained: false,
wantOpen: true
}
@@ -398,11 +440,19 @@ async function gatewayForProfile(
const entry = g.secondaries.get(key) ?? createSecondary(key)
- // Existing dev-HMR entries predate the request lease field.
+ // Existing dev-HMR entries predate the request lease/ownership fields.
if (!Number.isFinite(entry.activeRequests)) {
entry.activeRequests = 0
}
+ if (typeof entry.retained !== 'boolean') {
+ entry.retained = true
+ }
+
+ if (!leaseRequest) {
+ entry.retained = true
+ }
+
entry.wantOpen = true
if (leaseRequest) {
@@ -415,6 +465,14 @@ async function gatewayForProfile(
if (!released && leaseRequest) {
released = true
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
+
+ if (entry.activeRequests === 0 && !entry.retained && g.activeKey !== entry.scope) {
+ disposeSecondary(entry)
+
+ if (g.secondaries.get(entry.scope) === entry) {
+ g.secondaries.delete(entry.scope)
+ }
+ }
}
}
@@ -480,11 +538,15 @@ export async function requestGatewayForAgent<T>(
const entry = g.secondaries.get(scope) ?? createSecondary(key, connectionId)
- // Existing dev-HMR entries predate request leases.
+ // Existing dev-HMR entries predate request leases/ownership.
if (!Number.isFinite(entry.activeRequests)) {
entry.activeRequests = 0
}
+ if (typeof entry.retained !== 'boolean') {
+ entry.retained = true
+ }
+
entry.wantOpen = true
entry.activeRequests += 1
@@ -496,6 +558,14 @@ export async function requestGatewayForAgent<T>(
return await entry.gateway.request<T>(method, params)
} finally {
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
+
+ if (entry.activeRequests === 0 && !entry.retained && g.activeKey !== entry.scope) {
+ disposeSecondary(entry)
+
+ if (g.secondaries.get(entry.scope) === entry) {
+ g.secondaries.delete(entry.scope)
+ }
+ }
}
}
@@ -528,6 +598,7 @@ export async function openGatewayForAgent(connectionId: null | string, profile:
}
const entry = g.secondaries.get(scope) ?? createSecondary(profile, connectionId)
+ entry.retained = true
entry.wantOpen = true
if (!isOpen(entry.gateway)) {
@@ -546,12 +617,15 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile
throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')
}
+ const activationEpoch = beginGatewayActivation()
+
let entry = g.secondaries.get(scope)
if (!entry) {
entry = createSecondary(profile, connectionId)
}
+ entry.retained = true
entry.wantOpen = true
if (!isOpen(entry.gateway)) {
@@ -565,16 +639,26 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile
}
}
- setActive(scope)
+ // A source edit/remove may dispose this entry while its dial is still in
+ // flight. Only the still-registered, still-owned activation may publish.
+ if (
+ entry.wantOpen &&
+ g.secondaries.get(scope) === entry &&
+ applyActive(scope, activationEpoch) &&
+ entry.connection
+ ) {
+ publishActiveConnection(entry.connection)
+ }
}
// Make `profile` the active gateway, lazily opening its socket if needed. The
// primary is a no-op fast path. Background sockets are never closed here.
export async function ensureGatewayForProfile(profile: string): Promise<void> {
const key = normKey(profile)
+ const activationEpoch = beginGatewayActivation()
if (key === g.primaryProfile) {
- setActive(key)
+ applyActive(key, activationEpoch)
return
}
@@ -585,7 +669,7 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {
// descriptor — $activeGatewayProfile still moves to `key`, so request
// scoping and profile-aware surfaces behave identically.
if (await sharedPrimaryRoute(key)) {
- setActive(g.primaryProfile)
+ applyActive(g.primaryProfile, activationEpoch)
return
}
@@ -596,6 +680,7 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {
entry = createSecondary(key)
}
+ entry.retained = true
entry.wantOpen = true
if (!isOpen(entry.gateway)) {
@@ -609,7 +694,14 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {
}
}
- setActive(key)
+ if (
+ entry.wantOpen &&
+ g.secondaries.get(key) === entry &&
+ applyActive(key, activationEpoch) &&
+ entry.connection
+ ) {
+ publishActiveConnection(entry.connection)
+ }
}
// Reconnect the active gateway after a transient request failure. Primary
@@ -722,6 +814,7 @@ export function closeSecondaryGateways(): void {
// the active scope re-activates so the foreground keeps painting.
export function disposeSecondariesForConnection(connectionId: string, opts: { redial?: boolean } = {}): void {
const id = String(connectionId || '').trim()
+ let activeInvalidated = false
if (!id) {
return
@@ -733,6 +826,7 @@ export function disposeSecondariesForConnection(connectionId: string, opts: { re
}
const wasActive = key === g.activeKey
+ activeInvalidated ||= wasActive
disposeSecondary(entry)
g.secondaries.delete(key)
@@ -745,6 +839,11 @@ export function disposeSecondariesForConnection(connectionId: string, opts: { re
void reopen.catch(() => undefined)
}
}
+
+ if (activeInvalidated && !opts.redial) {
+ setActive(g.primaryProfile)
+ g.config?.onActiveConnectionInvalidated?.(g.primaryProfile, gatewayActivationEpoch())
+ }
}
// Self-accept so editing this module (or a fan-out that lands here) is an
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 1b0c3729a05..06fd4baa1b3 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -421,13 +421,17 @@ host.request<T>(method, params?) // active-gateway JSON-RPC — the re
cron, kanban, …). `host.requestProfile` accepts a descriptor from
`host.profileRoutes()` and routes that RPC through its exact registry source and
profile without changing the active chat or gateway. The profile-only overload is
-retained for unambiguous legacy v1/local callers; registry-aware plugins should pass
+retained only for the sole-local/legacy topology; registry-aware plugins should pass
the descriptor so two sources exposing the same profile name cannot collide.
-`host.profileRoutes()` inventories every reachable source in the current connection
-registry. `connectionId` is the registry routing identity; pair it with `profile`
-for keys and persistence. Endpoint, token, SSH host/key, and other raw connection
-fields never cross the plugin IPC boundary. `profile` is the source-local route used
+`host.profileRoutes()` inventories every registered source in the current connection
+registry. Connect-on-demand SSH sources expose a credential-free `default` seed
+route without opening a tunnel, so a plugin can be the first caller that dials them;
+an SSH `remoteProfile` remains the route's backend `targetProfile`. `connectionId`
+is the registry routing identity;
+pair it with `profile` for keys and persistence. Endpoint, token, SSH host/key, and
+other raw connection fields never cross the plugin IPC boundary. `profile` is the
+source-local route used
for requests; `targetProfile` is the backend Hermes profile served by that route.
They differ when a route explicitly maps to another backend profile (for example an
SSH `remoteProfile` override or a legacy per-profile URL alias). This distinction