The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): route model catalogs and picker reseeds through the focused owner
Brooklyn Nicholson308454b372cf
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 276271d64d5..afa9f3883ed 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -82,7 +82,10 @@ import { advanceTranscriptWindow, type TranscriptWindowState } from './transcripinterface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {gateway: HermesGateway | null+ modelOptionsOwnerConnectionId?: string+ modelOptionsProfile?: stringmodelMenuContent?: React.ReactNode+ requestModelOptionsForOwner?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>onToggleSelectedPin: () => voidonDeleteSelectedSession: () => voidonCancel: () => Promise<void> | void@@ -358,7 +361,10 @@ export const ChatView = memo(function ChatView(props: ChatViewProps) {const ChatViewContent = memo(function ChatViewContent({className,gateway,+ modelOptionsOwnerConnectionId,+ modelOptionsProfile,modelMenuContent,+ requestModelOptionsForOwner,onToggleSelectedPin,onDeleteSelectedSession,onCancel,@@ -538,8 +544,18 @@ const ChatViewContent = memo(function ChatViewContent({const threadKey = selectedSessionId || activeSessionId || (isRoutedSessionView ? location.pathname : 'new')const modelOptionsQuery = useQuery<ModelOptionsResponse>({- queryKey: modelOptionsQueryKey(activeGatewayProfile, activeSessionId),- queryFn: () => requestModelOptions({ gateway: gateway || undefined, sessionId: activeSessionId }),+ queryKey: modelOptionsQueryKey(+ modelOptionsProfile || activeGatewayProfile,+ activeSessionId,+ modelOptionsOwnerConnectionId+ ),+ queryFn: () =>+ requestModelOptions({+ gateway: gateway || undefined,+ profile: modelOptionsProfile || activeGatewayProfile,+ request: requestModelOptionsForOwner,+ sessionId: activeSessionId+ }),enabled: gatewayOpen})diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsxindex d58c4584fe9..37d6ded2721 100644--- a/apps/desktop/src/app/chat/session-tile.tsx+++ b/apps/desktop/src/app/chat/session-tile.tsx@@ -165,7 +165,12 @@ function TileChat({[ownerRoute, requestGateway])- const { selectModel } = useModelControls({ queryClient, requestGateway: requestTileGateway })+ const { selectModel } = useModelControls({+ cacheOwnerConnectionId: ownerRoute?.connectionId || undefined,+ cacheProfile: ownerRoute?.targetProfile || ownerRoute?.profile || undefined,+ queryClient,+ requestGateway: requestTileGateway+ })const activeGatewayProfile = useStore($activeGatewayProfile)const cwd = useStore(view.$cwd)const gatewayOpen = useStore($gatewayState) === 'open'@@ -233,11 +238,20 @@ function TileChat({gatewayOpen ? (<ModelMenuPanelonSelectModel={selectModel}+ ownerConnectionId={ownerRoute?.connectionId || undefined}profile={ownerRoute?.targetProfile || ownerRoute?.profile || activeGatewayProfile}requestGateway={requestTileGateway}/>) : null,- [activeGatewayProfile, gatewayOpen, ownerRoute?.profile, ownerRoute?.targetProfile, requestTileGateway, selectModel]+ [+ activeGatewayProfile,+ gatewayOpen,+ ownerRoute?.connectionId,+ ownerRoute?.profile,+ ownerRoute?.targetProfile,+ requestTileGateway,+ selectModel+ ])return (@@ -246,6 +260,8 @@ function TileChat({<ChatViewgateway={gateway}modelMenuContent={modelMenuContent}+ modelOptionsOwnerConnectionId={ownerRoute?.connectionId || undefined}+ modelOptionsProfile={ownerRoute?.targetProfile || ownerRoute?.profile || activeGatewayProfile}onAddContextRef={addContextRefAttachment}onAddUrl={onAddUrl}onAttachDroppedItems={composer.attachDroppedItems}@@ -268,6 +284,7 @@ function TileChat({onThreadMessagesChange={actions.handleThreadMessagesChange}onToggleSelectedPin={noop}onTranscribeAudio={tileTranscribeAudio}+ requestModelOptionsForOwner={requestTileGateway}/></ComposerScopeProvider></SessionViewProvider>diff --git a/apps/desktop/src/app/contrib/surfaces.tsx b/apps/desktop/src/app/contrib/surfaces.tsxindex 5353035c09f..0c367c5e3d4 100644--- a/apps/desktop/src/app/contrib/surfaces.tsx+++ b/apps/desktop/src/app/contrib/surfaces.tsx@@ -117,6 +117,7 @@ export const ChatRoutesSurface = memo(function ChatRoutesSurface({actions: WiringActionsmaxVoiceRecordingSeconds?: number}) {+ const activeConnectionId = useStore($activeConnectionId)const activeGatewayProfile = useStore($activeGatewayProfile)const gateway = useStore($gateway)const gatewayState = useStore($gatewayState)@@ -129,11 +130,12 @@ export const ChatRoutesSurface = memo(function ChatRoutesSurface({<ModelMenuPanelgateway={gateway || undefined}onSelectModel={actions.selectModel}+ ownerConnectionId={activeConnectionId || undefined}profile={activeGatewayProfile}requestGateway={actions.requestGateway}/>) : null,- [actions, activeGatewayProfile, gateway, gatewayState]+ [actions, activeConnectionId, activeGatewayProfile, gateway, gatewayState])const chatActions = useMemo(() => latestChatActions(actions), [actions])@@ -143,6 +145,9 @@ export const ChatRoutesSurface = memo(function ChatRoutesSurface({gateway={gateway}maxVoiceRecordingSeconds={maxVoiceRecordingSeconds}modelMenuContent={modelMenuContent}+ modelOptionsOwnerConnectionId={activeConnectionId || undefined}+ modelOptionsProfile={activeGatewayProfile}+ requestModelOptionsForOwner={actions.requestGateway}{...chatActions}/>)diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 90d328001d2..03fdf6de9c9 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -341,6 +341,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {const { refreshHermesConfig, sttEnabled, voiceMaxRecordingSeconds } = useHermesConfig({ activeSessionIdRef })const { applySavedMainModel, refreshCurrentModel, selectModel } = useModelControls({+ cacheOwnerConnectionId: activeConnectionId || undefined,+ cacheProfile: activeGatewayProfile,queryClient,requestGateway})@@ -1155,11 +1157,18 @@ export function ContribWiring({ children }: { children: ReactNode }) {requestGateway={requestGateway}/>)}- <ModelPickerOverlay gateway={gateway || undefined} onSelect={selectModel} profile={activeGatewayProfile} />+ <ModelPickerOverlay+ gateway={gateway || undefined}+ onSelect={selectModel}+ ownerConnectionId={activeConnectionId || undefined}+ profile={activeGatewayProfile}+ requestGateway={requestGateway}+ /><SessionPickerOverlay onResume={sessionId => openSession(sessionId, navigate)} /><ModelVisibilityOverlaygateway={gateway || undefined}onOpenProviders={openProviderSettings}+ ownerConnectionId={activeConnectionId || undefined}profile={activeGatewayProfile}/><UpdatesOverlay />diff --git a/apps/desktop/src/app/model-picker-overlay.tsx b/apps/desktop/src/app/model-picker-overlay.tsxindex b6599a14fb2..2666cdb856b 100644--- a/apps/desktop/src/app/model-picker-overlay.tsx+++ b/apps/desktop/src/app/model-picker-overlay.tsx@@ -1,8 +1,12 @@import { useStore } from '@nanostores/react'+import { useQueryClient } from '@tanstack/react-query'+import { useCallback } from 'react'+import { useModelControls } from '@/app/session/hooks/use-model-controls'import type { ModelSelection } from '@/app/shell/model-menu-panel'import { ModelPickerDialog } from '@/components/model-picker'import type { HermesGateway } from '@/hermes'+import { resolveModelPickerOwner } from '@/lib/model-picker-owner'import { useStoreSelector } from '@/lib/use-session-slice'import {$activeSessionId,@@ -10,21 +14,40 @@ import {$currentProvider,$gatewayState,$modelPickerOpen,+ $selectedStoredSessionId,setModelPickerOpen} from '@/store/session'-import { $focusedRuntimeId, $focusedSessionState } from '@/store/session-states'+import { requestForSessionProfile } from '@/store/session-request-router'+import {+ $focusedRuntimeId,+ $focusedSessionState,+ $focusedStoredSessionId,+ $sessionTiles+} from '@/store/session-states'interface ModelPickerOverlayProps {gateway?: HermesGatewayonSelect: (selection: ModelSelection) => void+ ownerConnectionId?: stringprofile: string+ requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>}-export function ModelPickerOverlay({ gateway, onSelect, profile }: ModelPickerOverlayProps) {+export function ModelPickerOverlay({+ gateway,+ onSelect,+ ownerConnectionId,+ profile,+ requestGateway+}: ModelPickerOverlayProps) {+ const queryClient = useQueryClient()const primarySessionId = useStore($activeSessionId)+ const selectedStoredSessionId = useStore($selectedStoredSessionId)const primaryModel = useStore($currentModel)const primaryProvider = useStore($currentProvider)const focusedRuntimeId = useStore($focusedRuntimeId)+ const focusedStoredSessionId = useStore($focusedStoredSessionId)+ const sessionTiles = useStore($sessionTiles)// `$focusedSessionState` is a projection of `$sessionStates`, republished on// EVERY message delta — and this overlay is mounted app-wide. Only two// fields are read off it, so subscribing to the whole object re-rendered@@ -36,6 +59,27 @@ export function ModelPickerOverlay({ gateway, onSelect, profile }: ModelPickerOvconst gatewayOpen = useStore($gatewayState) === 'open'const open = useStore($modelPickerOpen)+ const pickerOwner = resolveModelPickerOwner({+ ambientConnectionId: ownerConnectionId,+ ambientProfile: profile,+ focusedStoredSessionId,+ selectedStoredSessionId,+ sessionTiles+ })++ const requestPickerGateway = useCallback(+ <T,>(method: string, params?: Record<string, unknown>): Promise<T> =>+ requestForSessionProfile<T>(pickerOwner.route, requestGateway, method, params),+ [pickerOwner.route, requestGateway]+ )++ const { selectModel: selectFocusedModel } = useModelControls({+ cacheOwnerConnectionId: pickerOwner.connectionId,+ cacheProfile: pickerOwner.profile,+ queryClient,+ requestGateway: requestPickerGateway+ })+// Prefer the focused tile's runtime when the overlay opens from a tile that// lacked a live menu (gateway closed → fallback path).const sessionId = focusedRuntimeId ?? primarySessionId@@ -52,9 +96,13 @@ export function ModelPickerOverlay({ gateway, onSelect, profile }: ModelPickerOvcurrentProvider={currentProvider}gw={gateway}onOpenChange={setModelPickerOpen}- onSelect={selection => onSelect({ ...selection, sessionId })}+ onSelect={selection =>+ (pickerOwner.route ? selectFocusedModel : onSelect)({ ...selection, sessionId })+ }open={open}- profile={profile}+ ownerConnectionId={pickerOwner.connectionId}+ profile={pickerOwner.profile}+ request={pickerOwner.route ? requestPickerGateway : undefined}sessionId={sessionId}/>)diff --git a/apps/desktop/src/app/model-visibility-overlay.tsx b/apps/desktop/src/app/model-visibility-overlay.tsxindex a20dd7c4a5d..b9c8fd5025c 100644--- a/apps/desktop/src/app/model-visibility-overlay.tsx+++ b/apps/desktop/src/app/model-visibility-overlay.tsx@@ -8,10 +8,16 @@ import { $activeSessionId, $gatewayState } from '@/store/session'interface ModelVisibilityOverlayProps {gateway?: HermesGatewayonOpenProviders: () => void+ ownerConnectionId?: stringprofile: string}-export function ModelVisibilityOverlay({ gateway, onOpenProviders, profile }: ModelVisibilityOverlayProps) {+export function ModelVisibilityOverlay({+ gateway,+ onOpenProviders,+ ownerConnectionId,+ profile+}: ModelVisibilityOverlayProps) {const activeSessionId = useStore($activeSessionId)const gatewayOpen = useStore($gatewayState) === 'open'const open = useStore($modelVisibilityOpen)@@ -26,6 +32,7 @@ export function ModelVisibilityOverlay({ gateway, onOpenProviders, profile }: MoonOpenChange={setModelVisibilityOpen}onOpenProviders={onOpenProviders}open={open}+ ownerConnectionId={ownerConnectionId}profile={profile}sessionId={activeSessionId}/>diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsxindex 819eed1828f..da254e334c1 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx@@ -14,7 +14,7 @@ import {setCurrentModelSource,setCurrentProvider} from '@/store/session'-import type * as SessionStates from '@/store/session-states'+import * as SessionStates from '@/store/session-states'import { deferred } from '../../../test/deferred'@@ -85,6 +85,7 @@ describe('useModelControls', () => {setCurrentModel('')setCurrentModelSource('')setCurrentProvider('')+ SessionStates.$sessionStates.set({})})afterEach(() => {@@ -95,6 +96,29 @@ describe('useModelControls', () => {setCurrentModel('')setCurrentModelSource('')setCurrentProvider('')+ SessionStates.$sessionStates.set({})+ })++ it('writes optimistic selections only to the owning connection cache', async () => {+ const queryClient = new QueryClient()++ const { result } = renderHook(() =>+ useModelControls({+ cacheOwnerConnectionId: 'source-a',+ cacheProfile: 'beta',+ queryClient,+ requestGateway: vi.fn()+ })+ )++ await act(() => result.current.selectModel({ model: 'a/model', provider: 'a' }))++ expect(queryClient.getQueryData(modelOptionsQueryKey('beta', null, 'source-a'))).toMatchObject({+ model: 'a/model',+ provider: 'a'+ })+ expect(queryClient.getQueryData(modelOptionsQueryKey('beta'))).toBeUndefined()+ expect(queryClient.getQueryData(modelOptionsQueryKey('beta', null, 'source-b'))).toBeUndefined()})it('applies the global model when there is no active runtime session', async () => {@@ -491,6 +515,23 @@ describe('useModelControls', () => {expect($currentModel.get()).toBe('openai/gpt-5.5')})+ it('reads a forced profile reseed from that concrete profile', async () => {+ $activeGatewayProfile.set('fred-work')+ vi.mocked(getGlobalModelInfo).mockResolvedValue({ model: 'local/model', provider: 'custom:local' })++ const { result } = renderHook(() =>+ useModelControls({+ queryClient: new QueryClient(),+ requestGateway: vi.fn()+ })+ )++ await result.current.refreshCurrentModel(true)++ expect(getGlobalModelInfo).toHaveBeenCalledWith('fred-work')+ expect($currentProvider.get()).toBe('custom:local')+ })+it('reseeds a sticky manual pick that was removed from the catalog', async () => {vi.mocked(getGlobalModelInfo).mockResolvedValue({ model: 'openai/gpt-5.5', provider: 'openai-codex' })@@ -612,35 +653,82 @@ describe('useModelControls', () => {expect(getCurrentModelSource()).toBe('default')})- it('targets an explicit tile sessionId without clobbering the primary model', async () => {+ it('keeps an active-A focused-B selection cache and request on B', async () => {const queryClient = new QueryClient()- $activeGatewayProfile.set('compass')- $activeSessionId.set('primary-runtime')+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ $activeGatewayProfile.set('profile-a')+ $activeSessionId.set('runtime-a')setCurrentModel('primary/model')setCurrentProvider('openai')const requestGateway = vi.fn(async () => ({ key: 'model', value: 'tile-model' }) as never)- const { result } = renderHook(() => useModelControls({ queryClient, requestGateway }))++ const { result } = renderHook(() =>+ useModelControls({+ cacheOwnerConnectionId: 'connection-b',+ cacheProfile: 'profile-b',+ queryClient,+ requestGateway+ })+ )await expect(result.current.selectModel({model: 'tile-model',provider: 'anthropic',- sessionId: 'tile-runtime'+ sessionId: 'runtime-b'})).resolves.toBe(true)expect(requestGateway).toHaveBeenCalledWith('config.set', {- session_id: 'tile-runtime',+ session_id: 'runtime-b',key: 'model',value: 'tile-model --provider anthropic --session'})// Primary footer untouched — the busy primary must not absorb a tile pick.expect($currentModel.get()).toBe('primary/model')expect($currentProvider.get()).toBe('openai')- expect(queryClient.getQueryData(modelOptionsQueryKey('compass', 'tile-runtime'))).toMatchObject({+ expect(queryClient.getQueryData(modelOptionsQueryKey('profile-b', 'runtime-b', 'connection-b'))).toMatchObject({model: 'tile-model',provider: 'anthropic'})- expect(queryClient.getQueryData(modelOptionsQueryKey('default', 'tile-runtime'))).toBeUndefined()+ expect(queryClient.getQueryData(modelOptionsQueryKey('profile-a', 'runtime-b'))).toBeUndefined()+ expect(queryClient.getQueryData(modelOptionsQueryKey('profile-b', 'runtime-b', 'connection-a'))).toBeUndefined()+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: modelOptionsQueryKey('profile-b', 'runtime-b', 'connection-b')+ })+ })++ it('rolls a failed focused-B selection back only in B cache', async () => {+ const queryClient = new QueryClient()+ const ownerBKey = modelOptionsQueryKey('profile-b', 'runtime-b', 'connection-b')+ const ambientAKey = modelOptionsQueryKey('profile-a', 'runtime-b', 'connection-a')+ queryClient.setQueryData(ownerBKey, { model: 'old-b', provider: 'provider-b', providers: [] })+ queryClient.setQueryData(ambientAKey, { model: 'model-a', provider: 'provider-a', providers: [] })+ $activeGatewayProfile.set('profile-a')+ $activeSessionId.set('runtime-a')+ SessionStates.$sessionStates.set({+ 'runtime-b': { model: 'old-b', provider: 'provider-b' }+ } as never)++ const requestGateway = vi.fn(async () => {+ throw new Error('no such model')+ })++ const { result } = renderHook(() =>+ useModelControls({+ cacheOwnerConnectionId: 'connection-b',+ cacheProfile: 'profile-b',+ queryClient,+ requestGateway+ })+ )++ await expect(+ result.current.selectModel({ model: 'bogus', provider: 'xai', sessionId: 'runtime-b' })+ ).resolves.toBe(false)++ expect(queryClient.getQueryData(ownerBKey)).toMatchObject({ model: 'old-b', provider: 'provider-b' })+ expect(queryClient.getQueryData(ambientAKey)).toMatchObject({ model: 'model-a', provider: 'provider-a' })+ expect(notifyError).toHaveBeenCalled()})})diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.ts b/apps/desktop/src/app/session/hooks/use-model-controls.tsindex 46db8a1c6d3..392be887356 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts@@ -24,6 +24,8 @@ import { $sessionStates, sessionTileDelegate } from '@/store/session-states'import type { ModelOptionsResponse } from '@/types/hermes'interface ModelControlsOptions {+ cacheOwnerConnectionId?: string+ cacheProfile?: stringqueryClient: QueryClientrequestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>}@@ -34,7 +36,12 @@ interface ModelSwitchResponse {deferred?: boolean}-export function useModelControls({ queryClient, requestGateway }: ModelControlsOptions) {+export function useModelControls({+ cacheOwnerConnectionId,+ cacheProfile,+ queryClient,+ requestGateway+}: ModelControlsOptions) {const { t } = useI18n()const copy = t.desktopconst profileRefreshEpochRef = useRef(0)@@ -50,7 +57,8 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOprovider: string,model: string,includeGlobal: boolean,- profile = $activeGatewayProfile.get()+ profile = cacheProfile || $activeGatewayProfile.get(),+ ownerConnectionId = cacheOwnerConnectionId) => {const patch = (prev: ModelOptionsResponse | undefined) => {// Selection state can update before the catalog query has resolved.@@ -65,13 +73,16 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOreturn { ...prev, provider, model, providers }}- queryClient.setQueryData<ModelOptionsResponse>(modelOptionsQueryKey(profile, sessionId), patch)+ queryClient.setQueryData<ModelOptionsResponse>(+ modelOptionsQueryKey(profile, sessionId, ownerConnectionId),+ patch+ )if (includeGlobal) {- queryClient.setQueryData<ModelOptionsResponse>(modelOptionsQueryKey(profile), patch)+ queryClient.setQueryData<ModelOptionsResponse>(modelOptionsQueryKey(profile, null, ownerConnectionId), patch)}},- [queryClient]+ [cacheOwnerConnectionId, cacheProfile, queryClient])// Settings → Model writes the profile default, which the backend applies to@@ -111,6 +122,7 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO}const profileRefreshEpoch = profileRefreshEpochRef.current+ const profile = $activeGatewayProfile.get()try {if ($activeSessionId.get()) {@@ -128,7 +140,11 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO}const options = queryClient.getQueryData<ModelOptionsResponse>(- modelOptionsQueryKey($activeGatewayProfile.get())+ modelOptionsQueryKey(+ cacheProfile || $activeGatewayProfile.get(),+ null,+ cacheOwnerConnectionId+ ))return !manualPickRemoved(options?.providers, $currentProvider.get(), $currentModel.get())@@ -142,7 +158,7 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO// that lands while getGlobalModelInfo is in flight wins over this older// default — value comparisons alone miss re-selecting the same row.const selectionGeneration = getComposerSelectionGeneration()- const result = await getGlobalModelInfo()+ const result = await getGlobalModelInfo(profile)if (profileRefreshEpochRef.current !== profileRefreshEpoch ||@@ -168,7 +184,7 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO// The delayed session.info event still updates this once the agent is ready.}},- [queryClient]+ [cacheOwnerConnectionId, cacheProfile, queryClient])// Returns whether the switch was applied so callers can await it before@@ -201,7 +217,7 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO: ($sessionStates.get()[liveSessionId!]?.provider ?? '')const prevSource = getCurrentModelSource()- const liveGatewayProfile = $activeGatewayProfile.get()+ const liveGatewayProfile = cacheProfile || $activeGatewayProfile.get()const paintSelection = () => {if (touchesPrimary) {@@ -279,7 +295,9 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO// the switch publishes session.info when it lands, and that is what// re-syncs every surface.if (!result?.deferred) {- void queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(liveGatewayProfile, liveSessionId) })+ void queryClient.invalidateQueries({+ queryKey: modelOptionsQueryKey(liveGatewayProfile, liveSessionId, cacheOwnerConnectionId)+ })}}@@ -338,7 +356,15 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOreturn false}},- [copy.modelSwitchFailed, queryClient, requestGateway, t.common.confirm, updateModelOptionsCache]+ [+ cacheOwnerConnectionId,+ cacheProfile,+ copy.modelSwitchFailed,+ queryClient,+ requestGateway,+ t.common.confirm,+ updateModelOptionsCache+ ])return { applySavedMainModel, refreshCurrentModel, selectModel }diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsxindex 541a17d61cc..83deb56e773 100644--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx@@ -99,6 +99,9 @@ interface ModelCatalogMenuProps {/** Render the virtual `moa` provider's presets as a selectable section.* Off for override surfaces, where a MoA preset isn't a worker model. */includeMoa?: boolean+ /** Registry source owning this catalog. Profile/session names are not unique+ * across sources, so this participates in the React Query cache key. */+ ownerConnectionId?: stringprofile?: string/** Session whose catalog to fetch. A live session's catalog can differ from* the profile-global one, and the app invalidates the SESSION-scoped query@@ -124,6 +127,7 @@ export function ModelCatalogMenu({footer,gateway,includeMoa = false,+ ownerConnectionId,profile = 'default',request,sessionId = null@@ -141,7 +145,7 @@ export function ModelCatalogMenu({const visibleModels = useStore($visibleModels)const modelOptions = useQuery({- queryKey: modelOptionsQueryKey(profile, sessionId),+ queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),// Gateway-first even with no session: a connected (possibly remote)// gateway owns the model catalog, including virtual providers the local// REST fallback can't know about (#53817).diff --git a/apps/desktop/src/app/shell/model-menu-panel.test.tsx b/apps/desktop/src/app/shell/model-menu-panel.test.tsxindex 5206aa5e404..bbcb87dd2f0 100644--- a/apps/desktop/src/app/shell/model-menu-panel.test.tsx+++ b/apps/desktop/src/app/shell/model-menu-panel.test.tsx@@ -69,11 +69,19 @@ afterEach(() => {function renderPanel(onSelectModel = vi.fn()) {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'model.options') {+ return getGlobalModelOptions()+ }++ throw new Error(`unexpected gateway method: ${method}`)+ })+const content = render(<QueryClientProvider client={client}><DropdownMenu open><DropdownMenuContent>- <ModelMenuPanel onSelectModel={onSelectModel} requestGateway={vi.fn() as never} />+ <ModelMenuPanel onSelectModel={onSelectModel} requestGateway={requestGateway as never} /></DropdownMenuContent></DropdownMenu></QueryClientProvider>@@ -497,14 +505,18 @@ describe('ModelMenuPanel refresh reconcile × guarded-switch confirm handshake',providers: [{ models: ['muse-spark-1.2-contributor'], name: 'OpenCode', slug: 'opencode-go' }, MOA_PROVIDER]})- // Method-aware gateway: the panel's catalog reads (`model.options`) fall- // back to the REST mock; `config.set` runs the guarded handshake —+ // Method-aware gateway: the panel's catalog reads (`model.options`) use+ // the routed catalog mock; `config.set` runs the guarded handshake —// confirm_required first, success on the confirmed resend.let configSets = 0const requestGateway = vi.fn(async (method: string, _params?: Record<string, unknown>) => {+ if (method === 'model.options') {+ return getGlobalModelOptions()+ }+if (method !== 'config.set') {- throw new Error('use REST catalog')+ throw new Error(`unexpected gateway method: ${method}`)}configSets += 1diff --git a/apps/desktop/src/app/shell/model-menu-panel.tsx b/apps/desktop/src/app/shell/model-menu-panel.tsxindex 7e6fa4ab45c..eca7f2163ad 100644--- a/apps/desktop/src/app/shell/model-menu-panel.tsx+++ b/apps/desktop/src/app/shell/model-menu-panel.tsx@@ -37,6 +37,7 @@ export interface ModelSelection {interface ModelMenuPanelProps {gateway?: HermesGateway+ ownerConnectionId?: stringonSelectModel: (selection: ModelSelection) => Promise<boolean> | voidprofile?: stringrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>@@ -48,7 +49,13 @@ interface ModelMenuPanelProps {* surface's session, remember the pick as a global preset, keep the optimistic* stores honest, and roll back on a failed gateway write.*/-export function ModelMenuPanel({ gateway, onSelectModel, profile = 'default', requestGateway }: ModelMenuPanelProps) {+export function ModelMenuPanel({+ gateway,+ onSelectModel,+ ownerConnectionId,+ profile = 'default',+ requestGateway+}: ModelMenuPanelProps) {const { t } = useI18n()const copy = t.shell.modelMenuconst [refreshing, setRefreshing] = useState(false)@@ -72,7 +79,7 @@ export function ModelMenuPanel({ gateway, onSelectModel, profile = 'default', re// back to the catalog's reported current, and a non-reactive read would// never repaint that fallback once the catalog resolved.const modelOptions = useQuery({- queryKey: modelOptionsQueryKey(profile, activeSessionId),+ queryKey: modelOptionsQueryKey(profile, activeSessionId, ownerConnectionId),queryFn: (): Promise<ModelOptionsResponse> =>requestModelOptions({ gateway, profile, request: requestGateway, sessionId: activeSessionId })})@@ -94,7 +101,7 @@ export function ModelMenuPanel({ gateway, onSelectModel, profile = 'default', resetRefreshing(true)try {- const queryKey = modelOptionsQueryKey(profile, activeSessionId)+ const queryKey = modelOptionsQueryKey(profile, activeSessionId, ownerConnectionId)const next = await requestModelOptions({gateway,@@ -253,6 +260,7 @@ export function ModelMenuPanel({ gateway, onSelectModel, profile = 'default', re}gateway={gateway}includeMoa+ ownerConnectionId={ownerConnectionId}profile={profile}request={requestGateway}sessionId={activeSessionId}diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsxindex 4f5415f9205..e0eaaf706ae 100644--- a/apps/desktop/src/components/model-picker.tsx+++ b/apps/desktop/src/components/model-picker.tsx@@ -27,7 +27,9 @@ interface ModelPickerDialogProps {currentModel: stringcurrentProvider: stringonSelect: (selection: { provider: string; model: string }) => void+ ownerConnectionId?: stringprofile?: string+ request?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>/*** Optional class for DialogContent. Use it to lift the picker onto a higher* rung of the overlay ladder when it opens over another fixed overlay (the@@ -45,7 +47,9 @@ export function ModelPickerDialog({currentModel,currentProvider,onSelect,+ ownerConnectionId,profile = 'default',+ request,contentClassName}: ModelPickerDialogProps) {const { t } = useI18n()@@ -58,8 +62,8 @@ export function ModelPickerDialog({const [search, setSearch] = useState('')const modelOptions = useQuery({- queryKey: modelOptionsQueryKey(profile, sessionId),- queryFn: () => requestModelOptions({ gateway: gw, sessionId }),+ queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),+ queryFn: () => requestModelOptions({ gateway: gw, profile, request, sessionId }),enabled: open})diff --git a/apps/desktop/src/components/model-visibility-dialog.tsx b/apps/desktop/src/components/model-visibility-dialog.tsxindex 418ee9f3d7c..5fe32d929a4 100644--- a/apps/desktop/src/components/model-visibility-dialog.tsx+++ b/apps/desktop/src/components/model-visibility-dialog.tsx@@ -32,6 +32,7 @@ interface ModelVisibilityDialogProps {onOpenChange: (open: boolean) => voidonOpenProviders: () => voidopen: boolean+ ownerConnectionId?: stringprofile?: stringsessionId?: string | null}@@ -41,6 +42,7 @@ export function ModelVisibilityDialog({onOpenChange,onOpenProviders,open,+ ownerConnectionId,profile = 'default',sessionId}: ModelVisibilityDialogProps) {@@ -51,8 +53,8 @@ export function ModelVisibilityDialog({const collapsedProviders = useStore($collapsedProviders)const modelOptions = useQuery({- queryKey: modelOptionsQueryKey(profile, sessionId),- queryFn: (): Promise<ModelOptionsResponse> => requestModelOptions({ gateway: gw, sessionId }),+ queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),+ queryFn: (): Promise<ModelOptionsResponse> => requestModelOptions({ gateway: gw, profile, sessionId }),enabled: open})diff --git a/apps/desktop/src/lib/model-options.test.ts b/apps/desktop/src/lib/model-options.test.tsindex 7c46948571c..c7846521ee7 100644--- a/apps/desktop/src/lib/model-options.test.ts+++ b/apps/desktop/src/lib/model-options.test.ts@@ -1,3 +1,4 @@+import { QueryClient } from '@tanstack/react-query'import { afterEach, describe, expect, it, vi } from 'vitest'import { getGlobalModelOptions } from '@/hermes'@@ -119,6 +120,19 @@ describe('requestModelOptions', () => {expect(getGlobalModelOptions).toHaveBeenCalledWith({ explicitOnly: true, refresh: true })})+ it('passes the catalog owner profile through the shared gateway RPC', async () => {+ const gateway = {+ request: vi.fn(() => Promise.resolve(globalOptions))+ }++ await requestModelOptions({ gateway: gateway as never, profile: 'fred-work' })++ expect(gateway.request).toHaveBeenCalledWith('model.options', {+ explicit_only: true,+ profile: 'fred-work'+ })+ })+it('falls back to REST when no gateway is connected', async () => {await requestModelOptions({ refresh: true })@@ -155,19 +169,24 @@ describe('requestModelOptions', () => {expect(gateway.request).not.toHaveBeenCalled()})- it('scopes REST recovery to the catalog owner profile', async () => {- const restPayload = {- model: 'berry-local',- provider: 'hermes-local',- providers: [{ models: ['berry-local'], name: 'Hermes Local', slug: 'hermes-local' }]- }+ it('does not recover an owner-routed failure through the ambient REST connection', async () => {+ const ownerError = new Error('owner gateway unavailable')+ const request = vi.fn(() => Promise.reject(ownerError))- const request = vi.fn(() => Promise.reject(new Error('gateway request unavailable')))+ await expect(requestModelOptions({ profile: 'berry', request, sessionId: 'tile-1' })).rejects.toBe(ownerError)+ expect(getGlobalModelOptions).not.toHaveBeenCalled()+ })- vi.mocked(getGlobalModelOptions).mockResolvedValueOnce(restPayload)+ it('keeps an empty owner-routed catalog instead of replacing it from ambient REST', async () => {+ const ownerPayload = { model: 'berry-local', provider: 'hermes-local', providers: [] }- await expect(requestModelOptions({ profile: 'berry', request, sessionId: 'tile-1' })).resolves.toEqual(restPayload)- expect(getGlobalModelOptions).toHaveBeenCalledWith({ explicitOnly: true }, 'berry')+ const request = vi.fn(() => Promise.resolve(ownerPayload)) as unknown as <T>(+ method: string,+ params?: Record<string, unknown>+ ) => Promise<T>++ await expect(requestModelOptions({ profile: 'berry', request, sessionId: 'tile-1' })).resolves.toBe(ownerPayload)+ expect(getGlobalModelOptions).not.toHaveBeenCalled()})})@@ -181,6 +200,25 @@ describe('modelOptionsQueryKey', () => {it('keeps session catalogs inside the owning profile namespace', () => {expect(modelOptionsQueryKey(' compass ', 'session-1')).toEqual(['model-options', 'compass', 'session-1'])})++ it('isolates identical profile and session names across registry connections', () => {+ const sourceAKey = modelOptionsQueryKey('default', 'session-1', 'source-a')+ const sourceBKey = modelOptionsQueryKey('default', 'session-1', 'source-b')+ const queryClient = new QueryClient()++ expect(sourceAKey).toEqual([+ 'model-options',+ 'default',+ 'session-1',+ 'owner',+ 'source-a'+ ])+ queryClient.setQueryData(sourceAKey, { providers: [{ models: ['a/model'], slug: 'a' }] })+ queryClient.setQueryData(sourceBKey, { providers: [{ models: ['b/model'], slug: 'b' }] })++ expect(queryClient.getQueryData(sourceAKey)).toMatchObject({ providers: [{ models: ['a/model'] }] })+ expect(queryClient.getQueryData(sourceBKey)).toMatchObject({ providers: [{ models: ['b/model'] }] })+ })})describe('manualPickRemoved', () => {diff --git a/apps/desktop/src/lib/model-options.ts b/apps/desktop/src/lib/model-options.tsindex e2c72cb25a0..da89b8d15bc 100644--- a/apps/desktop/src/lib/model-options.ts+++ b/apps/desktop/src/lib/model-options.ts@@ -109,10 +109,15 @@ interface ModelOptionsRequest {sessionId?: null | string}-export function modelOptionsQueryKey(profile: null | string | undefined, sessionId?: null | string) {+export function modelOptionsQueryKey(+ profile: null | string | undefined,+ sessionId?: null | string,+ ownerConnectionId?: null | string+) {const profileKey = (profile ?? '').trim() || 'default'+ const ownerKey = (ownerConnectionId ?? '').trim()- return ['model-options', profileKey, sessionId || 'global'] as const+ return ['model-options', profileKey, sessionId || 'global', ...(ownerKey ? ['owner', ownerKey] : [])] as const}function hasSelectableModels(options: ModelOptionsResponse | null | undefined): boolean {@@ -155,6 +160,12 @@ export async function requestModelOptions({params.explicit_only = true}+ const profileKey = (profile ?? '').trim()++ if (profileKey) {+ params.profile = profileKey+ }+let gatewayError: unknownlet gatewayOptions: ModelOptionsResponse | undefined@@ -168,23 +179,26 @@ export async function requestModelOptions({return gatewayOptions}- // A connected Desktop gateway can occasionally return only the current- // provider/model (or an empty provider list) while its authenticated REST- // catalog is already populated. Recover through the same profile-scoped- // endpoint Settings uses, but keep the live session selection authoritative.- try {- const restOptions = await restModelOptions(explicitOnly, refresh, profile)-- if (hasSelectableModels(restOptions)) {- return {- ...restOptions,- ...(gatewayOptions?.provider ? { provider: gatewayOptions.provider } : {}),- ...(gatewayOptions?.model ? { model: gatewayOptions.model } : {})+ // An owner-routed dispatcher can name a different registry connection than+ // the ambient REST client. Never recover that request through ambient REST:+ // profile names are not unique across sources, so doing so can cache B's+ // catalog under A's tile. Ambient gateway requests retain the compatibility+ // recovery used by older backends with incomplete model.options responses.+ if (!request) {+ try {+ const restOptions = await restModelOptions(explicitOnly, refresh, profile)++ if (hasSelectableModels(restOptions)) {+ return {+ ...restOptions,+ ...(gatewayOptions?.provider ? { provider: gatewayOptions.provider } : {}),+ ...(gatewayOptions?.model ? { model: gatewayOptions.model } : {})+ }}+ } catch {+ // Preserve the gateway result (or its original error) when the recovery+ // path is unavailable.}- } catch {- // Preserve the gateway result (or its original error) when the recovery- // path is unavailable.}if (gatewayOptions) {diff --git a/apps/desktop/src/lib/model-picker-owner.test.ts b/apps/desktop/src/lib/model-picker-owner.test.tsnew file mode 100644index 00000000000..f14de178192--- /dev/null+++ b/apps/desktop/src/lib/model-picker-owner.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'++import { resolveModelPickerOwner } from './model-picker-owner'++describe('resolveModelPickerOwner', () => {+ it('keeps an active-A focused-B picker on the focused tile owner', () => {+ expect(+ resolveModelPickerOwner({+ ambientConnectionId: 'connection-a',+ ambientProfile: 'profile-a',+ focusedStoredSessionId: 'stored-b',+ selectedStoredSessionId: 'stored-a',+ sessionTiles: [+ {+ ownerRoute: {+ connectionId: 'connection-b',+ profile: 'desktop-b',+ targetProfile: 'backend-b'+ },+ storedSessionId: 'stored-b'+ }+ ]+ })+ ).toEqual({+ connectionId: 'connection-b',+ profile: 'backend-b',+ route: {+ connectionId: 'connection-b',+ profile: 'desktop-b',+ targetProfile: 'backend-b'+ }+ })+ })++ it('uses the ambient owner when the primary session is focused', () => {+ expect(+ resolveModelPickerOwner({+ ambientConnectionId: 'connection-a',+ ambientProfile: 'profile-a',+ focusedStoredSessionId: 'stored-a',+ selectedStoredSessionId: 'stored-a',+ sessionTiles: []+ })+ ).toEqual({ connectionId: 'connection-a', profile: 'profile-a', route: undefined })+ })+})\ No newline at end of filediff --git a/apps/desktop/src/lib/model-picker-owner.ts b/apps/desktop/src/lib/model-picker-owner.tsnew file mode 100644index 00000000000..7c71f9df06e--- /dev/null+++ b/apps/desktop/src/lib/model-picker-owner.ts@@ -0,0 +1,39 @@+import type { SessionOwnerRoute } from '@/store/session-request-router'++interface ModelPickerOwnerInput {+ ambientConnectionId?: string+ ambientProfile: string+ focusedStoredSessionId: null | string+ selectedStoredSessionId: null | string+ sessionTiles: readonly {+ ownerRoute?: SessionOwnerRoute+ storedSessionId: string+ }[]+}++export interface ModelPickerOwner {+ connectionId?: string+ profile: string+ route?: SessionOwnerRoute+}++/** Resolve one coherent owner for every picker operation. A tile route wins+ * only when the tile, rather than the primary session, owns keyboard focus. */+export function resolveModelPickerOwner({+ ambientConnectionId,+ ambientProfile,+ focusedStoredSessionId,+ selectedStoredSessionId,+ sessionTiles+}: ModelPickerOwnerInput): ModelPickerOwner {+ const route =+ focusedStoredSessionId && focusedStoredSessionId !== selectedStoredSessionId+ ? sessionTiles.find(tile => tile.storedSessionId === focusedStoredSessionId)?.ownerRoute+ : undefined++ return {+ connectionId: route?.connectionId || ambientConnectionId,+ profile: route?.targetProfile || route?.profile || ambientProfile,+ route+ }+}\ No newline at end of file