The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): empty profile sections sit with their gateway when local is a secondary
kshitijk4poor927fe54ff185
diff --git a/apps/desktop/src/app/chat/sidebar/gateway-group-model.ts b/apps/desktop/src/app/chat/sidebar/gateway-group-model.tsindex fa30dc7eb53..23db2282f11 100644--- a/apps/desktop/src/app/chat/sidebar/gateway-group-model.ts+++ b/apps/desktop/src/app/chat/sidebar/gateway-group-model.ts@@ -8,6 +8,7 @@ import type { SessionInfo } from '@/hermes'import { isBrowserHostedDesktop } from '@/lib/platform'import { resolveProfileColor } from '@/lib/profile-color'import { $connectionsRegistry } from '@/store/connection-registry-state'+import { $primaryGatewayRoute } from '@/store/gateway-primary-route'import { $sidebarShowArchived } from '@/store/layout'import { $profileColors, $profiles, normalizeProfileKey } from '@/store/profile'import { $sessionsLoadError } from '@/store/session'@@ -100,11 +101,17 @@ export function scopeGatewaySessionGroups(groups: SidebarSessionGroup[], scope:/** The owner id the profile list belongs to, in the same vocabulary rows are tagged with: a* non-local request connection stamps its rows with its id; the primary pool stays untagged- * natively, and a Webapp tab tags every row with `local` (its one gateway). */-export function profileListConnectionId(apiConnectionId: null | string, browserHosted: boolean): null | string {+ * natively, and a Webapp tab tags every row with `local` (its one gateway). `local` is that+ * untagged pool only while it is the aggregate base (the registry primary): as a secondary beside+ * a remote base its rows carry the `local` tag, and the untagged pool is the remote's. */+export function profileListConnectionId(+ apiConnectionId: null | string,+ browserHosted: boolean,+ localIsPrimary: boolean+): null | string {const owner = apiConnectionId?.trim()- if (owner && owner !== LOCAL_CONNECTION_ID) {+ if (owner && (owner !== LOCAL_CONNECTION_ID || !localIsPrimary)) {return owner}@@ -139,6 +146,14 @@ export function useGatewaySessionGroups(sessions: SessionInfo[], enabled: booleaconst colors = useStore($profileColors)const profiles = useStore($profiles)const { connectionId: apiConnectionId } = useStore($apiRequestScope)+ // The untagged pool is the registry primary's: Electron reads it as the aggregate's base. The+ // window primary's own mode speaks for it only while the window primary is that source; a+ // window booted on another registered route (the saved default route) leaves the base where it+ // is. Never the active gateway's ($connection): a foregrounded local secondary reports `local`+ // beside a remote primary. Unknown keeps local as the primary pool.+ const primary = useStore($primaryGatewayRoute)+ const windowIsBase = !registry || !primary.connectionId || primary.connectionId === registry.primary+ const localIsPrimary = windowIsBase ? primary.mode !== 'remote' : registry.primary === LOCAL_CONNECTION_IDconst showArchived = useStore($sidebarShowArchived)const loadError = useStore($sessionsLoadError)const includeEmptyProfiles = !narrowed && !showArchived && !loadError@@ -154,7 +169,7 @@ export function useGatewaySessionGroups(sessions: SessionInfo[], enabled: booleareturn groups}- const owner = profileListConnectionId(apiConnectionId, isBrowserHostedDesktop())+ const owner = profileListConnectionId(apiConnectionId, isBrowserHostedDesktop(), localIsPrimary)return withEmptyProfileGroups(groups,@@ -163,5 +178,5 @@ export function useGatewaySessionGroups(sessions: SessionInfo[], enabled: boolearegistry,colors)- }, [sessions, enabled, includeEmptyProfiles, registry, colors, profiles, apiConnectionId])+ }, [sessions, enabled, includeEmptyProfiles, registry, colors, profiles, apiConnectionId, localIsPrimary])}diff --git a/apps/desktop/src/app/chat/sidebar/gateway-groups-webapp.test.tsx b/apps/desktop/src/app/chat/sidebar/gateway-groups-webapp.test.tsxindex cb88fda2c9a..b9b19d0c4db 100644--- a/apps/desktop/src/app/chat/sidebar/gateway-groups-webapp.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/gateway-groups-webapp.test.tsx@@ -3,11 +3,14 @@ import { act, cleanup, render, screen, within } from '@testing-library/react'import { MemoryRouter } from 'react-router'import { afterEach, expect, it } from 'vitest'+import { setApiRequestConnection } from '@/api/client'import { SidebarProvider } from '@/components/ui/sidebar'+import type { HermesConnection } from '@/global'import { $connectionsRegistry } from '@/store/connection-registry-state'+import { setPrimaryGatewayConnection } from '@/store/gateway'import { $sidebarRowMeta, setSidebarGrouping } from '@/store/layout'import { $profiles, $showAllProfiles } from '@/store/profile'-import { $sessionProfilesUsage, $sessions } from '@/store/session'+import { $connection, $sessionProfilesUsage, $sessions } from '@/store/session'import { makeSessionInfo } from '@/test/session-info'import { ChatSidebar } from './index'@@ -41,6 +44,9 @@ const mount = () =>afterEach(() => {cleanup()delete window.document.documentElement.dataset.hermesDesktopHost+ $connection.set(null)+ setPrimaryGatewayConnection(null)+ setApiRequestConnection(null)$showAllProfiles.set(false)$sidebarRowMeta.set([])$sessionProfilesUsage.set({})@@ -130,3 +136,61 @@ it.each([expect(within(quiet!).getByRole('button', { name: 'New session in quiet' })).toBeTruthy()expect(screen.getByText('only chat')).toBeTruthy()})++// `local` rows are untagged only while local is the aggregate base (the registry primary); beside a+// remote base they carry `local`, so the empty profile sections read from `local` must too. The active descriptor+// ($connection) is the foregrounded gateway's, `local` for a local secondary, and null on a+// reconnect blip; neither says which gateway is the primary. Before the primary is recorded, local+// stays the untagged pool. The untagged pool is the registry primary's, so a window booted on+// another registered route (the saved default route) does not move it.+it.each([+ { primary: 'remote', active: 'local', base: 'remote-1', owner: 'local' },+ { primary: 'local', active: 'local', base: 'local', owner: null },+ { primary: 'local', active: null, base: 'local', owner: null },+ { primary: null, active: 'local', base: 'local', owner: null },+ { primary: 'remote', active: 'local', base: 'local', owner: null },+ { primary: 'local', active: 'local', base: 'remote-1', owner: 'local' }+] as const)(+ 'files empty profile sections under the owner its rows carry ($primary primary, $active active, $base base)',+ ({ primary, active, base, owner }) => {+ mount()+ act(() => {+ setPrimaryGatewayConnection(+ primary ? { connectionId: primary === 'remote' ? 'remote-1' : 'local', mode: primary } : null+ )+ $connection.set(active ? ({ mode: active } as HermesConnection) : null)+ setApiRequestConnection('local')+ $connectionsRegistry.set({+ version: 2,+ primary: base,+ secureTokenStorage: true,+ connections: [+ { id: 'local', label: 'This computer', kind: 'local', tokenSet: false, tokenPreview: null },+ { id: 'remote-1', label: 'Homelab', kind: 'remote', tokenSet: false, tokenPreview: null }+ ]+ })+ $profiles.set([+ { name: 'default', is_default: true },+ { name: 'quiet', is_default: false }+ ] as typeof $profiles.value)+ $showAllProfiles.set(true)+ setSidebarGrouping('profile')+ $sessions.set([+ makeSessionInfo({+ id: 'one',+ ...(owner ? { connection_id: owner } : {}),+ profile: 'default',+ title: 'only chat',+ last_active: Date.now() / 1000+ })+ ])+ })++ const groups = [...window.document.querySelectorAll('[data-gateway-group]')].map(group =>+ group.getAttribute('data-gateway-group')+ )++ expect(groups.sort()).toEqual([JSON.stringify([owner, 'default']), JSON.stringify([owner, 'quiet'])].sort())+ expect(window.document.querySelectorAll('[data-gateway-group-empty]')).toHaveLength(1)+ }+)diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.tsindex 21dc6d9ecd8..b49b52ed47a 100644--- a/apps/desktop/src/store/gateway-connection-scope.test.ts+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts@@ -44,6 +44,7 @@ const {closeLegacySecondaryGateways,closeSecondaryGateways,configureGatewayRegistry,+ dialedGatewayModeFor,ensureGatewayForAgent,ensureGatewayForProfile,openGatewayForAgent,@@ -108,6 +109,30 @@ describe('primary gateway registry scope', () => {expect(setApiRequestConnection).toHaveBeenLastCalledWith(null)})+ // The recorded route (id AND mode) describes one socket: re-publishing that socket keeps it, a+ // replacement socket starts unknown until its own route is recorded.+ it.each(['local', 'remote'] as const)(+ 'keeps a %s primary route while the socket is reused and clears it when a new socket replaces it',+ mode => {+ const socket = { connectionState: 'open' } as never++ setPrimaryGateway(socket, 'default')+ setPrimaryGatewayConnectionId('primary-1', mode)+ setPrimaryGateway(socket, 'default')++ expect(dialedGatewayModeFor(null, 'default')).toBe(mode)+ expect(dialedGatewayModeFor('primary-1', 'default')).toBe(mode)+ expect(activeGatewayConnectionId()).toBe('primary-1')++ setPrimaryGateway({ connectionState: 'open' } as never, 'default')++ expect(dialedGatewayModeFor(null, 'default')).toBeNull()+ expect(dialedGatewayModeFor('primary-1', 'default')).toBeNull()+ expect(activeGatewayConnectionId()).toBeNull()+ expect(setApiRequestConnection).toHaveBeenLastCalledWith(null)+ }+ )+it('records a primary re-dial made while a secondary scope is foregrounded (#95628 keeps ambient routing)', async () => {setPrimaryGateway({ connectionState: 'open' } as never, 'default')setPrimaryGatewayConnectionId('primary-vps')diff --git a/apps/desktop/src/store/gateway-primary-route.ts b/apps/desktop/src/store/gateway-primary-route.tsnew file mode 100644index 00000000000..8946b0d23ab--- /dev/null+++ b/apps/desktop/src/store/gateway-primary-route.ts@@ -0,0 +1,34 @@+import { atom } from 'nanostores'++/** The window primary socket's own route, whichever gateway is in front. */+export interface PrimaryGatewayRoute {+ /** Registry source the primary socket serves, when known. */+ connectionId: null | string+ /** Resolved mode of the primary's descriptor: a `local` primary is ONE+ * `hermes serve --profile <primary>` child and can never stand in for a+ * pooled profile's own backend. */+ mode: 'local' | 'remote' | null+}++const ROUTE_KEY = Symbol.for('hermes.desktop.primaryGatewayRoute')++// Same dev-HMR rule as the gateway registry state: a re-evaluated module must+// hand back the SAME atom, or existing subscribers are orphaned. Production has+// no `import.meta.hot`, so this is a plain module-local atom there.+function routeAtom() {+ const initial: PrimaryGatewayRoute = { connectionId: null, mode: null }++ if (import.meta.hot) {+ const store = globalThis as unknown as { [ROUTE_KEY]?: ReturnType<typeof atom<PrimaryGatewayRoute>> }++ return (store[ROUTE_KEY] ??= atom<PrimaryGatewayRoute>(initial))+ }++ return atom<PrimaryGatewayRoute>(initial)+}++/** store/gateway.ts's setPrimaryGateway / setPrimaryGatewayConnectionId are its only writers.+ * Unlike $connection, which follows the gateway in front (a foregrounded local secondary+ * reports `local` beside a remote primary) and goes null on a reconnect blip, this keeps+ * the last recorded primary until a new primary socket replaces it. */+export const $primaryGatewayRoute = routeAtom()diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 1c1da94caef..f6d269f10d6 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -32,6 +32,7 @@ import {} from '@/lib/with-timeout'import { $gatewayActivationEpoch } from '@/store/gateway-activation-epoch'import { isMissingConnectionError, isMissingProfileError } from '@/store/gateway-dial-failures'+import { $primaryGatewayRoute } from '@/store/gateway-primary-route'import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'import { markNativeNotifyBaseline } from '@/store/notify-baseline'import { setConnection, setGatewayState } from '@/store/session'@@ -216,12 +217,6 @@ const ACTIVATION_LEASE_MS = SOURCE_SWITCH_DIAL_TIMEOUT_MS + 15_000interface GatewayRegistryState {config: RegistryConfig | nullprimaryGateway: HermesGateway | null- /** Registry source currently served by primaryGateway, when known. */- primaryConnectionId: null | string- /** Resolved mode of the primary's descriptor: a `local` primary is ONE- * `hermes serve --profile <primary>` child and can never stand in for a- * pooled profile's own backend. */- primaryConnectionMode: 'local' | 'remote' | nullprimaryProfile: stringactiveKey: stringsecondaries: Map<string, Secondary>@@ -248,8 +243,6 @@ function createRegistryState(): GatewayRegistryState {return {config: null,primaryGateway: null,- primaryConnectionId: null,- primaryConnectionMode: null,primaryProfile: initialGatewayProfile(),activeKey: initialGatewayProfile(),secondaries: new Map<string, Secondary>(),@@ -366,12 +359,16 @@ export function dispatchPrimaryServerRequest(request: ServerRequest, profile: streturn dispatchServerRequest(request, profile, g.config?.activeConnectionId?.() ?? null)}+/** Registry source currently served by the window primary socket, when known. */+function primaryConnectionId(): null | string {+ return $primaryGatewayRoute.get().connectionId+}+export function setPrimaryGateway(gateway: HermesGateway | null, profile = 'default'): void {const next = normKey(profile)if (g.primaryGateway !== gateway) {- g.primaryConnectionId = null- g.primaryConnectionMode = null+ $primaryGatewayRoute.set({ connectionId: null, mode: null })}// Route identity is exact-scope, never bare-name (#93892 follow-up): when@@ -388,7 +385,7 @@ export function setPrimaryGateway(gateway: HermesGateway | null, profile = 'defag.primaryProfile = nextif (g.activeKey === g.primaryProfile) {- setApiRequestConnection(g.primaryConnectionId)+ setApiRequestConnection(primaryConnectionId())}}@@ -398,16 +395,17 @@ export function setPrimaryGatewayConnectionId(): void {// Every caller publishes the window's OWN primary socket (boot, reconnect,// connection apply, HMR survivor), so record it even while a secondary is- // foregrounded. Refusing it there left primaryConnectionId naming the+ // foregrounded. Refusing it there left the primary route naming the// machine the primary socket had just left, and owner routing then sent// that machine's requests to the other one. What belongs to the active// scope is the AMBIENT request connection (#95628), which moves only while// the primary is in front.- g.primaryConnectionId = (connectionId ?? '').trim() || null- g.primaryConnectionMode = mode === 'local' || mode === 'remote' ? mode : null+ const id = (connectionId ?? '').trim() || null+ const primaryMode = mode === 'local' || mode === 'remote' ? mode : null+ $primaryGatewayRoute.set({ connectionId: id, mode: primaryMode })if (g.activeKey === g.primaryProfile) {- setApiRequestConnection(g.primaryConnectionId)+ setApiRequestConnection(id)}}@@ -420,8 +418,10 @@ export function dialedGatewayModeFor(connectionId: null | string, profile: strinconst id = String(connectionId ?? '').trim() || nullconst key = normKey(profile)- if (key === g.primaryProfile && (!id || id === g.primaryConnectionId) && g.primaryConnectionMode) {- return g.primaryConnectionMode+ const primary = $primaryGatewayRoute.get()++ if (key === g.primaryProfile && (!id || id === primary.connectionId) && primary.mode) {+ return primary.mode}const mode = g.secondaries.get(registryBackendScopeKey(id, key))?.connection?.mode@@ -435,18 +435,13 @@ export function setPrimaryGatewayConnection(connection: Pick<HermesConnection, '}function traceAgentRoute(scope: string, via: string): void {- traceIdentityChange('gateway-route', scope, `via=${via} primary=${g.primaryConnectionId ?? '-'}/${g.primaryProfile}`)+ traceIdentityChange('gateway-route', scope, `via=${via} primary=${primaryConnectionId() ?? '-'}/${g.primaryProfile}`)}function isPrimaryRegistryRoute(connectionId: null | string, profile: string): boolean {const id = String(connectionId ?? '').trim()- return (- normKey(profile) === g.primaryProfile &&- Boolean(id) &&- Boolean(g.primaryConnectionId) &&- id === g.primaryConnectionId- )+ return normKey(profile) === g.primaryProfile && Boolean(id) && id === primaryConnectionId()}/** True when `connectionId` is the window's already-attached source AND main@@ -463,7 +458,7 @@ async function ridesPrimaryBackend(connectionId: null | string, profile: string)const id = String(connectionId ?? '').trim()const key = normKey(profile)- if (!id || !g.primaryConnectionId || id !== g.primaryConnectionId) {+ if (!id || id !== primaryConnectionId()) {return false}@@ -503,7 +498,7 @@ async function ridesPrimaryBackend(connectionId: null | string, profile: string)// its own pid, but the exact-owner route names the pool backend — after a// renderer reload or a pool respawn the resume dials that backend and is// refused SESSION_NOT_OWNED by a pid of the same Desktop (#101416).- return g.primaryConnectionMode !== 'local'+ return $primaryGatewayRoute.get().mode !== 'local'}}@@ -586,7 +581,7 @@ export function pendingSessionReplay(runtimeId: string): Promise<boolean> | unde*/export function activeGatewayConnectionId(): null | string {if (g.activeKey === g.primaryProfile) {- return g.primaryConnectionId ?? (g.config?.activeConnectionId?.()?.trim() || null)+ return primaryConnectionId() ?? (g.config?.activeConnectionId?.()?.trim() || null)}return g.secondaries.get(g.activeKey)?.connectionId ?? null