The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): unscopable mutations keep a process-scoped backend; stamp shared-primary event provenance
teknium125c74f731cb6
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.tsindex fd87fef6cd8..2cdae3d67fa 100644--- a/apps/desktop/electron/connection-config.test.ts+++ b/apps/desktop/electron/connection-config.test.ts@@ -376,7 +376,11 @@ const ROUTES = [expected: { backend: 'pool', descriptorProfile: null, scopePath: false }},{- name: 'an unscoped local profile request shares the host backend, scoped per request',+ // THE INVARIANT this collapse must not eat: a route the server cannot+ // profile-scope has only the backend PROCESS's HERMES_HOME left as a+ // scope, so it keeps a pooled backend. /api/files/upload acts on host+ // paths and takes no `profile` even after #118275.+ name: 'a mutating local request the server cannot scope keeps its pooled backend',profile: 'coder',opts: {primaryProfile: 'default',@@ -385,6 +389,34 @@ const ROUTES = [requestMethod: 'POST',requestPath: '/api/files/upload'},+ expected: { backend: 'pool', descriptorProfile: null, scopePath: false }+ },+ {+ // Same unscopable route, safe method: a read cannot corrupt the wrong+ // home, and holding reads back would spawn a backend per profile again.+ name: 'a read on an unscopable route still shares the host backend',+ profile: 'coder',+ opts: {+ primaryProfile: 'default',+ globalRemote: false,+ profileRemoteOverride: false,+ requestMethod: 'GET',+ requestPath: '/api/files/upload'+ },+ expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }+ },+ {+ // #118275 taught this handler `?profile=`, so the server CAN vouch for the+ // scope and the same destructive call rides the shared host backend.+ name: 'a destructive local request the server can scope shares the host backend',+ profile: 'coder',+ opts: {+ primaryProfile: 'default',+ globalRemote: false,+ profileRemoteOverride: false,+ requestMethod: 'POST',+ requestPath: '/api/memory/reset'+ },expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }},{@@ -436,7 +468,10 @@ const ROUTES = [expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }},{- name: 'a local session write shares the host backend, scoped per request',+ // Scoped by `body.profile` (rename_session_endpoint -> `_with_db`), not by+ // the query: shares the host backend with its path left alone. Appending+ // `?profile=` here would advertise a scope the handler ignores.+ name: 'a local session write shares the host backend, scoped by its body',profile: 'coder',opts: {primaryProfile: 'default',@@ -445,7 +480,7 @@ const ROUTES = [requestMethod: 'PATCH',requestPath: '/api/sessions/session-1'},- expected: { backend: 'primary', descriptorProfile: 'coder', scopePath: true }+ expected: { backend: 'primary', descriptorProfile: null, scopePath: false }},{name: 'a profile-management request uses the primary without a query scope',@@ -811,6 +846,57 @@ test('resolveProfileApiRequest scopes destructive profile-owned routes to the sh}})+test('resolveProfileApiRequest keeps an unscopable mutating route on a process-scoped backend', () => {+ // The load-bearing half of the collapse: a route the server cannot scope has+ // nothing left but the backend process's own HERMES_HOME, so it must NOT fall+ // through to the shared primary. Live proof of the failure mode this pins:+ // `POST /api/memory/reset?profile=beta` on an unfixed server deleted ALPHA's+ // MEMORY.md and returned ok:true.+ for (const [method, path] of [+ ['POST', '/api/files/upload'],+ ['DELETE', '/api/files/managed'],+ // A hypothetical future route: the gate is derived from+ // localPrimaryRequestScope(), not from a hardcoded list, so an endpoint+ // nobody has taught `profile` is held back the day it is added.+ ['POST', '/api/not-a-real-route/destroy']+ ]) {+ assert.deepEqual(+ resolveProfileApiRequest('iris', path, {+ globalRemote: false,+ profileRemoteOverride: false,+ requestMethod: method+ }),+ { backendProfile: 'iris', requestPath: path },+ `${method} ${path} must keep its own backend`+ )+ }++ // ...and the gate is about SCOPE, not about the word "destructive": the same+ // unscopable paths read fine on the shared backend.+ assert.deepEqual(+ resolveProfileApiRequest('iris', '/api/files/managed', {+ globalRemote: false,+ profileRemoteOverride: false,+ requestMethod: 'GET'+ }),+ { backendProfile: null, requestPath: '/api/files/managed?profile=iris' }+ )+})++test('resolveProfileApiRequest leaves a body-scoped session write unqueried on the shared backend', () => {+ // PATCH /api/sessions/{id} reads its target DB from `body.profile`; the query+ // is ignored. apps/desktop/src/api/sessions.ts always names the owner in the+ // body (sessionWriteProfile), so this rides the shared host backend.+ assert.deepEqual(+ resolveProfileApiRequest('iris', '/api/sessions/session-1', {+ globalRemote: false,+ profileRemoteOverride: false,+ requestMethod: 'PATCH'+ }),+ { backendProfile: null, requestPath: '/api/sessions/session-1' }+ )+})+test('resolveProfileApiRequest uses exact method and path eligibility for mixed families', () => {assert.deepEqual(resolveProfileApiRequest('iris', '/api/skills', {@@ -818,11 +904,13 @@ test('resolveProfileApiRequest uses exact method and path eligibility for mixed}),{ backendProfile: null, requestPath: '/api/skills?profile=iris' })+ // Only `GET /api/skills` is eligible: the exact method matters, and an+ // unlisted mutating method keeps its own process-scoped backend.assert.deepEqual(resolveProfileApiRequest('iris', '/api/skills', {requestMethod: 'POST'}),- { backendProfile: null, requestPath: '/api/skills?profile=iris' }+ { backendProfile: 'iris', requestPath: '/api/skills' })assert.deepEqual(resolveProfileApiRequest('iris', '/api/config/defaults', {diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.tsindex 78e2f04fd75..702088c96f7 100644--- a/apps/desktop/electron/connection-config.ts+++ b/apps/desktop/electron/connection-config.ts@@ -705,9 +705,48 @@ function localPrimaryRequestScope(opts: ProfileRouteOptions): boolean | null {return true}+ // Session WRITES are scoped by `body.profile` (`rename_session_endpoint` ->+ // `_with_db(body.profile, ...)`), not by the query. They ARE scopable — just+ // not through the URL — so they belong on the shared backend with the path+ // left alone; `apps/desktop/src/api/sessions.ts` always names the owner in+ // the body. Returning `true` here would append a `?profile=` the handler+ // ignores and advertise a scope that is not doing the work.+ if (method !== 'GET' && (pathname === '/api/sessions' || pathname.startsWith('/api/sessions/'))) {+ return false+ }+return null}+const SAFE_REQUEST_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])++/**+ * True when this is a REST request that CHANGES something and the server cannot+ * vouch for its profile scope (`localPrimaryRequestScope` → null: no+ * `?profile=`, no `body.profile`, no target named in the path).+ *+ * Such a route has exactly one scope left — the backend process's own+ * `HERMES_HOME` — so it keeps a pooled, profile-scoped backend even though every+ * other local request now shares the host one. Mechanical on purpose: the day a+ * handler learns to read `profile` it joins `LOCAL_PRIMARY_SCOPED_ROUTES` (or a+ * family above), `localPrimaryRequestScope` stops returning null, and this+ * predicate stops seeing it — there is no second list to keep in sync.+ *+ * A call with no `requestPath` is a BACKEND/descriptor resolution (WebSocket+ * dial, pool bookkeeping), not a REST call, and is never held back.+ */+export function unscopableMutatingRequest(opts: ProfileRouteOptions = {}): boolean {+ if (!String(opts.requestPath || '')) {+ return false+ }++ if (SAFE_REQUEST_METHODS.has(String(opts.requestMethod || 'GET').toUpperCase())) {+ return false+ }++ return localPrimaryRequestScope(opts) === null+}+/*** The one place that answers "which backend serves profile P, and does its* REST path need a profile scope?". Six routes, in precedence order:@@ -720,11 +759,16 @@ function localPrimaryRequestScope(opts: ProfileRouteOptions): boolean | null {* 3. A profile inheriting the app-global remote shares the primary backend —* one host serves every profile — so it is scoped per request instead.* 4. An unknown profile under a remote primary shares that remote backend.- * A stored local profile remains isolated in its own backend.- * 5. A local profile REST request that the primary backend can safely scope- * reuses that backend, with `?profile=` when the handler accepts it.- * 6. Any other local profile gets its own pooled backend, spawned with- * `--profile`, so its `HERMES_HOME` scopes it.+ * A stored local profile keeps its own pooled backend instead.+ * 5. A local profile REST request the primary backend can scope reuses that+ * backend, with `?profile=` when the handler reads the query (handlers that+ * name their target in the path or `body.profile` get no query).+ * 6. Every other LOCAL profile also shares the one host backend+ * (multiplex-only: one `hermes serve` per HOST). The two ways out are+ * `HERMES_DESKTOP_ISOLATED_BACKEND=1`, which gives this app a private+ * backend, and a MUTATING request the server cannot scope at all — that+ * one keeps a pooled backend whose HERMES_HOME does the scoping, so a+ * destructive call can never fall through to the primary's home.** Routing used to be spread across three overlapping predicates that each* re-derived part of this table, which is how case 3 ended up registering@@ -782,9 +826,10 @@ 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 })) {+ // a `hermes serve` child of its own — UNLESS this request mutates state+ // the server cannot scope, in which case the pooled backend's own+ // HERMES_HOME is the only scope left and it keeps one.+ if (sharesHostBackend({ isolated: opts.isolatedBackend, unscopableRequest: unscopableMutatingRequest(opts) })) {return { backend: 'primary', descriptorProfile: scopedProfile, scopePath: true }}diff --git a/apps/desktop/electron/host-backend-singleton.test.ts b/apps/desktop/electron/host-backend-singleton.test.tsindex 3883c49088d..5e16e736851 100644--- a/apps/desktop/electron/host-backend-singleton.test.ts+++ b/apps/desktop/electron/host-backend-singleton.test.ts@@ -4,7 +4,7 @@ import assert from 'node:assert/strict'import { test } from 'vitest'-import { resolveProfileBackendRoute } from './connection-config'+import { resolveProfileBackendRoute, unscopableMutatingRequest } from './connection-config'import { assertNoSecondLocalBackend, SecondLocalBackendError, sharesHostBackend } from './host-backend-singleton'const LOCAL = { globalRemote: false, primaryProfile: 'default', profileRemoteOverride: false }@@ -47,4 +47,35 @@ test('the local pool spawn path is unreachable, and the escape hatches still reaassert.equal(sharesHostBackend({ primaryRemoteActive: true }), false)assertNoSecondLocalBackend('worker', { profileRemoteOverride: true })assert.equal(resolveProfileBackendRoute('worker', { ...LOCAL, profileRemoteOverride: true }).backend, 'pool')++ // A mutating request the server cannot profile-scope is the third way+ // through: the pooled backend's HERMES_HOME is its only scope, so the guard+ // must let that spawn happen instead of refusing a legitimate route.+ assert.equal(sharesHostBackend({ unscopableRequest: true }), false)+ assertNoSecondLocalBackend('worker', { unscopableRequest: true })+})++test('the spawn guard and the router agree on which requests keep a backend', () => {+ // The guard is a backstop, not a second opinion: every request the router+ // sends to the pool must be one the guard admits, or the destructive write+ // fails with SecondLocalBackendError instead of reaching the right home.+ const cases: Array<[string, string]> = [+ ['POST', '/api/files/upload'],+ ['DELETE', '/api/files/managed'],+ ['POST', '/api/skills'],+ ['POST', '/api/memory/reset'],+ ['GET', '/api/config'],+ ['PATCH', '/api/sessions/session-1']+ ]++ for (const [requestMethod, requestPath] of cases) {+ const opts = { ...LOCAL, requestMethod, requestPath }+ const pooled = resolveProfileBackendRoute('worker', opts).backend === 'pool'++ assert.equal(+ sharesHostBackend({ unscopableRequest: unscopableMutatingRequest(opts) }),+ !pooled,+ `${requestMethod} ${requestPath}: guard and router disagree`+ )+ }})diff --git a/apps/desktop/electron/host-backend-singleton.ts b/apps/desktop/electron/host-backend-singleton.tsindex 1ab27f52d4f..0450eb5585c 100644--- a/apps/desktop/electron/host-backend-singleton.ts+++ b/apps/desktop/electron/host-backend-singleton.ts@@ -27,6 +27,13 @@ export interface HostBackendCollapseOptions {profileRemoteOverride?: boolean/** The primary profile's backend is itself a remote host. */primaryRemoteActive?: boolean+ /**+ * This request MUTATES state the server cannot profile-scope+ * (`connection-config.ts::unscopableMutatingRequest`). The pooled backend's+ * own `HERMES_HOME` is then the only scope there is, so the collapse must+ * not swallow it — and the spawn guard below must not refuse it.+ */+ unscopableRequest?: boolean}/**@@ -35,7 +42,7 @@ export interface HostBackendCollapseOptions {* route, never meant a local child in the first place.*/export function sharesHostBackend(opts: HostBackendCollapseOptions = {}): boolean {- if (opts.isolated) {+ if (opts.isolated || opts.unscopableRequest) {return false}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 6b69650512e..38dd6293d9f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -141,6 +141,7 @@ import {sanitizeRemoteHeaderValue,savedProfileSsh,tokenPreview,+ unscopableMutatingRequest,withTransientRetries} from './connection-config'import { applyConnectionConfigAtomically } from './connection-config-apply'@@ -1668,10 +1669,6 @@ function promotePoolEntry(entry: any): void {entry.localBackendSpawnRequest?.promote?.('foreground')}-// 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// storm while a user-triggered foreground open still gets its reserved slot.@@ -11421,7 +11418,10 @@ function profileRouteOptions(profile, request?) {// Resolve a backend connection for the given profile, per the routing table in// resolveProfileBackendRoute(). An empty / unknown profile resolves to the// primary, so legacy callers are unchanged.-async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}) {+async function ensureBackend(+ profile,+ opts: { passive?: boolean; request?: { method?: string; path?: string }; spawnPriority?: LocalBackendSpawnPriority } = {}+) {localBackendLifecycle.assertCanStart()const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()const spawnPriority = spawnPriorityFrom(opts.spawnPriority)@@ -11430,7 +11430,12 @@ async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?:profileDeletionGate.assertCanStart(key)- const route = resolveProfileBackendRoute(key, profileRouteOptions(key))+ // The REQUEST is part of the routing decision (case 5/6): resolving without+ // it would collapse a profile onto the shared backend that the caller's+ // resolveProfileApiRequest deliberately kept pooled, and the unscopable+ // destructive write would execute against the primary's home after all.+ const routeOpts = profileRouteOptions(key, opts.request)+ const route = resolveProfileBackendRoute(key, routeOpts)if (route.backend === 'primary') {const connection = await startHermes()@@ -11493,7 +11498,9 @@ async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?:spawnPriority}- entry.connectionPromise = spawnPoolBackend(key, entry).catch(async error => {+ entry.connectionPromise = spawnPoolBackend(key, entry, {+ unscopableRequest: unscopableMutatingRequest(routeOpts)+ }).catch(async error => {// Land the failure in desktop.log: without this a spawn that dies before// its child exists (guard rejection, runtime resolution) leaves no trace// beyond renderer-side rejections users never see in a bundle.@@ -12506,11 +12513,19 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>// 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.-function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {+function spawnPoolBackend(+ profile,+ entry,+ opts: { forceLocal?: boolean; poolKey?: string; unscopableRequest?: boolean } = {}+) {return localBackendLifecycle.start(() => runPoolBackendStart(profile, entry, opts))}-async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {+async function runPoolBackendStart(+ profile,+ entry,+ opts: { forceLocal?: boolean; poolKey?: string; unscopableRequest?: boolean } = {}+) {const poolKey = opts.poolKey || profileawait reapOrphanedBackendsOnce()@@ -12544,10 +12559,16 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;// 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.+ // Same options object the router reads, so the guard cannot drift from it+ // (profileRouteOptions folds the per-profile SSH override into+ // profileRemoteOverride; a hand-rolled term here missed that).+ const guardRoute = profileRouteOptions(profile)+assertNoSecondLocalBackend(poolKey, {- isolated: ISOLATED_BACKEND,- primaryRemoteActive: primaryBackendIsRemote(),- profileRemoteOverride: opts.forceLocal ? false : Boolean(profileRemoteOverride(readDesktopConnectionConfig(), profile))+ isolated: guardRoute.isolatedBackend,+ primaryRemoteActive: guardRoute.primaryRemoteActive,+ profileRemoteOverride: opts.forceLocal ? false : guardRoute.profileRemoteOverride,+ unscopableRequest: opts.unscopableRequest})// Bound the slot wait BELOW the renderer's backend-boot budget (45s): once@@ -17166,9 +17187,11 @@ async function handleHermesApiRequest(request) {// backend calls ensure_hermes_home() which recreates the profile directory,// defeating the deletion and leaving a zombie process.//- // Safe local-profile REST calls also stay on the primary dashboard and carry- // ?profile=. Endpoints that cannot honor that scope retain their pooled- // backend so a destructive call can never fall through to the primary home.+ // Local-profile REST calls stay on the primary dashboard and carry ?profile=+ // (or name the profile in the path / PATCH body). A request that MUTATES+ // state the server cannot scope at all retains its pooled backend, whose+ // HERMES_HOME is then the scope, so a destructive call can never fall+ // through to the primary home — `resolveProfileBackendRoute` case 6.//// A profile rename tears down the old-name backend the same way; for a// primary rename the lifecycle has already made `default` the temporary@@ -17183,7 +17206,11 @@ async function handleHermesApiRequest(request) {let connectiontry {- connection = await ensureBackend(routeProfile, { passive: request?.passive, spawnPriority })+ connection = await ensureBackend(routeProfile, {+ passive: request?.passive,+ request: { method: request?.method, path: request?.path },+ spawnPriority+ })const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)response = await fetchJsonForBackend(connection, apiRoute.requestPath, {diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.tsindex 3376573b562..f3399eab4aa 100644--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@ -5,6 +5,7 @@ vi.mock('@/store/transcript-tail', () => ({ recordTranscriptTail: vi.fn() }))vi.mock('./client', () => ({capabilityScoped: vi.fn(),getApiRequestConnection: vi.fn(() => 'prometheus'),+ getApiRequestProfile: vi.fn(() => null),hermesApi: vi.fn(),profileScoped: vi.fn(() => ({}))}))@@ -25,6 +26,7 @@ const hermesApi = vi.mocked(client.hermesApi)beforeEach(() => {vi.clearAllMocks()vi.mocked(client.getApiRequestConnection).mockReturnValue('prometheus')+ vi.mocked(client.getApiRequestProfile).mockReturnValue(null)})describe('deleteSession profile scoping', () => {@@ -124,11 +126,29 @@ describe('setSessionArchived profile scoping', () => {})})- it('omits the profile from the body when none is given', async () => {+ it('falls back to the ACTIVE profile in the body when no owner is given', async () => {+ // Multiplex-only: the PATCH handler resolves its state.db from+ // `body.profile` and there is no per-profile backend whose HERMES_HOME+ // could stand in. An unnamed owner therefore has to mean "the profile I am+ // looking at" — otherwise the archive lands on the shared backend's own+ // state.db and silently no-ops.hermesApi.mockResolvedValue({ ok: true } as never)+ vi.mocked(client.getApiRequestProfile).mockReturnValue('beta')await setSessionArchived('sess-b', false)+ expect(hermesApi.mock.calls[0][0]).toMatchObject({+ method: 'PATCH',+ profile: 'beta',+ body: { archived: false, profile: 'beta' }+ })+ })++ it('omits the profile from the body only when there is no active profile at all', async () => {+ hermesApi.mockResolvedValue({ ok: true } as never)++ await setSessionArchived('sess-b2', false)+const req = hermesApi.mock.calls[0][0] as { body: Record<string, unknown> }expect(req).toMatchObject({ method: 'PATCH', body: { archived: false } })expect(req.body).not.toHaveProperty('profile')@@ -162,14 +182,17 @@ describe('setSessionPinnedRemote / setSessionUnreadRemote profile scoping', () =})})- it('omits the profile from the body when none is given', async () => {+ it('falls back to the ACTIVE profile in the body when no owner is given', async () => {hermesApi.mockResolvedValue({ ok: true } as never)+ vi.mocked(client.getApiRequestProfile).mockReturnValue('beta')await setSessionPinnedRemote('sess-p2', false)- const req = hermesApi.mock.calls[0][0] as { body: Record<string, unknown> }- expect(req).toMatchObject({ method: 'PATCH', body: { pinned: false } })- expect(req.body).not.toHaveProperty('profile')+ expect(hermesApi.mock.calls[0][0]).toMatchObject({+ method: 'PATCH',+ profile: 'beta',+ body: { pinned: false, profile: 'beta' }+ })})})diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.tsindex 81c938caf49..d983fc10336 100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@ -42,6 +42,18 @@ function sessionScoped(scope?: ProfileScope): { connectionId?: string; profile?:return scoped}+/**+ * The profile a session WRITE must name in its body. The PATCH handler reads+ * its target DB from `body.profile` alone (`_with_db(body.profile, ...)`), and+ * under multiplex-only there is no per-profile backend whose HERMES_HOME could+ * stand in for it: an unnamed owner lands the rename/pin/archive/mark-read on+ * the shared backend's own state.db. "Unnamed" therefore means "the profile I+ * am looking at", not "whatever home the backend was launched in".+ */+function sessionWriteProfile(profile?: null | string): string | undefined {+ return String(profile ?? '').trim() || getApiRequestProfile() || undefined+}+function sessionScopeQuery(scope?: ProfileScope): string {const profile = sessionScoped(scope).profile@@ -344,11 +356,13 @@ export function setSessionArchived(id: string, archived: boolean, profile?: stri// remote gateway with no remoteProfile alias: the archive lands on the wrong// (default) state.db, no-ops on a missing row, and the archived/unarchived// state silently fails to stick — the same class as the unscoped DELETE.+ const owner = sessionWriteProfile(profile)+return hermesApi<{ ok: boolean }>({- ...(profile ? { profile } : {}),+ ...(owner ? { profile: owner } : {}),path: `/api/sessions/${encodeURIComponent(id)}`,method: 'PATCH',- body: { archived, ...(profile ? { profile } : {}) }+ body: { archived, ...(owner ? { profile: owner } : {}) }})}@@ -360,11 +374,13 @@ export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: st// Owning profile in the PATCH body (see setSessionArchived / renameSession):// the handler reads its target DB from body.profile, so a remote/foreign// profile's pin must travel in the body or it no-ops on the wrong state.db.+ const owner = sessionWriteProfile(profile)+return hermesApi<{ ok: boolean }>({- ...(profile ? { profile } : {}),+ ...(owner ? { profile: owner } : {}),path: `/api/sessions/${encodeURIComponent(id)}`,method: 'PATCH',- body: { pinned, ...(profile ? { profile } : {}) }+ body: { pinned, ...(owner ? { profile: owner } : {}) }})}@@ -377,11 +393,13 @@ export function setSessionUnreadRemote(id: string, unread: boolean, profile?: st// the handler reads its target DB from body.profile, so a remote/foreign// profile's unread toggle must travel in the body or it no-ops on the wrong// state.db.+ const owner = sessionWriteProfile(profile)+return hermesApi<{ ok: boolean }>({- ...(profile ? { profile } : {}),+ ...(owner ? { profile: owner } : {}),path: `/api/sessions/${encodeURIComponent(id)}`,method: 'PATCH',- body: { unread, ...(profile ? { profile } : {}) }+ body: { unread, ...(owner ? { profile: owner } : {}) }})}@@ -633,10 +651,12 @@ export function renameSession(title: string,profile?: string | null): Promise<{ ok: boolean; title: string }> {+ const owner = sessionWriteProfile(profile)+return hermesApi<{ ok: boolean; title: string }>({- ...(profile ? { profile } : {}),+ ...(owner ? { profile: owner } : {}),path: `/api/sessions/${encodeURIComponent(id)}`,method: 'PATCH',- body: { title, ...(profile ? { profile } : {}) }+ body: { title, ...(owner ? { profile: owner } : {}) }})}diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsxindex fb117d2b8a2..b2f3975d3ec 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx@@ -43,7 +43,13 @@ import {setActiveSessionId,setSelectedStoredSessionId} from '@/store/session'-import { $sessionTiles, $workingSessionIds, clearAllSessionStates, publishSessionState } from '@/store/session-states'+import {+ $sessionTiles,+ $workingSessionIds,+ clearAllSessionStates,+ publishSessionState,+ runtimeSessionOwner+} from '@/store/session-states'import { warnIfTerminalBackendUnavailable } from '@/store/terminal-backend-warning'import { deferred } from '../../../test/deferred'@@ -677,6 +683,67 @@ describe('primary failure foreground isolation', () => {)})+describe('shared host backend event provenance', () => {+ // Multiplex-only: ONE backend serves every local profile, so the primary+ // socket carries profile B's events and no secondary closure exists to stamp+ // them. Unstamped, runtimeSessionOwner() is blank for B and the live+ // sessions/cron sync falls back to slow polling.+ // A LOCAL host backend: no registry connection id, so ownership can only come+ // from the stamp (a registry-tagged event already carries its exact owner).+ const sharedPrimaryConn = {+ ...primaryConn,+ baseUrl: 'http://127.0.0.1:8899',+ connectionId: '',+ profile: 'beta',+ sharedPrimary: true,+ wsUrl: 'ws://127.0.0.1:8899/api/ws?token=t'+ }++ function deliverEvent(socket: FakeWebSocket, frame: Record<string, unknown>) {+ ;(socket as unknown as { emit: (type: string, ev: unknown) => void }).emit('message', {+ data: JSON.stringify({ jsonrpc: '2.0', method: 'event', params: frame })+ })+ }++ it("stamps a shared-primary profile-B event with B, not with the boot-time profile", async () => {+ const desktop = fakeDesktop()++ desktop.getConnection.mockResolvedValue(sharedPrimaryConn)+ desktop.getGatewayWsUrl.mockResolvedValue(sharedPrimaryConn.wsUrl)+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop++ render(<Harness />)+ await flushAsync()++ expect($gatewayState.get()).toBe('open')++ // The window moved to profile B after boot; the socket did not.+ act(() => {+ $connection.set(sharedPrimaryConn as unknown as ReturnType<typeof $connection.get>)+ $activeGatewayProfile.set('beta')+ })++ act(() => {+ deliverEvent(FakeWebSocket.instances[0], { session_id: 'rt-B', type: 'session.info' })+ })++ expect(runtimeSessionOwner('rt-B')).toBe('beta')+ })++ it('leaves an unshared primary on its exact owner — the socket already IS its profile', async () => {+ render(<Harness />)+ await flushAsync()++ act(() => {+ deliverEvent(FakeWebSocket.instances[0], { session_id: 'rt-A', type: 'session.info' })+ })++ // The registry (connectionId, profile) owner, NOT a bare-profile marker:+ // the stamp is reserved for the shared-primary topology.+ expect(runtimeSessionOwner('rt-A')).toEqual({ connectionId: 'primary-vps', profile: 'default' })+ })+})+describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () => {it('parks rejected primary auth across timers and wake signals until explicit recovery', async () => {const desktop = fakeDesktop()diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 9602d1c281a..28176c31358 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -85,6 +85,7 @@ import {setCurrentCwd,setSessionsLoading} from '@/store/session'+import { stampSecondaryProfileOwner } from '@/store/session-event-provenance'import {$attentionSessionIds,$sessionOwnerHoldRevision,@@ -1012,10 +1013,15 @@ export function useGatewayBoot({}})- const sourceProfile = normalizeProfileKey($activeGatewayProfile.get())+ // Read PER EVENT, never once at boot: under multiplex-only this one socket+ // serves every local profile, and the profile moves under it while the+ // socket stays open. A boot-time capture stamps every later profile's+ // events with whatever was active when the gateway booted.+ const sourceProfileNow = () => normalizeProfileKey($activeGatewayProfile.get())const offEvent = gateway.onEvent(event => {const connectionId = activeGatewayConnectionId()+ const sourceProfile = sourceProfileNow()const scopedEvent = {...event,@@ -1023,12 +1029,25 @@ export function useGatewayBoot({...(connectionId ? { connectionId } : {})}- recordSessionEventScope(scopedEvent)- callbacksRef.current.handleGatewayEvent(scopedEvent)+ // On a shared host backend the socket no longer PROVES the profile the+ // way a pooled secondary's closure did, so nothing stamps ownership and+ // runtimeSessionOwner() stays blank for every non-primary local profile+ // — the live sessions/cron sync dies and falls back to slow polling.+ // The shared-primary descriptor is exactly the topology where the active+ // profile is the authority for this socket's traffic. (The marker is the+ // LAST rung of knownOwnerForSession, so durable stored identity still+ // outranks it — #97511.)+ const ownedEvent =+ $connection.get()?.sharedPrimary === true+ ? stampSecondaryProfileOwner(scopedEvent, sourceProfile)+ : scopedEvent++ recordSessionEventScope(ownedEvent)+ callbacksRef.current.handleGatewayEvent(ownedEvent)})// Secondary sockets reach the same handler through the registry's onServerRequest.- const offRequest = gateway.onRequest(request => dispatchPrimaryServerRequest(request, sourceProfile))+ const offRequest = gateway.onRequest(request => dispatchPrimaryServerRequest(request, sourceProfileNow()))// Wake signals: power resume (macOS/Windows), network coming back, and the// window regaining focus/visibility. Each nudges an immediate reconnect.