Skip to content

The agent that grows with you

feat(desktop): multi-source agents end-to-end — sockets, roster, SDK, fan-out updates

Tekniumaff19d0251a8
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index 5e41b61187b..67ff99c92a1 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -14,6 +14,7 @@ import {
agentHandle,
backendScopeKey,
backendScopePrefix,
+ buildAgentRoster,
connectionIdForLabel,
labelKey,
labelSlug,
@@ -26,6 +27,7 @@ import {
removeConnection,
setPrimaryConnection,
uniqueLabel,
+ updateEligibility,
upsertConnection
} from './connection-registry'
@@ -74,6 +76,39 @@ test('uniqueLabel counts up (never "X 2 2") and clamps long candidates', () => {
// --- backendScopeKey (composite pool keys) ---
+// The electron and @hermes/shared implementations MUST stay byte-identical —
+// the renderer keys its socket registry with the shared copy while the main
+// process keys the backend pool with this one. This contract test is the
+// enforcement (see the NOTE on backendScopeKey).
+test('backendScopeKey: electron and shared implementations agree everywhere', async () => {
+ // Non-literal specifier on purpose: tsconfig.electron.json's project
+ // boundary excludes apps/shared sources, but vitest resolves the workspace
+ // package fine at runtime — which is exactly what this test needs.
+ const shared = (await import(String('@hermes/shared'))) as {
+ backendScopeKey: typeof backendScopeKey
+ backendScopePrefix: typeof backendScopePrefix
+ LOCAL_CONNECTION_ID: string
+ }
+
+ const cases: [null | string | undefined, null | string | undefined][] = [
+ [null, null],
+ [undefined, undefined],
+ ['', ''],
+ ['local', 'research'],
+ ['homelab', 'research'],
+ ['homelab', ''],
+ [' homelab ', ' research '],
+ ['spark-2', 'default']
+ ]
+
+ for (const [conn, profile] of cases) {
+ assert.equal(backendScopeKey(conn, profile), shared.backendScopeKey(conn, profile))
+ }
+
+ assert.equal(backendScopePrefix('homelab'), shared.backendScopePrefix('homelab'))
+ assert.equal(LOCAL_CONNECTION_ID, shared.LOCAL_CONNECTION_ID)
+})
+
test('backendScopeKey: local/empty connection keeps the bare profile key', () => {
assert.equal(backendScopeKey(null, 'research'), 'research')
assert.equal(backendScopeKey('', 'research'), 'research')
@@ -92,6 +127,54 @@ test('backendScopeKey: non-local connections get an unambiguous composite', () =
assert.ok(!'research'.startsWith(backendScopePrefix('homelab')))
})
+// --- buildAgentRoster (union roster + @name-device rule) ---
+
+test('roster: unique profiles keep bare handles; duplicates get @name-device', () => {
+ const local = { id: 'local', kind: 'local' as const, label: 'This device' }
+ const homelab = { id: 'homelab', kind: 'remote' as const, label: 'Homelab', url: 'http://h:1' }
+
+ const roster = buildAgentRoster([
+ { connection: local, profiles: ['default', 'research'] },
+ { connection: homelab, profiles: ['research', 'coder'] }
+ ])
+
+ const byKey = new Map(roster.map(a => [`${a.connectionId}/${a.profile}`, a.handle]))
+
+ // research exists on both sources → both disambiguate.
+ assert.equal(byKey.get('local/research'), 'research-this-device')
+ assert.equal(byKey.get('homelab/research'), 'research-homelab')
+ // default and coder are unique → bare names.
+ assert.equal(byKey.get('local/default'), 'default')
+ assert.equal(byKey.get('homelab/coder'), 'coder')
+ assert.equal(roster.length, 4)
+})
+
+test('roster: unreachable sources contribute no rows and cannot fake duplicates', () => {
+ const local = { id: 'local', kind: 'local' as const, label: 'This device' }
+ const dead = { id: 'dead', kind: 'remote' as const, label: 'Dead box', url: 'http://d:1' }
+
+ const roster = buildAgentRoster([
+ { connection: local, profiles: ['research'] },
+ { connection: dead, profiles: null, error: 'unreachable' }
+ ])
+
+ assert.equal(roster.length, 1)
+ // Only one live source has research → bare handle, no phantom duplicate.
+ assert.equal(roster[0].handle, 'research')
+})
+
+// --- updateEligibility ---
+
+test('update fan-out: cloud is platform-managed, everything else eligible', () => {
+ assert.deepEqual(updateEligibility({ id: 'c', kind: 'cloud', label: 'Cloud' }), {
+ eligible: false,
+ reason: 'cloud-managed'
+ })
+ assert.equal(updateEligibility({ id: 'local', kind: 'local', label: 'x' }).eligible, true)
+ assert.equal(updateEligibility({ id: 'r', kind: 'remote', label: 'x' }).eligible, true)
+ assert.equal(updateEligibility({ id: 's', kind: 'ssh', label: 'x' }).eligible, true)
+})
+
// --- normalizeConnectionInput ---
test('save rejects the reserved "local" id on non-local kinds', () => {
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index 9752aa2ca09..ca3c789d63c 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -140,8 +140,13 @@ export function agentHandle(profile: string, connectionLabel: string, duplicated
* log line, and touch call stays byte-identical for single-source users;
* non-local connections get an unambiguous composite (`conn:<id>::<profile>`)
* that cannot collide with a plain profile name (colons are invalid in
- * profile names). The single home of the composite-key rule — Electron pool
- * keying and any renderer socket registry must both derive keys here.
+ * profile names).
+ *
+ * NOTE: the renderer's socket registry uses the twin implementation in
+ * apps/shared/src/backend-scope.ts (`@hermes/shared`) — tsconfig project
+ * boundaries prevent a single physical module here. The two are pinned
+ * byte-identical by the cross-copy contract test in
+ * connection-registry.test.ts; change BOTH or that test fails.
*/
export function backendScopeKey(connectionId: null | string | undefined, profile: null | string | undefined): string {
const profileKey = String(profile ?? '').trim() || 'default'
@@ -159,6 +164,83 @@ export function backendScopePrefix(connectionId: string): string {
return `conn:${String(connectionId).trim()}::`
}
+// ── Union agent roster ──────────────────────────────────────────────────────
+
+export interface ConnectionAgents {
+ connection: RegistryConnection
+ /** Profile names enumerated from the connection, or null when unreachable /
+ * connect-on-demand (ssh not yet dialed). */
+ profiles: null | string[]
+ /** Present when profiles is null: why enumeration was skipped. */
+ error?: string
+}
+
+export interface RosterAgent {
+ connectionId: string
+ connectionKind: ConnectionKind
+ connectionLabel: string
+ profile: string
+ /** Bare profile name, or `<profile>-<label-slug>` when the profile name
+ * exists on more than one registered source (the @name-device rule). */
+ handle: string
+}
+
+/**
+ * Flatten per-connection profile enumerations into the union roster, applying
+ * the duplicate-handle rule ONCE across all sources. Pure so the disambiguation
+ * policy is testable without IPC; main.ts feeds it live enumerations.
+ */
+export function buildAgentRoster(enumerations: ConnectionAgents[]): RosterAgent[] {
+ const counts = new Map<string, number>()
+
+ for (const { profiles } of enumerations) {
+ for (const profile of profiles || []) {
+ const name = String(profile || '').trim() || 'default'
+ counts.set(name, (counts.get(name) || 0) + 1)
+ }
+ }
+
+ const roster: RosterAgent[] = []
+
+ for (const { connection, profiles } of enumerations) {
+ for (const profile of profiles || []) {
+ const name = String(profile || '').trim() || 'default'
+
+ roster.push({
+ connectionId: connection.id,
+ connectionKind: connection.kind,
+ connectionLabel: connection.label,
+ profile: name,
+ handle: agentHandle(name, connection.label, (counts.get(name) || 0) > 1)
+ })
+ }
+ }
+
+ return roster
+}
+
+// ── Fan-out update eligibility ──────────────────────────────────────────────
+
+export interface UpdateEligibility {
+ eligible: boolean
+ /** Present when not eligible: 'cloud-managed' (platform updates it). */
+ reason?: 'cloud-managed'
+}
+
+/**
+ * Whether "Update all instances" may drive this connection. Hermes Cloud
+ * instances are platform-managed — we never run `hermes update` against them.
+ * Local, remote, and ssh sources are all eligible (reachability and busy
+ * checks happen at dispatch time, not here).
+ */
+export function updateEligibility(connection: RegistryConnection): UpdateEligibility {
+ if (connection.kind === 'cloud') {
+ return { eligible: false, reason: 'cloud-managed' }
+ }
+
+ return { eligible: true }
+}
+
/** 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])
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index e55adacb0c7..a638d8e1d08 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -85,12 +85,14 @@ import {
import {
backendScopeKey,
backendScopePrefix,
+ buildAgentRoster,
mergeConnectionInput,
migrateV1ToRegistry,
normalizeConnectionInput,
normalizeRegistry,
removeConnection,
setPrimaryConnection,
+ updateEligibility,
upsertConnection
} from './connection-registry'
import { describeCrashReason, installCrashForensics } from './crash-forensics'
@@ -11915,6 +11917,156 @@ ipcMain.handle('hermes:connections:test', async (_event, id) => {
return { ok: true, baseUrl, version: status?.version || null }
})
+
+// ── Union agent roster + registry ws-url + fan-out updates (phase 3-5) ─────
+
+// Enumerate every registered connection's profiles concurrently and flatten
+// into the union roster. Eager REST enumeration, lazy sockets: local + already
+// -dialed sources answer instantly; unreachable ones return an error entry
+// instead of failing the whole roster. ssh sources that have never been dialed
+// are SKIPPED (connect-on-demand — dialing every ssh box just to list agents
+// would spawn tunnels the user never asked for); once dialed, their pooled
+// descriptor serves the enumeration like any remote.
+ipcMain.handle('hermes:agents:roster', async () => {
+ const registry = readDesktopConnectionsRegistry()
+
+ const enumerations = await Promise.all(
+ registry.connections.map(async connection => {
+ try {
+ if (
+ connection.kind === 'ssh' &&
+ ![...sshConnections.keys()].some(scope => String(scope).startsWith(backendScopePrefix(connection.id)))
+ ) {
+ return { connection, profiles: null, error: 'connect-on-demand' }
+ }
+
+ const descriptor: any = await ensureRegistryBackend(connection.id, null)
+ const body: any = await getJsonForBackend(descriptor, '/api/profiles', { timeoutMs: 8_000 })
+
+ const profiles = Array.isArray(body?.profiles)
+ ? body.profiles.map(p => String(p?.name || '').trim()).filter(Boolean)
+ : []
+
+ // The root HERMES_HOME is an agent too; enumerations that omit it
+ // (older backends list only named profiles) still get a default row.
+ if (!profiles.includes('default')) {
+ profiles.unshift('default')
+ }
+
+ return { connection, profiles }
+ } catch (error: any) {
+ return { connection, profiles: null, error: String(error?.message || error) }
+ }
+ })
+ )
+
+ return {
+ agents: buildAgentRoster(enumerations),
+ sources: enumerations.map(({ connection, profiles, error }) => ({
+ connectionId: connection.id,
+ label: connection.label,
+ kind: connection.kind,
+ reachable: profiles !== null,
+ ...(error ? { error } : {})
+ }))
+ }
+})
+
+// Registry-scoped fresh WS URL: the (connectionId, profile) analogue of
+// hermes:gateway:ws-url. Same single-use-ticket discipline for OAuth sources.
+ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {
+ const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)
+
+ return gatewayWsUrlIpcResult(async () => {
+ const connection: any = await ensureRegistryBackend(connectionId, profile)
+
+ if (connection.authMode === 'oauth') {
+ const ticket = await mintGatewayWsTicket(connection.baseUrl)
+
+ return buildGatewayWsUrlWithTicket(connection.baseUrl, ticket)
+ }
+
+ return connection.wsUrl
+ })
+})
+
+// Fan out `hermes update` to every eligible registered connection at once.
+// Cloud entries are excluded (platform-managed); each dispatch reports
+// independently so one dead LAN box can't wedge the batch. Local reuses the
+// app's own update pipeline; remote/ssh POST the backend's own
+// /api/hermes/update endpoint (the dashboard updater), which runs
+// `hermes update` on THAT machine.
+ipcMain.handle('hermes:connections:update-all', async () => {
+ const registry = readDesktopConnectionsRegistry()
+
+ const results = await Promise.all(
+ registry.connections.map(async connection => {
+ const base = { connectionId: connection.id, label: connection.label, kind: connection.kind }
+ const eligibility = updateEligibility(connection)
+
+ if (!eligibility.eligible) {
+ return { ...base, ok: false, skipped: true, reason: eligibility.reason }
+ }
+
+ try {
+ if (connection.kind === 'local') {
+ // The app-managed runtime updates through the same pipeline as the
+ // Settings → Updates button (marker + venv gate + relaunch flow).
+ const result: any = await applyUpdates({})
+
+ return { ...base, ok: result?.ok !== false, detail: result?.message || 'update started' }
+ }
+
+ const descriptor: any = await ensureRegistryBackend(connection.id, null)
+
+ const body: any = await postJsonForBackend(
+ descriptor,
+ '/api/hermes/update',
+ {},
+ { timeoutMs: 15_000 }
+ )
+
+ if (body?.ok === false) {
+ // The backend refused (docker/nix/externally-managed installs) —
+ // surface ITS message, per-row, instead of failing the batch.
+ return { ...base, ok: false, skipped: true, reason: body?.error || 'backend-refused', detail: body?.message }
+ }
+
+ return { ...base, ok: true, detail: body?.message || 'update started' }
+ } catch (error: any) {
+ return { ...base, ok: false, error: String(error?.message || error) }
+ }
+ })
+ )
+
+ return { ok: true, results }
+})
+
+// POST helper against a resolved backend descriptor. Token-auth descriptors
+// use the session-token header; OAuth descriptors have token: null and
+// authenticate via the OAuth partition's cookies (same split as the rest of
+// the REST surface).
+async function postJsonForBackend(descriptor, path, body, opts: any = {}) {
+ const url = `${descriptor.baseUrl}${path}`
+
+ if (descriptor.authMode === 'oauth') {
+ return fetchJsonViaOauthSession(url, { ...opts, body: body ?? {}, method: 'POST' })
+ }
+
+ return fetchJson(url, descriptor.token, { ...opts, body: body ?? {}, method: 'POST' })
+}
+
+// GET twin of postJsonForBackend — same token/cookie auth split.
+async function getJsonForBackend(descriptor, path, opts: any = {}) {
+ const url = `${descriptor.baseUrl}${path}`
+
+ if (descriptor.authMode === 'oauth') {
+ return fetchJsonViaOauthSession(url, opts)
+ }
+
+ return fetchJson(url, descriptor.token, opts)
+}
+
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.ts
index e6ff1ec104b..3c9f2ab1eb3 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -7,6 +7,11 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
revalidateConnection: () => ipcRenderer.invoke('hermes:connection:revalidate'),
touchBackend: profile => ipcRenderer.invoke('hermes:backend:touch', profile),
getGatewayWsUrl: profile => ipcRenderer.invoke('hermes:gateway:ws-url', profile),
+ // Registry-scoped fresh WS URL: { connectionId, profile } → result shape of
+ // getGatewayWsUrl, minted against that connection's backend.
+ getGatewayWsUrlFor: payload => ipcRenderer.invoke('hermes:gateway:ws-url-for', payload),
+ // Union agent roster across every registered connection.
+ getAgentRoster: () => ipcRenderer.invoke('hermes:agents:roster'),
openSessionWindow: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openSession', sessionId, opts),
openSessionInTerminal: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openInTerminal', sessionId, opts),
openWindow: () => ipcRenderer.invoke('hermes:window:openInstance'),
@@ -131,7 +136,9 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
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)
+ test: id => ipcRenderer.invoke('hermes:connections:test', id),
+ // Fan out `hermes update` to every eligible registered connection.
+ updateAll: () => ipcRenderer.invoke('hermes:connections:update-all')
},
sshConfigHosts: () => ipcRenderer.invoke('hermes:ssh-config:hosts'),
sshResolveHost: host => ipcRenderer.invoke('hermes:ssh-config:resolve', host),
diff --git a/apps/desktop/src/app/settings/connections-settings.tsx b/apps/desktop/src/app/settings/connections-settings.tsx
index 9f504b2ef8b..619531f3674 100644
--- a/apps/desktop/src/app/settings/connections-settings.tsx
+++ b/apps/desktop/src/app/settings/connections-settings.tsx
@@ -11,7 +11,7 @@ import type {
} from '@/global'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
-import { Cloud, Globe, Loader2, Monitor, Pencil, Plus, Terminal, Trash2 } from '@/lib/icons'
+import { Cloud, Globe, Loader2, Monitor, Pencil, Plus, RefreshCw, Terminal, Trash2 } from '@/lib/icons'
import { notify, notifyError } from '@/store/notifications'
import { EmptyState, ListRow, Pill, SectionHeading, SettingsContent, SettingsSkeleton } from './primitives'
@@ -74,6 +74,7 @@ export function ConnectionsSettings() {
const [testingId, setTestingId] = useState<null | string>(null)
const [removeTarget, setRemoveTarget] = useState<DesktopRegistryConnection | null>(null)
const [plainTextConfirm, setPlainTextConfirm] = useState(false)
+ const [updatingAll, setUpdatingAll] = useState(false)
const bridge = window.hermesDesktop?.connections
@@ -227,6 +228,34 @@ export function ConnectionsSettings() {
[bridge, s.testFailed, s.testOk]
)
+ // Fan out `hermes update` to every eligible source; per-connection results
+ // land as individual toasts so one dead box doesn't hide the others.
+ const updateAll = useCallback(async () => {
+ if (!bridge?.updateAll) {
+ return
+ }
+
+ setUpdatingAll(true)
+
+ try {
+ const { results } = await bridge.updateAll()
+
+ for (const row of results) {
+ if (row.ok) {
+ notify({ title: row.label, message: row.detail || s.updateAllDone })
+ } else if (row.skipped && row.reason === 'cloud-managed') {
+ notify({ title: row.label, message: s.updateSkippedCloud })
+ } else {
+ notifyError(new Error(row.error || row.detail || row.reason || row.label), s.updateAllFailed)
+ }
+ }
+ } catch (err) {
+ notifyError(err, s.updateAllFailed)
+ } finally {
+ setUpdatingAll(false)
+ }
+ }, [bridge, s.updateAllDone, s.updateAllFailed, s.updateSkippedCloud])
+
const kindMeta: Record<DesktopConnectionKind, { label: string; desc: string }> = {
cloud: { desc: s.kindCloudDesc, label: s.kindCloud },
local: { desc: s.kindLocalDesc, label: s.kindLocal },
@@ -425,7 +454,7 @@ export function ConnectionsSettings() {
</div>
</div>
) : (
- <div className="mt-4">
+ <div className="mt-4 flex items-center gap-2">
<Button
onClick={() => {
triggerHaptic('selection')
@@ -436,6 +465,27 @@ export function ConnectionsSettings() {
>
<Plus className="size-3.5" /> {s.addConnection}
</Button>
+ {bridge?.updateAll && (registry?.connections.length ?? 0) > 1 && (
+ <Button
+ disabled={updatingAll}
+ onClick={() => {
+ triggerHaptic('selection')
+ void updateAll()
+ }}
+ size="sm"
+ variant="outline"
+ >
+ {updatingAll ? (
+ <>
+ <Loader2 className="size-3.5 animate-spin" /> {s.updateAllRunning}
+ </>
+ ) : (
+ <>
+ <RefreshCw className="size-3.5" /> {s.updateAll}
+ </>
+ )}
+ </Button>
+ )}
</div>
)}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index def8874a34f..81aeadb2353 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -24,6 +24,13 @@ declare global {
connectionId?: null | string
profile?: null | string
}) => Promise<HermesConnection>
+ // Registry-scoped fresh WS URL (same result contract as getGatewayWsUrl).
+ getGatewayWsUrlFor?: (payload: {
+ connectionId?: null | string
+ profile?: null | string
+ }) => Promise<GatewayWsUrlResult>
+ // Union agent roster across every registered connection.
+ getAgentRoster?: () => Promise<DesktopAgentRoster>
// Reconnect-after-wake recovery: liveness-probe the cached PRIMARY backend
// and drop it if a remote one has gone unreachable, so the next
// getConnection() rebuilds a reachable descriptor instead of the renderer
@@ -133,6 +140,9 @@ declare global {
remove: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
setPrimary: (id: string) => Promise<{ ok: boolean; registry: DesktopConnectionsRegistry }>
test: (id: string) => Promise<DesktopConnectionTestResult>
+ // Fan out `hermes update` to every eligible registered connection;
+ // cloud entries are skipped (platform-managed), each row independent.
+ updateAll?: () => Promise<{ ok: boolean; results: DesktopConnectionUpdateResult[] }>
}
sshConfigHosts: () => Promise<DesktopSshHostsResult>
sshResolveHost: (host: string) => Promise<DesktopSshResolveResult>
@@ -743,6 +753,39 @@ export interface DesktopRegistryConnectionInput {
remoteProfile?: string
}
+// One agent in the union roster: a profile on a registered source, with the
+// pre-computed @name-device handle for duplicate profile names.
+export interface DesktopRosterAgent {
+ connectionId: string
+ connectionKind: DesktopConnectionKind
+ connectionLabel: string
+ profile: string
+ handle: string
+}
+
+export interface DesktopAgentRoster {
+ agents: DesktopRosterAgent[]
+ sources: {
+ connectionId: string
+ label: string
+ kind: DesktopConnectionKind
+ reachable: boolean
+ error?: string
+ }[]
+}
+
+// Per-connection result row from the update fan-out.
+export interface DesktopConnectionUpdateResult {
+ connectionId: string
+ label: string
+ kind: DesktopConnectionKind
+ ok: boolean
+ skipped?: boolean
+ reason?: string
+ detail?: string
+ error?: string
+}
+
export interface DesktopSshResolveResult {
hostname: string | null
identityFile: string | null
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index b1cd4282018..25d1cc34ee8 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -642,7 +642,7 @@ export const en: Translations = {
intro:
'Register every place your agents live — this device, remote gateways on your network, and Hermes Cloud instances. All of them are stored here.',
stagedNote:
- 'Side-by-side routing is rolling out in stages: connections are managed here today, while the active connection is still chosen in Settings → Gateway.',
+ 'Chats and the agent roster follow the source you pick; the app-managed window backend is still chosen in Settings → Gateway.',
loadFailed: 'Could not load connections',
primaryPill: 'Primary',
managedPill: 'This device',
@@ -658,6 +658,11 @@ export const en: Translations = {
testFailed: 'Connection test failed',
saveFailed: 'Could not save the connection',
removeFailed: 'Could not remove the connection',
+ updateAll: 'Update all instances',
+ updateAllRunning: 'Updating all instances…',
+ updateAllDone: 'Updates dispatched',
+ updateAllFailed: 'Update fan-out failed',
+ updateSkippedCloud: 'Managed by Hermes Cloud',
kindLocal: 'Local',
kindRemote: 'Remote gateway',
kindCloud: 'Hermes Cloud',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index d8b4b008424..4cff6eee18a 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -547,6 +547,11 @@ export interface Translations {
testFailed: string
saveFailed: string
removeFailed: string
+ updateAll: string
+ updateAllRunning: string
+ updateAllDone: string
+ updateAllFailed: string
+ updateSkippedCloud: string
kindLocal: string
kindRemote: string
kindCloud: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index fa0ad3bd675..11f06c02c23 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -847,7 +847,7 @@ export const zh: Translations = {
connections: {
title: '连接',
intro: '注册你的智能体所在的每个位置——本机、局域网中的远程网关、Hermes Cloud 实例——全部保存在这里。',
- stagedNote: '多来源路由正在分阶段推出:目前在此管理连接,活动连接仍在“设置 → 网关”中选择。',
+ stagedNote: '聊天和智能体列表会跟随你选择的来源;应用管理的窗口后端仍在“设置 → 网关”中选择。',
loadFailed: '无法加载连接',
primaryPill: '主连接',
managedPill: '本机',
@@ -862,6 +862,11 @@ export const zh: Translations = {
testFailed: '连接测试失败',
saveFailed: '无法保存连接',
removeFailed: '无法移除连接',
+ updateAll: '更新所有实例',
+ updateAllRunning: '正在更新所有实例…',
+ updateAllDone: '更新已分发',
+ updateAllFailed: '批量更新失败',
+ updateSkippedCloud: '由 Hermes Cloud 托管',
kindLocal: '本地',
kindRemote: '远程网关',
kindCloud: 'Hermes Cloud',
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index adf70aa325f..a2e81f64858 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -24,7 +24,7 @@ import { openSession, type OpenSessionIntent } from '@/app/open-session'
import { $narrowViewport } from '@/components/pane-shell/tree/store'
import { onGatewayEvent } from '@/contrib/events'
import { getLogs, getStatus } from '@/hermes'
-import { $gateway, openGatewayForProfile } from '@/store/gateway'
+import { $gateway, ensureGatewayForAgent, openGatewayForAgent, openGatewayForProfile } from '@/store/gateway'
import { notify, notifyError } from '@/store/notifications'
import { $activeGatewayProfile, ensureGatewayProfile, newSessionInProfile, setShowAllProfiles } from '@/store/profile'
import { $activeSessionId, $currentCwd, $currentModel, $gatewayState } from '@/store/session'
@@ -113,6 +113,47 @@ export const host = {
void openGatewayForProfile(name).catch(() => undefined)
},
+ // ── Multi-source agents (the Bot Mode door) ───────────────────────────────
+
+ /** The registered connection list (labels, kinds, primary) — token bytes
+ * never included. Rejects on Desktop builds without the registry. */
+ connections: async () => {
+ const bridge = window.hermesDesktop?.connections
+
+ if (!bridge) {
+ throw new Error('This Desktop build has no connection registry. Update Hermes Desktop.')
+ }
+
+ return bridge.list()
+ },
+
+ /** The union agent roster across every registered connection: one row per
+ * (source, profile) with the pre-computed @name-device handle for
+ * duplicates. Sources that are unreachable (or ssh connect-on-demand)
+ * appear in `sources` with an error instead of failing the call. */
+ agents: async () => {
+ const roster = window.hermesDesktop?.getAgentRoster
+
+ if (!roster) {
+ throw new Error('This Desktop build cannot enumerate multi-source agents. Update Hermes Desktop.')
+ }
+
+ return roster()
+ },
+
+ /** Pre-dial an agent's socket on ITS source — the (connection, profile)
+ * analogue of warmProfile. Fire-and-forget, same semantics. */
+ warmAgent: (connectionId: null | string, profile: string): void => {
+ void openGatewayForAgent(connectionId, (profile ?? '').trim() || 'default').catch(() => undefined)
+ },
+
+ /** Activate an agent's gateway (dialing it if needed) so subsequent
+ * host.request calls hit that agent's backend. The local source falls
+ * through to the profile path — single-source plugins keep working
+ * against older behavior unchanged. */
+ ensureAgent: async (connectionId: null | string, profile: string): Promise<void> =>
+ ensureGatewayForAgent(connectionId, (profile ?? '').trim() || 'default'),
+
openSession: async (
storedSessionId: string,
options: { intent?: OpenSessionIntent; keepAllProfilesScope?: boolean; profile?: null | string } = {}
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 8e73a1bfbf1..9c78d185d61 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -1,4 +1,4 @@
-import { type ConnectionState, type GatewayEvent, resolveGatewayWsUrl } from '@hermes/shared'
+import { backendScopeKey, type ConnectionState, type GatewayEvent, resolveGatewayWsUrl } from '@hermes/shared'
import { atom } from 'nanostores'
import { HermesGateway } from '@/hermes'
@@ -28,7 +28,11 @@ interface RegistryConfig {
// ── Secondary (pool) backends ──────────────────────────────────────────────
interface Secondary {
+ /** Scope key from backendScopeKey(connectionId, profile). */
+ scope: string
profile: string
+ /** Registry connection serving this socket; null = the local/legacy path. */
+ connectionId: null | string
gateway: HermesGateway
offEvent: () => void
offState: () => void
@@ -174,15 +178,31 @@ async function openSecondary(entry: Secondary): Promise<void> {
return
}
- const conn = await desktop.getConnection(entry.profile)
- const wsUrl = await resolveGatewayWsUrl(desktop, conn)
+ // Registry-scoped entries dial through getConnectionFor when the bridge has
+ // it (feature-detected: an older Electron main lacks the door and those
+ // entries simply can't exist yet — createSecondary guards creation).
+ const conn =
+ entry.connectionId && desktop.getConnectionFor
+ ? await desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile })
+ : await desktop.getConnection(entry.profile)
+
+ const wsUrl = await resolveGatewayWsUrl(
+ entry.connectionId && desktop.getGatewayWsUrlFor
+ ? {
+ getGatewayWsUrl: () =>
+ desktop.getGatewayWsUrlFor!({ connectionId: entry.connectionId, profile: entry.profile })
+ }
+ : desktop,
+ conn
+ )
+
await entry.gateway.connect(wsUrl)
- if (g.activeKey === entry.profile) {
+ if (g.activeKey === entry.scope) {
setConnection(conn)
}
- void desktop.touchBackend?.(entry.profile).catch(() => undefined)
+ void desktop.touchBackend?.(entry.scope).catch(() => undefined)
}
function scheduleReconnect(entry: Secondary): void {
@@ -221,11 +241,14 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {
}
}
-function createSecondary(profile: string): Secondary {
+function createSecondary(profile: string, connectionId: null | string = null): Secondary {
const gateway = new HermesGateway()
+ const scope = backendScopeKey(connectionId, profile)
const entry: Secondary = {
+ scope,
profile,
+ connectionId,
gateway,
offEvent: () => {},
offState: () => {},
@@ -235,9 +258,13 @@ function createSecondary(profile: string): Secondary {
wantOpen: true
}
- entry.offEvent = gateway.onEvent(event => g.config?.onEvent({ ...event, profile }))
+ // Events keep carrying the bare profile — session routing is profile-keyed
+ // everywhere. connectionId rides along for surfaces that need the source.
+ entry.offEvent = gateway.onEvent(event =>
+ g.config?.onEvent({ ...event, profile, ...(connectionId ? { connectionId } : {}) })
+ )
entry.offState = gateway.onState(state => {
- reportGatewayState(profile, state)
+ reportGatewayState(scope, state)
if (state === 'open') {
entry.reconnectAttempt = 0
@@ -247,7 +274,7 @@ function createSecondary(profile: string): Secondary {
}
})
- g.secondaries.set(profile, entry)
+ g.secondaries.set(scope, entry)
return entry
}
@@ -303,6 +330,65 @@ export async function openGatewayForProfile(profile: string): Promise<void> {
}
}
+// ── Connection-scoped agents (multi-source roster) ─────────────────────────
+// The (connectionId, profile) analogues of the profile functions above. A
+// null/'local' connectionId falls straight through to the profile path, so
+// callers can pass roster rows verbatim without special-casing the local
+// source. Feature-detected: without the Electron getConnectionFor door these
+// throw, and roster surfaces disable non-local rows instead.
+
+export async function openGatewayForAgent(connectionId: null | string, profile: string): Promise<void> {
+ const scope = backendScopeKey(connectionId, profile)
+
+ if (scope === normKey(profile)) {
+ return openGatewayForProfile(profile)
+ }
+
+ if (!window.hermesDesktop?.getConnectionFor) {
+ throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')
+ }
+
+ const entry = g.secondaries.get(scope) ?? createSecondary(profile, connectionId)
+ entry.wantOpen = true
+
+ if (!isOpen(entry.gateway)) {
+ await openSecondary(entry)
+ }
+}
+
+export async function ensureGatewayForAgent(connectionId: null | string, profile: string): Promise<void> {
+ const scope = backendScopeKey(connectionId, profile)
+
+ if (scope === normKey(profile)) {
+ return ensureGatewayForProfile(profile)
+ }
+
+ if (!window.hermesDesktop?.getConnectionFor) {
+ throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')
+ }
+
+ let entry = g.secondaries.get(scope)
+
+ if (!entry) {
+ entry = createSecondary(profile, connectionId)
+ }
+
+ entry.wantOpen = true
+
+ if (!isOpen(entry.gateway)) {
+ clearTimer(entry)
+ entry.reconnectAttempt = 0
+
+ try {
+ await openSecondary(entry)
+ } catch {
+ scheduleReconnect(entry)
+ }
+ }
+
+ setActive(scope)
+}
+
// 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> {
@@ -387,7 +473,7 @@ export function touchSecondaryGateways(): void {
for (const entry of g.secondaries.values()) {
if (entry.wantOpen) {
- void desktop?.touchBackend?.(entry.profile).catch(() => undefined)
+ void desktop?.touchBackend?.(entry.scope).catch(() => undefined)
}
}
}
@@ -404,9 +490,13 @@ function disposeSecondary(entry: Secondary): void {
// Close + evict secondaries whose profile is neither active nor in `keep`
// (profiles with a running / needs-input session). Bounds cost to live work.
+// `keep` carries PROFILE names (session ownership is profile-keyed), so a
+// registry-scoped entry survives when ITS profile has live work — matching on
+// the composite key alone would prune every non-local socket the moment the
+// user looks away.
export function pruneSecondaryGateways(keep: Set<string>): void {
for (const [key, entry] of [...g.secondaries]) {
- if (key === g.activeKey || keep.has(key)) {
+ if (key === g.activeKey || keep.has(key) || keep.has(entry.profile)) {
continue
}
diff --git a/apps/shared/src/backend-scope.ts b/apps/shared/src/backend-scope.ts
new file mode 100644
index 00000000000..0da9a73069c
--- /dev/null
+++ b/apps/shared/src/backend-scope.ts
@@ -0,0 +1,29 @@
+/**
+ * Composite backend scope keys for the multi-connection registry — shared
+ * between the Electron main process (backend pool keying) and the renderer
+ * (secondary socket registry), so both sides derive identical keys.
+ *
+ * The local/primary connection keeps the BARE profile key: every legacy pool
+ * entry, reaper log line, and touch call stays byte-identical for
+ * single-source users. Non-local connections get `conn:<id>::<profile>`,
+ * which cannot collide with a plain profile name (colons are invalid in
+ * profile names).
+ */
+
+export const LOCAL_CONNECTION_ID = 'local'
+
+export function backendScopeKey(connectionId: null | string | undefined, profile: null | string | undefined): string {
+ const profileKey = String(profile ?? '').trim() || 'default'
+ const connection = String(connectionId ?? '').trim()
+
+ if (!connection || connection === LOCAL_CONNECTION_ID) {
+ return profileKey
+ }
+
+ return `conn:${connection}::${profileKey}`
+}
+
+/** All pool keys owned by a connection share this prefix (teardown on remove). */
+export function backendScopePrefix(connectionId: string): string {
+ return `conn:${String(connectionId).trim()}::`
+}
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index 8a173429613..fd40c471744 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -1,3 +1,8 @@
+export {
+ backendScopeKey,
+ backendScopePrefix,
+ LOCAL_CONNECTION_ID
+} from './backend-scope'
export {
BILLING_REFUSAL_POLICY,
type BillingRecovery,
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index a881c806c4e..e46839937fa 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -238,7 +238,7 @@ Alongside the per-profile connection mode above, **Settings → Connections** ma
- Cloud entries come from the Hermes Cloud sign-in/discovery flow above, not from a hand-typed URL.
- Tokens are stored encrypted with the OS keyring (with the same explicit plain-text opt-in as Settings → Gateway on keyring-less Linux).
-Side-by-side routing is rolling out in stages: connections are managed here today, while the active connection is still chosen in **Settings → Gateway**. Follow-up releases route chats, the agent roster, and updates across all registered sources.
+Side-by-side routing is live: each registered source dials its own backends and sockets on demand (keyed per connection + profile), the plugin SDK exposes the union agent roster (`host.agents()` / `host.ensureAgent()`), and **Update all instances** in the Connections panel dispatches `hermes update` to every eligible source at once — Hermes Cloud entries are skipped (the platform updates them), and each instance reports its own result.
:::info The remote backend is a running `hermes serve` process