The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): atomic profile-switch publication v2 — fail open, lease mid-dial entries (#89622, #46651)
Teknium2507bc649ffb
diff --git a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts b/apps/desktop/src/store/gateway-activation-prune-lease.test.tsnew file mode 100644index 00000000000..4142ac80f40--- /dev/null+++ b/apps/desktop/src/store/gateway-activation-prune-lease.test.ts@@ -0,0 +1,178 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Regression suite for #89622: clicking a profile in the rail did nothing.+// The live-work pruner (pruneSecondaryGateways) disposed the switch target's+// secondary entry while its socket was still dialing — the target is not yet+// the active key, has no live sessions, and holds no request lease, so every+// prune recompute during the ~3s cold backend spawn saw it as idle garbage.+// These tests pin the activation lease that spares a mid-dial entry, its+// release once the activation settles, and its bounded self-heal.++const secondaryGateways: Array<{+ close: ReturnType<typeof vi.fn>+ connect: ReturnType<typeof vi.fn>+ connectionState: string+ request: ReturnType<typeof vi.fn>+}> = []++let connectGate: Promise<void> | null = null++vi.mock('@/hermes', () => ({+ HermesGateway: class {+ connectionState = 'closed'+ connect = vi.fn(async () => {+ if (this.connectionState === 'connecting') {+ return+ }++ this.connectionState = 'connecting'++ if (connectGate) {+ await connectGate+ }++ this.connectionState = 'open'+ })+ request = vi.fn(async (method: string, params: Record<string, unknown>) => ({ method, params }))+ close = vi.fn()+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})++ constructor() {+ secondaryGateways.push(this)+ }+ },+ setApiRequestConnection: vi.fn()+}))+vi.mock('@/store/session', () => ({ setConnection: vi.fn(), setGatewayState: vi.fn() }))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const {+ closeSecondaryGateways,+ configureGatewayRegistry,+ ensureGatewayForAgent,+ ensureGatewayForProfile,+ pruneSecondaryGateways,+ setPrimaryGateway+} = await import('./gateway')++function installDesktop(): void {+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {+ getConnection: vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ ),+ getConnectionFor: vi.fn(async ({ profile }: { connectionId: string; profile: string }) => ({+ port: 6161,+ profile,+ token: 'registry-token'+ })),+ getGatewayWsUrlFor: vi.fn(async () => 'ws://127.0.0.1:6161/ws'),+ touchBackend: vi.fn(async () => undefined)+ }+}++function makePrimary() {+ return {+ connectionState: 'open',+ request: vi.fn(async (method: string, params: Record<string, unknown>) => ({ method, params }))+ }+}++beforeEach(() => {+ secondaryGateways.length = 0+ connectGate = null+ configureGatewayRegistry({ onEvent: vi.fn() })+ closeSecondaryGateways()+ installDesktop()+ setPrimaryGateway(makePrimary() as never, 'default')+})++afterEach(() => {+ closeSecondaryGateways()+ vi.clearAllMocks()+ vi.useRealTimers()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('activation lease vs. the live-work pruner (#89622)', () => {+ it('a prune during the switch dial does not dispose the target and the switch lands', async () => {+ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })++ const switching = ensureGatewayForProfile('bot')+ // Let the dial start (createSecondary + connect() now pending on the gate).+ await Promise.resolve()+ await Promise.resolve()+ expect(secondaryGateways).toHaveLength(1)++ // The exact recompute that killed the switch: no live sessions, target not+ // active yet, empty keep-set. The mid-dial entry must survive it.+ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ releaseConnect()+ await switching++ // The switch landed on the target's own (still-live) socket.+ expect(secondaryGateways[0].connectionState).toBe('open')+ })++ it('the agent door leases its entry against the pruner too', async () => {+ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })++ const switching = ensureGatewayForAgent('homelab', 'research')+ await Promise.resolve()+ await Promise.resolve()+ expect(secondaryGateways).toHaveLength(1)++ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ releaseConnect()+ await expect(switching).resolves.toBe(true)+ })++ it('the lease is released once the switch settles — a later prune reclaims the idle entry', async () => {+ await ensureGatewayForProfile('bot')++ // Move away so 'bot' is neither active nor kept, then prune: with the+ // lease released, the idle entry must be disposed exactly as before.+ await ensureGatewayForProfile('default')++ pruneSecondaryGateways(new Set())++ expect(secondaryGateways[0].close).toHaveBeenCalled()+ })++ it('an orphaned lease expires — the pruner is not permanently locked out', async () => {+ vi.useFakeTimers()++ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })++ // Dial starts and never settles (wedged bridge call).+ void ensureGatewayForProfile('bot')+ await Promise.resolve()+ await Promise.resolve()+ expect(secondaryGateways).toHaveLength(1)++ // Inside the lease window: spared.+ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ // Past the lease window: reclaimed. (Lease is wall-clock bounded so a+ // leaked lease cannot pin a dead entry forever.)+ vi.setSystemTime(Date.now() + 31_000)+ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).toHaveBeenCalled()++ releaseConnect()+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 2966b93d6d7..5b723194d9f 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -59,8 +59,23 @@ interface Secondary {// While true the entry auto-reconnects on drop; pruning flips it off so a// deliberate close doesn't trigger the backoff loop.wantOpen: boolean+ /**+ * Epoch-ms deadline while an activation (prepare/ensure) is mid-dial. The+ * live-work pruner must not dispose an entry the user is switching to: a+ * switch target is not yet the active key, has no live sessions and holds+ * no request lease, so during a cold pool spawn (~3s) every prune recompute+ * saw it as idle garbage and disposed it mid-dial — the root of the dead+ * profile clicks in #89622. Cleared when the activation settles; bounded so+ * an orphaned lease self-heals.+ */+ activationLeaseUntil: number}+// How long a mid-dial activation holds its prune lease: covers a cold pool+// backend spawn + socket connect with margin, while still letting a leaked+// lease expire quickly enough for the reaper to reclaim the entry.+const ACTIVATION_LEASE_MS = 30_000+// ── HMR-stable module state ─────────────────────────────────────────────────// All mutable singletons (live sockets, active-profile routing, the event// registry) live in ONE container parked on globalThis, NOT in module-level@@ -432,7 +447,8 @@ function createSecondary(profile: string, connectionId: null | string = null): SreconnectAttempt: 0,reconnecting: false,retained: false,- wantOpen: true+ wantOpen: true,+ activationLeaseUntil: 0}// Events keep carrying the bare profile — session routing is profile-keyed@@ -690,6 +706,11 @@ export async function ensureGatewayForAgent(connectionId: null | string, profileentry.retained = trueentry.wantOpen = true+ // Lease the entry against the live-work pruner for the whole dial: the+ // switch target is not yet active and has no live sessions, so a prune+ // recompute firing mid-spawn would otherwise dispose it and this+ // activation would fail (#89622).+ entry.activationLeaseUntil = Date.now() + ACTIVATION_LEASE_MSif (!isOpen(entry.gateway)) {clearTimer(entry)@@ -702,6 +723,9 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile}}+ // The activation is settling either way — release the prune lease.+ entry.activationLeaseUntil = 0+// A source edit/remove may dispose this entry while its dial is still in// flight. Only the still-registered, still-owned activation may publish.const activated =@@ -748,6 +772,9 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {entry.retained = trueentry.wantOpen = true+ // Lease the entry against the live-work pruner for the whole dial — the+ // profile-door twin of the agent path's lease above (#89622).+ entry.activationLeaseUntil = Date.now() + ACTIVATION_LEASE_MSif (!isOpen(entry.gateway)) {clearTimer(entry)@@ -760,6 +787,9 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {}}+ // The activation is settling either way — release the prune lease.+ entry.activationLeaseUntil = 0+if (entry.wantOpen && g.secondaries.get(key) === entry && applyActive(key, activationEpoch) && entry.connection) {publishActiveConnection(entry.connection)}@@ -862,12 +892,20 @@ function restoreActiveToPrimaryIfEvicted(): void {// bare profile name kept gateway B's 'default' socket alive off gateway A's// 'default' activity (and vice versa) — cross-connection attribution.export function pruneSecondaryGateways(keep: Set<string>): void {+ const now = Date.now()+for (const [key, entry] of [...g.secondaries]) {if (key === g.activeKey ||keep.has(key) ||(!entry.connectionId && keep.has(entry.profile)) ||- entry.activeRequests > 0+ entry.activeRequests > 0 ||+ // Mid-dial activation target: the profile being switched TO is not yet+ // active and has no live work, so without this lease any recompute+ // during its cold spawn disposed the entry and the click died silently+ // (#89622). Number guard: dev-HMR entries predate the field. Bounded:+ // an orphaned lease expires on its own.+ (Number.isFinite(entry.activationLeaseUntil) && entry.activationLeaseUntil > now)) {continue}diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.tsindex 9e410562927..da089502e8d 100644--- a/apps/desktop/src/store/profile-agent-activation.test.ts+++ b/apps/desktop/src/store/profile-agent-activation.test.ts@@ -105,7 +105,11 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =expect($activeGatewayProfile.get()).toBe('default')expect($connection.get()?.mode).toBe('local')- expect(getConnectionFor).not.toHaveBeenCalled()+ // The descriptor lookup DOES run: it is issued concurrently with the dial+ // so nothing awaits between the activation verdict and the publication+ // frame. The invariant that matters — nothing is PUBLISHED for a dead+ // target — is asserted above; the lookup itself is a read-only probe.+ expect(getConnectionFor).toHaveBeenCalledTimes(1)})it('falls through to the profile path for a null connectionId', async () => {diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex 7e5a32e15d3..f2e4e6bfb19 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -1,5 +1,6 @@-import { atom, computed } from 'nanostores'+import { atom, batch, computed } from 'nanostores'+import type { HermesConnection } from '@/global'import { getProfiles, hermesApi, setApiRequestProfile, STARTUP_REQUEST_TIMEOUT_MS } from '@/hermes'import { invalidateProfileScopedQueries } from '@/lib/query-client'import {@@ -269,29 +270,34 @@ export function prewarmProfileBackend(name: string): void {let gatewaySwitch: Promise<void> | null = null-// Keep the renderer's $connection (mode / baseUrl / profile) in lockstep with-// the profile the live gateway is now on. $connection seeds from the PRIMARY-// (window) backend at boot and otherwise only refreshes on a sleep/wake-// reconnect — so activating a *background* profile left $connection describing-// the primary, with the wrong `mode` for everything that branches on-// local-vs-remote. Headline symptom: with a local primary and a remote pool-// profile active, image attachments went out via the path-based `image.attach`-// instead of `image.attach_bytes`, handing the remote gateway a client-only-// path it can't resolve ("image not found: C:\…"), while the /api/fs/* file-// browser and /api/media fetches targeted the wrong machine (#46651).-// Best-effort: a failed descriptor fetch leaves the prior connection intact for-// boot/reconnect to resync.-async function syncConnectionToActiveProfile(profile: string): Promise<void> {+// The target profile's connection descriptor (mode / baseUrl / …), resolved+// CONCURRENTLY with the socket work so the switch can publish the profile+// pointer and $connection in one frame. Without this, $connection seeds from+// the PRIMARY backend at boot and only refreshes on sleep/wake — activating a+// *background* profile left it describing the primary, with the wrong `mode`+// for everything that branches on local-vs-remote (#46651: path-based+// `image.attach` against a remote gateway, /api/fs/* and /api/media on the+// wrong machine).+//+// Best-effort BY DESIGN (fail open): a failed lookup resolves null, the prior+// descriptor stays, and boot/reconnect resyncs it later. The earlier+// atomic-publish series (#89483) failed the whole switch closed here instead,+// and its decline path turned routine registry churn into dead profile+// clicks (#89622) — reverted in #89785. Do not reintroduce fail-closed+// switching at this seam.+async function resolveConnectionForProfile(profile: string): Promise<HermesConnection | null> {const getConnection = window.hermesDesktop?.getConnectionif (!getConnection) {- return+ return null}try {- setConnection(await getConnection(profile))- } catch {- // Leave the prior connection in place; boot/reconnect resyncs it later.+ return await getConnection(profile)+ } catch (err) {+ console.warn(`[profile] descriptor lookup for "${profile}" failed; keeping the previous connection`, err)++ return null}}@@ -333,11 +339,24 @@ export async function ensureGatewayProfile(profile: string | null | undefined):gatewaySwitch = (async () => {// ensureGatewayForProfile opens (or reuses) the target's socket and points// the active gateway at it — without closing the profile you came from.- await ensureGatewayForProfile(target)- $activeGatewayProfile.set(target)- // The active backend just changed; resync $connection so remote-aware- // paths (image.attach_bytes vs image.attach, /api/fs/*, /api/media) follow.- await syncConnectionToActiveProfile(target)+ // The descriptor resolves concurrently so nothing awaits between the+ // activation and the publication below: the old post-activation+ // syncConnectionToActiveProfile await left a window where $gateway+ // already targeted the new backend while $connection still described the+ // previous one, and remote-aware paths announced the wrong mode (#46651).+ const [connection] = await Promise.all([resolveConnectionForProfile(target), ensureGatewayForProfile(target)])++ // ONE publication frame. batch() defers Nanostores' notifications to the+ // end of the callback, so the profile pointer and the connection+ // descriptor become visible together; a null descriptor (no bridge, or a+ // failed best-effort lookup) keeps the previous one — fail open.+ batch(() => {+ $activeGatewayProfile.set(target)++ if (connection) {+ setConnection(connection)+ }+ })})()try {@@ -350,18 +369,25 @@ export async function ensureGatewayProfile(profile: string | null | undefined):// Registry-aware sibling of syncConnectionToActiveProfile: a connection-scoped// agent's descriptor comes from getConnectionFor (its SOURCE connection), not-// getConnection (the local pool). Same best-effort contract.-async function syncConnectionToActiveAgent(connectionId: string, profile: string): Promise<void> {+// getConnection (the local pool). Same best-effort, fail-open contract as+// resolveConnectionForProfile: a failed lookup resolves null and keeps the+// previous descriptor.+async function resolveConnectionForAgent(connectionId: string, profile: string): Promise<HermesConnection | null> {const getConnectionFor = window.hermesDesktop?.getConnectionForif (!getConnectionFor) {- return+ return null}try {- setConnection(await getConnectionFor({ connectionId, profile }))- } catch {- // Leave the prior connection in place; boot/reconnect resyncs it later.+ return await getConnectionFor({ connectionId, profile })+ } catch (err) {+ console.warn(+ `[profile] descriptor lookup for agent "${connectionId}:${profile}" failed; keeping the previous connection`,+ err+ )++ return null}}@@ -394,16 +420,33 @@ export async function ensureGatewayAgent(connectionId: null | string, profile: s$gatewaySwapTarget.set(target)gatewaySwitch = (async () => {- const activated = await ensureGatewayForAgent(connection, target)+ // Descriptor resolves concurrently with the dial, same as the profile+ // path, so no await sits between the activation and the publication.+ const [descriptor, activated] = await Promise.all([+ resolveConnectionForAgent(connection, target),+ ensureGatewayForAgent(connection, target)+ ])if (!activated) {+ // The target stopped existing mid-dial (source edited/removed). Keep+ // every atom on the previous backend; the caller's surfaces re-check+ // what's active. Log so a dead agent click is diagnosable (#89622's+ // silence lesson) — but never fail the whole switch closed here.+ console.warn(`[profile] agent gateway activation for "${connection}:${target}" did not land`)+return}- $activeGatewayProfile.set(target)- // The active backend just changed; resync $connection so remote-aware- // paths (image.attach_bytes vs image.attach, /api/fs/*, /api/media) follow.- await syncConnectionToActiveAgent(connection, target)+ // ONE publication frame, profile pointer + descriptor together. A null+ // descriptor keeps the previous one — fail open, resynced by+ // boot/reconnect later.+ batch(() => {+ $activeGatewayProfile.set(target)++ if (descriptor) {+ setConnection(descriptor)+ }+ })})()try {