The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): multi-connection registry — named agent sources (schema v2 + IPC + Settings UI)
Tekniumb54b0521dc28
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.tsnew file mode 100644index 00000000000..88398cfbec7--- /dev/null+++ b/apps/desktop/electron/connection-registry.test.ts@@ -0,0 +1,305 @@+/**+ * Tests for electron/connection-registry.ts — the v2 multi-connection+ * registry: label rules (required, unique, @handle disambiguation), input+ * validation, registry normalization from disk, the v1→v2 migration, and the+ * pure upsert/remove/set-primary operations.+ */++import assert from 'node:assert/strict'++import { test } from 'vitest'++import type {+ ConnectionRegistry} from './connection-registry';+import {+ agentHandle,+ connectionIdForLabel,+ labelKey,+ labelSlug,+ LOCAL_CONNECTION_ID,+ migrateV1ToRegistry,+ normalizeConnectionInput,+ normalizeRegistry,+ REGISTRY_VERSION,+ removeConnection,+ setPrimaryConnection,+ upsertConnection+} from './connection-registry'++function emptyRegistry(): ConnectionRegistry {+ return normalizeRegistry(null)+}++// --- labels, slugs, handles ---++test('labelKey is case-insensitive and trimmed', () => {+ assert.equal(labelKey(' Homelab '), 'homelab')+ assert.equal(labelKey('HOMELAB'), labelKey('homelab'))+})++test('labelSlug kebab-cases and never returns empty for non-empty input', () => {+ assert.equal(labelSlug('Work Laptop'), 'work-laptop')+ assert.equal(labelSlug('Spark Box #2'), 'spark-box-2')+ assert.equal(labelSlug('!!!'), 'connection')+})++test('agentHandle bare when unique, @name-device shape when duplicated', () => {+ assert.equal(agentHandle('research', 'Homelab', false), 'research')+ assert.equal(agentHandle('research', 'Homelab', true), 'research-homelab')+ assert.equal(agentHandle('research', 'Work Laptop', true), 'research-work-laptop')+ assert.equal(agentHandle('', 'Homelab', false), 'default')+})++test('connectionIdForLabel suffixes on collision and never mints "local"', () => {+ assert.equal(connectionIdForLabel('Homelab', []), 'homelab')+ assert.equal(connectionIdForLabel('Homelab', ['homelab']), 'homelab-2')+ assert.equal(connectionIdForLabel('Homelab', ['homelab', 'homelab-2']), 'homelab-3')+ assert.equal(connectionIdForLabel('Local', []), 'local-2')+})++// --- normalizeConnectionInput ---++test('save rejects a missing label with a device-name message', () => {+ assert.throws(+ () => normalizeConnectionInput({ kind: 'remote', label: ' ', url: 'http://10.0.0.5:9119' }, emptyRegistry()),+ /device name/+ )+})++test('save rejects a duplicate label case-insensitively', () => {+ let registry = emptyRegistry()+ registry = upsertConnection(+ registry,+ normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)+ )++ assert.throws(+ () => normalizeConnectionInput({ kind: 'remote', label: ' homelab ', url: 'http://10.0.0.9:9119' }, registry),+ /must be unique/+ )+})++test('editing an entry does not collide with its own label', () => {+ let registry = emptyRegistry()+ const entry = normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)+ registry = upsertConnection(registry, entry)++ const edited = normalizeConnectionInput(+ { id: entry.id, kind: 'remote', label: 'Homelab', url: 'http://10.0.0.6:9119' },+ registry+ )++ assert.equal(edited.id, entry.id)+ assert.equal(edited.url, 'http://10.0.0.6:9119')+})++test('remote input normalizes URL and auth mode; cloud keeps org', () => {+ const registry = emptyRegistry()++ const remote = normalizeConnectionInput(+ { kind: 'remote', label: 'LAN box', url: '10.0.0.5:9119', authMode: 'weird' },+ registry+ )++ assert.equal(remote.url, 'http://10.0.0.5:9119')+ assert.equal(remote.authMode, 'token')++ const cloud = normalizeConnectionInput(+ { kind: 'cloud', label: 'Cloud', url: 'https://foo.hermes.cloud', authMode: 'oauth', org: 'nous' },+ registry+ )++ assert.equal(cloud.kind, 'cloud')+ assert.equal(cloud.org, 'nous')+ assert.equal(cloud.authMode, 'oauth')+})++test('ssh input requires a host; local input only carries the label', () => {+ const registry = emptyRegistry()++ assert.throws(() => normalizeConnectionInput({ kind: 'ssh', label: 'Spark', host: ' ' }, registry), /host/)++ const ssh = normalizeConnectionInput({ kind: 'ssh', label: 'Spark', host: 'tek@spark1:2222' }, registry)++ assert.equal(ssh.host, 'spark1')+ assert.equal(ssh.user, 'tek')+ assert.equal(ssh.port, 2222)++ const local = normalizeConnectionInput({ kind: 'local', label: 'My MacBook' }, registry)++ assert.equal(local.id, LOCAL_CONNECTION_ID)+ assert.deepEqual(Object.keys(local).sort(), ['id', 'kind', 'label'])+})++// --- normalizeRegistry ---++test('normalizeRegistry degrades junk to a local-only registry', () => {+ for (const junk of [null, undefined, 42, 'nope', { connections: 'zzz' }, { version: 99 }]) {+ const registry = normalizeRegistry(junk)++ assert.equal(registry.version, REGISTRY_VERSION)+ assert.equal(registry.primary, LOCAL_CONNECTION_ID)+ assert.equal(registry.connections.length, 1)+ assert.equal(registry.connections[0].kind, 'local')+ }+})++test('normalizeRegistry guarantees local, dedupes labels, fixes dangling primary', () => {+ const registry = normalizeRegistry({+ version: 2,+ primary: 'ghost',+ connections: [+ { id: 'a', kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' },+ { id: 'b', kind: 'remote', label: 'homelab', url: 'http://10.0.0.6:9119' },+ { id: 'c', kind: 'remote', label: 'No URL entry' },+ { kind: 'nonsense', label: 'x' }+ ]+ })++ assert.equal(registry.primary, LOCAL_CONNECTION_ID)+ assert.ok(registry.connections.some(c => c.kind === 'local'))++ const labels = registry.connections.map(c => labelKey(c.label))++ assert.equal(new Set(labels).size, labels.length)+ // The url-less remote entry is dropped, the junk kind is dropped.+ assert.equal(registry.connections.filter(c => c.kind === 'remote').length, 2)+})++test('normalizeRegistry round-trips a valid registry unchanged in shape', () => {+ const input = {+ version: 2,+ primary: 'homelab',+ connections: [+ { id: 'local', kind: 'local', label: 'This device' },+ { id: 'homelab', kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119', authMode: 'token', token: { v: 1 } },+ { id: 'cloud-1', kind: 'cloud', label: 'Hermes Cloud', url: 'https://a.hermes.cloud', authMode: 'oauth', org: 'nous' },+ { id: 'spark', kind: 'ssh', label: 'Spark', host: 'spark1', user: 'tek', port: 2222 }+ ]+ }++ const registry = normalizeRegistry(input)++ assert.equal(registry.primary, 'homelab')+ assert.equal(registry.connections.length, 4)+ assert.deepEqual(registry.connections.map(c => c.id), ['local', 'homelab', 'cloud-1', 'spark'])+ assert.deepEqual(registry.connections[1].token, { v: 1 })+ assert.equal(registry.connections[3].port, 2222)+})++// --- v1 → v2 migration ---++test('migrate: v1 local-only config → local-only registry', () => {+ const registry = migrateV1ToRegistry({ mode: 'local', remote: {}, profiles: {} })++ assert.equal(registry.primary, LOCAL_CONNECTION_ID)+ assert.equal(registry.connections.length, 1)+})++test('migrate: v1 global remote becomes a labeled entry and the primary', () => {+ const registry = migrateV1ToRegistry({+ mode: 'remote',+ remote: { url: 'http://homelab.lan:9119', authMode: 'token', token: { enc: 'x' } }+ })++ const remote = registry.connections.find(c => c.kind === 'remote')++ assert.ok(remote)+ assert.equal(registry.primary, remote.id)+ assert.equal(remote.label, 'homelab.lan:9119')+ assert.deepEqual(remote.token, { enc: 'x' })+})++test('migrate: v1 cloud keeps cloud provenance + org', () => {+ const registry = migrateV1ToRegistry({+ mode: 'cloud',+ remote: { url: 'https://a.hermes.cloud', authMode: 'oauth', org: 'nous' }+ })++ const cloud = registry.connections.find(c => c.kind === 'cloud')++ assert.ok(cloud)+ assert.equal(registry.primary, cloud.id)+ assert.equal(cloud.org, 'nous')+})++test('migrate: per-profile overrides become extra sources, deduped by URL', () => {+ const registry = migrateV1ToRegistry({+ mode: 'remote',+ remote: { url: 'http://homelab.lan:9119', authMode: 'token', token: { enc: 'x' } },+ profiles: {+ research: { mode: 'remote', url: 'http://homelab.lan:9119', authMode: 'token', token: { enc: 'x' } },+ coder: { mode: 'remote', url: 'http://other.lan:9119', authMode: 'token', token: { enc: 'y' } },+ sparky: { mode: 'ssh', host: 'spark1', user: 'tek' },+ plain: { mode: 'local', savedSsh: { mode: 'ssh', host: 'spark1', user: 'tek' } }+ }+ })++ // homelab (global+research deduped), other.lan, spark ssh (override+savedSsh deduped), local+ assert.equal(registry.connections.length, 4)+ assert.equal(registry.connections.filter(c => c.kind === 'remote').length, 2)+ assert.equal(registry.connections.filter(c => c.kind === 'ssh').length, 1)+})++test('migrate: v1 global ssh becomes the primary', () => {+ const registry = migrateV1ToRegistry({+ mode: 'ssh',+ remote: { mode: 'ssh', host: 'spark1', user: 'tek', port: 2222 }+ })++ const ssh = registry.connections.find(c => c.kind === 'ssh')++ assert.ok(ssh)+ assert.equal(registry.primary, ssh.id)+ assert.equal(ssh.label, 'spark1')+})++test('migrate: duplicate host labels are suffixed, not dropped', () => {+ const registry = migrateV1ToRegistry({+ mode: 'remote',+ remote: { url: 'http://box.lan:9119', authMode: 'token', token: {} },+ profiles: {+ a: { mode: 'ssh', host: 'box.lan' }+ }+ })++ const labels = registry.connections.map(c => labelKey(c.label))++ assert.equal(new Set(labels).size, labels.length)+ assert.equal(registry.connections.length, 3)+})++// --- registry operations ---++test('removeConnection: local refuses, primary retargets to local', () => {+ let registry = emptyRegistry()+ const entry = normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry)+ registry = upsertConnection(registry, entry)+ registry = setPrimaryConnection(registry, entry.id)++ assert.throws(() => removeConnection(registry, LOCAL_CONNECTION_ID), /cannot be removed/)++ const after = removeConnection(registry, entry.id)++ assert.equal(after.primary, LOCAL_CONNECTION_ID)+ assert.equal(after.connections.length, 1)+ // Removing an unknown id is a no-op, not an error.+ assert.equal(removeConnection(after, 'ghost'), after)+})++test('setPrimaryConnection validates the target id', () => {+ const registry = emptyRegistry()++ assert.throws(() => setPrimaryConnection(registry, 'ghost'), /No connection/)+ assert.equal(setPrimaryConnection(registry, LOCAL_CONNECTION_ID).primary, LOCAL_CONNECTION_ID)+})++test('upsertConnection replaces by id and appends new ids', () => {+ let registry = emptyRegistry()+ const a = normalizeConnectionInput({ kind: 'remote', label: 'A', url: 'http://a:1' }, registry)+ registry = upsertConnection(registry, a)+ registry = upsertConnection(registry, { ...a, url: 'http://a:2' })++ assert.equal(registry.connections.filter(c => c.id === a.id).length, 1)+ assert.equal(registry.connections.find(c => c.id === a.id)?.url, 'http://a:2')+})diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.tsnew file mode 100644index 00000000000..f1fca1ff17b--- /dev/null+++ b/apps/desktop/electron/connection-registry.ts@@ -0,0 +1,492 @@+/**+ * connection-registry.ts+ *+ * Pure, electron-free helpers for the desktop's multi-connection registry —+ * the v2 successor to the single global `mode` + `remote` block in+ * connection.json. The registry is a named list of agent SOURCES (local+ * runtime, remote gateways, Hermes Cloud instances, SSH hosts) that are all+ * registered at once; routing/pooling changes that consume the registry land+ * separately, so this module is deliberately storage-shaped, not+ * transport-shaped.+ *+ * Design rules (agreed with Teknium, Aug 2026):+ * - Every connection carries a REQUIRED, registry-unique `label` (the+ * "device name"). Uniqueness is case-insensitive so `Homelab` and+ * `homelab` can't coexist and produce two identical badges.+ * - When two sources expose the same profile name, surfaces disambiguate as+ * `@<profile>-<label-slug>` — `agentHandle()` is the one place that rule+ * lives.+ * - The registry ALWAYS contains exactly one `local` connection (the app's+ * own runtime). It cannot be removed; it is the default primary.+ * - `primary` designates the connection that owns the window backend (boot+ * overlay, install/update machinery). Removing the primary retargets to+ * the local entry rather than leaving a dangling id.+ *+ * Kept standalone (no `import 'electron'`) so it unit-tests with `node --test`+ * — same pattern as connection-config.ts / backend-probes.ts. main.ts wires+ * these into the IPC layer and owns file I/O + secret encryption.+ */++import { hostLabelFromBaseUrl, modeIsRemoteLike, normalizeRemoteBaseUrl, normalizeSshConfig, normAuthMode } from './connection-config'++export const REGISTRY_VERSION = 2++export const LOCAL_CONNECTION_ID = 'local'++/** Connection kinds. 'cloud' is remote-shaped (see modeIsRemoteLike) but keeps+ * its provenance so the UI can render the right card and updates can skip+ * platform-managed instances. */+export type ConnectionKind = 'cloud' | 'local' | 'remote' | 'ssh'++export interface RegistryConnection {+ id: string+ kind: ConnectionKind+ /** Required, unique (case-insensitive) display name — the "device name". */+ label: string+ /** remote/cloud: normalized base URL. */+ url?: string+ /** remote/cloud: 'token' | 'oauth'. */+ authMode?: 'oauth' | 'token'+ /** remote: encrypted token envelope (opaque here; main.ts encrypts/decrypts). */+ token?: unknown+ /** cloud: portal org slug/id the instance was discovered under. */+ org?: string+ /** ssh fields (normalizeSshConfig shapes). */+ host?: string+ user?: string+ port?: number+ keyPath?: string+ remoteHermesPath?: string+ remoteProfile?: string+}++export interface ConnectionRegistry {+ version: typeof REGISTRY_VERSION+ /** id of the connection that owns the window/primary backend. */+ primary: string+ connections: RegistryConnection[]+}++// ── Labels and ids ──────────────────────────────────────────────────────────++const LABEL_MAX = 64++/** Canonical comparison key for label uniqueness. */+export function labelKey(label: string): string {+ return String(label || '')+ .trim()+ .toLowerCase()+}++/** Kebab-slug of a label for ids and @handles. Never empty for a non-empty label. */+export function labelSlug(label: string): string {+ const slug = String(label || '')+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 48)++ return slug || 'connection'+}++/**+ * The one place the duplicate-agent naming rule lives: a profile that exists+ * on several registered sources renders as `@<profile>-<label-slug>`;+ * a profile unique across the roster keeps its bare name.+ */+export function agentHandle(profile: string, connectionLabel: string, duplicated: boolean): string {+ const name = String(profile || '').trim() || 'default'++ return duplicated ? `${name}-${labelSlug(connectionLabel)}` : name+}++/** Mint a registry-unique id from a label (slug, then -2/-3… suffixes). */+export function connectionIdForLabel(label: string, taken: Iterable<string>): string {+ const used = new Set([...taken])+ const base = labelSlug(label)++ if (!used.has(base) && base !== LOCAL_CONNECTION_ID) {+ return base+ }++ for (let n = 2; ; n += 1) {+ const candidate = `${base}-${n}`++ if (!used.has(candidate) && candidate !== LOCAL_CONNECTION_ID) {+ return candidate+ }+ }+}++// ── Validation ──────────────────────────────────────────────────────────────++export interface ConnectionInput {+ id?: string+ kind: ConnectionKind+ label: string+ url?: string+ authMode?: string+ token?: unknown+ org?: string+ host?: string+ user?: string+ port?: number | string+ keyPath?: string+ remoteHermesPath?: string+ remoteProfile?: string+}++/**+ * Validate + normalize a save payload into a RegistryConnection.+ * Throws with a user-facing message on any violation. `registry` supplies the+ * uniqueness context; when `input.id` matches an existing entry this is an+ * edit and that entry is excluded from the label-collision check.+ */+export function normalizeConnectionInput(input: ConnectionInput, registry: ConnectionRegistry): RegistryConnection {+ const label = String(input.label || '').trim()++ if (!label) {+ throw new Error('Every connection needs a name. Give this instance a device name (e.g. "Homelab", "Work laptop").')+ }++ if (label.length > LABEL_MAX) {+ throw new Error(`Connection name is too long (max ${LABEL_MAX} characters).`)+ }++ const key = labelKey(label)+ const collision = registry.connections.find(c => labelKey(c.label) === key && c.id !== input.id)++ if (collision) {+ throw new Error(`A connection named "${collision.label}" already exists. Connection names must be unique.`)+ }++ const kind = input.kind++ if (kind === 'local') {+ // The local entry is managed by the app; only its label is editable.+ return { id: LOCAL_CONNECTION_ID, kind: 'local', label }+ }++ const id = input.id || connectionIdForLabel(label, registry.connections.map(c => c.id))++ if (kind === 'ssh') {+ const ssh = normalizeSshConfig({+ mode: 'ssh',+ host: input.host,+ user: input.user,+ port: input.port,+ keyPath: input.keyPath,+ remoteHermesPath: input.remoteHermesPath,+ remoteProfile: input.remoteProfile+ })++ if (!ssh) {+ throw new Error('SSH connections need a host.')+ }++ const { mode: _mode, ...sshFields } = ssh++ return { id, kind: 'ssh', label, ...sshFields }+ }++ if (kind === 'remote' || kind === 'cloud') {+ // normalizeRemoteBaseUrl throws its own user-facing message on bad input.+ const url = normalizeRemoteBaseUrl(input.url)+ const authMode = normAuthMode(input.authMode)+ const entry: RegistryConnection = { id, kind, label, url, authMode }++ if (input.token !== undefined) {+ entry.token = input.token+ }++ const org = String(input.org || '').trim()++ if (kind === 'cloud' && org) {+ entry.org = org+ }++ return entry+ }++ throw new Error(`Unknown connection kind: ${String(kind)}`)+}++// ── Registry-level operations (all pure: return a new registry) ────────────++function localEntry(label = 'This device'): RegistryConnection {+ return { id: LOCAL_CONNECTION_ID, kind: 'local', label }+}++/**+ * Coerce arbitrary parsed JSON into a valid registry: version stamped, a+ * local entry guaranteed, labels de-duplicated defensively (suffix, never+ * drop), primary always pointing at an existing entry. A hand-edited or+ * corrupt file degrades to a minimal local-only registry rather than+ * throwing at boot.+ */+export function normalizeRegistry(raw: unknown): ConnectionRegistry {+ const parsed = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}+ const rawConnections = Array.isArray(parsed.connections) ? parsed.connections : []+ const seenLabels = new Set<string>()+ const seenIds = new Set<string>()+ const connections: RegistryConnection[] = []++ for (const item of rawConnections) {+ if (!item || typeof item !== 'object') {+ continue+ }++ const entry = item as Record<string, unknown>+ const kind = entry.kind++ if (kind !== 'local' && kind !== 'remote' && kind !== 'cloud' && kind !== 'ssh') {+ continue+ }++ let label = String(entry.label || '').trim()++ if (!label) {+ // Defensive: registry entries are always written with labels, but a+ // hand-edited file may drop one. Derive rather than discard.+ label =+ kind === 'ssh' ? String(entry.host || 'ssh') : hostLabelFromBaseUrl(String(entry.url || '')) || String(kind)+ }++ while (seenLabels.has(labelKey(label))) {+ label = `${label} 2`+ }++ let id = kind === 'local' ? LOCAL_CONNECTION_ID : String(entry.id || '').trim()++ if (!id || (seenIds.has(id) && kind !== 'local')) {+ id = connectionIdForLabel(label, seenIds)+ }++ if (seenIds.has(id)) {+ continue // second 'local' entry — first one wins+ }++ seenLabels.add(labelKey(label))+ seenIds.add(id)++ const clean: RegistryConnection = { id, kind, label }++ if (kind === 'remote' || kind === 'cloud') {+ const url = String(entry.url || '').trim()++ if (!url) {+ continue+ }++ clean.url = url+ clean.authMode = normAuthMode(entry.authMode)++ if (entry.token !== undefined) {+ clean.token = entry.token+ }++ const org = String(entry.org || '').trim()++ if (kind === 'cloud' && org) {+ clean.org = org+ }+ } else if (kind === 'ssh') {+ const ssh = normalizeSshConfig({ ...entry, mode: 'ssh' })++ if (!ssh) {+ continue+ }++ const { mode: _mode, ...sshFields } = ssh+ Object.assign(clean, sshFields)+ }++ connections.push(clean)+ }++ if (!connections.some(c => c.kind === 'local')) {+ connections.unshift(localEntry())+ }++ const primary = String(parsed.primary || '').trim()++ return {+ version: REGISTRY_VERSION,+ primary: connections.some(c => c.id === primary) ? primary : LOCAL_CONNECTION_ID,+ connections+ }+}++/**+ * One-time import of the v1 connection.json shape (global `mode` + `remote`+ * block + per-profile `profiles` map) into a v2 registry. v1 had no labels,+ * so they are derived (URL host, SSH host, "This device") and uniqued by+ * suffixing. The active v1 global connection becomes the primary. The v1+ * file is left untouched by the caller — old builds keep working.+ *+ * Per-profile override entries become registry connections too (deduped by+ * URL/host against the global block), so a user who had `research` pinned to+ * a second gateway sees both sources registered on first launch.+ */+export function migrateV1ToRegistry(v1: unknown): ConnectionRegistry {+ const config = v1 && typeof v1 === 'object' ? (v1 as Record<string, any>) : {}+ const connections: RegistryConnection[] = [localEntry()]+ const byFingerprint = new Map<string, RegistryConnection>()++ const addRemoteLike = (block: Record<string, any>, kind: 'cloud' | 'remote'): null | RegistryConnection => {+ const url = String(block?.url || '').trim()++ if (!url) {+ return null+ }++ const fingerprint = `${kind}:${url}`+ const existing = byFingerprint.get(fingerprint)++ if (existing) {+ return existing+ }++ let label = hostLabelFromBaseUrl(url) || (kind === 'cloud' ? 'Hermes Cloud' : 'Remote gateway')++ while (connections.some(c => labelKey(c.label) === labelKey(label))) {+ label = `${label} 2`+ }++ const entry: RegistryConnection = {+ id: connectionIdForLabel(label, connections.map(c => c.id)),+ kind,+ label,+ url,+ authMode: normAuthMode(block.authMode)+ }++ if (block.token !== undefined) {+ entry.token = block.token+ }++ const org = String(block.org || '').trim()++ if (kind === 'cloud' && org) {+ entry.org = org+ }++ connections.push(entry)+ byFingerprint.set(fingerprint, entry)++ return entry+ }++ const addSsh = (block: Record<string, any>): null | RegistryConnection => {+ const ssh = normalizeSshConfig({ ...block, mode: 'ssh' })++ if (!ssh) {+ return null+ }++ const fingerprint = `ssh:${ssh.user || ''}@${ssh.host}:${ssh.port || 22}`+ const existing = byFingerprint.get(fingerprint)++ if (existing) {+ return existing+ }++ let label = ssh.host++ while (connections.some(c => labelKey(c.label) === labelKey(label))) {+ label = `${label} 2`+ }++ const { mode: _mode, ...sshFields } = ssh++ const entry: RegistryConnection = {+ id: connectionIdForLabel(label, connections.map(c => c.id)),+ kind: 'ssh',+ label,+ ...sshFields+ }++ connections.push(entry)+ byFingerprint.set(fingerprint, entry)++ return entry+ }++ // Global connection → an entry + the primary designation.+ let primary = LOCAL_CONNECTION_ID+ const globalMode = config.mode++ if (modeIsRemoteLike(globalMode)) {+ const entry = addRemoteLike(config.remote || {}, globalMode === 'cloud' ? 'cloud' : 'remote')++ if (entry) {+ primary = entry.id+ }+ } else if (globalMode === 'ssh') {+ const entry = addSsh(config.remote || {})++ if (entry) {+ primary = entry.id+ }+ }++ // Per-profile overrides → additional registered sources (deduped).+ const profiles = config.profiles && typeof config.profiles === 'object' ? config.profiles : {}++ for (const block of Object.values(profiles) as Record<string, any>[]) {+ if (!block || typeof block !== 'object') {+ continue+ }++ if (modeIsRemoteLike(block.mode)) {+ addRemoteLike(block, block.mode === 'cloud' ? 'cloud' : 'remote')+ } else if (block.mode === 'ssh') {+ addSsh(block)+ } else if (block.mode === 'local' && block.savedSsh) {+ addSsh(block.savedSsh)+ }+ }++ return { version: REGISTRY_VERSION, primary, connections }+}++/** Insert or replace by id. Input must already be normalized/validated. */+export function upsertConnection(registry: ConnectionRegistry, entry: RegistryConnection): ConnectionRegistry {+ const connections = registry.connections.some(c => c.id === entry.id)+ ? registry.connections.map(c => (c.id === entry.id ? entry : c))+ : [...registry.connections, entry]++ return { ...registry, connections }+}++/**+ * Remove a connection. The local entry is not removable; removing the+ * current primary retargets primary to local.+ */+export function removeConnection(registry: ConnectionRegistry, id: string): ConnectionRegistry {+ const target = registry.connections.find(c => c.id === id)++ if (!target) {+ return registry+ }++ if (target.kind === 'local') {+ throw new Error('The local connection cannot be removed.')+ }++ return {+ ...registry,+ primary: registry.primary === id ? LOCAL_CONNECTION_ID : registry.primary,+ connections: registry.connections.filter(c => c.id !== id)+ }+}++/** Point the window/primary backend at another registered connection. */+export function setPrimaryConnection(registry: ConnectionRegistry, id: string): ConnectionRegistry {+ if (!registry.connections.some(c => c.id === id)) {+ throw new Error(`No connection with id "${id}".`)+ }++ return { ...registry, primary: id }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex d194d7c345c..0af57083167 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -83,6 +83,14 @@ import {savedProfileSsh,tokenPreview} from './connection-config'+import {+ migrateV1ToRegistry,+ normalizeConnectionInput,+ normalizeRegistry,+ removeConnection,+ setPrimaryConnection,+ upsertConnection+} from './connection-registry'import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'@@ -659,6 +667,11 @@ const BOOTSTRAP_COMPLETE_MARKER = path.join(ACTIVE_HERMES_ROOT, '.hermes-bootstrconst BOOTSTRAP_MARKER_SCHEMA_VERSION = 1const DESKTOP_CONNECTION_CONFIG_PATH = path.join(app.getPath('userData'), 'connection.json')+// v2 multi-connection registry (named agent sources). Lives BESIDE+// connection.json — v1 stays on disk untouched so older builds sharing the+// profile keep working; the registry imports from it once and then owns its+// own file. Same secret posture as connection.json (encrypted tokens, 0600).+const DESKTOP_CONNECTIONS_REGISTRY_PATH = path.join(app.getPath('userData'), 'connections.json')const DESKTOP_INSTALLATION_PATH = path.join(app.getPath('userData'), 'desktop-installation.json')const DESKTOP_UPDATE_CONFIG_PATH = path.join(app.getPath('userData'), 'updates.json')const DESKTOP_WINDOW_STATE_PATH = path.join(app.getPath('userData'), 'window-state.json')@@ -1175,6 +1188,8 @@ let bootstrapRepairAttempt = 0const MAX_BOOTSTRAP_REPAIR_SOFT_ATTEMPTS = 3let connectionConfigCache = nulllet connectionConfigCacheMtime = null+let connectionRegistryCache = null+let connectionRegistryCacheMtime = nullconst hermesLog = []const previewWatchers = new Map()let previewShortcutActive = false@@ -7550,6 +7565,118 @@ function writeDesktopConnectionConfig(config) {connectionConfigCacheMtime = fs.statSync(DESKTOP_CONNECTION_CONFIG_PATH).mtimeMs}+// ── v2 connection registry (multi-source) ──────────────────────────────────++/**+ * Read the v2 registry, importing from v1 connection.json exactly once (when+ * connections.json does not exist yet). Same mtime-cache + tighten-mode+ * discipline as readDesktopConnectionConfig; a corrupt registry degrades to+ * local-only via normalizeRegistry rather than throwing at boot.+ */+function readDesktopConnectionsRegistry() {+ let mtime = null++ try {+ mtime = fs.statSync(DESKTOP_CONNECTIONS_REGISTRY_PATH).mtimeMs+ } catch {+ mtime = null+ }++ if (connectionRegistryCache && connectionRegistryCacheMtime === mtime) {+ return connectionRegistryCache+ }++ let registry++ if (mtime === null) {+ // First run on this build: import the v1 single-connection config. The v1+ // file is NOT modified or deleted — older builds keep reading it.+ registry = migrateV1ToRegistry(readDesktopConnectionConfig())+ writeDesktopConnectionsRegistry(registry)++ return connectionRegistryCache+ }++ try {+ // Same rationale as connection.json: tighten BEFORE parse so a corrupt+ // file that still holds token bytes gets its mode fixed anyway.+ tightenSecretFileMode(DESKTOP_CONNECTIONS_REGISTRY_PATH)+ registry = normalizeRegistry(JSON.parse(fs.readFileSync(DESKTOP_CONNECTIONS_REGISTRY_PATH, 'utf8')))+ } catch {+ registry = normalizeRegistry(null)+ }++ connectionRegistryCache = registry+ connectionRegistryCacheMtime = mtime++ return registry+}++function writeDesktopConnectionsRegistry(registry) {+ fs.mkdirSync(path.dirname(DESKTOP_CONNECTIONS_REGISTRY_PATH), { recursive: true })+ // Owner-only for the same reason as connection.json: entries carry+ // safeStorage-encrypted tokens plus URLs and SSH host/user/keyPath.+ writeSecretFileAtomic(DESKTOP_CONNECTIONS_REGISTRY_PATH, JSON.stringify(registry, null, 2))+ connectionRegistryCache = registry+ connectionRegistryCacheMtime = fs.statSync(DESKTOP_CONNECTIONS_REGISTRY_PATH).mtimeMs+}++/**+ * Renderer-facing view of a registry entry: token bytes never cross the IPC+ * boundary — the renderer gets a preview + set flag, mirroring+ * sanitizeDesktopConnectionConfig.+ */+function sanitizeRegistryConnection(entry) {+ const { token, ...rest } = entry+ const decrypted = decryptDesktopSecret(token)++ return {+ ...rest,+ tokenSet: Boolean(decrypted),+ tokenPreview: tokenPreview(decrypted)+ }+}++function sanitizeConnectionsRegistry(registry = readDesktopConnectionsRegistry()) {+ return {+ version: registry.version,+ primary: registry.primary,+ connections: registry.connections.map(sanitizeRegistryConnection)+ }+}++/**+ * Save (create or edit) a registry connection from a renderer payload.+ * Token handling mirrors coerceDesktopConnectionConfig: an incoming plaintext+ * token is encrypted (with the same plain-text opt-in seam); an absent token+ * field inherits the stored envelope on edit.+ */+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() : ''++ const token = resolvePersistedRemoteToken({+ incomingToken,+ persistToken: true,+ existingToken: existing?.token,+ allowPlainText: input.allowPlainTextToken,+ encryptSecret: encryptDesktopSecret+ })++ const entry = normalizeConnectionInput({ ...input, token }, registry)++ // Token-auth remotes must actually have a token to be dialable. OAuth and+ // cloud entries authenticate via cookies/native tokens instead.+ if (entry.kind === 'remote' && entry.authMode !== 'oauth' && !decryptDesktopSecret(entry.token)) {+ throw new Error('Remote gateway session token is required.')+ }++ writeDesktopConnectionsRegistry(upsertConnection(registry, entry))++ return sanitizeRegistryConnection(entry)+}+// Returns the desktop's chosen profile name, or null when unset. "default" is// a valid stored value (pins the root HERMES_HOME explicitly); null means "no// preference" and preserves the legacy launch (no --profile flag).@@ -11194,6 +11321,62 @@ ipcMain.handle('hermes:ssh-config:resolve', async (_event, host) => {})})ipcMain.handle('hermes:connection-config:test', async (_event, payload) => testDesktopConnectionConfig(payload))++// ── v2 connection registry IPC (multi-source) ───────────────────────────────+// Storage-level CRUD for named agent sources. Routing/pooling consumption of+// the registry lands separately; these handlers only manage the persisted+// 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)++ return { ok: true, connection: saved, registry: sanitizeConnectionsRegistry() }+})+ipcMain.handle('hermes:connections:remove', async (_event, id) => {+ const registry = removeConnection(readDesktopConnectionsRegistry(), String(id || ''))+ writeDesktopConnectionsRegistry(registry)++ return { ok: true, registry: sanitizeConnectionsRegistry(registry) }+})+ipcMain.handle('hermes:connections:set-primary', async (_event, id) => {+ const registry = setPrimaryConnection(readDesktopConnectionsRegistry(), String(id || ''))+ writeDesktopConnectionsRegistry(registry)++ return { ok: true, registry: sanitizeConnectionsRegistry(registry) }+})+ipcMain.handle('hermes:connections:test', async (_event, id) => {+ const registry = readDesktopConnectionsRegistry()+ const entry = registry.connections.find(c => c.id === String(id || ''))++ if (!entry) {+ throw new Error(`No connection with id "${String(id || '')}".`)+ }++ // Reuse the existing probe stack by mapping the registry entry onto the+ // settings-payload shape testDesktopConnectionConfig already understands.+ if (entry.kind === 'local') {+ return testDesktopConnectionConfig({ mode: 'local' })+ }++ if (entry.kind === 'ssh') {+ return testDesktopConnectionConfig({+ mode: 'ssh',+ sshHost: entry.host,+ sshUser: entry.user,+ sshPort: entry.port,+ sshKeyPath: entry.keyPath,+ sshRemoteHermesPath: entry.remoteHermesPath+ })+ }++ return testDesktopConnectionConfig({+ mode: entry.kind,+ remoteUrl: entry.url,+ remoteAuthMode: entry.authMode,+ remoteToken: decryptDesktopSecret(entry.token) || undefined,+ cloudOrg: entry.org+ })+})ipcMain.handle('hermes:connection-config:probe', async (_event, rawUrl) => probeRemoteAuthMode(rawUrl))ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) => {// Capability-gated login (RFC 8252). Probe the gateway's public /api/status:diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 0c0ec40c8c3..b6b592f2b42 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -123,6 +123,14 @@ contextBridge.exposeInMainWorld('hermesDesktop', {saveConnectionConfig: payload => ipcRenderer.invoke('hermes:connection-config:save', payload),applyConnectionConfig: payload => ipcRenderer.invoke('hermes:connection-config:apply', payload),testConnectionConfig: payload => ipcRenderer.invoke('hermes:connection-config:test', payload),+ // v2 multi-connection registry: named agent sources (local / remote / cloud / ssh).+ connections: {+ list: () => ipcRenderer.invoke('hermes:connections:list'),+ save: payload => ipcRenderer.invoke('hermes:connections:save', payload),+ remove: id => ipcRenderer.invoke('hermes:connections:remove', id),+ setPrimary: id => ipcRenderer.invoke('hermes:connections:set-primary', id),+ test: id => ipcRenderer.invoke('hermes:connections:test', id)+ },sshConfigHosts: () => ipcRenderer.invoke('hermes:ssh-config:hosts'),sshResolveHost: host => ipcRenderer.invoke('hermes:ssh-config:resolve', host),probeConnectionConfig: remoteUrl => ipcRenderer.invoke('hermes:connection-config:probe', remoteUrl),diff --git a/apps/desktop/src/app/settings/connections-settings.test.tsx b/apps/desktop/src/app/settings/connections-settings.test.tsxnew file mode 100644index 00000000000..aaaba36d1b5--- /dev/null+++ b/apps/desktop/src/app/settings/connections-settings.test.tsx@@ -0,0 +1,101 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { DesktopConnectionsRegistry } from '@/global'++import { ConnectionsSettings } from './connections-settings'++const list = vi.fn()+const save = vi.fn()+const remove = vi.fn()+const setPrimary = vi.fn()+const test = vi.fn()++const registry: DesktopConnectionsRegistry = {+ connections: [+ { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false },+ {+ authMode: 'token',+ id: 'homelab',+ kind: 'remote',+ label: 'Homelab',+ tokenPreview: '...abc123',+ tokenSet: true,+ url: 'http://homelab.lan:9119'+ }+ ],+ primary: 'local',+ version: 2+}++beforeEach(() => {+ list.mockResolvedValue(registry)+ save.mockResolvedValue({ connection: registry.connections[1], ok: true, registry })+ remove.mockResolvedValue({ ok: true, registry: { ...registry, connections: [registry.connections[0]] } })+ setPrimary.mockResolvedValue({ ok: true, registry: { ...registry, primary: 'homelab' } })+ test.mockResolvedValue({ ok: true, reachable: true })+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { connections: { list, remove, save, setPrimary, test } }+ })+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('ConnectionsSettings', () => {+ it('lists registered connections with primary + local pills', async () => {+ render(<ConnectionsSettings />)++ await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy())+ // Label and the managed pill share the copy, so expect both instances.+ expect(screen.getAllByText('This device').length).toBeGreaterThan(0)+ expect(screen.getByText('Primary')).toBeTruthy()+ expect(list).toHaveBeenCalledTimes(1)+ })++ it('opens the add-connection editor and saves with a required label', async () => {+ render(<ConnectionsSettings />)++ await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy())+ fireEvent.click(screen.getByText('Add connection'))++ // Save is disabled until a label is present.+ const saveButton = screen.getByText('Save connection').closest('button')!+ expect(saveButton.disabled).toBe(true)++ fireEvent.change(screen.getByPlaceholderText('Homelab'), { target: { value: 'Spark box' } })+ fireEvent.change(screen.getByPlaceholderText('http://homelab.lan:9119'), {+ target: { value: 'http://spark.lan:9119' }+ })+ expect(saveButton.disabled).toBe(false)+ fireEvent.click(saveButton)++ await waitFor(() => expect(save).toHaveBeenCalledTimes(1))+ expect(save.mock.calls[0][0]).toMatchObject({+ kind: 'remote',+ label: 'Spark box',+ url: 'http://spark.lan:9119'+ })+ })++ it('makes a non-primary connection primary', async () => {+ render(<ConnectionsSettings />)++ await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy())+ fireEvent.click(screen.getByText('Make primary'))++ await waitFor(() => expect(setPrimary).toHaveBeenCalledWith('homelab'))+ })++ it('tests a connection through the bridge', async () => {+ render(<ConnectionsSettings />)++ await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy())+ fireEvent.click(screen.getAllByText('Test')[0])++ await waitFor(() => expect(test).toHaveBeenCalled())+ })+})diff --git a/apps/desktop/src/app/settings/connections-settings.tsx b/apps/desktop/src/app/settings/connections-settings.tsxnew file mode 100644index 00000000000..ef793cd1ea6--- /dev/null+++ b/apps/desktop/src/app/settings/connections-settings.tsx@@ -0,0 +1,419 @@+import { useCallback, useEffect, useState } from 'react'++import { Button } from '@/components/ui/button'+import { ConfirmDialog } from '@/components/ui/confirm-dialog'+import { Input } from '@/components/ui/input'+import type {+ DesktopConnectionKind,+ DesktopConnectionsRegistry,+ DesktopRegistryConnection,+ DesktopRegistryConnectionInput+} from '@/global'+import { useI18n } from '@/i18n'+import { triggerHaptic } from '@/lib/haptics'+import { Cloud, Globe, Loader2, Monitor, Pencil, Plus, Terminal, Trash2 } from '@/lib/icons'+import { notify, notifyError } from '@/store/notifications'++import { EmptyState, ListRow, Pill, SectionHeading, SettingsContent, SettingsSkeleton } from './primitives'++const KIND_ICONS: Record<DesktopConnectionKind, typeof Globe> = {+ cloud: Cloud,+ local: Monitor,+ remote: Globe,+ ssh: Terminal+}++interface EditorState {+ // null id → creating a new connection.+ id: null | string+ kind: DesktopConnectionKind+ label: string+ url: string+ authMode: 'oauth' | 'token'+ token: string+ host: string+ user: string+ port: string+ keyPath: string+}++function editorFromConnection(conn: DesktopRegistryConnection): EditorState {+ return {+ id: conn.id,+ kind: conn.kind,+ label: conn.label,+ url: conn.url || '',+ authMode: conn.authMode || 'token',+ token: '',+ host: conn.host || '',+ user: conn.user || '',+ port: conn.port ? String(conn.port) : '',+ keyPath: conn.keyPath || ''+ }+}++function emptyEditor(kind: DesktopConnectionKind): EditorState {+ return { id: null, kind, label: '', url: '', authMode: 'token', token: '', host: '', user: '', port: '', keyPath: '' }+}++/**+ * Settings → Connections: manage the registry of named agent sources (local+ * runtime + any number of remote gateways / Hermes Cloud instances / SSH+ * hosts). Storage-level management only — the active/primary switchover UX+ * stays in Settings → Gateway until the routing generalization lands.+ */+export function ConnectionsSettings() {+ const { t } = useI18n()+ const s = t.settings.connections+ const [registry, setRegistry] = useState<DesktopConnectionsRegistry | null>(null)+ const [loading, setLoading] = useState(true)+ const [editor, setEditor] = useState<EditorState | null>(null)+ const [saving, setSaving] = useState(false)+ const [busyId, setBusyId] = useState<null | string>(null)+ const [testingId, setTestingId] = useState<null | string>(null)+ const [removeTarget, setRemoveTarget] = useState<DesktopRegistryConnection | null>(null)++ const bridge = window.hermesDesktop?.connections++ const load = useCallback(async () => {+ if (!bridge) {+ setLoading(false)++ return+ }++ setLoading(true)++ try {+ setRegistry(await bridge.list())+ } catch (err) {+ notifyError(err, s.loadFailed)+ } finally {+ setLoading(false)+ }+ }, [bridge, s.loadFailed])++ useEffect(() => {+ void load()+ }, [load])++ const save = useCallback(async () => {+ if (!bridge || !editor) {+ return+ }++ setSaving(true)++ try {+ const payload: DesktopRegistryConnectionInput = {+ kind: editor.kind,+ label: editor.label+ }++ if (editor.id) {+ payload.id = editor.id+ }++ if (editor.kind === 'remote' || editor.kind === 'cloud') {+ payload.url = editor.url+ payload.authMode = editor.authMode++ if (editor.token.trim()) {+ payload.token = editor.token.trim()+ }+ } else if (editor.kind === 'ssh') {+ payload.host = editor.host+ payload.user = editor.user || undefined+ payload.port = editor.port.trim() ? Number(editor.port) : null+ payload.keyPath = editor.keyPath || undefined+ }++ const result = await bridge.save(payload)+ setRegistry(result.registry)+ setEditor(null)+ } catch (err) {+ notifyError(err, s.saveFailed)+ } finally {+ setSaving(false)+ }+ }, [bridge, editor, s.saveFailed])++ const remove = useCallback(async () => {+ if (!bridge || !removeTarget) {+ return+ }++ setBusyId(removeTarget.id)++ try {+ const result = await bridge.remove(removeTarget.id)+ setRegistry(result.registry)+ } catch (err) {+ notifyError(err, s.removeFailed)+ } finally {+ setBusyId(null)+ setRemoveTarget(null)+ }+ }, [bridge, removeTarget, s.removeFailed])++ const makePrimary = useCallback(+ async (id: string) => {+ if (!bridge) {+ return+ }++ setBusyId(id)++ try {+ const result = await bridge.setPrimary(id)+ setRegistry(result.registry)+ } catch (err) {+ notifyError(err, s.saveFailed)+ } finally {+ setBusyId(null)+ }+ },+ [bridge, s.saveFailed]+ )++ const test = useCallback(+ async (conn: DesktopRegistryConnection) => {+ if (!bridge) {+ return+ }++ setTestingId(conn.id)++ try {+ const result = await bridge.test(conn.id)+ const reachable = result.ok === true || result.reachable === true++ if (reachable) {+ notify({ title: conn.label, message: s.testOk })+ } else {+ notifyError(new Error(result.error || s.testFailed), conn.label)+ }+ } catch (err) {+ notifyError(err, s.testFailed)+ } finally {+ setTestingId(null)+ }+ },+ [bridge, s.testFailed, s.testOk]+ )++ const kindMeta: Record<DesktopConnectionKind, { label: string; desc: string }> = {+ cloud: { desc: s.kindCloudDesc, label: s.kindCloud },+ local: { desc: s.kindLocalDesc, label: s.kindLocal },+ remote: { desc: s.kindRemoteDesc, label: s.kindRemote },+ ssh: { desc: s.kindSshDesc, label: s.kindSsh }+ }++ if (loading) {+ return <SettingsSkeleton />+ }++ return (+ <SettingsContent>+ <SectionHeading icon={Globe} title={s.title} />+ <p className="mb-4 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{s.intro}</p>++ {!registry || registry.connections.length === 0 ? (+ <EmptyState title={s.empty} />+ ) : (+ registry.connections.map(conn => {+ const Icon = KIND_ICONS[conn.kind]+ const isPrimary = registry.primary === conn.id+ const busy = busyId === conn.id++ return (+ <ListRow+ action={+ <div className="flex items-center gap-2">+ <Button+ disabled={testingId === conn.id}+ onClick={() => {+ triggerHaptic('selection')+ void test(conn)+ }}+ size="sm"+ variant="outline"+ >+ {testingId === conn.id ? <Loader2 className="size-3.5 animate-spin" /> : s.testConnection}+ </Button>+ {!isPrimary && (+ <Button disabled={busy} onClick={() => void makePrimary(conn.id)} size="sm" variant="outline">+ {s.makePrimary}+ </Button>+ )}+ {conn.kind !== 'local' && (+ <>+ <Button+ aria-label={s.editConnection}+ onClick={() => setEditor(editorFromConnection(conn))}+ size="icon-sm"+ variant="ghost"+ >+ <Pencil className="size-3.5" />+ </Button>+ <Button+ aria-label={s.removeConnection}+ disabled={busy}+ onClick={() => setRemoveTarget(conn)}+ size="icon-sm"+ variant="ghost"+ >+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Trash2 className="size-3.5" />}+ </Button>+ </>+ )}+ </div>+ }+ description={+ conn.kind === 'ssh'+ ? `${kindMeta[conn.kind].label} · ${conn.user ? `${conn.user}@` : ''}${conn.host}${conn.port ? `:${conn.port}` : ''}`+ : conn.url+ ? `${kindMeta[conn.kind].label} · ${conn.url}`+ : kindMeta[conn.kind].desc+ }+ key={conn.id}+ title={+ <span className="flex items-center gap-2">+ <Icon className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate">{conn.label}</span>+ {isPrimary && <Pill tone="primary">{s.primaryPill}</Pill>}+ {conn.kind === 'local' && <Pill>{s.managedPill}</Pill>}+ </span>+ }+ />+ )+ })+ )}++ {editor ? (+ <div className="mt-4 space-y-3 rounded-lg border border-border/60 p-4">+ <div className="grid grid-cols-2 gap-2 @2xl:grid-cols-4">+ {(['remote', 'cloud', 'ssh'] as const).map(kind => (+ <Button+ disabled={Boolean(editor.id)}+ key={kind}+ onClick={() => setEditor({ ...editor, kind })}+ size="sm"+ variant={editor.kind === kind ? 'default' : 'outline'}+ >+ {kindMeta[kind].label}+ </Button>+ ))}+ </div>+ <p className="text-xs text-muted-foreground">{kindMeta[editor.kind].desc}</p>++ <ListRow+ action={+ <Input+ onChange={e => setEditor({ ...editor, label: e.target.value })}+ placeholder={s.labelPlaceholder}+ value={editor.label}+ />+ }+ description={s.labelDesc}+ title={s.labelTitle}+ />++ {(editor.kind === 'remote' || editor.kind === 'cloud') && (+ <ListRow+ action={+ <Input+ onChange={e => setEditor({ ...editor, url: e.target.value })}+ placeholder="http://homelab.lan:9119"+ value={editor.url}+ />+ }+ title={s.urlTitle}+ />+ )}++ {editor.kind === 'remote' && (+ <>+ <ListRow+ action={+ <div className="flex gap-2">+ {(['token', 'oauth'] as const).map(mode => (+ <Button+ key={mode}+ onClick={() => setEditor({ ...editor, authMode: mode })}+ size="sm"+ variant={editor.authMode === mode ? 'default' : 'outline'}+ >+ {mode === 'token' ? t.settings.gateway.tokenTitle : 'OAuth'}+ </Button>+ ))}+ </div>+ }+ title={t.settings.gateway.authTitle}+ />+ {editor.authMode === 'token' && (+ <ListRow+ action={+ <Input+ onChange={e => setEditor({ ...editor, token: e.target.value })}+ placeholder={t.settings.gateway.pasteSessionToken}+ type="password"+ value={editor.token}+ />+ }+ description={t.settings.gateway.tokenDesc}+ title={t.settings.gateway.tokenTitle}+ />+ )}+ </>+ )}++ {editor.kind === 'ssh' && (+ <ListRow+ action={+ <Input+ onChange={e => setEditor({ ...editor, host: e.target.value })}+ placeholder="user@host:22"+ value={editor.host}+ />+ }+ title={s.sshHostTitle}+ />+ )}++ <div className="flex justify-end gap-2">+ <Button disabled={saving} onClick={() => setEditor(null)} size="sm" variant="ghost">+ {s.cancel}+ </Button>+ <Button disabled={saving || !editor.label.trim()} onClick={() => void save()} size="sm">+ {saving ? s.saving : s.save}+ </Button>+ </div>+ </div>+ ) : (+ <div className="mt-4">+ <Button+ onClick={() => {+ triggerHaptic('selection')+ setEditor(emptyEditor('remote'))+ }}+ size="sm"+ variant="outline"+ >+ <Plus className="size-3.5" /> {s.addConnection}+ </Button>+ </div>+ )}++ <ConfirmDialog+ confirmLabel={s.removeConnection}+ description={removeTarget ? s.removeConfirmDesc(removeTarget.label) : ''}+ destructive+ onClose={() => setRemoveTarget(null)}+ onConfirm={() => remove()}+ open={Boolean(removeTarget)}+ title={s.removeConfirmTitle}+ />+ </SettingsContent>+ )+}diff --git a/apps/desktop/src/app/settings/index.tsx b/apps/desktop/src/app/settings/index.tsxindex f55503702b4..7a8d45c7f56 100644--- a/apps/desktop/src/app/settings/index.tsx+++ b/apps/desktop/src/app/settings/index.tsx@@ -15,6 +15,7 @@ import {Info,Keyboard,KeyRound,+ Network,Package,RefreshCw,Settings2,@@ -34,6 +35,7 @@ import { AboutSettings } from './about-settings'import { AppearanceSettings } from './appearance-settings'import { BillingSettings } from './billing'import { ConfigSettings } from './config-settings'+import { ConnectionsSettings } from './connections-settings'import { SECTIONS } from './constants'import { GatewaySettings } from './gateway-settings'import { KeybindSettings } from './keybind-settings'@@ -48,6 +50,7 @@ const SETTINGS_VIEWS: readonly SettingsViewId[] = [...SECTIONS.map(s => `config:${s.id}` as SettingsViewId),'providers','gateway',+ 'connections','keybinds','keys','notifications',@@ -206,6 +209,13 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Setlabel: t.settings.nav.gateway,onSelect: () => setActiveView('gateway')},+ {+ active: activeView === 'connections',+ icon: Network,+ id: 'connections',+ label: t.settings.nav.connections,+ onSelect: () => setActiveView('connections')+ },{active: activeView === 'keybinds',icon: Keyboard,@@ -305,6 +315,8 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set<AboutSettings />) : activeView === 'gateway' ? (<GatewaySettings />+ ) : activeView === 'connections' ? (+ <ConnectionsSettings />) : activeView === 'keybinds' ? (<KeybindSettings />) : activeView.startsWith('config:') ? (diff --git a/apps/desktop/src/app/settings/types.ts b/apps/desktop/src/app/settings/types.tsindex 2828609ef63..5ecdf27a4a2 100644--- a/apps/desktop/src/app/settings/types.ts+++ b/apps/desktop/src/app/settings/types.ts@@ -7,6 +7,7 @@ import type { EnvVarInfo } from '@/types/hermes'export type SettingsView =| 'about'| 'billing'+ | 'connections'| 'gateway'| 'keybinds'| 'keys'diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 6d383b98ca6..4c504c84ba6 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -117,6 +117,17 @@ declare global {saveConnectionConfig: (payload: DesktopConnectionConfigInput) => Promise<DesktopConnectionConfig>applyConnectionConfig: (payload: DesktopConnectionConfigInput) => Promise<DesktopConnectionConfig>testConnectionConfig: (payload: DesktopConnectionConfigInput) => Promise<DesktopConnectionTestResult>+ // v2 multi-connection registry: named agent sources, all persisted+ // together (local + any number of remote/cloud/ssh instances).+ connections: {+ list: () => Promise<DesktopConnectionsRegistry>+ save: (+ payload: DesktopRegistryConnectionInput+ ) => Promise<{ ok: boolean; connection: DesktopRegistryConnection; registry: DesktopConnectionsRegistry }>+ remove: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>+ setPrimary: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>+ test: (id: string) => Promise<DesktopConnectionTestResult>+ }sshConfigHosts: () => Promise<DesktopSshHostsResult>sshResolveHost: (host: string) => Promise<DesktopSshResolveResult>probeConnectionConfig: (remoteUrl: string) => Promise<DesktopConnectionProbeResult>@@ -657,6 +668,56 @@ export interface DesktopConnectionTestResult {remotePlatform?: string}+// ── v2 multi-connection registry (named agent sources) ─────────────────────++export type DesktopConnectionKind = 'cloud' | 'local' | 'remote' | 'ssh'++// A registered agent source as the renderer sees it: token bytes never cross+// the IPC boundary (preview + set flag instead, like DesktopConnectionConfig).+export interface DesktopRegistryConnection {+ id: string+ kind: DesktopConnectionKind+ // Required, registry-unique device name ("Homelab", "Work laptop").+ label: string+ url?: string+ authMode?: 'oauth' | 'token'+ org?: string+ host?: string+ user?: string+ port?: number+ keyPath?: string+ remoteHermesPath?: string+ remoteProfile?: string+ tokenSet: boolean+ tokenPreview: null | string+}++export interface DesktopConnectionsRegistry {+ version: number+ // id of the connection that owns the window/primary backend.+ primary: string+ connections: DesktopRegistryConnection[]+}++export interface DesktopRegistryConnectionInput {+ // Present for edits; omitted on create (the main process mints the id).+ id?: string+ kind: DesktopConnectionKind+ label: string+ url?: string+ authMode?: 'oauth' | 'token'+ // Plaintext token to store (encrypted at rest); omit to keep the saved one.+ token?: string+ allowPlainTextToken?: boolean+ org?: string+ host?: string+ user?: string+ port?: null | number+ keyPath?: string+ remoteHermesPath?: string+ remoteProfile?: string+}+export interface DesktopSshResolveResult {hostname: string | nullidentityFile: string | nulldiff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex d8bafbb7bba..7ebd6d70dd0 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -345,6 +345,7 @@ export const en: Translations = {providerApiKeys: 'API keys',providerCustomEndpoints: 'Custom Endpoints',gateway: 'Gateway',+ connections: 'Connections',apiKeys: 'Tools & Keys',keybinds: 'Keyboard Shortcuts',keysTools: 'Tools',@@ -621,6 +622,46 @@ export const en: Translations = {set: 'Set',clear: 'Clear'},+ // v2 multi-connection registry: Settings → Connections.+ connections: {+ title: 'Connections',+ intro:+ 'Register every place your agents live — this device, remote gateways on your network, and Hermes Cloud instances — and use them side by side.',+ loading: 'Loading connections…',+ loadFailed: 'Could not load connections',+ primaryPill: 'Primary',+ managedPill: 'This device',+ addConnection: 'Add connection',+ editConnection: 'Edit',+ removeConnection: 'Remove',+ removeConfirmTitle: 'Remove this connection?',+ removeConfirmDesc: (label: string) =>+ `“${label}” will be removed from this app. The instance itself is not touched — you can add it again any time.`,+ makePrimary: 'Make primary',+ testConnection: 'Test',+ testing: 'Testing…',+ testOk: 'Reachable',+ testFailed: 'Connection test failed',+ saveFailed: 'Could not save the connection',+ removeFailed: 'Could not remove the connection',+ kindLocal: 'Local',+ kindRemote: 'Remote gateway',+ kindCloud: 'Hermes Cloud',+ kindSsh: 'SSH',+ kindLocalDesc: 'The Hermes runtime managed by this app.',+ kindRemoteDesc: 'A Hermes gateway reachable over HTTP(S) — LAN, Tailscale, or the internet.',+ kindCloudDesc: 'A hosted instance discovered through your Hermes Cloud account.',+ kindSshDesc: 'A Hermes install reached over SSH.',+ labelTitle: 'Name',+ labelDesc: 'Required. Shown everywhere this instance appears; must be unique (e.g. “Homelab”, “Work laptop”).',+ labelPlaceholder: 'Homelab',+ urlTitle: 'Gateway URL',+ sshHostTitle: 'SSH host',+ save: 'Save connection',+ saving: 'Saving…',+ cancel: 'Cancel',+ empty: 'No connections registered yet.'+ },gateway: {loading: 'Loading gateway settings...',unavailableTitle: 'Gateway settings unavailable',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex fb994d6de9a..a7f021a291a 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -295,6 +295,7 @@ export interface Translations {providerApiKeys: stringproviderCustomEndpoints: stringgateway: string+ connections: stringapiKeys: stringkeybinds: stringkeysTools: string@@ -515,6 +516,44 @@ export interface Translations {set: stringclear: string}+ // v2 multi-connection registry: Settings → Connections.+ connections: {+ title: string+ intro: string+ loading: string+ loadFailed: string+ primaryPill: string+ managedPill: string+ addConnection: string+ editConnection: string+ removeConnection: string+ removeConfirmTitle: string+ removeConfirmDesc: (label: string) => string+ makePrimary: string+ testConnection: string+ testing: string+ testOk: string+ testFailed: string+ saveFailed: string+ removeFailed: string+ kindLocal: string+ kindRemote: string+ kindCloud: string+ kindSsh: string+ kindLocalDesc: string+ kindRemoteDesc: string+ kindCloudDesc: string+ kindSshDesc: string+ labelTitle: string+ labelDesc: string+ labelPlaceholder: string+ urlTitle: string+ sshHostTitle: string+ save: string+ saving: string+ cancel: string+ empty: string+ }gateway: {loading: stringunavailableTitle: stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 69c9c0680ad..18186fe2cf0 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -334,6 +334,7 @@ export const zh: Translations = {providerApiKeys: 'API 密钥',providerCustomEndpoints: '自定义端点',gateway: '网关',+ connections: '连接',apiKeys: '工具与密钥',keybinds: '键盘快捷键',keysTools: '工具',@@ -828,6 +829,44 @@ export const zh: Translations = {set: '设置',clear: '清除'},+ // v2 多连接注册表:设置 → 连接。+ connections: {+ title: '连接',+ intro: '注册你的智能体所在的每个位置——本机、局域网中的远程网关、Hermes Cloud 实例——并同时使用它们。',+ loading: '正在加载连接…',+ loadFailed: '无法加载连接',+ primaryPill: '主连接',+ managedPill: '本机',+ addConnection: '添加连接',+ editConnection: '编辑',+ removeConnection: '移除',+ removeConfirmTitle: '移除此连接?',+ removeConfirmDesc: (label: string) => `“${label}”将从本应用移除。实例本身不受影响——你可以随时重新添加。`,+ makePrimary: '设为主连接',+ testConnection: '测试',+ testing: '测试中…',+ testOk: '可访问',+ testFailed: '连接测试失败',+ saveFailed: '无法保存连接',+ removeFailed: '无法移除连接',+ kindLocal: '本地',+ kindRemote: '远程网关',+ kindCloud: 'Hermes Cloud',+ kindSsh: 'SSH',+ kindLocalDesc: '由本应用管理的 Hermes 运行时。',+ kindRemoteDesc: '可通过 HTTP(S) 访问的 Hermes 网关——局域网、Tailscale 或互联网。',+ kindCloudDesc: '通过你的 Hermes Cloud 账户发现的托管实例。',+ kindSshDesc: '通过 SSH 访问的 Hermes 安装。',+ labelTitle: '名称',+ labelDesc: '必填。此实例出现的所有位置都会显示该名称;必须唯一(例如“家庭服务器”、“工作笔记本”)。',+ labelPlaceholder: '家庭服务器',+ urlTitle: '网关 URL',+ sshHostTitle: 'SSH 主机',+ save: '保存连接',+ saving: '保存中…',+ cancel: '取消',+ empty: '尚未注册任何连接。'+ },gateway: {loading: '正在加载网关设置...',unavailableTitle: '网关设置不可用',diff --git a/apps/desktop/src/lib/icons.ts b/apps/desktop/src/lib/icons.tsindex 6b3d5f80cc7..943dd1870a1 100644--- a/apps/desktop/src/lib/icons.ts+++ b/apps/desktop/src/lib/icons.ts@@ -80,6 +80,7 @@ import {IconDots as MoreHorizontal,IconDots as MoreHorizontalIcon,IconDotsVertical as MoreVertical,+ IconNetwork as Network,IconNotebook as NotebookTabs,IconPackage as Package,IconPalette as Palette,@@ -207,6 +208,7 @@ export {MoreHorizontal,MoreHorizontalIcon,MoreVertical,+ Network,NotebookTabs,Package,Palette,