The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): never resolve a missing named gateway scope to the primary
Teknium45398957b76c
diff --git a/apps/desktop/src/store/gateway-agent-scope.test.ts b/apps/desktop/src/store/gateway-agent-scope.test.tsnew file mode 100644index 00000000000..ddf8e68be45--- /dev/null+++ b/apps/desktop/src/store/gateway-agent-scope.test.ts@@ -0,0 +1,142 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Registry-agent scoping regression (multi-source roster): the active key can+// name a `conn:<id>::<profile>` scope whose secondaries entry gets evicted by+// a teardown path (closeSecondaryGateways during a soft gateway switch,+// pruneSecondaryGateways). activeGateway() used to silently fall back to the+// PRIMARY gateway for a missing NAMED scope — every send/session op then hit+// the wrong machine with no error. These tests pin the invariant: a missing+// named scope never resolves to the primary; every eviction site explicitly+// re-points the active key at the primary so `activeKey` always resolves.++const gatewayMocks = vi.hoisted(() => ({+ connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined),+ setConnection: vi.fn(),+ setGatewayState: vi.fn()+}))++vi.mock('@/hermes', () => ({+ HermesGateway: class {+ connectionState = 'closed'+ connect = async (wsUrl: string): Promise<void> => {+ await gatewayMocks.connect(wsUrl)+ this.connectionState = 'open'+ }+ close = (): void => {+ this.connectionState = 'closed'+ }+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})+ }+}))+vi.mock('@/store/session', () => ({+ setConnection: gatewayMocks.setConnection,+ setGatewayState: gatewayMocks.setGatewayState+}))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const {+ $gateway,+ activeGateway,+ closeSecondaryGateways,+ configureGatewayRegistry,+ ensureGatewayForAgent,+ isActivePrimary,+ pruneSecondaryGateways,+ setPrimaryGateway+} = await import('./gateway')++interface DesktopStub {+ getConnection: ReturnType<typeof vi.fn>+ getConnectionFor: ReturnType<typeof vi.fn>+}++function installDesktop(stub: DesktopStub): void {+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = stub+}++function makePrimary(): { connectionState: string } {+ return { connectionState: 'open' }+}++const agentConn = {+ authMode: 'token',+ baseUrl: 'https://homelab.invalid',+ mode: 'remote',+ profile: 'research',+ token: 'fake-test-token',+ wsUrl: 'wss://homelab.invalid/api/ws?token=fake-test-token'+}++function installAgentDesktop(): DesktopStub {+ const stub: DesktopStub = {+ getConnection: vi.fn(async () => agentConn),+ getConnectionFor: vi.fn(async () => agentConn)+ }++ installDesktop(stub)++ return stub+}++beforeEach(() => {+ configureGatewayRegistry({ onEvent: vi.fn() })+})++afterEach(() => {+ closeSecondaryGateways()+ vi.clearAllMocks()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('registry-agent scope eviction (activeGateway must never silently hit the primary)', () => {+ it('activates the agent socket, not the primary, for a registry scope', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installAgentDesktop()++ await ensureGatewayForAgent('homelab', 'research')++ expect(isActivePrimary()).toBe(false)+ expect(activeGateway()).not.toBe(primary)+ expect($gateway.get()).not.toBe(primary)+ expect(gatewayMocks.connect).toHaveBeenCalledWith(agentConn.wsUrl)+ })++ it('closeSecondaryGateways re-points the active key at the primary instead of dangling', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installAgentDesktop()++ await ensureGatewayForAgent('homelab', 'research')+ expect(isActivePrimary()).toBe(false)++ // The soft gateway switch path (use-gateway-boot) tears every secondary+ // down without knowing which one was active.+ closeSecondaryGateways()++ // Regression: activeKey used to keep naming the evicted scope while+ // activeGateway() fell back to the primary — wrong machine, no error.+ // Now the teardown restores the primary EXPLICITLY (atoms follow).+ expect(isActivePrimary()).toBe(true)+ expect(activeGateway()).toBe(primary)+ expect($gateway.get()).toBe(primary)+ })++ it('pruneSecondaryGateways never evicts the active scope and keeps the invariant', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installAgentDesktop()++ await ensureGatewayForAgent('homelab', 'research')+ const agentGateway = activeGateway()++ // Empty keep-set: everything non-active is evictable — the active agent+ // scope must survive, and the active pointer must still resolve to it.+ pruneSecondaryGateways(new Set())++ expect(isActivePrimary()).toBe(false)+ expect(activeGateway()).toBe(agentGateway)+ expect($gateway.get()).toBe(agentGateway)+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 9c78d185d61..52b34a11331 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -134,7 +134,12 @@ export function activeGateway(): HermesGateway | null {return g.primaryGateway}- return g.secondaries.get(g.activeKey)?.gateway ?? g.primaryGateway+ // A named scope resolves to ITS socket or nothing. Falling back to the+ // primary here would silently route calls (sends, session ops, roster+ // requests) to the WRONG backend whenever the scope's entry is gone —+ // teardown sites keep the invariant "activeKey always resolves" by+ // re-pointing the active key at the primary when they evict it.+ return g.secondaries.get(g.activeKey)?.gateway ?? null}// Mirror a backend's connection state into the global composer state, but only@@ -488,6 +493,18 @@ function disposeSecondary(entry: Secondary): void {entry.gateway.close()}+// Invariant restore for every eviction path: if the active key names a+// secondary that no longer exists, fall back to the primary EXPLICITLY (atoms+// and composer state follow) instead of leaving a dangling key that+// activeGateway() can no longer resolve. Without this, a soft gateway switch+// (closeSecondaryGateways in use-gateway-boot) left activeKey pointing at an+// evicted registry scope and every call silently hit the primary backend.+function restoreActiveToPrimaryIfEvicted(): void {+ if (g.activeKey !== g.primaryProfile && !g.secondaries.has(g.activeKey)) {+ setActive(g.primaryProfile)+ }+}+// Close + evict secondaries whose profile is neither active nor in `keep`// (profiles with a running / needs-input session). Bounds cost to live work.// `keep` carries PROFILE names (session ownership is profile-keyed), so a@@ -503,6 +520,8 @@ export function pruneSecondaryGateways(keep: Set<string>): void {disposeSecondary(entry)g.secondaries.delete(key)}++ restoreActiveToPrimaryIfEvicted()}export function closeSecondaryGateways(): void {@@ -511,6 +530,7 @@ export function closeSecondaryGateways(): void {}g.secondaries.clear()+ restoreActiveToPrimaryIfEvicted()}// Self-accept so editing this module (or a fan-out that lands here) is an