Skip to content

The agent that grows with you

fix(desktop): route registry 'local' entry to the genuinely-local runtime

Tekniumd905954634a2
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index 65676161844..05675323b97 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -26,6 +26,7 @@ import {
normalizeRegistry,
REGISTRY_VERSION,
removeConnection,
+ resolveRegistryLocalRoute,
setPrimaryConnection,
uniqueLabel,
updateEligibility,
@@ -128,6 +129,36 @@ test('backendScopeKey: non-local connections get an unambiguous composite', () =
assert.ok(!'research'.startsWith(backendScopePrefix('homelab')))
})
+// --- resolveRegistryLocalRoute (registry 'local' entry vs the v1 route) ---
+
+test("registry local route: delegates to the legacy path when v1 is local (single-source users byte-identical)", () => {
+ assert.deepEqual(resolveRegistryLocalRoute('research', {}), { delegate: true, poolKey: 'research' })
+ assert.deepEqual(resolveRegistryLocalRoute('', {}), { delegate: true, poolKey: 'default' })
+ assert.deepEqual(resolveRegistryLocalRoute(null, { globalRemote: false }), { delegate: true, poolKey: 'default' })
+})
+
+test("registry local route: v1 REMOTE global mode forces a genuinely-local backend (migration scenario)", () => {
+ // The migration keeps the mandatory 'local' entry AND makes the v1 remote
+ // the registry primary. If 'local' delegated to the v1 route here, the
+ // roster's "This device" rows would enumerate + dial the REMOTE primary —
+ // every profile duplicated and local agents talking to the remote box.
+ const route = resolveRegistryLocalRoute('default', { globalRemote: true })
+
+ assert.equal(route.delegate, false)
+ // The forced-local child must NOT pool under the bare profile key: that
+ // slot is where the v1 route caches the REMOTE descriptor. The composite
+ // form is prefix-owned by the local connection and collision-free.
+ assert.equal(route.poolKey, 'conn:local::default')
+ assert.ok(route.poolKey.startsWith(backendScopePrefix(LOCAL_CONNECTION_ID)))
+ assert.notEqual(route.poolKey, backendScopeKey(LOCAL_CONNECTION_ID, 'default'))
+})
+
+test('registry local route: a per-profile remote override also forces local', () => {
+ const route = resolveRegistryLocalRoute('research', { profileRemoteOverride: true })
+
+ assert.deepEqual(route, { delegate: false, poolKey: 'conn:local::research' })
+})
+
// --- buildAgentRoster (union roster + @name-device rule) ---
test('roster: unique profiles keep bare handles; duplicates get @name-device', () => {
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index 08296d2a717..4ffd294dab6 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -164,6 +164,47 @@ export function backendScopePrefix(connectionId: string): string {
return `conn:${String(connectionId).trim()}::`
}
+export interface RegistryLocalRoute {
+ /** Reuse the legacy v1 ensureBackend path — it already resolves to the
+ * app's own local runtime, so single-source behavior stays byte-identical. */
+ delegate: boolean
+ /** Pool key for the forced-local child when not delegating. */
+ poolKey: string
+}
+
+/**
+ * How the registry's 'local' entry resolves a backend for `profile`.
+ *
+ * The 'local' entry means THIS machine's runtime — always. The legacy
+ * ensureBackend() path instead follows the v1 connection.json routing table,
+ * where a global remote mode (or a per-profile remote override) resolves to a
+ * REMOTE descriptor. A migrated user whose v1 global mode was remote gets that
+ * remote as the registry primary AND keeps the mandatory 'local' entry, so
+ * delegating 'local' to the v1 route made the roster's "This device" rows
+ * enumerate and dial the remote box: every profile appeared twice (forcing
+ * -slug handles) and "local" agents talked to the remote.
+ *
+ * When the v1 route is already local we delegate (legacy path, byte-identical
+ * pool keys). When v1 says remote, the local entry spawns its own genuinely
+ * local child under a composite pool key: backendScopeKey('local', p) maps to
+ * the BARE profile key by design, and that slot may already hold the v1
+ * route's REMOTE descriptor — so the forced-local child pools under the
+ * `conn:local::<profile>` form instead (colons are invalid in profile names,
+ * so it cannot collide).
+ */
+export function resolveRegistryLocalRoute(
+ profile: null | string | undefined,
+ opts: { globalRemote?: boolean; profileRemoteOverride?: boolean } = {}
+): RegistryLocalRoute {
+ const profileKey = String(profile ?? '').trim() || 'default'
+
+ if (opts.globalRemote || opts.profileRemoteOverride) {
+ return { delegate: false, poolKey: `${backendScopePrefix(LOCAL_CONNECTION_ID)}${profileKey}` }
+ }
+
+ return { delegate: true, poolKey: profileKey }
+}
+
// ── Union agent roster ──────────────────────────────────────────────────────
export interface ConnectionAgents {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 529c2d8ea36..47f1508b041 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -92,6 +92,7 @@ import {
normalizeConnectionInput,
normalizeRegistry,
removeConnection,
+ resolveRegistryLocalRoute,
setPrimaryConnection,
updateEligibility,
upsertConnection
@@ -9290,10 +9291,11 @@ async function ensureBackend(profile) {
// ── Registry-scoped backends (multi-connection, PR 2 of the campaign) ──────
// Resolve a backend for (connectionId, profile) against the v2 registry.
-// The LOCAL connection routes through ensureBackend() untouched, so every
-// single-source path stays byte-identical; non-local connections pool under
-// the composite key from backendScopeKey() and reuse the same pool entry
-// lifecycle (LRU, idle reaper, touch) as per-profile local backends.
+// The LOCAL connection routes through ensureBackend() when the v1 route is
+// itself local (so every single-source path stays byte-identical), and forces
+// a genuinely-local child when the v1 mode says remote; non-local connections
+// pool under the composite key from backendScopeKey() and reuse the same pool
+// entry lifecycle (LRU, idle reaper, touch) as per-profile local backends.
async function ensureRegistryBackend(connectionId, profile) {
const registry = readDesktopConnectionsRegistry()
const id = String(connectionId || '').trim() || registry.primary
@@ -9304,7 +9306,61 @@ async function ensureRegistryBackend(connectionId, profile) {
}
if (source.kind === 'local') {
- return ensureBackend(profile)
+ // The registry's 'local' entry means THIS machine's runtime — always.
+ // ensureBackend() follows the v1 routing table, which resolves to a
+ // REMOTE descriptor when the v1 global mode is remote (or the profile
+ // has its own remote override). A migrated remote-mode user would then
+ // see the roster's "This device" rows enumerate + dial the remote box
+ // (every profile duplicated, -slug handles forced). Delegate only when
+ // the v1 route is genuinely local; otherwise spawn/reuse a forced-local
+ // child pooled under the composite 'conn:local::<profile>' key so it
+ // can't collide with the v1 remote descriptor cached at the bare key.
+ const profileKey = String(profile ?? '').trim() || 'default'
+
+ const localRoute = resolveRegistryLocalRoute(profileKey, {
+ globalRemote: globalRemoteActive(),
+ profileRemoteOverride: Boolean(profileHasRemoteOverride(profileKey))
+ })
+
+ if (localRoute.delegate) {
+ return ensureBackend(profile)
+ }
+
+ const existingLocal = backendPool.get(localRoute.poolKey)
+
+ if (existingLocal) {
+ existingLocal.lastActiveAt = Date.now()
+
+ return existingLocal.connectionPromise
+ }
+
+ evictLruPoolBackends(POOL_MAX_BACKENDS - 1)
+
+ const localEntry = {
+ process: null,
+ port: null,
+ token: null,
+ connectionPromise: null,
+ lastActiveAt: Date.now(),
+ remoteBaseUrl: null
+ }
+
+ localEntry.connectionPromise = spawnPoolBackend(profileKey, localEntry, {
+ forceLocal: true,
+ poolKey: localRoute.poolKey
+ }).catch(async error => {
+ if (backendPool.get(localRoute.poolKey) === localEntry) {
+ backendPool.delete(localRoute.poolKey)
+ }
+
+ stopBackendChild(localEntry.process)
+ await waitForBackendExit(localEntry.process)
+ throw error
+ })
+ backendPool.set(localRoute.poolKey, localEntry)
+ startPoolIdleReaper()
+
+ return localEntry.connectionPromise
}
const key = backendScopeKey(id, profile)
@@ -9495,7 +9551,13 @@ function startPoolIdleReaper() {
// Spawn an additional dashboard backend pinned to a named profile. Mirrors the
// local-spawn portion of startHermes() but without the boot-progress UI,
// bootstrap, or remote handling (those belong to the primary backend only).
-async function spawnPoolBackend(profile, entry) {
+// `opts.forceLocal` skips remote resolution entirely (the registry 'local'
+// entry means THIS machine regardless of the v1 routing table); `opts.poolKey`
+// is the backendPool key when it differs from the profile name (composite
+// registry scopes) so the exit/error cleanup evicts the right entry.
+async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {
+ const poolKey = opts.poolKey || profile
+
await reapOrphanedBackendsOnce()
// A profile may point at its OWN remote backend (connection.json
// `profiles[name]`), or inherit the app-wide remote (env / global settings).
@@ -9503,7 +9565,7 @@ async function spawnPoolBackend(profile, entry) {
// remote is reachable and hand back its connection descriptor. The pool
// entry keeps `entry.process === null`, which stopPoolBackend/evict already
// tolerate.
- const remote = await resolveRemoteBackend(profile)
+ const remote = opts.forceLocal ? null : await resolveRemoteBackend(profile)
if (remote) {
await waitForHermes(remote.baseUrl, remote.token, undefined, remote.authMode)
@@ -9605,13 +9667,13 @@ async function spawnPoolBackend(profile, entry) {
child.once('error', error => {
rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)
releaseBackendChild(child)
- backendPool.delete(profile)
+ backendPool.delete(poolKey)
rejectStart?.(error)
})
child.once('exit', (code, signal) => {
rememberLog(`Hermes backend for profile "${profile}" exited (${signal || code})`)
releaseBackendChild(child)
- backendPool.delete(profile)
+ backendPool.delete(poolKey)
if (!ready) {
rejectStart?.(
@@ -11370,7 +11432,9 @@ function createWindow() {
ipcMain.handle('hermes:connection', async (_event, profile) => ensureBackend(profile))
// Registry-scoped variant: resolve a backend for (connectionId, profile).
// connectionId '' / 'local' / the registry primary all behave sensibly; the
-// local kind delegates to ensureBackend so legacy behavior is untouched.
+// local kind delegates to ensureBackend when the v1 route is local, and
+// forces a genuinely-local child when the v1 global mode is remote (the
+// registry 'local' entry always means this machine).
ipcMain.handle('hermes:connection:for', async (_event, payload) => {
const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)