Skip to content

The agent that grows with you

fix(desktop): a superseded model pick no longer rolls back the pill

Maciej Lisiewski9d532eddf42e
diff --git a/apps/desktop/src/app/session/hooks/model-pick-ledger.ts b/apps/desktop/src/app/session/hooks/model-pick-ledger.ts
new file mode 100644
index 00000000000..9d24be6e9b7
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/model-pick-ledger.ts
@@ -0,0 +1,91 @@
+// Per-session ledger of in-flight model picks, shared by every surface that
+// mounts useModelControls. A pick's own pre-pick snapshot is only the
+// OPTIMISTIC paint of whatever pick came before it, so rollback must target
+// the last confirmed selection (or the newest pick still in flight), never
+// that snapshot.
+
+import type { ComposerModelSource } from '@/store/session'
+
+export interface ModelPickSnapshot {
+ model: string
+ provider: string
+ reasoningEffortWire: string
+ source: ComposerModelSource
+}
+
+interface PendingPick {
+ painted: ModelPickSnapshot
+ token: number
+}
+
+interface SessionPicks {
+ confirmed: ModelPickSnapshot
+ pending: PendingPick[]
+ shown: ModelPickSnapshot
+}
+
+let pickSequence = 0
+const picksBySession = new Map<string, SessionPicks>()
+// Newest pick per session while it is unsettled; a settled newest pick leaves no entry.
+const latestPickBySession = new Map<string, number>()
+
+/** Register a pick. `before` becomes the confirmed selection only when no other pick is in flight. */
+export function beginModelPick(sessionId: string, before: ModelPickSnapshot, painted: ModelPickSnapshot): number {
+ const token = ++pickSequence
+ const picks = picksBySession.get(sessionId)
+
+ latestPickBySession.set(sessionId, token)
+
+ if (picks) {
+ picks.pending.push({ painted, token })
+ picks.shown = painted
+ } else {
+ picksBySession.set(sessionId, { confirmed: before, pending: [{ painted, token }], shown: painted })
+ }
+
+ return token
+}
+
+/** Whether a newer pick for the session was made after this one. Ask before settling it. */
+export function isPickSuperseded(sessionId: string, token: number): boolean {
+ return latestPickBySession.get(sessionId) !== token
+}
+
+/**
+ * Settle a pick. An applied pick becomes the confirmed selection. Returns the
+ * snapshot to repaint — the newest pick still in flight, else the confirmed
+ * selection — when that differs from what the ledger last painted; null means
+ * the current paint stays.
+ */
+export function settleModelPick(sessionId: string, token: number, applied: boolean): ModelPickSnapshot | null {
+ const picks = picksBySession.get(sessionId)
+ const index = picks?.pending.findIndex(pick => pick.token === token) ?? -1
+
+ if (!picks || index < 0) {
+ return null
+ }
+
+ const [settled] = picks.pending.splice(index, 1)
+
+ if (latestPickBySession.get(sessionId) === token) {
+ latestPickBySession.delete(sessionId)
+ }
+
+ if (applied) {
+ picks.confirmed = settled.painted
+ }
+
+ if (picks.pending.length === 0) {
+ picksBySession.delete(sessionId)
+ }
+
+ const target = picks.pending.at(-1)?.painted ?? picks.confirmed
+
+ if (applied || target === picks.shown) {
+ return null
+ }
+
+ picks.shown = target
+
+ return target
+}
diff --git a/apps/desktop/src/app/session/hooks/use-model-controls-stale-pick.test.tsx b/apps/desktop/src/app/session/hooks/use-model-controls-stale-pick.test.tsx
new file mode 100644
index 00000000000..3931c921ba5
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-model-controls-stale-pick.test.tsx
@@ -0,0 +1,307 @@
+// Stale model-pick ordering: a superseded selectModel (newer pick, or a chat
+// switch while config.set is in flight) must never roll the pill or a tile back.
+import { QueryClient } from '@tanstack/react-query'
+import { cleanup, render, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { confirm } from '@/store/confirm'
+import { $activeGatewayProfile } from '@/store/profile'
+import {
+ $activeSessionId,
+ $currentModel,
+ $currentProvider,
+ markComposerSelectionManual,
+ setCurrentModel,
+ setCurrentModelSource,
+ setCurrentProvider,
+ setCurrentReasoningEffort
+} from '@/store/session'
+import * as SessionStates from '@/store/session-states'
+
+import { deferred } from '../../../test/deferred'
+
+import { useModelControls } from './use-model-controls'
+
+const tile = vi.hoisted(() => ({ delegate: null as unknown }))
+const notifyError = vi.fn()
+
+vi.mock('@/hermes', () => ({
+ getGlobalModelInfo: vi.fn(),
+ setApiRequestProfile: vi.fn(),
+ setGlobalModel: vi.fn()
+}))
+
+vi.mock('@/store/session-states', async importOriginal => {
+ const actual = await importOriginal<typeof SessionStates>()
+
+ return {
+ ...actual,
+ sessionTileDelegate: () => tile.delegate
+ }
+})
+
+vi.mock('@/i18n', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useI18n: () => ({
+ t: {
+ desktop: {
+ modelSwitchFailed: 'Model switch failed'
+ }
+ }
+ })
+}))
+
+vi.mock('@/store/confirm', () => ({
+ confirm: vi.fn()
+}))
+
+vi.mock('@/store/notifications', () => ({
+ dismissNotification: vi.fn(),
+ notify: vi.fn(),
+ notifyError: (...args: Parameters<typeof notifyError>) => notifyError(...args)
+}))
+
+type Controls = ReturnType<typeof useModelControls>
+
+function Harness({
+ onReady,
+ requestGateway
+}: {
+ onReady: (controls: Controls) => void
+ requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>
+}) {
+ const controls = useModelControls({
+ queryClient: new QueryClient(),
+ requestGateway
+ })
+
+ onReady(controls)
+
+ return null
+}
+
+function resetStores() {
+ $activeGatewayProfile.set('default')
+ $activeSessionId.set(null)
+ setCurrentModel('')
+ setCurrentModelSource('')
+ setCurrentProvider('')
+ SessionStates.$sessionStates.set({})
+}
+
+describe('useModelControls stale pick ordering', () => {
+ beforeEach(() => {
+ notifyError.mockReset()
+ resetStores()
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ resetStores()
+ })
+
+ it('does not roll a failed older pick back over a newer one that applied', async () => {
+ $activeSessionId.set('session-1')
+ setCurrentModel('fable-5')
+ setCurrentProvider('nous')
+
+ const older = deferred<never>()
+ const newer = deferred<unknown>()
+ const requestGateway = vi.fn().mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
+ let controls!: Controls
+
+ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
+
+ const olderPick = controls.selectModel({ model: 'grok-4.5', provider: 'xai' })
+ const newerPick = controls.selectModel({ model: 'gpt-6.1-luna', provider: 'openai' })
+
+ newer.resolve({})
+ await expect(newerPick).resolves.toBe(true)
+ older.reject(new Error('timeout'))
+ await expect(olderPick).resolves.toBe(false)
+
+ expect($currentModel.get()).toBe('gpt-6.1-luna')
+ expect($currentProvider.get()).toBe('openai')
+ // The abandoned pick's failure is not the user's current choice: no error toast.
+ expect(notifyError).not.toHaveBeenCalled()
+ })
+
+ it('does not paint the previous session rollback into a session opened mid-switch', async () => {
+ $activeSessionId.set('session-1')
+ setCurrentModel('fable-5')
+ setCurrentProvider('nous')
+
+ const pending = deferred<never>()
+ const requestGateway = vi.fn(() => pending.promise)
+ let controls!: Controls
+
+ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
+
+ const pick = controls.selectModel({ model: 'grok-4.5', provider: 'xai' })
+
+ // The user opens another chat; its session.info paints that chat's model.
+ $activeSessionId.set('session-2')
+ setCurrentModel('gpt-6.1-luna')
+ setCurrentProvider('openai')
+
+ pending.reject(new Error('timeout'))
+ await expect(pick).resolves.toBe(false)
+
+ expect($currentModel.get()).toBe('gpt-6.1-luna')
+ expect($currentProvider.get()).toBe('openai')
+ expect(notifyError).not.toHaveBeenCalled()
+ })
+
+ // Two overlapping picks A then B from X: B's own pre-pick snapshot is A (painted, never applied),
+ // so the pill must settle on the last CONFIRMED selection, whichever request fails first.
+ interface InFlightPick {
+ promise: Promise<boolean>
+ reject: (reason?: unknown) => void
+ resolve: (value: unknown) => void
+ }
+
+ async function overlappingPicks(settle: (a: InFlightPick, b: InFlightPick) => Promise<void>) {
+ $activeSessionId.set('session-1')
+ setCurrentModel('fable-5')
+ setCurrentProvider('nous')
+
+ const a = deferred<unknown>()
+ const b = deferred<unknown>()
+ const requestGateway = vi.fn().mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise)
+ let controls!: Controls
+
+ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
+
+ const pickA = controls.selectModel({ model: 'grok-4.5', provider: 'xai' })
+ const pickB = controls.selectModel({ model: 'gpt-6.1-luna', provider: 'openai' })
+
+ await settle({ ...a, promise: pickA }, { ...b, promise: pickB })
+ }
+
+ it('settles on the confirmed model when the newer pick fails before the older one', async () => {
+ await overlappingPicks(async (a, b) => {
+ b.reject(new Error('timeout'))
+ await expect(b.promise).resolves.toBe(false)
+ a.reject(new Error('timeout'))
+ await expect(a.promise).resolves.toBe(false)
+ })
+
+ expect($currentModel.get()).toBe('fable-5')
+ expect($currentProvider.get()).toBe('nous')
+ // Only the newest pick's failure is reported; the superseded one stays quiet.
+ expect(notifyError).toHaveBeenCalledTimes(1)
+ })
+
+ it('settles on the confirmed model when the older pick fails before the newer one', async () => {
+ await overlappingPicks(async (a, b) => {
+ a.reject(new Error('timeout'))
+ await expect(a.promise).resolves.toBe(false)
+ b.reject(new Error('timeout'))
+ await expect(b.promise).resolves.toBe(false)
+ })
+
+ expect($currentModel.get()).toBe('fable-5')
+ expect($currentProvider.get()).toBe('nous')
+ })
+
+ it('shows the older pick when the newer one fails and the older one then applies', async () => {
+ await overlappingPicks(async (a, b) => {
+ b.reject(new Error('timeout'))
+ await expect(b.promise).resolves.toBe(false)
+ a.resolve({})
+ await expect(a.promise).resolves.toBe(true)
+ })
+
+ expect($currentModel.get()).toBe('grok-4.5')
+ expect($currentProvider.get()).toBe('xai')
+ })
+
+ // A confirm-gated pick leaves the ledger while its dialog is open; once confirmed and applied it
+ // must count as the confirmed selection, or an older pick failing later restores the start.
+ it('keeps a confirmed expensive pick when an older pick fails afterwards', async () => {
+ $activeSessionId.set('session-1')
+ setCurrentModel('fable-5')
+ setCurrentProvider('nous')
+ vi.mocked(confirm).mockResolvedValueOnce(true)
+
+ const older = deferred<never>()
+ const confirmed = deferred<unknown>()
+
+ const requestGateway = vi
+ .fn()
+ .mockReturnValueOnce(older.promise)
+ .mockResolvedValueOnce({ confirm_required: true, confirm_message: 'Expensive model' })
+ .mockReturnValueOnce(confirmed.promise)
+
+ let controls!: Controls
+
+ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
+
+ const olderPick = controls.selectModel({ model: 'grok-4.5', provider: 'xai' })
+ await expect(controls.selectModel({ model: 'opus-9', provider: 'anthropic' })).resolves.toBe(false)
+ await vi.waitFor(() => expect(requestGateway).toHaveBeenCalledTimes(3))
+ confirmed.resolve({})
+ await vi.waitFor(() => expect($currentModel.get()).toBe('opus-9'))
+
+ older.reject(new Error('timeout'))
+ await expect(olderPick).resolves.toBe(false)
+
+ expect($currentModel.get()).toBe('opus-9')
+ expect($currentProvider.get()).toBe('anthropic')
+ })
+
+ it('rolls a failed pick back even when the reasoning effort stepped mid-switch', async () => {
+ $activeSessionId.set('session-1')
+ setCurrentModel('fable-5')
+ setCurrentProvider('nous')
+
+ const pending = deferred<never>()
+ const requestGateway = vi.fn(() => pending.promise)
+ let controls!: Controls
+
+ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
+
+ const pick = controls.selectModel({ model: 'grok-4.5', provider: 'xai' })
+
+ // The effort keybind (and the preset editor) bump the composer selection generation without
+ // touching the model; that must not cost the failed pick its rollback.
+ markComposerSelectionManual()
+ setCurrentReasoningEffort('high')
+
+ pending.reject(new Error('timeout'))
+ await expect(pick).resolves.toBe(false)
+
+ expect($currentModel.get()).toBe('fable-5')
+ expect($currentProvider.get()).toBe('nous')
+ expect(notifyError).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not roll a failed older tile pick back over a newer one that applied', async () => {
+ $activeSessionId.set('runtime-a')
+ SessionStates.$sessionStates.set({ 'runtime-b': { model: 'old-b', provider: 'provider-b' } } as never)
+ const updateSession = vi.fn()
+ tile.delegate = { updateSession }
+
+ const older = deferred<never>()
+ const newer = deferred<unknown>()
+ const requestGateway = vi.fn().mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
+ const { result } = renderHook(() => useModelControls({ queryClient: new QueryClient(), requestGateway }))
+
+ const olderPick = result.current.selectModel({ model: 'grok-4.5', provider: 'xai', sessionId: 'runtime-b' })
+ const newerPick = result.current.selectModel({ model: 'gpt-6.1-luna', provider: 'openai', sessionId: 'runtime-b' })
+
+ try {
+ newer.resolve({})
+ await expect(newerPick).resolves.toBe(true)
+ updateSession.mockClear()
+ older.reject(new Error('timeout'))
+ await expect(olderPick).resolves.toBe(false)
+ } finally {
+ tile.delegate = null
+ }
+
+ // The older failure must not repaint the tile with its pre-pick model.
+ expect(updateSession).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.ts b/apps/desktop/src/app/session/hooks/use-model-controls.ts
index f3ee32ae39f..c2143b410ab 100644
--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts
+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts
@@ -30,6 +30,8 @@ import {
} from '@/store/session'
import { $sessionStates, sessionTileDelegate } from '@/store/session-states'
+import { beginModelPick, isPickSuperseded, type ModelPickSnapshot, settleModelPick } from './model-pick-ledger'
+
interface ModelControlsOptions {
cacheOwnerConnectionId?: string
cacheProfile?: string
@@ -257,17 +259,20 @@ export function useModelControls({
const liveSessionId = 'sessionId' in selection ? (selection.sessionId ?? null) : primaryRuntimeId
const touchesPrimary = !liveSessionId || liveSessionId === primaryRuntimeId
- const prevModel = touchesPrimary ? $currentModel.get() : ($sessionStates.get()[liveSessionId!]?.model ?? '')
-
- const prevProvider = touchesPrimary
- ? $currentProvider.get()
- : ($sessionStates.get()[liveSessionId!]?.provider ?? '')
+ const readSnapshot = (): ModelPickSnapshot => {
+ const tileState = touchesPrimary ? undefined : $sessionStates.get()[liveSessionId!]
- const prevWire = touchesPrimary
- ? $currentReasoningEffortWire.get()
- : ($sessionStates.get()[liveSessionId!]?.reasoningEffortWire ?? '')
+ return {
+ model: touchesPrimary ? $currentModel.get() : (tileState?.model ?? ''),
+ provider: touchesPrimary ? $currentProvider.get() : (tileState?.provider ?? ''),
+ reasoningEffortWire: touchesPrimary
+ ? $currentReasoningEffortWire.get()
+ : (tileState?.reasoningEffortWire ?? ''),
+ source: getCurrentModelSource()
+ }
+ }
- const prevSource = getCurrentModelSource()
+ const before = readSnapshot()
const liveGatewayProfile = cacheProfile || $activeGatewayProfile.get()
const paintSelection = () => {
@@ -291,23 +296,23 @@ export function useModelControls({
updateModelOptionsCache(liveSessionId, provider, model, touchesPrimary && !liveSessionId, liveGatewayProfile)
}
- const rollbackSelection = () => {
+ const restoreSnapshot = (snapshot: ModelPickSnapshot) => {
if (touchesPrimary) {
- setCurrentModel(prevModel)
- setCurrentProvider(prevProvider)
+ setCurrentModel(snapshot.model)
+ setCurrentProvider(snapshot.provider)
// The setters withdraw the wire stamp on a change; the old route's stamp is still true.
- setCurrentReasoningEffortWire(prevWire)
- setCurrentModelSource(prevSource)
+ setCurrentReasoningEffortWire(snapshot.reasoningEffortWire)
+ setCurrentModelSource(snapshot.source)
} else if (liveSessionId) {
sessionTileDelegate()?.updateSession(liveSessionId, state => ({
...state,
- model: prevModel,
- provider: prevProvider,
- reasoningEffortWire: prevWire
+ model: snapshot.model,
+ provider: snapshot.provider,
+ reasoningEffortWire: snapshot.reasoningEffortWire
}))
}
- cacheSelection(prevProvider, prevModel)
+ cacheSelection(snapshot.provider, snapshot.model)
}
paintSelection()
@@ -319,6 +324,22 @@ export function useModelControls({
return true
}
+ // Overlapping picks on one session settle through the shared ledger: a
+ // failed pick repaints the newest pick still in flight, else the last
+ // confirmed selection — never its own pre-pick snapshot, which may be an
+ // earlier pick's optimistic paint that never applied. A primary session
+ // switch while config.set is in flight means nothing is repainted. The
+ // composer selection generation is deliberately not consulted: effort
+ // steps and preset edits bump it without touching the model.
+ const pickToken = beginModelPick(liveSessionId, before, readSnapshot())
+
+ // The snapshot to repaint after this pick failed to apply, or null to leave the paint alone.
+ const settleUnapplied = () => {
+ const repaint = settleModelPick(liveSessionId, pickToken, false)
+
+ return repaint && !(touchesPrimary && $activeSessionId.get() !== liveSessionId) ? repaint : null
+ }
+
// The PRIMARY profile's main agent lets the gateway decide persistence
// (resolve_persist_behavior): session-only by default, persisted when
// model.persist_switch_by_default is true or when no default has ever
@@ -360,7 +381,16 @@ export function useModelControls({
const result = await requestSwitch()
if (result?.confirm_required) {
- rollbackSelection()
+ // A newer pick already owns the pill; asking to confirm this one
+ // would only offer to undo it.
+ const restored = settleUnapplied()
+
+ if (!restored) {
+ return false
+ }
+
+ restoreSnapshot(restored)
+ let retryToken: null | number = null
// ONE shared applier for guarded switches (#95293): the same
// confirm flow the Bots editor routes through — never fork this
// logic per surface.
@@ -369,7 +399,6 @@ export function useModelControls({
void surfaceModelSwitchConfirm({
confirmMessage: result.confirm_message,
failureMessage: copy.modelSwitchFailed,
- finish: finishSwitch,
// Staleness guard — the session or model can move on while the
// dialog is open. Answering it must not clobber the newer choice:
// bail (with a notice) if the live state no longer matches the
@@ -377,23 +406,42 @@ export function useModelControls({
isStale: () =>
touchesPrimary
? $activeSessionId.get() !== liveSessionId ||
- $currentModel.get() !== prevModel ||
- $currentProvider.get() !== prevProvider
+ $currentModel.get() !== restored.model ||
+ $currentProvider.get() !== restored.provider
: !liveSessionId ||
- $sessionStates.get()[liveSessionId]?.model !== prevModel ||
- $sessionStates.get()[liveSessionId]?.provider !== prevProvider,
+ $sessionStates.get()[liveSessionId]?.model !== restored.model ||
+ $sessionStates.get()[liveSessionId]?.provider !== restored.provider,
model: selection.model,
+ // The confirmed retry is a fresh pick in the ledger: it joins whatever is still in
+ // flight, becomes the confirmed selection when it applies, and settles like any pick
+ // when it fails — so an older pick failing later cannot restore what it replaced.
repaint: () => {
+ const retryBefore = readSnapshot()
paintSelection()
cacheSelection(selection.provider, selection.model)
+ retryToken = beginModelPick(liveSessionId, retryBefore, readSnapshot())
},
requestConfirmed: () => requestSwitch(true),
- rollback: rollbackSelection
+ finish: result => {
+ if (retryToken !== null) {
+ settleModelPick(liveSessionId, retryToken, true)
+ }
+
+ finishSwitch(result)
+ },
+ rollback: () => {
+ const repaint = retryToken === null ? restored : settleModelPick(liveSessionId, retryToken, false)
+
+ if (repaint && !(touchesPrimary && $activeSessionId.get() !== liveSessionId)) {
+ restoreSnapshot(repaint)
+ }
+ }
})
return false
}
+ settleModelPick(liveSessionId, pickToken, true)
finishSwitch(result)
return true
@@ -404,11 +452,25 @@ export function useModelControls({
// what the NEXT turn runs anyway. Current gateways never take this
// path — they answer `deferred`.
if (isBusySessionModelSwitch(err)) {
+ settleModelPick(liveSessionId, pickToken, true)
+
return true
}
- rollbackSelection()
- notifyError(err, copy.modelSwitchFailed)
+ // An abandoned pick (a newer one was made, or the user left the chat)
+ // is not the user's current choice; its failure is not worth a toast.
+ const abandoned =
+ isPickSuperseded(liveSessionId, pickToken) || (touchesPrimary && $activeSessionId.get() !== liveSessionId)
+
+ const restored = settleUnapplied()
+
+ if (restored) {
+ restoreSnapshot(restored)
+ }
+
+ if (!abandoned) {
+ notifyError(err, copy.modelSwitchFailed)
+ }
return false
}