Skip to content

The agent that grows with you

fix(desktop): synchronize applied gateway registry

Alessandro Levantini96e5898542ec
diff --git a/apps/desktop/electron/connection-config-apply.test.ts b/apps/desktop/electron/connection-config-apply.test.ts
new file mode 100644
index 00000000000..9f1a204d118
--- /dev/null
+++ b/apps/desktop/electron/connection-config-apply.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { applyConnectionConfigAtomically } from './connection-config-apply'
+
+describe('applyConnectionConfigAtomically', () => {
+ it('commits legacy and registry state before activation', async () => {
+ const events: string[] = []
+
+ await applyConnectionConfigAtomically({
+ previousConfig: 'old-config',
+ previousRegistry: 'old-registry',
+ nextConfig: 'remote-config',
+ nextRegistry: 'remote-registry',
+ writeConfig: value => events.push(`config:${value}`),
+ writeRegistry: value => events.push(`registry:${value}`),
+ apply: async () => {
+ events.push('activate')
+ }
+ })
+
+ expect(events).toEqual(['config:remote-config', 'registry:remote-registry', 'activate'])
+ })
+
+ it('rolls both stores back when activation fails', async () => {
+ const writeConfig = vi.fn()
+ const writeRegistry = vi.fn()
+
+ await expect(
+ applyConnectionConfigAtomically({
+ previousConfig: 'local-config',
+ previousRegistry: 'local-registry',
+ nextConfig: 'remote-config',
+ nextRegistry: 'remote-registry',
+ writeConfig,
+ writeRegistry,
+ apply: async () => {
+ throw new Error('activation failed')
+ }
+ })
+ ).rejects.toThrow('activation failed')
+
+ expect(writeConfig.mock.calls).toEqual([['remote-config'], ['local-config']])
+ expect(writeRegistry.mock.calls).toEqual([['remote-registry'], ['local-registry']])
+ })
+
+ it('rolls legacy state back when the registry write fails', async () => {
+ const writes: string[] = []
+ let registryWrites = 0
+
+ await expect(
+ applyConnectionConfigAtomically({
+ previousConfig: 'local-config',
+ previousRegistry: 'local-registry',
+ nextConfig: 'remote-config',
+ nextRegistry: 'remote-registry',
+ writeConfig: value => writes.push(`config:${value}`),
+ writeRegistry: value => {
+ registryWrites += 1
+
+ if (registryWrites === 1) {
+ throw new Error('disk full')
+ }
+
+ writes.push(`registry:${value}`)
+ },
+ apply: vi.fn()
+ })
+ ).rejects.toThrow('disk full')
+
+ expect(writes).toEqual(['config:remote-config', 'config:local-config', 'registry:local-registry'])
+ })
+})
diff --git a/apps/desktop/electron/connection-config-apply.ts b/apps/desktop/electron/connection-config-apply.ts
new file mode 100644
index 00000000000..9e430769492
--- /dev/null
+++ b/apps/desktop/electron/connection-config-apply.ts
@@ -0,0 +1,41 @@
+interface ApplyConnectionConfigAtomicallyOptions<TConfig, TRegistry> {
+ apply: () => Promise<void>
+ nextConfig: TConfig
+ nextRegistry: TRegistry
+ previousConfig: TConfig
+ previousRegistry: TRegistry
+ writeConfig: (config: TConfig) => void
+ writeRegistry: (registry: TRegistry) => void
+}
+
+/**
+ * Commit the legacy config and v2 registry as one recoverable Apply boundary.
+ * File replacement itself is atomic per file; this wrapper restores both
+ * previous snapshots when the second write or synchronous re-home fails.
+ */
+export async function applyConnectionConfigAtomically<TConfig, TRegistry>({
+ apply,
+ nextConfig,
+ nextRegistry,
+ previousConfig,
+ previousRegistry,
+ writeConfig,
+ writeRegistry
+}: ApplyConnectionConfigAtomicallyOptions<TConfig, TRegistry>): Promise<void> {
+ try {
+ writeConfig(nextConfig)
+ writeRegistry(nextRegistry)
+ await apply()
+ } catch (error) {
+ try {
+ writeConfig(previousConfig)
+ writeRegistry(previousRegistry)
+ } catch {
+ // Preserve the original activation/write failure. Both storage writers
+ // are atomic replacements, so a rollback failure cannot be repaired by
+ // retrying one side blindly here.
+ }
+
+ throw error
+ }
+}
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index ce90a9a01cb..a2eb602d5e9 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -25,6 +25,7 @@ import {
normalizeConnectionInput,
normalizeRegistry,
parseRemoteProfileListing,
+ reconcileAppliedGlobalConnection,
REGISTRY_VERSION,
rememberSshEnumeration,
removeConnection,
@@ -1218,6 +1219,90 @@ test('upsertConnection replaces by id and appends new ids', () => {
assert.equal(registry.connections.find(c => c.id === a.id)?.url, 'http://a:2')
})
+test('Apply remote inserts into an existing local-only registry and becomes primary/current', () => {
+ const registry = reconcileAppliedGlobalConnection(emptyRegistry(), {
+ mode: 'remote',
+ remote: { url: 'https://gateway.example.com/', authMode: 'oauth' }
+ })
+
+ const remote = registry.connections.find(connection => connection.kind === 'remote')
+
+ assert.ok(remote)
+ assert.equal(registry.primary, remote.id)
+ assert.equal(registry.lastUsed, remote.id)
+ assert.equal(
+ resolvedConnectionId(registry, {
+ baseUrl: 'https://gateway.example.com',
+ mode: 'remote',
+ remoteKind: 'url'
+ }),
+ remote.id
+ )
+})
+
+test('Apply remote preserves an existing URL identity and label without duplicates', () => {
+ let registry = emptyRegistry()
+
+ registry = upsertConnection(registry, {
+ id: 'hermes-alex',
+ kind: 'remote',
+ label: 'Existing gateway',
+ url: 'https://gateway.example.com',
+ authMode: 'token',
+ token: { old: true }
+ })
+
+ const applied = reconcileAppliedGlobalConnection(registry, {
+ mode: 'remote',
+ remote: { url: 'https://GATEWAY.example.com/', authMode: 'oauth' }
+ })
+
+ const matches = applied.connections.filter(connection => connection.url === 'https://gateway.example.com')
+
+ assert.equal(matches.length, 1)
+ assert.equal(matches[0].id, 'hermes-alex')
+ assert.equal(matches[0].label, 'Existing gateway')
+ assert.equal(matches[0].authMode, 'oauth')
+ assert.equal(applied.primary, 'hermes-alex')
+ assert.equal(applied.lastUsed, 'hermes-alex')
+})
+
+test('Apply local moves primary/current to This device without deleting registered remotes', () => {
+ const remoteRegistry = reconcileAppliedGlobalConnection(emptyRegistry(), {
+ mode: 'remote',
+ remote: { url: 'https://one.example.com', authMode: 'oauth' }
+ })
+
+ const localRegistry = reconcileAppliedGlobalConnection(remoteRegistry, { mode: 'local', remote: {} })
+
+ assert.equal(localRegistry.primary, LOCAL_CONNECTION_ID)
+ assert.equal(localRegistry.lastUsed, LOCAL_CONNECTION_ID)
+ assert.equal(localRegistry.connections.filter(connection => connection.kind === 'remote').length, 1)
+ assert.equal(resolvedConnectionId(localRegistry, { mode: 'local' }), LOCAL_CONNECTION_ID)
+})
+
+test('Apply between two remotes keeps each real registration once and activates the latest', () => {
+ const first = reconcileAppliedGlobalConnection(emptyRegistry(), {
+ mode: 'remote',
+ remote: { url: 'https://one.example.com', authMode: 'oauth' }
+ })
+
+ const second = reconcileAppliedGlobalConnection(first, {
+ mode: 'remote',
+ remote: { url: 'https://two.example.com/', authMode: 'oauth' }
+ })
+
+ const remotes = second.connections.filter(connection => connection.kind === 'remote')
+
+ assert.deepEqual(
+ remotes.map(connection => connection.url).sort(),
+ ['https://one.example.com', 'https://two.example.com']
+ )
+ assert.equal(new Set(remotes.map(connection => connection.id)).size, 2)
+ assert.equal(second.primary, remotes.find(connection => connection.url === 'https://two.example.com')?.id)
+ assert.equal(second.lastUsed, second.primary)
+})
+
// --- connectionDialFieldsChanged (edit → recycle decision) ---
test('connectionDialFieldsChanged: label-only edits do not recycle', () => {
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index 2df7e733763..a05c54d3cc2 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -1207,6 +1207,79 @@ export function setLastUsedConnection(registry: ConnectionRegistry, id: string):
return { ...registry, lastUsed: id }
}
+/**
+ * Reconcile a successfully-coerced global v1 connection config into the v2
+ * registry. Settings still writes connection.json for compatibility, but an
+ * Apply must publish the same primary identity to connections.json in the
+ * same transaction or the live remote descriptor has no connectionId.
+ *
+ * Remote-shaped entries are matched by normalized URL across remote/cloud so
+ * changing provenance never duplicates a gateway. Existing identity and
+ * user-chosen label win; a new entry derives both from the host. Switching to
+ * local keeps registered remotes available while moving primary/last-used
+ * back to This device.
+ */
+export function reconcileAppliedGlobalConnection(
+ registry: ConnectionRegistry,
+ config: Record<string, any>
+): ConnectionRegistry {
+ const mode = config?.mode
+
+ if (!modeIsRemoteLike(mode)) {
+ if (mode === 'local') {
+ return { ...registry, primary: LOCAL_CONNECTION_ID, lastUsed: LOCAL_CONNECTION_ID }
+ }
+
+ // SSH registry identity is managed by its existing registry editor and
+ // migration path. Do not reinterpret or delete it here.
+ return registry
+ }
+
+ const block = config.remote && typeof config.remote === 'object' ? config.remote : {}
+ const url = normalizeRemoteBaseUrl(block.url)
+
+ const existing = registry.connections.find(connection => {
+ if (connection.kind !== 'remote' && connection.kind !== 'cloud') {
+ return false
+ }
+
+ try {
+ return normalizeRemoteBaseUrl(connection.url) === url
+ } catch {
+ return false
+ }
+ })
+
+ const kind: ConnectionKind = mode === 'cloud' ? 'cloud' : 'remote'
+
+ const label =
+ existing?.label ||
+ uniqueLabel(
+ hostLabelFromBaseUrl(url) || (kind === 'cloud' ? 'Hermes Cloud' : 'Remote gateway'),
+ registry.connections.map(connection => connection.label)
+ )
+
+ const entry = normalizeConnectionInput(
+ {
+ id: existing?.id,
+ kind,
+ label,
+ url,
+ authMode: block.authMode,
+ token: block.token,
+ headers: block.headers,
+ org: block.org
+ },
+ registry
+ )
+
+ return {
+ ...upsertConnection(registry, entry),
+ primary: entry.id,
+ lastUsed: entry.id
+ }
+}
+
/** Choose whether launch restores the explicit primary or the last-used source. */
export function setConnectionLaunchMode(registry: ConnectionRegistry, launchMode: string): ConnectionRegistry {
if (launchMode !== 'last-used' && launchMode !== 'primary') {
diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.ts
index 04e9c4a6213..dd04e586c06 100644
--- a/apps/desktop/electron/hardening.test.ts
+++ b/apps/desktop/electron/hardening.test.ts
@@ -938,6 +938,30 @@ test('registry JSON helpers retain native OAuth bearer authentication', () => {
assert.doesNotMatch(helpers, /fetchJsonViaOauthSession/)
})
+test('connection tests authenticate protected OAuth status probes', () => {
+ const source = readMain()
+ const helperStart = source.indexOf('async function fetchConnectionStatus(')
+ const helperEnd = source.indexOf('\nfunction ', helperStart + 1)
+ const helper = source.slice(helperStart, helperEnd === -1 ? undefined : helperEnd)
+
+ assert.notEqual(helperStart, -1)
+ assert.match(helper, /ensureNativeAccessToken\(baseUrl\)/)
+ assert.match(helper, /fetchJsonViaOauthSession\(url/)
+ assert.match(helper, /bearer: nativeAt/)
+})
+
+test('global remote Apply preflights before the atomic persistence boundary', () => {
+ const source = readMain()
+ const handlerStart = source.indexOf("ipcMain.handle('hermes:connection-config:apply'")
+ const handlerEnd = source.indexOf("ipcMain.handle('hermes:profile:get'", handlerStart)
+ const handler = source.slice(handlerStart, handlerEnd)
+ const preflight = handler.indexOf('await testDesktopConnectionConfig(payload)')
+ const commit = handler.indexOf('await applyConnectionConfigAtomically({')
+
+ assert.notEqual(handlerStart, -1)
+ assert.ok(preflight >= 0 && preflight < commit, 'remote REST+WS validation must happen before either config is committed')
+})
+
test('coerceDesktopConnectionConfig routes token persistence through resolvePersistedRemoteToken', () => {
const source = readMain()
const fnStart = source.indexOf('function coerceDesktopConnectionConfig(')
@@ -974,7 +998,7 @@ test('connection-config save and apply IPC handlers route payloads through coerc
const handlerBody = source.slice(handlerStart, handlerStart + 400)
assert.match(
handlerBody,
- /coerceDesktopConnectionConfig\(payload\)/,
+ /coerceDesktopConnectionConfig\(payload(?:, previousConfig)?\)/,
`${channel} must coerce its payload (the propagation seam) before persisting`
)
}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 478298d7ee1..9f5f6aa2bdf 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -102,6 +102,7 @@ import {
translateSelfProfileQuery,
withTransientRetries
} from './connection-config'
+import { applyConnectionConfigAtomically } from './connection-config-apply'
import {
backendScopeKey,
backendScopePrefix,
@@ -111,6 +112,7 @@ import {
migrateV1ToRegistry,
normalizeConnectionInput,
normalizeRegistry,
+ reconcileAppliedGlobalConnection,
rememberSshEnumeration,
removeConnection,
resolvedConnectionId,
@@ -9717,10 +9719,11 @@ async function testDesktopConnectionConfig(input: any = {}) {
const wantRemote =
modeIsRemoteLike(block?.mode) || (!key && modeIsRemoteLike(config.mode)) || (modeIsRemoteLike(input.mode) && block)
- // ``/api/status`` is public on every gateway (no creds needed), so a
- // reachability test works for local, token, and oauth modes alike — we only
- // need a base URL. For a remote config we normalize the URL from the input;
- // for local we fall back to the resolved/started backend.
+ // Test ``/api/status`` through the connection's real auth path. Self-hosted
+ // gateways may protect it, and an anonymous success/failure would not prove
+ // that the OAuth cookie/native bearer or configured token is reusable. For
+ // a remote config we normalize the URL from the input; for local we fall
+ // back to the resolved/started backend.
let baseUrl
let token = null
let authMode = 'token'
@@ -9742,7 +9745,7 @@ async function testDesktopConnectionConfig(input: any = {}) {
testHeaders = remote.headers || {}
}
- const status = (await fetchJson(`${baseUrl}/api/status`, token, { timeoutMs: 8_000, headers: testHeaders })) as any
+ const status = (await fetchConnectionStatus(baseUrl, authMode, token, testHeaders)) as any
// The HTTP status check above proves the backend is reachable, but the chat
// surface only works once the renderer's live WebSocket to ``/api/ws``
@@ -9776,6 +9779,22 @@ async function testDesktopConnectionConfig(input: any = {}) {
}
}
+async function fetchConnectionStatus(baseUrl, authMode, token, headers = {}) {
+ const url = `${baseUrl}/api/status`
+
+ if (authMode === 'oauth') {
+ const nativeAt = await ensureNativeAccessToken(baseUrl).catch(() => null)
+
+ if (nativeAt) {
+ return fetchJson(url, null, { timeoutMs: 8_000, bearer: nativeAt, headers })
+ }
+
+ return fetchJsonViaOauthSession(url, { timeoutMs: 8_000, headers })
+ }
+
+ return fetchJson(url, token, { timeoutMs: 8_000, headers })
+}
+
function resetBootProgressForReconnect() {
updateBootProgress(
{
@@ -12809,7 +12828,7 @@ ipcMain.handle('hermes:connections:test', async (_event, id) => {
}
}
- const status = (await fetchJson(`${baseUrl}/api/status`, token, { timeoutMs: 8_000, headers: testHeaders })) as any
+ const status = (await fetchConnectionStatus(baseUrl, authMode, token, testHeaders)) as any
// The Test button is the cheapest moment to (re)learn this backend's stable
// identity for the same-backend roster collapse + Settings hint.
@@ -13322,32 +13341,50 @@ ipcMain.handle('hermes:connection-config:save', async (_event, payload) => {
return sanitizeDesktopConnectionConfig(config, payload?.profile)
})
ipcMain.handle('hermes:connection-config:apply', async (_event, payload) => {
- const config = coerceDesktopConnectionConfig(payload)
- writeDesktopConnectionConfig(config)
+ const previousConfig = readDesktopConnectionConfig()
+ const previousRegistry = readDesktopConnectionsRegistry()
+ const config = coerceDesktopConnectionConfig(payload, previousConfig)
const key = connectionScopeKey(payload?.profile)
const scope = key || ''
-
- await applyConnectionChange({
- cancelAndWait: value => sshBootstrapCoordinator.cancelAndWait(value),
- isPrimary: !key || key === primaryProfileKey(),
- rehomePrimary: () =>
- rehomePrimaryConnection({
- clearLocalBootstrapFailure: () => {
- // A remote connection bypasses local runtime/bootstrap failures. Clear
- // the local-install latch so unsupported/failure escape paths can re-home.
- bootstrapFailure = null
- },
- mode: config.mode,
- notifyConnectionApplied: sendConnectionApplied,
- resumeFirstRunRemote: abandonFirstRunSetupChoiceForRemoteApply,
- teardownPrimaryBackend: teardownPrimaryBackendAndWait
- }),
- scope,
- sendApplied: sendConnectionApplied,
- stopPool: stopPoolBackend,
- teardownPrimary: () => teardownPrimaryBackendAndWait({ soft: true }),
- teardownSsh: value => teardownSshConnection(value || null)
+ const nextRegistry = key ? previousRegistry : reconcileAppliedGlobalConnection(previousRegistry, config)
+
+ // Exercise the same authenticated REST + real WebSocket legs before either
+ // config file changes. A rejected OAuth session or blocked /api/ws leaves
+ // the previous primary/current connection intact.
+ if (!key && modeIsRemoteLike(config.mode)) {
+ await testDesktopConnectionConfig(payload)
+ }
+
+ await applyConnectionConfigAtomically({
+ previousConfig,
+ previousRegistry,
+ nextConfig: config,
+ nextRegistry,
+ writeConfig: writeDesktopConnectionConfig,
+ writeRegistry: writeDesktopConnectionsRegistry,
+ apply: () =>
+ applyConnectionChange({
+ cancelAndWait: value => sshBootstrapCoordinator.cancelAndWait(value),
+ isPrimary: !key || key === primaryProfileKey(),
+ rehomePrimary: () =>
+ rehomePrimaryConnection({
+ clearLocalBootstrapFailure: () => {
+ // A remote connection bypasses local runtime/bootstrap failures. Clear
+ // the local-install latch so unsupported/failure escape paths can re-home.
+ bootstrapFailure = null
+ },
+ mode: config.mode,
+ notifyConnectionApplied: sendConnectionApplied,
+ resumeFirstRunRemote: abandonFirstRunSetupChoiceForRemoteApply,
+ teardownPrimaryBackend: teardownPrimaryBackendAndWait
+ }),
+ scope,
+ sendApplied: sendConnectionApplied,
+ stopPool: stopPoolBackend,
+ teardownPrimary: () => teardownPrimaryBackendAndWait({ soft: true }),
+ teardownSsh: value => teardownSshConnection(value || null)
+ })
})
return sanitizeDesktopConnectionConfig(config, payload?.profile)