Skip to content

The agent that grows with you

fix(desktop): count unified session totals once per backend install_id

Teknium6d69fa8c55b4
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index c38983e3a74..caf6d0df482 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -497,6 +497,14 @@ import {
createQuitTeardownCoordinator,
type QuitTeardownTask
} from './quit-teardown'
+import {
+ boundedInstallId,
+ createPrimaryInstallIdResolver,
+ INSTALL_ID_NEGATIVE_TTL_MS,
+ INSTALL_ID_TTL_MS,
+ probeCachedConnectionInstallId,
+ rememberConnectionInstallId
+} from './registry-backend-identity'
import * as remoteLifecycle from './remote-lifecycle'
import {
attachPowerResumeRemoteRevalidation,
@@ -15088,47 +15096,10 @@ ipcMain.handle('hermes:connections:test', async (_event, id) => {
// removing a connection or re-pointing it must evict them (`evictConnectionCaches`).
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 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
- }
-}
+// Stable backend identity per registered connection: the `install_id` its /api/status reports,
+// TTL-cached in `connectionInstallIds` (see registry-backend-identity.ts).
+const probeConnectionInstallId = (connectionId: string, descriptor: any) =>
+ probeCachedConnectionInstallId(connectionId, () => getJsonForBackend(descriptor, '/api/status', { timeoutMs: 8_000 }))
async function probeSshProfileInventory(connection) {
if (
@@ -16256,7 +16227,9 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
if (registrySources.length) {
const getRegistryJson = (descriptor, path) => getJsonForBackend(descriptor, path, { timeoutMs: 10_000 })
- total += await mergeRegistrySessionRows(registrySources, remoteParams, getRegistryJson, merged, profileTotals)
+ // RT-42: count each backend (install_id) once; remote-override profiles are another backend.
+ const identity = { primaryBackendId: await primaryBackendInstallId(), unknownPrimaryProfiles: remoteProfiles }
+ total += await mergeRegistrySessionRows(registrySources, remoteParams, getRegistryJson, merged, profileTotals, identity)
}
const recency = s => s?.[order] ?? s?.started_at ?? 0
@@ -16316,13 +16289,22 @@ async function pooledRegistrySessionSources(includeLocal = false): Promise<Regis
}
if (backends.length) {
- sources.push({ backends, connectionId: connection.id, kind: connection.kind })
+ const backendId = await boundedInstallId(probeConnectionInstallId(connection.id, backends[0].descriptor))
+ sources.push({ backendId, backends, connectionId: connection.id, kind: connection.kind })
}
}
return sources
}
+// RT-42: install_id of the backend the primary session aggregate reads (see the module).
+const primaryBackendInstallId = createPrimaryInstallIdResolver({
+ resolve: () => ensureBackend(null, { passive: true }),
+ status: descriptor => getJsonForBackend(descriptor, '/api/status', { timeoutMs: 2_000 }),
+ ttlMs: INSTALL_ID_TTL_MS,
+ negativeTtlMs: INSTALL_ID_NEGATIVE_TTL_MS
+})
+
async function dispatchRegistryApiRequest(
request,
registryConnectionId,
diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.ts
index fcb34bb0748..f6408596302 100644
--- a/apps/desktop/electron/profile-session-routing.test.ts
+++ b/apps/desktop/electron/profile-session-routing.test.ts
@@ -547,6 +547,154 @@ for (const [label, primaryIds] of [
})
}
+// Review round 2 (RT-42): production primary rows are never tagged with a connection_id, so
+// overlap must come from the BACKEND each side read (its install_id), not from row tags.
+// Unknown identity takes the larger total per profile and never the sum.
+const rt42Host = (all: Array<{ id: string; profile: string; started_at: number }>) => {
+ const profileTotals: Record<string, number> = {}
+
+ for (const row of all) {
+ profileTotals[row.profile] = (profileTotals[row.profile] || 0) + 1
+ }
+
+ return async (_descriptor: unknown, path: string) => {
+ const params = new URL(path, 'http://x').searchParams
+ const start = Number(params.get('offset'))
+ const limit = Number(params.get('limit'))
+
+ return { sessions: all.slice(start, start + limit).map(row => ({ ...row })), total: all.length, profile_totals: profileTotals }
+ }
+}
+
+const rt42Rows = Array.from({ length: 650 }, (_, i) => ({ id: `s${i}`, profile: 'default', started_at: 650 - i }))
+
+const rt42Source = (connectionId: string, backendId?: string) => ({
+ connectionId,
+ kind: 'remote',
+ backends: [{ descriptor: 'r', profileLabel: null }],
+ ...(backendId ? { backendId } : {})
+})
+
+for (const [label, ids] of [
+ ['the oldest half of', Array.from({ length: 325 }, (_, i) => 325 + i)],
+ ['the newest half of', Array.from({ length: 325 }, (_, i) => i)],
+ ['all of', Array.from({ length: 650 }, (_, i) => i)]
+] as const) {
+ for (const identity of ['unknown', 'the same install_id'] as const) {
+ test(`an untagged primary holding ${label} a registry host (${identity}) totals the 650 union`, async () => {
+ const merged: unknown[] = ids.slice(0, 20).map(i => ({ id: `s${i}`, profile: 'default' }))
+ const profileTotals: Record<string, number> = { default: ids.length }
+ const same = identity !== 'unknown'
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R', same ? 'host' : undefined)],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(rt42Rows),
+ merged,
+ profileTotals,
+ same ? { primaryBackendId: 'host' } : {}
+ )
+
+ assert.equal(ids.length + contribution, 650)
+ assert.equal(profileTotals.default, 650)
+ })
+ }
+}
+
+test('two registry connections to one install plus a known-distinct primary total the 750 union', async () => {
+ const merged: unknown[] = Array.from({ length: 20 }, (_, i) => ({ id: `L${i}`, profile: 'default' }))
+ const profileTotals: Record<string, number> = { default: 100 }
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R1', 'host'), rt42Source('R2', 'host')],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(rt42Rows),
+ merged,
+ profileTotals,
+ { primaryBackendId: 'local' }
+ )
+
+ assert.equal(100 + contribution, 750)
+ assert.equal(profileTotals.default, 750)
+})
+
+test('two registry connections with unknown identity never sum: the larger total wins', async () => {
+ const merged: unknown[] = Array.from({ length: 20 }, (_, i) => ({ id: `L${i}`, profile: 'default' }))
+ const profileTotals: Record<string, number> = { default: 100 }
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R1'), rt42Source('R2')],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(rt42Rows),
+ merged,
+ profileTotals
+ )
+
+ // An undercount (650, not 750) is acceptable here; 1300 would be a double count.
+ assert.equal(100 + contribution, 650)
+ assert.equal(profileTotals.default, 650)
+})
+
+test('a registry host known to differ from the primary is summed', async () => {
+ const merged: unknown[] = Array.from({ length: 20 }, (_, i) => ({ id: `L${i}`, profile: 'default' }))
+ const profileTotals: Record<string, number> = { default: 100 }
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R', 'host')],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(rt42Rows),
+ merged,
+ profileTotals,
+ { primaryBackendId: 'local' }
+ )
+
+ assert.equal(100 + contribution, 750)
+})
+
+for (const identity of ['unknown', 'the same install_id'] as const) {
+ test(`primary and registry on one host (${identity}): a profile absent from the prefix is not double counted`, async () => {
+ const all = [
+ ...Array.from({ length: 650 }, (_, i) => ({ id: `d${i}`, profile: 'default', started_at: 10_000 - i })),
+ ...Array.from({ length: 100 }, (_, i) => ({ id: `w${i}`, profile: 'work', started_at: 100 - i }))
+ ]
+
+ const merged: unknown[] = all.slice(0, 20).map(row => ({ ...row }))
+ const profileTotals: Record<string, number> = { default: 650, work: 100 }
+ const same = identity !== 'unknown'
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R', same ? 'host' : undefined)],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(all),
+ merged,
+ profileTotals,
+ same ? { primaryBackendId: 'host' } : {}
+ )
+
+ assert.equal(750 + contribution, 750)
+ assert.equal(profileTotals.work, 100)
+ })
+}
+
+test('a remote-override profile on the primary side is never summed with a registry host', async () => {
+ // `work` came from a per-profile remote override, not the primary backend: its backend is
+ // unknown even though the primary's own install_id differs from the registry host's.
+ const all = Array.from({ length: 100 }, (_, i) => ({ id: `w${i}`, profile: 'work', started_at: 100 - i }))
+ const merged: unknown[] = all.slice(0, 20).map(row => ({ ...row }))
+ const profileTotals: Record<string, number> = { work: 100 }
+
+ const contribution = await mergeRegistrySessionRows(
+ [rt42Source('R', 'host')],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ rt42Host(all),
+ merged,
+ profileTotals,
+ { primaryBackendId: 'local', unknownPrimaryProfiles: ['work'] }
+ )
+
+ assert.equal(100 + contribution, 100)
+})
+
test('a failed later registry page does not contribute a stale first-page total', async () => {
const reported = new Map<string, number>()
diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.ts
index 8a482696b12..e28173d3e6b 100644
--- a/apps/desktop/electron/profile-session-routing.ts
+++ b/apps/desktop/electron/profile-session-routing.ts
@@ -297,6 +297,9 @@ export interface RegistrySessionSource {
* a shared host serving every profile via ?profile=. */
kind: string
backends: Array<{ descriptor: unknown; profileLabel: null | string }>
+ /** The connection's gateway install_id, when known. Sources sharing one are the same backend
+ * and count their session totals once; a source without one is never summed with another. */
+ backendId?: string
}
type PinnedRegistrySessionSource = Pick<RegistrySessionSource, 'connectionId'> &
@@ -621,101 +624,159 @@ export function spliceRegistrySessionRows(
return { added }
}
-/** Report registry totals for scopes the primary/override path did not already count.
- * The fetched prefix can be shorter than the backend's total and can include pins outside
- * the ordinary cursor, so counting only its rows undercounts deep pages or overcounts pins.
+/** Which backend each side of a unified session list read, for counting each backend once.
+ * Identities are the gateway `install_id` (`hermes_cli/install_identity.py`), never a row tag:
+ * production primary rows carry no `connection_id`, so a row can't say which backend served it. */
+export interface RegistryBackendIdentity {
+ /** install_id of the backend the primary aggregate read; absent when unknown. */
+ primaryBackendId?: null | string
+ /** Profiles whose primary-side rows came from somewhere other than the primary backend
+ * (per-profile remote overrides), so their backend is unknown. */
+ unknownPrimaryProfiles?: Iterable<string>
+ /** install_id per registry connection id; a connection without one is unknown. */
+ backendIds?: ReadonlyMap<string, string>
+}
+
+/** Recompute each profile's total once a registry scan is spliced in, counting each backend once.
*
- * Overlap with the primary is never extrapolated from the fetched prefix: duplicates in
- * one page say nothing about how much of the deeper scope the primary also holds. A scope
- * is disjoint (its full backend total is owed) only when no fetched row was a duplicate
- * AND the primary served no row from the same connection. Otherwise both sides counted
- * the same backend scope, and the only exact-or-safe figure is max(primary, registry):
- * exact when they are the same backend (their totals agree), a lower bound otherwise.
- * `primaryRows` are the merged rows BEFORE the registry splice. */
+ * The fetched prefix can be shorter than the backend's total and can include pins outside the
+ * ordinary cursor, so each registry scope contributes its backend-reported total, not its rows.
+ * Per profile, every contributor (the primary side and each registry scope) is grouped by the
+ * backend it read:
+ * - contributors with the same known install_id are one backend: the larger total counts once;
+ * - distinct known backends are summed, since they are known to differ;
+ * - a contributor whose backend is unknown can't be compared with anything, so it only raises
+ * the profile to its own total (max), never adds to it. An undercount is possible there; a
+ * double count is not.
+ * The result never drops below the rows the merged list visibly holds for that profile.
+ * `primaryRows` are the merged rows BEFORE the registry splice. Returns the change to the
+ * grand total. */
export function applyRegistrySessionTotals(
fetchedRows: unknown[],
addedRows: unknown[],
reportedTotals: Map<string, number>,
profileTotals: Record<string, number>,
- primaryRows: unknown[] = []
+ primaryRows: unknown[] = [],
+ identity: RegistryBackendIdentity = {}
): number {
const connectionOf = (row: unknown) =>
row && typeof row === 'object' && typeof (row as { connection_id?: unknown }).connection_id === 'string'
? (row as { connection_id: string }).connection_id
: ''
- const counts = (rows: unknown[]) => {
- const perScope = new Map<string, number>()
+ const profileOf = (row: unknown) => {
+ const profile = row && typeof row === 'object' ? (row as { profile?: unknown }).profile : undefined
+
+ return typeof profile === 'string' && profile ? profile : 'default'
+ }
+
+ const counts = (rows: unknown[], keyOf: (row: unknown) => string) => {
+ const tally = new Map<string, number>()
for (const row of rows) {
if (!row || typeof row !== 'object') {
continue
}
- const session = row as Record<string, unknown>
- const profile = typeof session.profile === 'string' && session.profile ? session.profile : 'default'
- const key = `${connectionOf(row)}\0${profile}`
- perScope.set(key, (perScope.get(key) || 0) + 1)
+ const key = keyOf(row)
+ tally.set(key, (tally.get(key) || 0) + 1)
}
- return perScope
+ return tally
}
- const primaryConnections = new Set(primaryRows.map(connectionOf).filter(Boolean))
- const fetched = counts(fetchedRows)
- const added = counts(addedRows)
+ const scopeOf = (row: unknown) => `${connectionOf(row)}\0${profileOf(row)}`
+ const fetched = counts(fetchedRows, scopeOf)
+ const addedPerProfile = counts(addedRows, profileOf)
+ const primaryVisible = counts(primaryRows, profileOf)
// Per-profile totals as the primary/override side left them, before this scan's splice.
const primaryTotals: Record<string, number> = { ...profileTotals }
- for (const [key, n] of added) {
- const profile = key.slice(key.indexOf('\0') + 1)
+ for (const [profile, n] of addedPerProfile) {
primaryTotals[profile] = (primaryTotals[profile] || 0) - n
}
- let contribution = 0
+ const scopes = new Map<string, Array<{ backend: null | string; total: number }>>()
for (const key of new Set([...fetched.keys(), ...reportedTotals.keys()])) {
- const addedCount = added.get(key) || 0
- const duplicates = (fetched.get(key) || 0) - addedCount
const connection = key.slice(0, key.indexOf('\0'))
const profile = key.slice(key.indexOf('\0') + 1)
+ // An older aggregate without profile_totals: its fetched rows are all it vouches for.
+ const total = reportedTotals.get(key) ?? fetched.get(key) ?? 0
+ const list = scopes.get(profile) ?? []
+ list.push({ backend: identity.backendIds?.get(connection) || null, total })
+ scopes.set(profile, list)
+ }
+
+ const unknownPrimary = new Set(identity.unknownPrimaryProfiles ?? [])
+ const primaryBackend = identity.primaryBackendId || null
+ let contribution = 0
+
+ for (const [profile, list] of scopes) {
const primaryCount = Math.max(0, primaryTotals[profile] || 0)
- const overlaps = duplicates > 0 || primaryConnections.has(connection)
- let count = addedCount
+ const known = new Map<string, number>()
+ let unknownMax = 0
+
+ const add = (backend: null | string, total: number) => {
+ if (backend) {
+ known.set(backend, Math.max(known.get(backend) || 0, total))
+ } else {
+ unknownMax = Math.max(unknownMax, total)
+ }
+ }
- if (reportedTotals.has(key)) {
- const reported = reportedTotals.get(key)!
- // Never below the rows this scope visibly added.
- count = Math.max(addedCount, overlaps ? reported - primaryCount : reported)
+ if (primaryCount > 0) {
+ add(unknownPrimary.has(profile) ? null : primaryBackend, primaryCount)
}
- profileTotals[profile] = (profileTotals[profile] || 0) + count - addedCount
- contribution += count
+ for (const { backend, total } of list) {
+ add(backend, total)
+ }
+
+ let knownSum = 0
+
+ for (const total of known.values()) {
+ knownSum += total
+ }
+
+ const visible = (primaryVisible.get(profile) || 0) + (addedPerProfile.get(profile) || 0)
+ const union = Math.max(primaryCount, knownSum, unknownMax, visible)
+ profileTotals[profile] = union
+ contribution += union - primaryCount
}
return contribution
}
-/** Fetch and merge one registry scan, retaining its backend totals for deep pages. */
+/** Fetch and merge one registry scan, retaining its backend totals for deep pages. Each source's
+ * `backendId` and `identity.primaryBackendId` decide which totals are the same backend. */
export async function mergeRegistrySessionRows(
sources: RegistrySessionSource[],
searchParams: URLSearchParams,
getJson: GetJsonForDescriptor,
merged: unknown[],
- profileTotals: Record<string, number>
+ profileTotals: Record<string, number>,
+ identity: Omit<RegistryBackendIdentity, 'backendIds'> = {}
): Promise<number> {
const reportedTotals = new Map<string, number>()
const registryRows = await fetchRegistrySessionRows(sources, searchParams, getJson, reportedTotals)
const before = merged.length
spliceRegistrySessionRows(merged, registryRows, profileTotals)
- return applyRegistrySessionTotals(
- registryRows,
- merged.slice(before),
- reportedTotals,
- profileTotals,
- merged.slice(0, before)
- )
+ const backendIds = new Map<string, string>()
+
+ for (const source of sources) {
+ const id = typeof source.backendId === 'string' ? source.backendId.trim() : ''
+
+ if (id) {
+ backendIds.set(source.connectionId, id)
+ }
+ }
+
+ return applyRegistrySessionTotals(registryRows, merged.slice(before), reportedTotals, profileTotals, merged.slice(0, before), {
+ ...identity,
+ backendIds
+ })
}
/**
diff --git a/apps/desktop/electron/registry-backend-identity.test.ts b/apps/desktop/electron/registry-backend-identity.test.ts
new file mode 100644
index 00000000000..b6b8bed590f
--- /dev/null
+++ b/apps/desktop/electron/registry-backend-identity.test.ts
@@ -0,0 +1,77 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { connectionInstallIds } from './connection-caches'
+import {
+ boundedInstallId,
+ createPrimaryInstallIdResolver,
+ installIdFromStatus,
+ probeCachedConnectionInstallId
+} from './registry-backend-identity'
+
+test('installIdFromStatus reads a non-empty install_id only', () => {
+ assert.equal(installIdFromStatus({ install_id: ' abc ' }), 'abc')
+ assert.equal(installIdFromStatus({ install_id: '' }), undefined)
+ assert.equal(installIdFromStatus({}), undefined)
+ assert.equal(installIdFromStatus(null), undefined)
+})
+
+test('a slow or failing identity probe reads as unknown', async () => {
+ assert.equal(await boundedInstallId(new Promise(() => {}), 5), undefined)
+ assert.equal(await boundedInstallId(Promise.reject(new Error('down'))), undefined)
+ assert.equal(await boundedInstallId(Promise.resolve('abc')), 'abc')
+})
+
+test('the primary install id is cached per backend URL and re-probed when the primary moves', async () => {
+ let url = 'http://local'
+ let probes = 0
+
+ const resolve = createPrimaryInstallIdResolver({
+ resolve: async () => ({ baseUrl: url }),
+ status: async (descriptor: any) => {
+ probes += 1
+
+ return { install_id: descriptor.baseUrl === 'http://local' ? 'L' : 'R' }
+ },
+ ttlMs: 60_000,
+ negativeTtlMs: 1_000
+ })
+
+ assert.equal(await resolve(), 'L')
+ assert.equal(await resolve(), 'L')
+ assert.equal(probes, 1)
+ url = 'http://remote'
+ assert.equal(await resolve(), 'R')
+ assert.equal(probes, 2)
+})
+
+test('an unresolvable primary has no identity', async () => {
+ const resolve = createPrimaryInstallIdResolver({
+ resolve: async () => {
+ throw new Error('not started')
+ },
+ status: async () => ({ install_id: 'x' }),
+ ttlMs: 1,
+ negativeTtlMs: 1
+ })
+
+ assert.equal(await resolve(), undefined)
+})
+
+test('a connection install id is cached, and a failed re-probe keeps the known id', async () => {
+ connectionInstallIds.clear()
+ let calls = 0
+
+ assert.equal(await probeCachedConnectionInstallId('c', async () => (calls++, { install_id: 'abc' })), 'abc')
+ assert.equal(await probeCachedConnectionInstallId('c', async () => (calls++, { install_id: 'zzz' })), 'abc')
+ assert.equal(calls, 1)
+ connectionInstallIds.set('c', { id: 'abc', ts: 0 })
+ assert.equal(
+ await probeCachedConnectionInstallId('c', async () => {
+ throw new Error('down')
+ }),
+ 'abc'
+ )
+ connectionInstallIds.clear()
+})
diff --git a/apps/desktop/electron/registry-backend-identity.ts b/apps/desktop/electron/registry-backend-identity.ts
new file mode 100644
index 00000000000..9b96e9f6085
--- /dev/null
+++ b/apps/desktop/electron/registry-backend-identity.ts
@@ -0,0 +1,128 @@
+/**
+ * Backend identity for the unified session list (RT-42).
+ *
+ * Session totals are counted once per BACKEND, keyed on the gateway `install_id` that
+ * `/api/status` reports (`hermes_cli/install_identity.py`). A sidebar refresh never waits on an
+ * identity probe: an unanswered probe reads as "unknown", which only makes the totals take
+ * max() instead of a sum.
+ */
+
+import { connectionInstallIds } from './connection-caches'
+
+const IDENTITY_PROBE_BUDGET_MS = 2_000
+
+// Per-connection identity is probed on the ~5s Bot Mode roster poll, which only hits /api/profiles,
+// so the status probe is TTL-cached per connection to avoid doubling roster traffic; the Test button
+// refreshes it eagerly. A missing id simply bypasses the same-backend roster collapse and makes
+// session totals take max() instead of a sum — fully backward compatible.
+export const INSTALL_ID_TTL_MS = 5 * 60_000
+export const INSTALL_ID_NEGATIVE_TTL_MS = 60_000
+
+/** Settle an identity probe within the sidebar's budget; a slow or failed probe is unknown. */
+export async function boundedInstallId(
+ probe: Promise<string | undefined>,
+ budgetMs = IDENTITY_PROBE_BUDGET_MS
+): Promise<string | undefined> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+
+ try {
+ return await Promise.race([
+ probe,
+ new Promise<undefined>(resolve => {
+ timer = setTimeout(() => resolve(undefined), budgetMs)
+ })
+ ])
+ } catch {
+ return undefined
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+/** The non-empty `install_id` a `/api/status` body reports, else undefined. */
+export function installIdFromStatus(body: unknown): string | undefined {
+ const raw = body && typeof body === 'object' ? (body as { install_id?: unknown }).install_id : undefined
+
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined
+}
+
+export interface PrimaryInstallIdDeps {
+ /** The primary backend's descriptor, without dialing or spawning anything. */
+ resolve: () => Promise<unknown>
+ /** GET /api/status against a descriptor. */
+ status: (descriptor: unknown) => Promise<unknown>
+ ttlMs: number
+ negativeTtlMs: number
+ now?: () => number
+ budgetMs?: number
+}
+
+/**
+ * Resolve the install_id of the backend the primary session aggregate reads (local or global
+ * remote). Cached per resolved base URL, so switching the primary never reuses the previous
+ * backend's identity; a miss is cached for the shorter negative TTL.
+ */
+export function createPrimaryInstallIdResolver(deps: PrimaryInstallIdDeps): () => Promise<string | undefined> {
+ const now = deps.now ?? Date.now
+ let cached: { id?: string; key: string; ts: number } | null = null
+
+ return async () => {
+ try {
+ const descriptor = await deps.resolve()
+ const key = String((descriptor as { baseUrl?: unknown } | null)?.baseUrl || '')
+
+ if (!key) {
+ return undefined
+ }
+
+ if (cached && cached.key === key && now() - cached.ts < (cached.id ? deps.ttlMs : deps.negativeTtlMs)) {
+ return cached.id
+ }
+
+ const id = await boundedInstallId(
+ Promise.resolve(deps.status(descriptor)).then(installIdFromStatus),
+ deps.budgetMs
+ )
+
+ cached = { id, key, ts: now() }
+
+ return id
+ } catch {
+ return undefined
+ }
+ }
+}
+
+/** Record the install_id a connection's `/api/status` body reports (or its absence). */
+export function rememberConnectionInstallId(connectionId: string, statusBody: unknown): string | undefined {
+ const id = installIdFromStatus(statusBody)
+ connectionInstallIds.set(connectionId, { id, ts: Date.now() })
+
+ return id
+}
+
+/** A connection's install_id, TTL-cached; `fetchStatus` runs only on a cache miss. */
+export async function probeCachedConnectionInstallId(
+ connectionId: string,
+ fetchStatus: () => Promise<unknown>
+): 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 {
+ return rememberConnectionInstallId(connectionId, await fetchStatus())
+ } 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
+ }
+}