The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retain local secondary profile gateway for foreground sessions
StanleyStetson0ffed8e7c426
diff --git a/apps/desktop/src/store/gateway-foreground-retention.test.ts b/apps/desktop/src/store/gateway-foreground-retention.test.tsindex b51eb01ef84..36eb7d82202 100644--- a/apps/desktop/src/store/gateway-foreground-retention.test.ts+++ b/apps/desktop/src/store/gateway-foreground-retention.test.ts@@ -41,19 +41,24 @@ const {openGatewayForAgent,pruneSecondaryGateways,requestGatewayForAgent,+ requestGatewayForProfile,setPrimaryGateway,SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')-const { $sessionTiles, foregroundSessionScopes, liveSessionScopes } = await import('./session-states')+const { $sessionTiles, foregroundSessionScopes, liveSessionScopes, recordSessionEventScope } = await import(+ './session-states'+)+const { stampSecondaryProfileOwner } = await import('./session-event-provenance')+const { $selectedStoredSessionId, $sessions, setActiveSessionId } = await import('@/store/session')function installDesktop(): void {;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {- getConnection: vi.fn(async () => ({+ getConnection: vi.fn(async (profile?: string) => ({authMode: 'token',- profile: 'default',+ profile: profile || 'default',token: 't',- wsUrl: 'wss://local.invalid/api/ws?token=t'+ wsUrl: `wss://local.invalid/api/ws?profile=${profile || 'default'}`})),getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({authMode: 'token',@@ -93,6 +98,9 @@ beforeEach(() => {afterEach(() => {closeSecondaryGateways()$sessionTiles.set([])+ $sessions.set([])+ setActiveSessionId(null)+ $selectedStoredSessionId.set(null)vi.clearAllMocks()delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})@@ -185,3 +193,40 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {expect(gatewayMocks.closed).toEqual(['wss://homelab.invalid/api/ws?profile=bot'])})})++describe('local secondary profile foreground retention across lease release (#121865)', () => {+ it('keeps a local secondary profile socket when its session is in foreground across request lease release', async () => {+ const event = stampSecondaryProfileOwner({ session_id: 'rt-jody' } as never, 'jody')+ recordSessionEventScope(event)+ setActiveSessionId('rt-jody')++ await requestGatewayForProfile('jody', 'session.control.read', { session_id: 'rt-jody' })++ expect(gatewayMocks.closed).toEqual([])+ })++ it('keeps a local secondary profile socket for an active session whose owner is known before events arrive', async () => {+ $sessions.set([{ id: 'stored-jody', profile: 'jody' }] as never)+ $selectedStoredSessionId.set('stored-jody')+ setActiveSessionId('rt-jody-idle')++ await requestGatewayForProfile('jody', 'session.control.read', { session_id: 'rt-jody-idle' })++ expect(gatewayMocks.closed).toEqual([])+ })++ it('keeps a local secondary socket via fallback before events arrive, but disposes an unrelated secondary socket (#121865)', async () => {+ $sessions.set([{ id: 'stored-jody', profile: 'jody' }] as never)+ $selectedStoredSessionId.set('stored-jody')+ setActiveSessionId('rt-jody-idle')++ // Jody session is active; events have not streamed yet (fallback active).+ await requestGatewayForProfile('jody', 'session.control.read', { session_id: 'rt-jody-idle' })++ // Unrelated profile request arrives and finishes its lease.+ await requestGatewayForProfile('unrelated', 'session.control.read', { session_id: 'rt-other' })++ // Only unrelated was closed; jody remains pinned open by fallback!+ expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=unrelated'])+ })+})diff --git a/apps/desktop/src/store/session-states-foreground-scopes.test.ts b/apps/desktop/src/store/session-states-foreground-scopes.test.tsindex 2518a9fce4c..86d3897f80d 100644--- a/apps/desktop/src/store/session-states-foreground-scopes.test.ts+++ b/apps/desktop/src/store/session-states-foreground-scopes.test.ts@@ -2,11 +2,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import {$selectedStoredSessionId,+ $sessions,_resetSessionOwnerHintsForTests,setActiveSessionId,setSessionOwnerHint} from '@/store/session'+import { stampSecondaryProfileOwner } from './session-event-provenance'import {$sessionOwnerHoldRevision,$sessionTiles,@@ -26,6 +28,7 @@ import {afterEach(() => {$sessionTiles.set([])+ $sessions.set([])setActiveSessionId(null)$selectedStoredSessionId.set(null)_resetSessionOwnerHoldsForTests()@@ -131,4 +134,39 @@ describe('foregroundSessionScopes: owner hold across the create → foreground gexpect(foregroundSessionScopes()).toEqual(new Set(['research']))})++ it('names the local secondary profile when a foreground session is active on it (#121865)', () => {+ const event = stampSecondaryProfileOwner({ session_id: 'rt-jody' } as never, 'jody')+ recordSessionEventScope(event)+ setActiveSessionId('rt-jody')++ expect(foregroundSessionScopes()).toEqual(new Set(['jody']))+ })++ it('names the local secondary profile for an active session whose owner is known before events arrive (#121865)', () => {+ $sessions.set([{ id: 'stored-jody', profile: 'jody' }] as never)+ $selectedStoredSessionId.set('stored-jody')+ setActiveSessionId('rt-jody-idle')++ expect(foregroundSessionScopes()).toEqual(new Set(['jody']))+ })++ it('names the local secondary profile for an active session whose hint was stamped at open (#121865)', () => {+ setSessionOwnerHint('stored-hinted', { connectionId: 'local', mode: 'local' as const, profile: 'jody' })+ $selectedStoredSessionId.set('stored-hinted')+ setActiveSessionId('rt-hinted-idle')++ expect(foregroundSessionScopes()).toEqual(new Set(['conn:local::jody']))+ })++ it('does not name unrelated secondary profiles when another session is active (#121865)', () => {+ $sessions.set([+ { id: 'stored-jody', profile: 'jody' },+ { id: 'stored-other', profile: 'unrelated' }+ ] as never)+ $selectedStoredSessionId.set('stored-jody')+ setActiveSessionId('rt-jody')++ expect(foregroundSessionScopes()).toEqual(new Set(['jody']))+ })})diff --git a/apps/desktop/src/store/session-states-reconnect.test.ts b/apps/desktop/src/store/session-states-reconnect.test.tsindex 5b13b0ae6d7..297759eae7e 100644--- a/apps/desktop/src/store/session-states-reconnect.test.ts+++ b/apps/desktop/src/store/session-states-reconnect.test.ts@@ -11,12 +11,14 @@ import {$selectedStoredSessionId,$unreadFinishedSessionIds} from './session'+import { stampSecondaryProfileOwner } from './session-event-provenance'import {$attentionSessionIds,$sessionStates,$stalledSessionIds,$workingSessionIds,clearAllSessionStates,+ liveSessionScopes,publishSessionState,reconcileBusyStatesOnReconnect,recordSessionEventScope,@@ -141,6 +143,29 @@ describe('reconcileBusyStatesOnReconnect', () => {expect($workingSessionIds.get()).toContain('sLocal')})+ it('primary reconcile leaves local-secondary scoped sessions alone, and scoped reconcile clears them (#121865)', () => {+ publishSessionState('rtJody', state({ busy: true, storedSessionId: 'sJody' }))+ const event = stampSecondaryProfileOwner({ session_id: 'rtJody' } as never, 'jody')+ recordSessionEventScope(event)+ publishSessionState('rtLocalPrimary', state({ busy: true, storedSessionId: 'sLocalPrimary' }))++ reconcileBusyStatesOnReconnect()++ expect($workingSessionIds.get()).toContain('sJody')+ expect($workingSessionIds.get()).not.toContain('sLocalPrimary')++ reconcileBusyStatesOnReconnect('jody')+ expect($workingSessionIds.get()).not.toContain('sJody')+ })++ it('liveSessionScopes includes local secondary profiles for busy sessions (#121865)', () => {+ publishSessionState('rtJody', state({ busy: true, storedSessionId: 'sJody' }))+ const event = stampSecondaryProfileOwner({ session_id: 'rtJody' } as never, 'jody')+ recordSessionEventScope(event)++ expect(liveSessionScopes().has('jody')).toBe(true)+ })+// #93059: the store is a mirror of the wiring cache; downgrading only the// mirror leaves the cache busy, and warm resume ORs it over `running: false`.it('routes the downgrade through the session-state write path (#93059)', () => {diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 0e724eb5361..b96f1deca25 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -90,13 +90,14 @@ import { isBrowserWindow, isSecondaryWindow } from './windows'export const $sessionStates = atom<Record<string, ClientSessionState>>({})// ----------------------------------------------------------------------------// Event-source scopes: which registry connection's socket delivered a runtime-// session's events. Working/attention membership alone is profile-blind — two-// connected gateways can both expose a 'default' profile, so the gateway-// keep-set (pruneSecondaryGateways) must key live work by the composite-// (connectionId, profile) scope, not the bare profile name. Recorded at-// event fan-in (use-gateway-boot); local/primary events carry no connectionId-// and record nothing, so single-source behavior is untouched.+// Event-source scopes: which registry connection's socket (or local secondary+// gateway) delivered a runtime session's events. Working/attention membership+// alone is profile-blind — two connected gateways can both expose a 'default'+// profile, so the gateway keep-set (pruneSecondaryGateways) must key live work+// by the composite (connectionId, profile) scope for remote connections, or+// by the normalized profile name for local secondary gateways. Recorded at+// event fan-in (use-gateway-boot); local primary events carry no connectionId+// or secondary marker and record nothing, so single-source behavior is untouched.// ---------------------------------------------------------------------------const sessionScopeByRuntimeId = new Map<string, string>()@@ -133,7 +134,9 @@ export function recordSessionEventScope(event: { connectionId?: string; profile?const profile = secondaryProfileOwnerForEvent(event as GatewayEvent)if (profile) {- sessionOwnerByRuntimeId.set(event.session_id, profile)+ const profileKey = normalizeProfileKey(profile)+ sessionOwnerByRuntimeId.set(event.session_id, profileKey)+ sessionScopeByRuntimeId.set(event.session_id, profileKey)}syncPreviewScope()@@ -160,6 +163,7 @@ export function forgetProfileOnlyRuntimeOwners(profile: string): void {for (const [runtimeId, owner] of sessionOwnerByRuntimeId) {if (typeof owner === 'string' && normalizeProfileKey(owner) === retired) {sessionOwnerByRuntimeId.delete(runtimeId)+ sessionScopeByRuntimeId.delete(runtimeId)}}}@@ -282,14 +286,6 @@ export function _resetSessionOwnerHoldsForTests(): void {export function foregroundSessionScopes(): Set<string> {const scopes = new Set<string>()- const addRuntimeScope = (runtimeId: string | undefined) => {- const scope = runtimeId ? sessionScopeByRuntimeId.get(runtimeId) : undefined-- if (scope) {- scopes.add(scope)- }- }-const addRouteScope = (route: SessionOwnerRoute | undefined) => {const connectionId = route?.connectionId?.trim()const profile = route?.profile?.trim()@@ -299,6 +295,37 @@ export function foregroundSessionScopes(): Set<string> {}}+ const addOwnerScope = (owner: SessionOwnerScope | undefined) => {+ if (!owner) {+ return+ }++ if (typeof owner === 'string') {+ const key = normalizeProfileKey(owner)+ if (key) {+ scopes.add(key)+ }+ return+ }++ addRouteScope(owner)+ }++ const addRuntimeScope = (runtimeId: string | undefined) => {+ if (!runtimeId) {+ return+ }++ const scope = sessionScopeByRuntimeId.get(runtimeId)++ if (scope) {+ scopes.add(scope)+ return+ }++ addOwnerScope(knownOwnerForSession(runtimeId))+ }+addRuntimeScope($activeSessionId.get() ?? undefined)for (const tile of $sessionTiles.get()) {@@ -861,10 +888,10 @@ export function clearAllSessionStates() {* hours after the turn actually ended (#53902, #73082 — stale-flag half).** `scope` picks which socket's sessions to reconcile, keyed by the event-- * source scope recorded at fan-in: a SECONDARY (registry) reconnect passes- * its composite scope and touches only runtimes that arrived on that socket;+ * source scope recorded at fan-in: a SECONDARY (registry or local secondary)+ * reconnect passes its scope and touches only runtimes that arrived on that socket;* the PRIMARY reconnect passes undefined and touches only scope-less- * runtimes (primary/local events record no scope). Neither can clear live+ * runtimes (primary events record no scope). Neither can clear live* work riding a different, still-healthy connection.** Direction of failure is deliberate: a turn that IS still live (transient