Skip to content

The agent that grows with you

refactor(desktop): collapse the per-profile backend pool onto one host backend

teknium158eb248d0801
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index 0ccd85cb8f7..fd87fef6cd8 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -376,7 +376,7 @@ const ROUTES = [
expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
},
{
- name: 'an unscoped local profile request keeps its pooled backend',
+ name: 'an unscoped local profile request shares the host backend, scoped per request',
profile: 'coder',
opts: {
primaryProfile: 'default',
@@ -385,7 +385,7 @@ const ROUTES = [
requestMethod: 'POST',
requestPath: '/api/files/upload'
},
- expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
+ expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }
},
{
name: 'a remote sub-profile without a local entry routes through the primary remote gateway',
@@ -436,7 +436,7 @@ const ROUTES = [
expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }
},
{
- name: 'a local session write keeps its pooled backend',
+ name: 'a local session write shares the host backend, scoped per request',
profile: 'coder',
opts: {
primaryProfile: 'default',
@@ -445,7 +445,7 @@ const ROUTES = [
requestMethod: 'PATCH',
requestPath: '/api/sessions/session-1'
},
- expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
+ expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }
},
{
name: 'a profile-management request uses the primary without a query scope',
@@ -472,6 +472,17 @@ const ROUTES = [
requestPath: '/api/config'
},
expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
+ },
+ {
+ name: 'HERMES_DESKTOP_ISOLATED_BACKEND keeps a local profile on its own pooled backend',
+ profile: 'coder',
+ opts: {
+ primaryProfile: 'default',
+ globalRemote: false,
+ profileRemoteOverride: false,
+ isolatedBackend: true
+ },
+ expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
}
]
@@ -599,13 +610,15 @@ test('pathWithGlobalRemoteProfile does not replace an explicit profile query', (
)
})
-test('pathWithGlobalRemoteProfile skips local and per-profile remote override paths', () => {
+test('pathWithGlobalRemoteProfile scopes a shared-host local path and skips per-profile remote overrides', () => {
+ // Multiplex-only: the local profile now shares the host backend, so its
+ // path must name the profile or the request reads the launch home.
assert.equal(
pathWithGlobalRemoteProfile('/api/model/info', 'iris', {
globalRemote: false,
profileRemoteOverride: false
}),
- '/api/model/info'
+ '/api/model/info?profile=iris'
)
assert.equal(
pathWithGlobalRemoteProfile('/api/model/info', 'iris', {
@@ -684,7 +697,7 @@ test('translateSelfProfileQuery no-ops when alias and backend profile agree or a
assert.equal(translateSelfProfileQuery('/api/cron/jobs?profile=mara', '', 'default'), '/api/cron/jobs?profile=mara')
})
-test('pathWithGlobalRemoteProfile appends local-primary profile scope only for eligible routes', () => {
+test('pathWithGlobalRemoteProfile appends the profile scope on the shared host backend', () => {
assert.equal(
pathWithGlobalRemoteProfile('/api/config', 'iris', {
globalRemote: false,
@@ -713,6 +726,17 @@ test('pathWithGlobalRemoteProfile appends local-primary profile scope only for e
}),
'/api/files/upload'
)
+ // The profile-management family names its target in the path and must not
+ // be self-scoped.
+ assert.equal(
+ pathWithGlobalRemoteProfile('/api/profiles/worker', 'iris', {
+ globalRemote: false,
+ profileRemoteOverride: false,
+ requestMethod: 'DELETE',
+ requestPath: '/api/profiles/worker'
+ }),
+ '/api/profiles/worker'
+ )
})
test('pathWithGlobalRemoteProfile skips empty profile/path safely', () => {
@@ -764,8 +788,9 @@ test('resolveProfileApiRequest scopes read-only session probes without spawning
test('resolveProfileApiRequest scopes destructive profile-owned routes to the shared backend', () => {
// These handlers used to read the process home directly, so they had to ride a
- // per-profile backend. They now take `?profile=` and refuse an unnamed profile
- // while several are served, so the shared primary is what reaches the right home.
+ // per-profile backend. No per-profile backend exists any more, and they now take
+ // `?profile=` and refuse an unnamed profile while several are served, so the
+ // query param is what reaches the right home.
for (const [method, path] of [
['POST', '/api/memory/reset'],
['POST', '/api/curator/run'],
@@ -797,21 +822,21 @@ test('resolveProfileApiRequest uses exact method and path eligibility for mixed
resolveProfileApiRequest('iris', '/api/skills', {
requestMethod: 'POST'
}),
- { backendProfile: 'iris', requestPath: '/api/skills' }
+ { backendProfile: null, requestPath: '/api/skills?profile=iris' }
)
assert.deepEqual(
resolveProfileApiRequest('iris', '/api/config/defaults', {
requestMethod: 'GET'
}),
- { backendProfile: 'iris', requestPath: '/api/config/defaults' }
+ { backendProfile: null, requestPath: '/api/config/defaults?profile=iris' }
)
assert.deepEqual(
resolveProfileApiRequest('iris', '/api/model/recommended-default?provider=nous', {
requestMethod: 'GET'
}),
{
- backendProfile: 'iris',
- requestPath: '/api/model/recommended-default?provider=nous'
+ backendProfile: null,
+ requestPath: '/api/model/recommended-default?provider=nous&profile=iris'
}
)
})
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index c91c4a86144..78e2f04fd75 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -35,6 +35,7 @@
// AT cookie. A liveness check that looked only at the AT cookie would
// force a needless full re-login every ~15 min — hence cookiesHaveLiveSession.
import { readStatusCode } from './api-transport'
+import { sharesHostBackend } from './host-backend-singleton'
const AT_COOKIE_VARIANTS = ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at']
const RT_COOKIE_VARIANTS = ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt']
@@ -561,6 +562,8 @@ export interface ProfileRouteOptions {
primaryRemoteActive?: boolean
/** A stored per-profile entry exists for this profile (local or remote). */
ownEntry?: boolean
+ /** `HERMES_DESKTOP_ISOLATED_BACKEND=1`: opt out of the host singleton. */
+ isolatedBackend?: boolean
requestMethod?: null | string
requestPath?: null | string
}
@@ -777,6 +780,14 @@ function resolveProfileBackendRoute(profile, opts: ProfileRouteOptions = {}): Pr
}
}
+ // 6. Multiplex-only: every other LOCAL profile shares the one host backend
+ // too, carrying `?profile=` / the `profile` RPC param instead of getting
+ // a `hermes serve` child of its own. `HERMES_DESKTOP_ISOLATED_BACKEND=1`
+ // is the only way back to a private per-profile process.
+ if (sharesHostBackend({ isolated: opts.isolatedBackend })) {
+ return { backend: 'primary', descriptorProfile: scopedProfile, scopePath: true }
+ }
+
return { backend: 'pool', descriptorProfile: null, scopePath: false }
}
diff --git a/apps/desktop/electron/host-backend-singleton.test.ts b/apps/desktop/electron/host-backend-singleton.test.ts
new file mode 100644
index 00000000000..3883c49088d
--- /dev/null
+++ b/apps/desktop/electron/host-backend-singleton.test.ts
@@ -0,0 +1,50 @@
+// Multiplex-only invariants for the Desktop backend pool: one host backend
+// serves every profile, and the local pooled-spawn path is unreachable.
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { resolveProfileBackendRoute } from './connection-config'
+import { assertNoSecondLocalBackend, SecondLocalBackendError, sharesHostBackend } from './host-backend-singleton'
+
+const LOCAL = { globalRemote: false, primaryProfile: 'default', profileRemoteOverride: false }
+
+test('two local profiles connecting concurrently produce ZERO additional backends, each bound to its own profile', () => {
+ // The routing decision is the whole spawn decision: `ensureBackend` spawns a
+ // pooled child if and only if the route says `pool`. Resolve both profiles
+ // the way two concurrent renderer dials would.
+ const routes = ['worker', 'venture'].map(profile => resolveProfileBackendRoute(profile, LOCAL))
+
+ assert.deepEqual(
+ routes.filter(route => route.backend === 'pool'),
+ [],
+ 'a local profile must never resolve to a pooled backend of its own'
+ )
+
+ // Both land on the SAME backend and still carry distinct wire identities, so
+ // each connection's turns bind to its own home (`session.create {profile}` ->
+ // `profile_home`; sessionless RPCs take the explicit `profile` argument).
+ assert.deepEqual(
+ routes.map(route => [route.backend, route.descriptorProfile, route.scopePath]),
+ [
+ ['primary', 'worker', true],
+ ['primary', 'venture', true]
+ ]
+ )
+})
+
+test('the local pool spawn path is unreachable, and the escape hatches still reach it', () => {
+ assert.throws(() => assertNoSecondLocalBackend('worker', { isolated: false }), SecondLocalBackendError)
+
+ // HERMES_DESKTOP_ISOLATED_BACKEND=1: a private backend for this app.
+ assert.equal(sharesHostBackend({ isolated: true }), false)
+ assertNoSecondLocalBackend('worker', { isolated: true })
+ assert.equal(resolveProfileBackendRoute('worker', { ...LOCAL, isolatedBackend: true }).backend, 'pool')
+
+ // A remote/SSH backend is a DIFFERENT host: out of scope for the singleton,
+ // and its pooled descriptor never meant a local child anyway.
+ assert.equal(sharesHostBackend({ profileRemoteOverride: true }), false)
+ assert.equal(sharesHostBackend({ primaryRemoteActive: true }), false)
+ assertNoSecondLocalBackend('worker', { profileRemoteOverride: true })
+ assert.equal(resolveProfileBackendRoute('worker', { ...LOCAL, profileRemoteOverride: true }).backend, 'pool')
+})
diff --git a/apps/desktop/electron/host-backend-singleton.ts b/apps/desktop/electron/host-backend-singleton.ts
new file mode 100644
index 00000000000..1ab27f52d4f
--- /dev/null
+++ b/apps/desktop/electron/host-backend-singleton.ts
@@ -0,0 +1,83 @@
+// Multiplex-only, Desktop half: ONE `hermes serve` per HOST serves every
+// profile, so a local profile never gets a backend process of its own.
+//
+// `backend-discovery.ts` + `host-backend-attach.ts` made the PRIMARY backend
+// attach to a backend the host is already running. This module removes the
+// other producer of `hermes serve` children: the per-profile backend pool.
+// Every local profile now resolves onto the same host backend and carries its
+// own `profile` on the wire — the server binds a SESSION to a profile home
+// (`session.create {profile}` -> `profile_home`) and a sessionless RPC to the
+// explicit `profile` argument (`tui_gateway/server.py::@_profile_scoped`), so
+// one process genuinely serves N homes.
+//
+// Two things are deliberately NOT collapsed:
+// * `HERMES_DESKTOP_ISOLATED_BACKEND=1` — the escape hatch that gives this
+// app a private backend instead of the host's.
+// * Remote / SSH / Cloud backends — a DIFFERENT host. Its ownership proof
+// (`remote-lifecycle.ts` isolated_count === 1) is about that machine's
+// process, not ours, and stays pooled.
+//
+// Pure and dependency-injected so the decision tests without Electron.
+
+/** Everything the collapse decision needs about one profile's routing. */
+export interface HostBackendCollapseOptions {
+ /** `HERMES_DESKTOP_ISOLATED_BACKEND=1`: this app wants its own backend. */
+ isolated?: boolean
+ /** This profile points at its own remote host (connection.json / SSH). */
+ profileRemoteOverride?: boolean
+ /** The primary profile's backend is itself a remote host. */
+ primaryRemoteActive?: boolean
+}
+
+/**
+ * True when a LOCAL profile shares the one host backend instead of spawning
+ * its own. False keeps the legacy pooled descriptor — which, for a remote
+ * route, never meant a local child in the first place.
+ */
+export function sharesHostBackend(opts: HostBackendCollapseOptions = {}): boolean {
+ if (opts.isolated) {
+ return false
+ }
+
+ return !opts.profileRemoteOverride && !opts.primaryRemoteActive
+}
+
+/** Raised when something still tries to start a second local backend. */
+export class SecondLocalBackendError extends Error {
+ readonly poolKey: string
+
+ constructor(poolKey: string) {
+ super(
+ `Refusing to start a second local Hermes backend for "${poolKey}": one backend serves every profile on this host. ` +
+ 'Set HERMES_DESKTOP_ISOLATED_BACKEND=1 for a private backend.'
+ )
+ this.name = 'SecondLocalBackendError'
+ this.poolKey = poolKey
+ }
+}
+
+/**
+ * The single enforcement point for "never spawn a second backend".
+ *
+ * Routing is what normally prevents a pooled local spawn; this guard sits at
+ * the one place a local `hermes serve` child is actually started, so a future
+ * caller that reaches it through a path routing does not cover fails loudly
+ * instead of quietly reintroducing a process per profile.
+ */
+export function assertNoSecondLocalBackend(poolKey: string, opts: HostBackendCollapseOptions = {}): void {
+ if (sharesHostBackend(opts)) {
+ throw new SecondLocalBackendError(poolKey)
+ }
+}
+
+/**
+ * A passive read (background tile reconcile, #103375) may only be served by a
+ * backend that already exists: it never cold-starts a child and never
+ * refreshes `lastActiveAt`, so an open-but-unviewed tile cannot keep the pool
+ * saturated. Callers treat the rejection as "nothing to refresh yet".
+ */
+export function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {
+ if (passive) {
+ throw new Error(`Passive read: no warm backend for "${poolKey}"`)
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 037e7deb569..6b69650512e 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -261,6 +261,7 @@ import {
spawnLedgerPath,
type SpawnReservation
} from './host-backend-attach'
+import { assertNoSecondLocalBackend, assertNotPassiveSpawn } from './host-backend-singleton'
import { requestHudClose } from './hud-close'
import { cursorPointInWindow } from './hud-cursor'
import { startHudGameOverlayWatch } from './hud-game-overlay'
@@ -1667,16 +1668,9 @@ function promotePoolEntry(entry: any): void {
entry.localBackendSpawnRequest?.promote?.('foreground')
}
-// A passive read (background tile reconcile, #103375) may only be served by a
-// backend that already exists: it never cold-starts a pooled child, never
-// takes a slot, and never refreshes lastActiveAt, so an open-but-unviewed tile
-// cannot keep the pool saturated. Callers treat the rejection as "nothing to
-// refresh yet"; primary-routed profiles are always warm and never reach here.
-function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {
- if (passive) {
- throw new Error(`Passive read: no warm backend for "${poolKey}"`)
- }
-}
+// A passive read may only be served by a backend that already exists; the
+// guard itself lives in host-backend-singleton.ts next to the singleton
+// enforcement point (see assertNoSecondLocalBackend).
// Land a spawn failure in desktop.log. Background slot waits back off per
// profile under a saturated pool, so a roster refresh cannot create a retry
@@ -11418,6 +11412,7 @@ function profileRouteOptions(profile, request?) {
// A stored per-profile entry (local or remote) — pins this profile to
// its own backend; absent entries inherit the primary's remote.
ownEntry: Boolean((config.profiles || {})[key]),
+ isolatedBackend: ISOLATED_BACKEND,
requestMethod: request?.method,
requestPath: request?.path
}
@@ -12545,6 +12540,16 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;
}
}
+ // Everything below starts a LOCAL `hermes serve` child. Multiplex-only says
+ // the host has exactly one, and routing (resolveProfileBackendRoute case 6)
+ // keeps local profiles off this path — this is the backstop that makes the
+ // pool spawn path genuinely unreachable rather than merely unused.
+ assertNoSecondLocalBackend(poolKey, {
+ isolated: ISOLATED_BACKEND,
+ primaryRemoteActive: primaryBackendIsRemote(),
+ profileRemoteOverride: opts.forceLocal ? false : Boolean(profileRemoteOverride(readDesktopConnectionConfig(), profile))
+ })
+
// Bound the slot wait BELOW the renderer's backend-boot budget (45s): once
// the renderer has given up on this spawn, a ticket still queued for the
// pool-idle window (10 min) would hold the pool key hostage and every