fix(desktop): one roster row per bot even when a backend is registered under two addresses — /api/status install_id + roster collapse
Backend: /api/status now carries a stable random install_id persisted once under the root HERMES_HOME, shared by every profile of the install. Desktop: roster enumeration captures it per connection (TTL-cached probe), buildAgentRoster collapses same-install rows with a deterministic canonical pick (active > local > ssh > remote > cloud > earliest), the @name-device handle rule runs after the collapse, and Settings → Gateways shows a display-only 'Same backend as' hint. Backends without install_id bypass the collapse (fully backward compatible).
This commit is contained in:
@@ -284,6 +284,137 @@ test('roster: duplicate profiles from one connection remain one routable agent',
|
||||
)
|
||||
})
|
||||
|
||||
// --- buildAgentRoster: same-backend (install_id) collapse ---
|
||||
|
||||
test('roster: two connections with the same install_id collapse to one row per profile', () => {
|
||||
const hostname = { id: 'spark', kind: 'remote' as const, label: 'Spark', url: 'http://spark:8642' }
|
||||
const tailscale = { id: 'spark-ts', kind: 'remote' as const, label: 'Spark TS', url: 'http://100.1.2.3:8642' }
|
||||
|
||||
const roster = buildAgentRoster([
|
||||
{ connection: hostname, profiles: ['default', 'research'], installId: 'aaa' },
|
||||
{ connection: tailscale, profiles: ['default', 'research'], installId: 'aaa' }
|
||||
])
|
||||
|
||||
// One row per (install, profile) — no duplicate bots for the same box.
|
||||
assert.deepEqual(
|
||||
roster.map(agent => `${agent.connectionId}/${agent.profile}`).sort(),
|
||||
['spark/default', 'spark/research']
|
||||
)
|
||||
// Handle disambiguation runs AFTER the collapse: no more suffixed names.
|
||||
assert.deepEqual(
|
||||
roster.map(agent => agent.handle).sort(),
|
||||
['default', 'research']
|
||||
)
|
||||
})
|
||||
|
||||
test('roster: collapse prefers the active (primary) connection', () => {
|
||||
const hostname = { id: 'spark', kind: 'remote' as const, label: 'Spark', url: 'http://spark:8642' }
|
||||
const tailscale = { id: 'spark-ts', kind: 'remote' as const, label: 'Spark TS', url: 'http://100.1.2.3:8642' }
|
||||
|
||||
const roster = buildAgentRoster(
|
||||
[
|
||||
{ connection: hostname, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: tailscale, profiles: ['default'], installId: 'aaa' }
|
||||
],
|
||||
{ primaryConnectionId: 'spark-ts' }
|
||||
)
|
||||
|
||||
assert.equal(roster.length, 1)
|
||||
assert.equal(roster[0].connectionId, 'spark-ts')
|
||||
})
|
||||
|
||||
test('roster: collapse pick order is local > ssh > remote > cloud, then registration order', () => {
|
||||
const local = { id: 'local', kind: 'local' as const, label: 'This device' }
|
||||
const remote = { id: 'loop', kind: 'remote' as const, label: 'Loopback', url: 'http://127.0.0.1:8642' }
|
||||
const cloud = { id: 'cl', kind: 'cloud' as const, label: 'Cloud twin', url: 'http://cl:1' }
|
||||
const ssh = { id: 'tun', kind: 'ssh' as const, label: 'Tunnel', host: 'box' }
|
||||
|
||||
// Same box registered four ways; primary is NOT one of them (unset).
|
||||
const roster = buildAgentRoster([
|
||||
{ connection: cloud, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: remote, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: ssh, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: local, profiles: ['default'], installId: 'aaa' }
|
||||
])
|
||||
|
||||
assert.equal(roster.length, 1)
|
||||
assert.equal(roster[0].connectionId, 'local')
|
||||
|
||||
// Without the local candidate, ssh wins over remote/cloud.
|
||||
const noLocal = buildAgentRoster([
|
||||
{ connection: cloud, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: remote, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: ssh, profiles: ['default'], installId: 'aaa' }
|
||||
])
|
||||
|
||||
assert.equal(noLocal[0].connectionId, 'tun')
|
||||
|
||||
// Same kind → earliest-registered (enumeration order) wins.
|
||||
const twin = { id: 'loop2', kind: 'remote' as const, label: 'Loopback 2', url: 'http://[::1]:8642' }
|
||||
const sameKind = buildAgentRoster([
|
||||
{ connection: remote, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: twin, profiles: ['default'], installId: 'aaa' }
|
||||
])
|
||||
|
||||
assert.equal(sameKind[0].connectionId, 'loop')
|
||||
})
|
||||
|
||||
test('roster: missing install_id bypasses the collapse (older backends keep current behavior)', () => {
|
||||
const hostname = { id: 'spark', kind: 'remote' as const, label: 'Spark', url: 'http://spark:8642' }
|
||||
const tailscale = { id: 'spark-ts', kind: 'remote' as const, label: 'Spark TS', url: 'http://100.1.2.3:8642' }
|
||||
|
||||
// Neither reports an id → both rows survive, handles disambiguate.
|
||||
const roster = buildAgentRoster([
|
||||
{ connection: hostname, profiles: ['default'] },
|
||||
{ connection: tailscale, profiles: ['default'] }
|
||||
])
|
||||
|
||||
assert.equal(roster.length, 2)
|
||||
assert.deepEqual(roster.map(a => a.handle).sort(), ['default-spark', 'default-spark-ts'])
|
||||
|
||||
// One id + one missing must NOT collapse either (undefined never matches).
|
||||
const mixed = buildAgentRoster([
|
||||
{ connection: hostname, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: tailscale, profiles: ['default'] }
|
||||
])
|
||||
|
||||
assert.equal(mixed.length, 2)
|
||||
})
|
||||
|
||||
test('roster: different install_ids stay separate rows with disambiguated handles', () => {
|
||||
const spark = { id: 'spark', kind: 'remote' as const, label: 'Spark', url: 'http://spark:8642' }
|
||||
const mini = { id: 'mini', kind: 'remote' as const, label: 'Mini', url: 'http://mini:8642' }
|
||||
|
||||
const roster = buildAgentRoster([
|
||||
{ connection: spark, profiles: ['default'], installId: 'aaa' },
|
||||
{ connection: mini, profiles: ['default'], installId: 'bbb' }
|
||||
])
|
||||
|
||||
assert.equal(roster.length, 2)
|
||||
assert.deepEqual(roster.map(a => a.handle).sort(), ['default-mini', 'default-spark'])
|
||||
})
|
||||
|
||||
test('roster: collapse also folds a third same-box connection from a per-profile v1 override import', () => {
|
||||
// The reporter's "profile with cron appears as another duplicate": the v1
|
||||
// migration imports per-profile override blocks as EXTRA connections, so a
|
||||
// cron profile pinned to the same box via a third URL becomes a third
|
||||
// registry entry. Same install_id → still one row per profile.
|
||||
const hostname = { id: 'spark', kind: 'remote' as const, label: 'Spark', url: 'http://spark:8642' }
|
||||
const tailscale = { id: 'spark-ts', kind: 'remote' as const, label: 'Spark TS', url: 'http://100.1.2.3:8642' }
|
||||
const override = { id: 'spark-lan', kind: 'remote' as const, label: 'Spark LAN', url: 'http://192.168.1.5:8642' }
|
||||
|
||||
const roster = buildAgentRoster([
|
||||
{ connection: hostname, profiles: ['default', 'cron-bot'], installId: 'aaa' },
|
||||
{ connection: tailscale, profiles: ['default', 'cron-bot'], installId: 'aaa' },
|
||||
{ connection: override, profiles: ['default', 'cron-bot'], installId: 'aaa' }
|
||||
])
|
||||
|
||||
assert.deepEqual(
|
||||
roster.map(agent => `${agent.profile}:${agent.handle}`).sort(),
|
||||
['cron-bot:cron-bot', 'default:default']
|
||||
)
|
||||
})
|
||||
|
||||
// --- updateEligibility ---
|
||||
|
||||
test('update fan-out: cloud is platform-managed, everything else eligible', () => {
|
||||
|
||||
@@ -242,6 +242,12 @@ export interface ConnectionAgents {
|
||||
profiles: null | string[]
|
||||
/** Present when profiles is null: why enumeration was skipped. */
|
||||
error?: string
|
||||
/** Stable backend identity from the connection's /api/status (`install_id`).
|
||||
* Two connections reporting the same id are the SAME physical install
|
||||
* registered under two addresses (hostname + Tailscale IP), so the roster
|
||||
* collapses their rows. Absent on older backends → no collapse (fully
|
||||
* backward compatible). */
|
||||
installId?: string
|
||||
}
|
||||
|
||||
export interface RosterAgent {
|
||||
@@ -333,33 +339,64 @@ export function parseRemoteProfileListing(text: string): string[] {
|
||||
* 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[] {
|
||||
export function buildAgentRoster(
|
||||
enumerations: ConnectionAgents[],
|
||||
opts: { primaryConnectionId?: string } = {}
|
||||
): RosterAgent[] {
|
||||
// A connection can transiently report the same profile more than once (or
|
||||
// arrive twice while registry state is reconciling). A roster row represents
|
||||
// one routable identity, so collapse strictly by connection + profile before
|
||||
// counting names for @name-device disambiguation.
|
||||
const identities = new Map<string, { connection: RegistryConnection; profile: string }>()
|
||||
const identities = new Map<
|
||||
string,
|
||||
{ connection: RegistryConnection; installId?: string; order: number; profile: string }
|
||||
>()
|
||||
let order = 0
|
||||
|
||||
for (const { connection, profiles } of enumerations) {
|
||||
for (const { connection, installId, profiles } of enumerations) {
|
||||
for (const profile of profiles || []) {
|
||||
const name = String(profile || '').trim() || 'default'
|
||||
const key = `${connection.id}\0${name}`
|
||||
|
||||
if (!identities.has(key)) {
|
||||
identities.set(key, { connection, profile: name })
|
||||
identities.set(key, { connection, installId, order, profile: name })
|
||||
}
|
||||
}
|
||||
|
||||
order += 1
|
||||
}
|
||||
|
||||
// Backend-identity collapse: two connections reporting the same install_id
|
||||
// are the SAME physical install registered under two addresses, so their
|
||||
// (install, profile) rows are one bot, not two. Connections without an id
|
||||
// (older backends, undialed ssh) keep a per-connection key — no collapse.
|
||||
const backends = new Map<string, { connection: RegistryConnection; order: number; profile: string }[]>()
|
||||
|
||||
for (const { connection, installId, order: rank, profile } of identities.values()) {
|
||||
const key = installId ? `id:${installId}\0${profile}` : `conn:${connection.id}\0${profile}`
|
||||
const group = backends.get(key)
|
||||
|
||||
if (group) {
|
||||
group.push({ connection, order: rank, profile })
|
||||
} else {
|
||||
backends.set(key, [{ connection, order: rank, profile }])
|
||||
}
|
||||
}
|
||||
|
||||
const rows = [...backends.values()].map(group => pickCanonicalConnection(group, opts.primaryConnectionId))
|
||||
|
||||
// The @name-device duplicate-handle rule runs AFTER the collapse, so a
|
||||
// profile that only *looked* duplicated (one box, two addresses) keeps its
|
||||
// bare name once the rows are recognized as one backend.
|
||||
const counts = new Map<string, number>()
|
||||
|
||||
for (const { profile } of identities.values()) {
|
||||
for (const { profile } of rows) {
|
||||
counts.set(profile, (counts.get(profile) || 0) + 1)
|
||||
}
|
||||
|
||||
const roster: RosterAgent[] = []
|
||||
|
||||
for (const { connection, profile } of identities.values()) {
|
||||
for (const { connection, profile } of rows) {
|
||||
roster.push({
|
||||
connectionId: connection.id,
|
||||
connectionKind: connection.kind,
|
||||
@@ -372,6 +409,32 @@ export function buildAgentRoster(enumerations: ConnectionAgents[]): RosterAgent[
|
||||
return roster
|
||||
}
|
||||
|
||||
/** Deterministic route priority for same-backend rows: local is definitionally
|
||||
* this box; ssh beats HTTP remotes; cloud last. */
|
||||
const CANONICAL_KIND_PRIORITY: Record<ConnectionKind, number> = { cloud: 3, local: 0, remote: 2, ssh: 1 }
|
||||
|
||||
/**
|
||||
* Which connection represents a collapsed same-backend roster row: the ACTIVE
|
||||
* (primary) connection when it is one of the candidates — the row should route
|
||||
* where the window already routes — else the highest kind priority, else the
|
||||
* earliest-registered (enumeration order follows registry order).
|
||||
*/
|
||||
function pickCanonicalConnection<T extends { connection: RegistryConnection; order: number }>(
|
||||
candidates: T[],
|
||||
primaryConnectionId?: string
|
||||
): T {
|
||||
const active = primaryConnectionId ? candidates.find(c => c.connection.id === primaryConnectionId) : undefined
|
||||
|
||||
if (active) {
|
||||
return active
|
||||
}
|
||||
|
||||
return [...candidates].sort(
|
||||
(a, b) =>
|
||||
CANONICAL_KIND_PRIORITY[a.connection.kind] - CANONICAL_KIND_PRIORITY[b.connection.kind] || a.order - b.order
|
||||
)[0]
|
||||
}
|
||||
|
||||
// ── Fan-out update eligibility ──────────────────────────────────────────────
|
||||
|
||||
export interface UpdateEligibility {
|
||||
|
||||
@@ -8200,11 +8200,16 @@ function writeDesktopConnectionsRegistry(registry) {
|
||||
function sanitizeRegistryConnection(entry) {
|
||||
const { token, headers, ...rest } = entry
|
||||
const decrypted = decryptDesktopSecret(token)
|
||||
// Last-known stable backend identity (from roster enumeration / Test) so
|
||||
// Settings can hint "Same backend as <label>" on connections that are two
|
||||
// addresses for one box. Display-only; absent until a probe has seen it.
|
||||
const knownInstallId = connectionInstallIds.get(entry.id)?.id
|
||||
|
||||
return {
|
||||
...rest,
|
||||
tokenSet: Boolean(decrypted),
|
||||
tokenPreview: tokenPreview(decrypted),
|
||||
...(knownInstallId ? { installId: knownInstallId } : {}),
|
||||
// Header VALUES are secrets (Cloudflare Access client secrets etc.) and
|
||||
// never cross the IPC boundary — the renderer only needs the names to
|
||||
// render the edit form.
|
||||
@@ -12304,7 +12309,7 @@ ipcMain.handle('hermes:plugin-profile-routes', async (_event, rawProfileNames) =
|
||||
|
||||
const registry = readDesktopConnectionsRegistry()
|
||||
const enumerations = await enumerateRegistryAgentSources(registry)
|
||||
let agents = buildAgentRoster(enumerations)
|
||||
let agents = buildAgentRoster(enumerations, { primaryConnectionId: registry.primary })
|
||||
|
||||
// Roster enumeration deliberately does not dial connect-on-demand SSH
|
||||
// sources. Publish one credential-free seed route so a plugin can be the
|
||||
@@ -12494,6 +12499,10 @@ ipcMain.handle('hermes:connections:test', async (_event, id) => {
|
||||
|
||||
const status = (await fetchJson(`${baseUrl}/api/status`, token, { timeoutMs: 8_000, headers: testHeaders })) as any
|
||||
|
||||
// The Test button is the cheapest moment to (re)learn this backend's stable
|
||||
// identity for the same-backend roster collapse + Settings hint.
|
||||
rememberConnectionInstallId(entry.id, status)
|
||||
|
||||
// Same HTTP+WS two-leg check as testDesktopConnectionConfig: HTTP alone is
|
||||
// a false positive when the WebSocket leg is blocked.
|
||||
const wsUrl = await resolveTestWsUrl(baseUrl, authMode, token, {
|
||||
@@ -12528,6 +12537,49 @@ const sshRosterCache = new Map<string, string[]>()
|
||||
const sshInventoryAttemptedAt = new Map<string, number>()
|
||||
const SSH_INVENTORY_RETRY_MS = 60_000
|
||||
|
||||
// Stable backend identity per registered connection: the `install_id` its
|
||||
// /api/status reports (absent on backends older than the field). Enumeration
|
||||
// runs on the ~5s Bot Mode roster poll and only hits /api/profiles, so the
|
||||
// status probe is cached per connection with a TTL to avoid doubling roster
|
||||
// traffic; the Test button refreshes it eagerly. A missing id simply bypasses
|
||||
// the same-backend roster collapse — fully backward compatible.
|
||||
const connectionInstallIds = new Map<string, { id?: string; ts: number }>()
|
||||
const INSTALL_ID_TTL_MS = 5 * 60_000
|
||||
const INSTALL_ID_NEGATIVE_TTL_MS = 60_000
|
||||
|
||||
function rememberConnectionInstallId(connectionId: string, statusBody: any) {
|
||||
const raw = statusBody && typeof statusBody === 'object' ? statusBody.install_id : undefined
|
||||
const id = typeof raw === 'string' && raw.trim() ? raw.trim() : undefined
|
||||
connectionInstallIds.set(connectionId, { id, ts: Date.now() })
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
async function probeConnectionInstallId(connectionId: string, descriptor: any): Promise<string | undefined> {
|
||||
const cached = connectionInstallIds.get(connectionId)
|
||||
|
||||
if (cached && Date.now() - cached.ts < (cached.id ? INSTALL_ID_TTL_MS : INSTALL_ID_NEGATIVE_TTL_MS)) {
|
||||
return cached.id
|
||||
}
|
||||
|
||||
try {
|
||||
const status: any = await getJsonForBackend(descriptor, '/api/status', { timeoutMs: 8_000 })
|
||||
|
||||
return rememberConnectionInstallId(connectionId, status)
|
||||
} catch {
|
||||
// Keep any previously-known id (identity is stable; a transient fetch
|
||||
// failure must not flap the roster collapse), but do not cache a MISS
|
||||
// over it.
|
||||
if (cached?.id) {
|
||||
return cached.id
|
||||
}
|
||||
|
||||
connectionInstallIds.set(connectionId, { id: undefined, ts: Date.now() })
|
||||
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function probeSshProfileInventory(connection) {
|
||||
if (
|
||||
!shouldRetrySshInventory(
|
||||
@@ -12581,7 +12633,7 @@ async function probeSshProfileInventory(connection) {
|
||||
async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRegistry()) {
|
||||
return Promise.all(
|
||||
registry.connections.map(async connection => {
|
||||
let raw: { connection: typeof connection; error?: string; profiles: null | string[] }
|
||||
let raw: { connection: typeof connection; error?: string; installId?: string; profiles: null | string[] }
|
||||
|
||||
try {
|
||||
// SSH roster listing must never spawn a dashboard. A stale
|
||||
@@ -12615,6 +12667,10 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe
|
||||
const descriptor: any = await ensureRegistryBackend(connection.id, null)
|
||||
const body: any = await getJsonForBackend(descriptor, '/api/profiles', { timeoutMs: 8_000 })
|
||||
|
||||
// Cached with a TTL, so the 5s roster poll usually pays zero extra
|
||||
// requests for the backend-identity probe.
|
||||
const installId = await probeConnectionInstallId(connection.id, descriptor)
|
||||
|
||||
const profiles = Array.isArray(body?.profiles)
|
||||
? body.profiles.map(p => String(p?.name || '').trim()).filter(Boolean)
|
||||
: []
|
||||
@@ -12625,7 +12681,7 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe
|
||||
profiles.unshift('default')
|
||||
}
|
||||
|
||||
raw = { connection, profiles }
|
||||
raw = { connection, profiles, ...(installId ? { installId } : {}) }
|
||||
}
|
||||
} catch (error: any) {
|
||||
raw = { connection, profiles: null, error: String(error?.message || error) }
|
||||
@@ -12637,7 +12693,7 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe
|
||||
|
||||
const remembered = rememberSshEnumeration(raw, sshRosterCache.get(connection.id), connection.kind)
|
||||
|
||||
return { connection, ...remembered }
|
||||
return { connection, ...remembered, ...(raw.installId ? { installId: raw.installId } : {}) }
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -12647,18 +12703,19 @@ ipcMain.handle('hermes:agents:roster', async () => {
|
||||
const enumerations = await enumerateRegistryAgentSources(registry)
|
||||
|
||||
return {
|
||||
agents: buildAgentRoster(enumerations),
|
||||
agents: buildAgentRoster(enumerations, { primaryConnectionId: registry.primary }),
|
||||
// The active gateway owns the renderer's profiles.list — union agents
|
||||
// that report THIS connection are the same identities, not extra rows.
|
||||
// Expose the primary id so the plugin merger can annotate them in place
|
||||
// instead of appending duplicates (remote-only desktops doubled every
|
||||
// bot otherwise; see #88344).
|
||||
primaryConnectionId: registry.primary,
|
||||
sources: enumerations.map(({ connection, profiles, error }) => ({
|
||||
sources: enumerations.map(({ connection, error, installId, profiles }) => ({
|
||||
connectionId: connection.id,
|
||||
label: connection.label,
|
||||
kind: connection.kind,
|
||||
reachable: profiles !== null,
|
||||
...(installId ? { installId } : {}),
|
||||
...(error ? { error } : {})
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ConnectionsRegistrySection,
|
||||
findDuplicateConnection,
|
||||
normalizeGatewayUrl,
|
||||
sameBackendPeerLabel,
|
||||
sshCompositeKey
|
||||
} from './connections-registry'
|
||||
|
||||
@@ -215,4 +216,19 @@ describe('dedupe helpers', () => {
|
||||
)
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('hints "Same backend as" only on later rows sharing an install_id', () => {
|
||||
const spark = { id: 'spark', installId: 'aaa', label: 'Spark' }
|
||||
const sparkTs = { id: 'spark-ts', installId: 'aaa', label: 'Spark TS' }
|
||||
const mini = { id: 'mini', installId: 'bbb', label: 'Mini' }
|
||||
const legacy = { id: 'old', label: 'Old box' }
|
||||
const connections = [spark, sparkTs, mini, legacy]
|
||||
|
||||
// The first occurrence carries no hint; the later duplicate points back.
|
||||
expect(sameBackendPeerLabel(spark, connections)).toBeNull()
|
||||
expect(sameBackendPeerLabel(sparkTs, connections)).toBe('Spark')
|
||||
// Unique ids and id-less (older backend) rows never hint.
|
||||
expect(sameBackendPeerLabel(mini, connections)).toBeNull()
|
||||
expect(sameBackendPeerLabel(legacy, connections)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -160,6 +160,37 @@ export function findDuplicateConnection(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Display-only same-backend hint: when two registered connections report the
|
||||
* same /api/status install_id, they are one physical backend registered under
|
||||
* two addresses (hostname + Tailscale IP). Returns the label of the FIRST
|
||||
* earlier sibling sharing this connection's id, or null. Never blocks or
|
||||
* deletes — dual routes are legitimate failover config; the roster already
|
||||
* collapses the duplicate bot rows.
|
||||
*/
|
||||
export function sameBackendPeerLabel(
|
||||
conn: Pick<DesktopRegistryConnection, 'id' | 'installId'>,
|
||||
connections: Pick<DesktopRegistryConnection, 'id' | 'installId' | 'label'>[]
|
||||
): null | string {
|
||||
if (!conn.installId) {
|
||||
return null
|
||||
}
|
||||
|
||||
for (const other of connections) {
|
||||
if (other.id === conn.id) {
|
||||
// Only rows AFTER the first occurrence carry the hint, so exactly one
|
||||
// of a same-backend pair is annotated (the later-listed one).
|
||||
return null
|
||||
}
|
||||
|
||||
if (other.installId === conn.installId) {
|
||||
return other.label
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The connections registry section of Settings → Gateways: manage the named
|
||||
* agent sources (local runtime + any number of remote gateways / Hermes Cloud
|
||||
@@ -432,6 +463,15 @@ export function ConnectionsRegistrySection() {
|
||||
const Icon = KIND_ICONS[conn.kind]
|
||||
const isPrimary = registry.primary === conn.id
|
||||
const busy = busyId === conn.id
|
||||
// Display-only: this connection is a second address for a backend
|
||||
// already registered under another entry (same install_id).
|
||||
const sameBackendPeer = sameBackendPeerLabel(conn, registry.connections)
|
||||
const baseDescription =
|
||||
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
|
||||
|
||||
return (
|
||||
<ListRow
|
||||
@@ -476,13 +516,7 @@ export function ConnectionsRegistrySection() {
|
||||
)}
|
||||
</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
|
||||
}
|
||||
description={sameBackendPeer ? `${baseDescription} · ${s.sameBackendHint(sameBackendPeer)}` : baseDescription}
|
||||
key={conn.id}
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
|
||||
Vendored
+7
@@ -763,6 +763,11 @@ export interface DesktopRegistryConnection {
|
||||
// header VALUES are secrets and never cross the IPC boundary. Optional so
|
||||
// fixtures/older payloads without the field remain valid.
|
||||
headerNames?: string[]
|
||||
// Last-known stable backend identity (the /api/status `install_id`).
|
||||
// Present once a roster enumeration or connection test has seen it; two
|
||||
// connections sharing it are one physical backend registered under two
|
||||
// addresses (display-only "Same backend as …" hint in Settings).
|
||||
installId?: string
|
||||
}
|
||||
|
||||
export interface DesktopConnectionsRegistry {
|
||||
@@ -817,6 +822,8 @@ export interface DesktopAgentRoster {
|
||||
kind: DesktopConnectionKind
|
||||
reachable: boolean
|
||||
error?: string
|
||||
// Stable backend identity (/api/status install_id) when known.
|
||||
installId?: string
|
||||
}[]
|
||||
}
|
||||
|
||||
|
||||
@@ -699,6 +699,7 @@ export const en: Translations = {
|
||||
duplicateLocal: 'This app already manages a local connection — there can only be one.',
|
||||
duplicateUrl: (label: string) => `A connection to this gateway URL already exists (“${label}”).`,
|
||||
duplicateSsh: (label: string) => `A connection to this SSH host already exists (“${label}”).`,
|
||||
sameBackendHint: (label: string) => `Same backend as “${label}”`,
|
||||
localAddHint: 'Local is unavailable: the managed local connection already exists (there is only ever one).',
|
||||
cloudAddHint:
|
||||
'Tip: signing in under Hermes Cloud above discovers your agents automatically — use this form only to register a known instance URL by hand.',
|
||||
|
||||
@@ -586,6 +586,7 @@ export interface Translations {
|
||||
duplicateLocal: string
|
||||
duplicateUrl: (label: string) => string
|
||||
duplicateSsh: (label: string) => string
|
||||
sameBackendHint: (label: string) => string
|
||||
localAddHint: string
|
||||
cloudAddHint: string
|
||||
save: string
|
||||
|
||||
@@ -903,6 +903,7 @@ export const zh: Translations = {
|
||||
duplicateLocal: '本应用已管理一个本地连接——只能有一个。',
|
||||
duplicateUrl: (label: string) => `已存在指向此网关 URL 的连接(“${label}”)。`,
|
||||
duplicateSsh: (label: string) => `已存在指向此 SSH 主机的连接(“${label}”)。`,
|
||||
sameBackendHint: (label: string) => `与“${label}”是同一后端`,
|
||||
localAddHint: '“本地”不可用:应用管理的本地连接已存在(永远只有一个)。',
|
||||
cloudAddHint: '提示:在上方登录 Hermes Cloud 可自动发现你的智能体——此表单仅用于手动注册已知的实例 URL。',
|
||||
save: '保存连接',
|
||||
|
||||
@@ -3318,6 +3318,78 @@ _TOPOLOGY_CACHE: Dict[str, Any] = {"ts": 0.0, "data": None, "fn": None}
|
||||
_TOPOLOGY_CACHE_LOCK = threading.Lock()
|
||||
_TOPOLOGY_CACHE_TTL = 10.0
|
||||
|
||||
# Stable install identity for /api/status. One random opaque id per physical
|
||||
# install, minted on first read and persisted under the ROOT Hermes home
|
||||
# (get_default_hermes_root()) — NOT the profile-scoped HERMES_HOME — so every
|
||||
# profile served by the same install reports the same id. Clients (the desktop
|
||||
# connection registry) use it to recognize that two registered addresses
|
||||
# (hostname + Tailscale IP, LAN + WAN) are one backend and collapse duplicate
|
||||
# roster rows. Privacy: uuid4 hex, no hardware/user-derived material; the only
|
||||
# fact it reveals is "these addresses are the same box", which is the feature.
|
||||
# It must never change across restarts/updates, so reads are cached for the
|
||||
# process lifetime and the file is written once, atomically.
|
||||
_INSTALL_ID_FILENAME = "install_id"
|
||||
_INSTALL_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
||||
_INSTALL_ID_CACHE: Dict[str, Optional[str]] = {"value": None}
|
||||
_INSTALL_ID_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _read_or_create_install_id() -> Optional[str]:
|
||||
"""Read (or mint + persist) the install id under the root Hermes home.
|
||||
|
||||
Returns ``None`` only when the id can neither be read nor persisted (e.g.
|
||||
a read-only filesystem) — an unpersisted id would violate the stability
|
||||
contract, so callers omit the field rather than emit a churning value.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from hermes_constants import get_default_hermes_root
|
||||
|
||||
root = get_default_hermes_root()
|
||||
path = root / _INSTALL_ID_FILENAME
|
||||
try:
|
||||
existing = path.read_text(encoding="utf-8").strip().lower()
|
||||
if _INSTALL_ID_RE.match(existing):
|
||||
return existing
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return None
|
||||
|
||||
minted = uuid.uuid4().hex
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
# Atomic replace so a crash mid-write can't leave a truncated id that
|
||||
# would be regenerated (i.e. changed) on the next boot.
|
||||
fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(minted + "\n")
|
||||
os.replace(tmp_name, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
except OSError:
|
||||
return None
|
||||
return minted
|
||||
|
||||
|
||||
def get_install_id() -> Optional[str]:
|
||||
"""Process-lifetime-cached stable install id (see _read_or_create_install_id)."""
|
||||
cached = _INSTALL_ID_CACHE["value"]
|
||||
if cached:
|
||||
return cached
|
||||
with _INSTALL_ID_LOCK:
|
||||
cached = _INSTALL_ID_CACHE["value"]
|
||||
if cached:
|
||||
return cached
|
||||
value = _read_or_create_install_id()
|
||||
if value:
|
||||
_INSTALL_ID_CACHE["value"] = value
|
||||
return value
|
||||
|
||||
|
||||
# Serializes read-modify-write cycles over config.yaml for handlers that run
|
||||
# in worker threads (asyncio.to_thread). config.py's _CONFIG_LOCK covers each
|
||||
# load_config()/save_config() call individually, not the span between them —
|
||||
@@ -3734,6 +3806,16 @@ async def get_status(profile: Optional[str] = None):
|
||||
"nous_session_valid": nous_session_valid,
|
||||
}
|
||||
|
||||
# Stable per-install identity (see get_install_id above). First call
|
||||
# may touch disk, so keep it off the event loop; afterwards it is a
|
||||
# process-global cache hit. Omitted (not null) when unpersistable so
|
||||
# older-client behavior and the no-identity fallback stay identical.
|
||||
install_id = await asyncio.get_running_loop().run_in_executor(
|
||||
None, get_install_id
|
||||
)
|
||||
if install_id:
|
||||
status["install_id"] = install_id
|
||||
|
||||
# Component-level health rollup. Counts and status enums only — this
|
||||
# payload is public (PUBLIC_API_PATHS), so no messages, paths, or
|
||||
# other detail that could carry secrets. The storage probe reuses the
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import asyncio
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
@@ -3143,6 +3144,98 @@ class TestStatusRemoteGateway:
|
||||
assert data["gateway_state"] == "running"
|
||||
|
||||
|
||||
class TestStatusInstallId:
|
||||
"""Stable per-install identity on /api/status.
|
||||
|
||||
Behaviour contracts: the id is minted once, persisted under the ROOT
|
||||
Hermes home (not the profile home), survives a fresh process-cache read,
|
||||
and is byte-identical for every profile served by the same install — the
|
||||
desktop uses it to collapse duplicate roster rows when one backend is
|
||||
registered under two addresses.
|
||||
"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _setup_test_client(self, monkeypatch):
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
|
||||
|
||||
# Fresh process cache per test: the cache is process-global by design
|
||||
# (stability), so tests must not observe a previous test's id.
|
||||
monkeypatch.setattr(ws, "_INSTALL_ID_CACHE", {"value": None})
|
||||
self.client = TestClient(app)
|
||||
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
|
||||
|
||||
def test_status_reports_persistent_install_id(self, monkeypatch):
|
||||
import hermes_cli.web_server as ws
|
||||
from hermes_constants import get_default_hermes_root
|
||||
|
||||
monkeypatch.setattr(ws, "get_running_pid_cached", lambda: None)
|
||||
monkeypatch.setattr(ws, "read_runtime_status", lambda: None)
|
||||
|
||||
first = self.client.get("/api/status")
|
||||
assert first.status_code == 200
|
||||
install_id = first.json().get("install_id")
|
||||
assert isinstance(install_id, str)
|
||||
# Opaque random hex only — no hardware/user-derived material.
|
||||
assert re.fullmatch(r"[0-9a-f]{32}", install_id)
|
||||
|
||||
# Persisted under the ROOT home, and stable across calls.
|
||||
id_file = get_default_hermes_root() / "install_id"
|
||||
assert id_file.is_file()
|
||||
assert id_file.read_text(encoding="utf-8").strip() == install_id
|
||||
|
||||
second = self.client.get("/api/status")
|
||||
assert second.json().get("install_id") == install_id
|
||||
|
||||
def test_install_id_survives_process_cache_reset(self, monkeypatch):
|
||||
"""A restart (fresh cache) re-reads the SAME persisted id."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
first = ws.get_install_id()
|
||||
assert first
|
||||
monkeypatch.setattr(ws, "_INSTALL_ID_CACHE", {"value": None})
|
||||
assert ws.get_install_id() == first
|
||||
|
||||
def test_all_profiles_of_one_install_share_the_id(self, monkeypatch, tmp_path):
|
||||
"""HERMES_HOME=<root> and HERMES_HOME=<root>/profiles/<name> resolve to
|
||||
the same id file — profiles share one physical install identity."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
root = tmp_path / "hermes-root"
|
||||
profile_home = root / "profiles" / "research"
|
||||
profile_home.mkdir(parents=True)
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(root))
|
||||
monkeypatch.setattr(ws, "_INSTALL_ID_CACHE", {"value": None})
|
||||
root_id = ws.get_install_id()
|
||||
assert root_id
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile_home))
|
||||
monkeypatch.setattr(ws, "_INSTALL_ID_CACHE", {"value": None})
|
||||
assert ws.get_install_id() == root_id
|
||||
# Exactly one id file exists — under the root, not the profile home.
|
||||
assert (root / "install_id").is_file()
|
||||
assert not (profile_home / "install_id").exists()
|
||||
|
||||
def test_corrupt_id_file_is_replaced_not_propagated(self, monkeypatch, tmp_path):
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
root = tmp_path / "hermes-root"
|
||||
root.mkdir()
|
||||
(root / "install_id").write_text("not-a-valid-id\n", encoding="utf-8")
|
||||
monkeypatch.setenv("HERMES_HOME", str(root))
|
||||
monkeypatch.setattr(ws, "_INSTALL_ID_CACHE", {"value": None})
|
||||
|
||||
value = ws.get_install_id()
|
||||
assert value and re.fullmatch(r"[0-9a-f]{32}", value)
|
||||
assert (root / "install_id").read_text(encoding="utf-8").strip() == value
|
||||
|
||||
|
||||
class TestGatewayBusyReadout:
|
||||
"""Tests for the NAS busy/drainable readout on /api/status.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user