The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): confirm guarded model switches instead of snapping back
etzelvon7450266a3a6a
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 f3b9c5e0209..9eddf703e95 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@@ -1,5 +1,5 @@import { QueryClient } from '@tanstack/react-query'-import { cleanup, render, renderHook } from '@testing-library/react'+import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { getGlobalModelInfo } from '@/hermes'@@ -21,6 +21,7 @@ import { deferred } from '../../../test/deferred'import { useModelControls } from './use-model-controls'const setGlobalModel = vi.fn()+const notify = vi.fn()const notifyError = vi.fn()vi.mock('@/hermes', () => ({@@ -41,6 +42,9 @@ vi.mock('@/store/session-states', async importOriginal => {vi.mock('@/i18n', () => ({useI18n: () => ({t: {+ common: {+ confirm: 'Confirm'+ },desktop: {modelSwitchFailed: 'Model switch failed'}@@ -49,6 +53,7 @@ vi.mock('@/i18n', () => ({}))vi.mock('@/store/notifications', () => ({+ notify: (...args: Parameters<typeof notify>) => notify(...args),notifyError: (...args: Parameters<typeof notifyError>) => notifyError(...args)}))@@ -301,6 +306,56 @@ describe('useModelControls', () => {expect(invalidate).toHaveBeenCalled()})+ it('confirms a guarded model switch before retrying it', async () => {+ $activeSessionId.set('session-1')+ setCurrentModel('gpt-5.6-sol')+ setCurrentProvider('openai-codex')++ const requestGateway = vi+ .fn()+ .mockResolvedValueOnce({+ confirm_message: 'This contributor model trains on your data.',+ confirm_required: true,+ key: 'model',+ value: 'muse-spark-1.2-contributor'+ })+ .mockResolvedValueOnce({ key: 'model', scope: 'global', value: 'muse-spark-1.2-contributor' })++ let controls!: Controls++ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)++ await expect(+ controls.selectModel({ model: 'muse-spark-1.2-contributor', provider: 'opencode-go' })+ ).resolves.toBe(false)++ expect($currentModel.get()).toBe('gpt-5.6-sol')+ expect($currentProvider.get()).toBe('openai-codex')+ expect(notify).toHaveBeenCalledWith(+ expect.objectContaining({+ action: expect.objectContaining({ label: 'Confirm' }),+ kind: 'warning',+ message: 'This contributor model trains on your data.'+ })+ )++ const action = notify.mock.calls.at(-1)?.[0]?.action++ await act(async () => {+ await action?.onClick()+ })++ await waitFor(() => expect(requestGateway).toHaveBeenCalledTimes(2))+ expect(requestGateway).toHaveBeenLastCalledWith('config.set', {+ confirm_expensive_model: true,+ key: 'model',+ session_id: 'session-1',+ value: 'muse-spark-1.2-contributor --provider opencode-go --global'+ })+ expect($currentModel.get()).toBe('muse-spark-1.2-contributor')+ expect($currentProvider.get()).toBe('opencode-go')+ })+it('keeps the pick when an OLDER gateway refuses a mid-turn switch', async () => {// Pre-deferral backends answer 4009 instead of parking the pick. Rolling// back would bounce the pill to the old model and toast an error at a userdiff --git a/apps/desktop/src/app/session/hooks/use-model-controls.ts b/apps/desktop/src/app/session/hooks/use-model-controls.tsindex e6a48fabadb..013148b0d3d 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts@@ -6,7 +6,7 @@ import { getGlobalModelInfo } from '@/hermes'import { useI18n } from '@/i18n'import { isBusySessionModelSwitch } from '@/lib/gateway-rpc'import { manualPickRemoved, modelOptionsQueryKey } from '@/lib/model-options'-import { notifyError } from '@/store/notifications'+import { notify, notifyError } from '@/store/notifications'import { $activeGatewayProfile } from '@/store/profile'import {$activeSessionId,@@ -27,6 +27,12 @@ interface ModelControlsOptions {requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>}+interface ModelSwitchResponse {+ confirm_message?: string+ confirm_required?: boolean+ deferred?: boolean+}+export function useModelControls({ queryClient, requestGateway }: ModelControlsOptions) {const { t } = useI18n()const copy = t.desktop@@ -190,26 +196,43 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOconst prevSource = getCurrentModelSource()const liveGatewayProfile = $activeGatewayProfile.get()- if (touchesPrimary) {- setCurrentModel(selection.model)- setCurrentProvider(selection.provider)- markComposerSelectionManual()- } else if (liveSessionId) {- // Optimistic tile paint — session.info will confirm; rollback on error.- sessionTileDelegate()?.updateSession(liveSessionId, state => ({- ...state,- model: selection.model,- provider: selection.provider- }))+ const paintSelection = () => {+ if (touchesPrimary) {+ setCurrentModel(selection.model)+ setCurrentProvider(selection.provider)+ markComposerSelectionManual()+ } else if (liveSessionId) {+ // Optimistic tile paint — session.info will confirm; rollback on error.+ sessionTileDelegate()?.updateSession(liveSessionId, state => ({+ ...state,+ model: selection.model,+ provider: selection.provider+ }))+ }}- updateModelOptionsCache(- liveSessionId,- selection.provider,- selection.model,- touchesPrimary && !liveSessionId,- liveGatewayProfile- )+ const cacheSelection = (provider: string, model: string) => {+ updateModelOptionsCache(liveSessionId, provider, model, touchesPrimary && !liveSessionId, liveGatewayProfile)+ }++ const rollbackSelection = () => {+ if (touchesPrimary) {+ setCurrentModel(prevModel)+ setCurrentProvider(prevProvider)+ setCurrentModelSource(prevSource)+ } else if (liveSessionId) {+ sessionTileDelegate()?.updateSession(liveSessionId, state => ({+ ...state,+ model: prevModel,+ provider: prevProvider+ }))+ }++ cacheSelection(prevProvider, prevModel)+ }++ paintSelection()+ cacheSelection(selection.provider, selection.model)// No live session yet: the pick is pure UI state. session.create reads// $currentModel/$currentProvider and applies it as that session's override.@@ -217,30 +240,32 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOreturn true}- try {- // The PRIMARY profile's main agent is the profile's default — its- // model/provider choice IS the default, so persist it to config.yaml- // (model.default + model.provider) via --global. This is what makes- // the selection "stick": a set model.provider outranks a leftover- // OPENAI_API_KEY env var in resolve_provider(), so the main agent- // keeps the chosen (e.g. subscription) provider across restarts- // instead of silently falling back to an env key.- //- // Two things stay --session, deliberately:- // - a SECONDARY chat tile: picking a model there must not rewrite the- // profile default (the cross-session-contamination guard).- // - MoA (mixture-of-agents) presets: a transient orchestration choice- // that must never become the persisted global gateway default.- const isSessionOnlyPreset = (selection.provider || '').toLowerCase() === 'moa'- const persistsAsDefault = touchesPrimary && !isSessionOnlyPreset- const scope = persistsAsDefault ? '--global' : '--session'-- const result = await requestGateway<{ deferred?: boolean }>('config.set', {+ // The PRIMARY profile's main agent is the profile's default — its+ // model/provider choice IS the default, so persist it to config.yaml+ // (model.default + model.provider) via --global. This is what makes+ // the selection "stick": a set model.provider outranks a leftover+ // OPENAI_API_KEY env var in resolve_provider(), so the main agent+ // keeps the chosen (e.g. subscription) provider across restarts+ // instead of silently falling back to an env key.+ //+ // Two things stay --session, deliberately:+ // - a SECONDARY chat tile: picking a model there must not rewrite the+ // profile default (the cross-session-contamination guard).+ // - MoA (mixture-of-agents) presets: a transient orchestration choice+ // that must never become the persisted global gateway default.+ const isSessionOnlyPreset = (selection.provider || '').toLowerCase() === 'moa'+ const persistsAsDefault = touchesPrimary && !isSessionOnlyPreset+ const scope = persistsAsDefault ? '--global' : '--session'++ const requestSwitch = (confirmExpensiveModel = false) =>+ requestGateway<ModelSwitchResponse>('config.set', {session_id: liveSessionId,key: 'model',- value: `${selection.model} --provider ${selection.provider} ${scope}`+ value: `${selection.model} --provider ${selection.provider} ${scope}`,+ ...(confirmExpensiveModel ? { confirm_expensive_model: true } : {})})+ const finishSwitch = (result: ModelSwitchResponse | undefined) => {// A pick made DURING a turn is queued by the gateway and applied at the// next turn start (`deferred`). Re-fetching now would answer with the// model still running and repaint the old name over the user's choice —@@ -249,6 +274,45 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOif (!result?.deferred) {void queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(liveGatewayProfile, liveSessionId) })}+ }++ const applyConfirmedSwitch = async () => {+ paintSelection()+ cacheSelection(selection.provider, selection.model)++ try {+ const result = await requestSwitch(true)++ if (result?.confirm_required) {+ throw new Error(result.confirm_message?.trim() || copy.modelSwitchFailed)+ }++ finishSwitch(result)+ } catch (err) {+ rollbackSelection()+ notifyError(err, copy.modelSwitchFailed)+ }+ }++ try {+ const result = await requestSwitch()++ if (result?.confirm_required) {+ rollbackSelection()+ notify({+ action: {+ label: t.common.confirm,+ onClick: applyConfirmedSwitch+ },+ kind: 'warning',+ message: result.confirm_message?.trim() || copy.modelSwitchFailed,+ title: t.common.confirm+ })++ return false+ }++ finishSwitch(result)return true} catch (err) {@@ -261,31 +325,13 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsOreturn true}- if (touchesPrimary) {- setCurrentModel(prevModel)- setCurrentProvider(prevProvider)- setCurrentModelSource(prevSource)- } else if (liveSessionId) {- sessionTileDelegate()?.updateSession(liveSessionId, state => ({- ...state,- model: prevModel,- provider: prevProvider- }))- }-- updateModelOptionsCache(- liveSessionId,- prevProvider,- prevModel,- touchesPrimary && !liveSessionId,- liveGatewayProfile- )+ rollbackSelection()notifyError(err, copy.modelSwitchFailed)return false}},- [copy.modelSwitchFailed, queryClient, requestGateway, updateModelOptionsCache]+ [copy.modelSwitchFailed, queryClient, requestGateway, t.common.confirm, updateModelOptionsCache])return { applySavedMainModel, refreshCurrentModel, selectModel }