The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope the config-record cache to the active gateway
brooklyn!b609c745dfc0
diff --git a/apps/desktop/src/app/hooks/use-config-record.test.tsx b/apps/desktop/src/app/hooks/use-config-record.test.tsxindex 143b9de0839..681ca3beaf4 100644--- a/apps/desktop/src/app/hooks/use-config-record.test.tsx+++ b/apps/desktop/src/app/hooks/use-config-record.test.tsx@@ -1,13 +1,19 @@import { QueryClientProvider } from '@tanstack/react-query'-import { cleanup, renderHook, waitFor } from '@testing-library/react'+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'import { createElement } from 'react'import { afterEach, expect, it, vi } from 'vitest'import type * as HermesApi from '@/hermes'import { bindConfigReadOrigin, getHermesConfigRecord } from '@/hermes'import { queryClient } from '@/lib/query-client'+import { $connection } from '@/store/session'-import { HERMES_CONFIG_KEY, useHermesConfigRecord } from './use-config-record'+import {+ HERMES_CONFIG_KEY,+ hermesConfigCacheWriter,+ setHermesConfigCache,+ useHermesConfigRecord+} from './use-config-record'vi.mock('@/hermes', async importOriginal => ({...(await importOriginal<typeof HermesApi>()),@@ -17,6 +23,7 @@ vi.mock('@/hermes', async importOriginal => ({afterEach(() => {cleanup()queryClient.clear()+ $connection.set(null)vi.clearAllMocks()})@@ -46,3 +53,68 @@ it('updates the write origin when a refetch replaces the displayed record', asynawait waitFor(() => expect(result.current.data).toEqual(second))await waitFor(() => expect(result.current.writeScope).toEqual({ connectionId: 'connection-b', profile: 'worker' }))})++function useGateway(connectionId: string) {+ $connection.set({ connectionId, mode: 'remote' } as never)+}++it('does not share one config record across two gateways', async () => {+ const laptop = { display: { theme: 'dark' } }+ const devbox = { display: { theme: 'light' } }+ let releaseDevbox: (record: typeof devbox) => void = () => undefined+ const devboxFetch = new Promise<typeof devbox>(resolve => {+ releaseDevbox = resolve+ })++ vi.mocked(getHermesConfigRecord).mockImplementation(() =>+ $connection.get()?.connectionId === 'devbox' ? devboxFetch : Promise.resolve(laptop)+ )++ useGateway('laptop')+ const { result } = renderHook(() => useHermesConfigRecord(), { wrapper })++ await waitFor(() => expect(result.current.data).toEqual(laptop))++ await act(async () => {+ useGateway('devbox')+ })++ // A settings save paints from this cache. The previous machine's record must+ // not still be the displayed one after the switch, or the save PUTs it onto+ // the other machine's config.yaml.+ expect(result.current.data).not.toEqual(laptop)++ await act(async () => {+ releaseDevbox(devbox)+ })+ await waitFor(() => expect(result.current.data).toEqual(devbox))++ const cached = queryClient.getQueriesData({ queryKey: HERMES_CONFIG_KEY }).map(([, data]) => data)++ expect(cached).toContainEqual(laptop)+ expect(cached).toContainEqual(devbox)+})++it('a settings cache write after switching gateways does not replace the other gateway record', () => {+ const laptop = { display: { theme: 'dark' } }+ const devbox = { display: { theme: 'light' } }+ // Config settings memoize the writer on the profile name. Both gateways are+ // on `default`, so a captured unscoped key would let the second save replace+ // the first machine's record.+ const writer = hermesConfigCacheWriter('default')++ useGateway('laptop')+ setHermesConfigCache(laptop)+ writer({ agent: { model: 'laptop-model' } })++ useGateway('devbox')+ setHermesConfigCache(devbox)+ writer({ agent: { model: 'devbox-model' } })++ const cached = queryClient.getQueriesData({ queryKey: HERMES_CONFIG_KEY }).map(([, data]) => data)++ expect(cached).toContainEqual(laptop)+ expect(cached).toContainEqual(devbox)+ expect(cached).toContainEqual({ agent: { model: 'laptop-model' } })+ expect(cached).toContainEqual({ agent: { model: 'devbox-model' } })+})diff --git a/apps/desktop/src/app/hooks/use-config-record.ts b/apps/desktop/src/app/hooks/use-config-record.tsindex aebe1ce1055..478cc3eac05 100644--- a/apps/desktop/src/app/hooks/use-config-record.ts+++ b/apps/desktop/src/app/hooks/use-config-record.ts@@ -1,3 +1,4 @@+import { useStore } from '@nanostores/react'import { replaceEqualDeep, useQuery } from '@tanstack/react-query'import {@@ -8,6 +9,7 @@ import {retainConfigReadOrigin} from '@/hermes'import { queryClient } from '@/lib/query-client'+import { $activeConnectionId } from '@/store/connections'import type { HermesConfigRecord } from '@/types/hermes'// One shared cache for the whole profile config record (`GET /api/config`).@@ -19,27 +21,74 @@ import type { HermesConfigRecord } from '@/types/hermes'// it pushes personality/cwd/voice/… into the session stores for live chat.export const HERMES_CONFIG_KEY = ['hermes-config-record'] as const-// Per-scope cache key. The base key (no suffix) is the app-wide active-// profile, unchanged for every caller that passes nothing. An explicit scope —-// the Capabilities scope selector configuring ANOTHER profile, possibly on-// another registered gateway — gets its own suffixed key so switching the-// selector refetches and never paints stale cross-profile config (the-// AGENTS.md scope-in-key rule). profileScopeKey folds a remote pin's-// connection id into the suffix, so two gateways' same-named profiles never-// share a cache row.-export const hermesConfigKey = (profile?: ProfileScope) =>- profile == null ? HERMES_CONFIG_KEY : ([...HERMES_CONFIG_KEY, profileScopeKey(profile)] as const)+// Slot for one gateway inside the existing config-record cache. The id is+// `$activeConnectionId` — the resolved descriptor identity the rest of the app+// already uses — not a second cache. A bare root key let a settings save after+// a gateway switch paint the previous machine's record and PUT it onto the+// other config.yaml. An explicit pin that already names a connection keeps+// profileScopeKey's suffix; a string profile (settings "Applies to") is+// namespaced the same way so two gateways' `default` profiles do not share a row.+function configRecordSlot(profile: ProfileScope | undefined, connectionId: null | string | undefined): string | null {+ const active = (connectionId ?? '').trim()++ if (profile && typeof profile === 'object') {+ const pinned = (profile.connectionId ?? '').trim()++ if (pinned || !active) {+ return profileScopeKey(profile)+ }++ return profileScopeKey({ ...profile, connectionId: active })+ }++ if (profile == null) {+ return active || null+ }++ const scope = profileScopeKey(profile)++ return active ? `${active}::${scope}` : scope+}++export const hermesConfigKey = (+ profile?: ProfileScope,+ connectionId: null | string | undefined = $activeConnectionId.get()+) => {+ const slot = configRecordSlot(profile, connectionId)++ return slot == null ? HERMES_CONFIG_KEY : ([...HERMES_CONFIG_KEY, slot] as const)+}// staleTime 0 → serve cache instantly, background-revalidate on every mount.-// `profile` scopes both the query key and the fetch; omitting it preserves the-// exact app-wide behavior (base key, `profileScoped(undefined)` fallback).+// `profile` scopes both the query key and the fetch. Omitting it still targets+// the app-wide active profile (`profileScoped(undefined)` fallback), but the+// cache slot is the active gateway's — not the bare root key.export const useHermesConfigRecord = (profile?: ProfileScope) => {+ // Reactive read, not a store getter: under the React Compiler a value with+ // no reactive inputs is computed once per component instance, so a+ // getter-based key would freeze on the first gateway and keep serving its+ // record after a switch.+ const connectionId = useStore($activeConnectionId)const query = useQuery({- queryKey: hermesConfigKey(profile),+ queryKey: hermesConfigKey(profile, connectionId),// null/undefined both mean "no override" → fetch with undefined so// capabilityScoped falls back to the app-wide active profile (passing null// would wrongly target the primary backend).- queryFn: () => getHermesConfigRecord(profile ?? undefined),+ queryFn: () => {+ // $activeConnectionId.listen invalidates profile queries in the same+ // turn it publishes the new id, before this observer moves to the new+ // key. A refetch of the slot we are leaving must not store the new+ // gateway's record there — that is the other machine's config.yaml.+ if (connectionId && $activeConnectionId.get() !== connectionId) {+ const cached = queryClient.getQueryData<HermesConfigRecord>(hermesConfigKey(profile, connectionId))++ if (cached !== undefined) {+ return cached+ }+ }++ return getHermesConfigRecord(profile ?? undefined)+ },staleTime: 0,// Keep structural sharing so an unchanged refetch (every consumer mount at// staleTime 0, every invalidate) yields the SAME object and consumers'@@ -75,16 +124,17 @@ export const useHermesConfigRecord = (profile?: ProfileScope) => {return query as typeof query & { writeScope: ReturnType<typeof peekConfigReadOrigin> }}-// setHermesConfigCache writes the app-wide (base-key) record. Pass a profile to-// write the suffixed per-profile cache instead — keeps the selector's optimistic-// write-through landing on the same key its query reads.+// setHermesConfigCache writes the active gateway's record. The key is resolved+// at WRITE time, not when the writer is created, so a writer memoized by a+// long-lived settings panel (keyed only on the profile name) lands on whichever+// gateway is active when the save happens — the same row its query reads.const writeHermesConfigCache =- (key: ReturnType<typeof hermesConfigKey>) =>+ (keyFor: () => ReturnType<typeof hermesConfigKey>) =>(next:HermesConfigRecord | undefined | ((previous: HermesConfigRecord | undefined) => HermesConfigRecord | undefined)) =>- void queryClient.setQueryData<HermesConfigRecord>(key, previous => {+ void queryClient.setQueryData<HermesConfigRecord>(keyFor(), previous => {const record = typeof next === 'function' ? next(previous) : next// setQueryData also runs the hook's structuralSharing (query.setData →@@ -95,8 +145,9 @@ const writeHermesConfigCache =return record ? retainConfigReadOrigin(record, previous) : record})-export const setHermesConfigCache = writeHermesConfigCache(HERMES_CONFIG_KEY)-export const hermesConfigCacheWriter = (profile?: ProfileScope) => writeHermesConfigCache(hermesConfigKey(profile))+export const setHermesConfigCache = writeHermesConfigCache(() => hermesConfigKey())+export const hermesConfigCacheWriter = (profile?: ProfileScope) =>+ writeHermesConfigCache(() => hermesConfigKey(profile))export const invalidateHermesConfig = (profile?: ProfileScope) =>queryClient.invalidateQueries({ queryKey: hermesConfigKey(profile) })