Skip to content

The agent that grows with you

fix(desktop): show a refused or guarded next-turn model pick, and repaint the committed model

Teknium686a5f747146
diff --git a/apps/desktop/src/api/canonical-live-pick.test.ts b/apps/desktop/src/api/canonical-live-pick.test.ts
index 58206d86c5c..69ef100c32f 100644
--- a/apps/desktop/src/api/canonical-live-pick.test.ts
+++ b/apps/desktop/src/api/canonical-live-pick.test.ts
@@ -81,3 +81,14 @@ test('an older pick refused after a newer pick committed is not retried and neve
// B's receipt moved the revision to 7; A's late refusal naming 5 must not rewind it.
expect(calls[2].params).toMatchObject({ expected_revision: 7 })
})
+
+test("a guarded next-turn pick's confirmed resend carries the owner's token from its session.updated ask", async () => {
+ const { calls, client } = await attached(params => ({ session_id: 's', operation: 'model', model: (params.payload as { model: string }).model, revision: 5 }))
+ const protocol = (client as unknown as { protocol: { event: (event: Record<string, unknown>) => void } }).protocol
+
+ protocol.event({ type: 'session.updated', session_id: 's', payload: {
+ session_id: 's', operation: 'model', status: 'confirmation_required', confirm: 'owner-token', payload: { model: 'guarded', provider: 'custom' } } })
+ await client.request('config.set', { ...pick, value: 'guarded --provider custom --session', confirm_expensive_model: true })
+
+ expect(calls[0].params.payload).toEqual({ model: 'guarded', provider: 'custom', confirm: 'owner-token' })
+})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 47947035388..e622f2f8b71 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -516,6 +516,13 @@ export class CanonicalDesktopProtocol {
this.adoptEventRevision(event.type, sid, profile, payload)
+ // A pick deferred during a turn asked at the boundary (a guarded target): keep the owner's token, so
+ // the user's confirmed resend of that target carries it exactly like an idle pick's confirmation.
+ if (event.type === 'session.updated' && payload.operation === 'model' && payload.status === 'confirmation_required'
+ && typeof payload.confirm === 'string' && payload.payload && typeof payload.payload === 'object') {
+ this.modelConfirmations.set(this.modelConfirmationKey({ session_id: sid, profile }, payload.payload as Record<string, unknown>), { token: payload.confirm, sent: false })
+ }
+
if (typeof payload.prompt_id === 'string') {
if (event.type.endsWith('.settled')) { this.prompts.delete(canonicalSessionKey(payload.prompt_id, profile));
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.test.ts
new file mode 100644
index 00000000000..21f6b7cb329
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { $currentModel, $currentProvider, setCurrentModelTransient, setCurrentProviderTransient } from '@/store/session'
+
+import { handleDeferredPickEvent } from './deferred-pick'
+import type { GatewayEventContext } from './types'
+
+const notifyError = vi.hoisted(() => vi.fn())
+const surfaceModelSwitchConfirm = vi.hoisted(() => vi.fn(async () => true))
+
+vi.mock('@/store/notifications', async importOriginal => ({ ...(await importOriginal<object>()), notifyError }))
+vi.mock('@/lib/guarded-model-switch', () => ({ surfaceModelSwitchConfirm }))
+
+function context(payload: Record<string, unknown>) {
+ const states: Record<string, Record<string, unknown>> = { s: { model: 'picked', provider: 'custom' } }
+
+ const ctx = {
+ deps: {
+ activeGatewayProfile: 'default',
+ queryClient: { invalidateQueries: vi.fn(async () => undefined) },
+ updateSessionState: (sid: string, updater: (state: never) => never) => (states[sid] = updater(states[sid] as never))
+ },
+ event: { payload, session_id: 's', type: 'session.updated' },
+ explicitSid: 's',
+ fromActiveSource: () => true,
+ isActiveEvent: true,
+ occurredAt: 0,
+ payload,
+ scheduleConfigRefresh: vi.fn(),
+ sessionId: 's'
+ } as unknown as GatewayEventContext
+
+ return { ctx, states }
+}
+
+describe('handleDeferredPickEvent', () => {
+ afterEach(() => { vi.clearAllMocks() })
+
+ it('shows a refused next-turn pick by name and repaints the committed model', () => {
+ setCurrentModelTransient('picked')
+ setCurrentProviderTransient('custom')
+
+ const { ctx, states } = context({ model: 'frozen', operation: 'model', provider: 'openrouter',
+ reason: 'model_resolution_failed', session_id: 's', status: 'refused', target_model: 'picked' })
+
+ expect(handleDeferredPickEvent(ctx)).toBe(true)
+ expect(notifyError).toHaveBeenCalledWith(expect.objectContaining({ message: 'model_resolution_failed' }), 'Model switch failed')
+ expect(states.s).toMatchObject({ model: 'frozen', provider: 'openrouter' })
+ expect([$currentModel.get(), $currentProvider.get()]).toEqual(['frozen', 'openrouter'])
+ })
+
+ it('asks for a guarded next-turn pick instead of dropping it', () => {
+ const { ctx } = context({ confirm: 'token', confirm_message: 'Costly', operation: 'model',
+ payload: { model: 'guarded', provider: 'custom' }, session_id: 's', status: 'confirmation_required', target_model: 'guarded' })
+
+ expect(handleDeferredPickEvent(ctx)).toBe(true)
+ expect(surfaceModelSwitchConfirm).toHaveBeenCalledWith(expect.objectContaining({ confirmMessage: 'Costly', model: 'guarded' }))
+ expect(notifyError).not.toHaveBeenCalled()
+ })
+
+ it('leaves other session updates to their handlers', () => {
+ expect(handleDeferredPickEvent(context({ operation: 'rename', session_id: 's', title: 'x' }).ctx)).toBe(false)
+ expect(handleDeferredPickEvent(context({ model: 'm', operation: 'model', revision: 3, session_id: 's' }).ctx)).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.ts
new file mode 100644
index 00000000000..7f2fdb180b0
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/deferred-pick.ts
@@ -0,0 +1,77 @@
+import { translateNow } from '@/i18n'
+import { surfaceModelSwitchConfirm } from '@/lib/guarded-model-switch'
+import { modelOptionsQueryKey } from '@/lib/model-options'
+import { activeGatewayConnectionId, requestGatewayForAgent } from '@/store/gateway'
+import { notifyError } from '@/store/notifications'
+import { $currentModel, $currentProvider, setCurrentModelTransient, setCurrentProviderTransient } from '@/store/session'
+
+import type { GatewayEventContext } from './types'
+
+/**
+ * A model pick made during a turn ("applies from your next message") resolves at the next turn
+ * boundary. When it does not apply, the owner says so on `session.updated`:
+ * - `refused` (with a reason): show the named refusal and paint the committed model again;
+ * - `confirmation_required`: a guarded target asks, through the same dialog as an idle pick.
+ * Applied picks announce themselves through session.info like any switch.
+ */
+export function handleDeferredPickEvent({ deps, event, payload, sessionId, isActiveEvent }: GatewayEventContext): boolean {
+ const update = payload as Record<string, unknown> | undefined
+
+ // Receipt broadcasts are not in the generated event map; the dispatch fence passes them through.
+ if ((event.type as string) !== 'session.updated' || update?.operation !== 'model' || !sessionId) {
+ return false
+ }
+
+ if (update.status === 'refused') {
+ const model = typeof update.model === 'string' ? update.model : ''
+ const provider = typeof update.provider === 'string' ? update.provider : ''
+
+ if (model) {
+ deps.updateSessionState(sessionId, state => ({ ...state, model, ...(provider ? { provider } : {}) }))
+
+ // The composer still shows the refused pick: give the pill back to the committed model.
+ if (isActiveEvent && $currentModel.get() === update.target_model) {
+ setCurrentModelTransient(model)
+
+ if (provider) {
+ setCurrentProviderTransient(provider)
+ }
+ }
+ }
+
+ void deps.queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(deps.activeGatewayProfile, sessionId) })
+ notifyError(new Error(String(update.reason ?? 'refused')), translateNow('desktop.modelSwitchFailed'))
+
+ return true
+ }
+
+ if (update.status === 'confirmation_required' && typeof update.confirm === 'string') {
+ const pick = (update.payload ?? {}) as { model?: string; provider?: string }
+ const connectionId = event.connectionId ?? activeGatewayConnectionId()
+ const profile = event.profile ?? deps.activeGatewayProfile
+ const before = { model: $currentModel.get(), provider: $currentProvider.get() }
+
+ void surfaceModelSwitchConfirm({
+ confirmMessage: typeof update.confirm_message === 'string' ? update.confirm_message : undefined,
+ failureMessage: translateNow('desktop.modelSwitchFailed'),
+ // A newer pick replaced this one while the dialog was open: confirming it would undo that pick.
+ isStale: () => $currentModel.get() !== before.model || $currentProvider.get() !== before.provider,
+ model: String(update.target_model ?? pick.model ?? ''),
+ // The protocol attaches the owner's token (kept from this event) to the same target's resend.
+ requestConfirmed: () =>
+ requestGatewayForAgent(
+ connectionId,
+ profile,
+ pick.provider ? 'config.set' : 'slash.exec',
+ pick.provider
+ ? { session_id: sessionId, key: 'model', value: `${pick.model} --provider ${pick.provider} --session`, confirm_expensive_model: true }
+ : { session_id: sessionId, command: `/model ${pick.model}`, confirm_expensive_model: true }
+ ),
+ finish: () => void deps.queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(deps.activeGatewayProfile, sessionId) })
+ })
+
+ return true
+ }
+
+ return false
+}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
index 6647f7b3f8e..88646d431af 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
@@ -17,6 +17,7 @@ import { isSessionGone } from '@/store/session-gone-latch'
import { noteSessionEvent } from '@/store/session-states'
import { setSessionDraftingTool } from '@/store/tool-drafting'
+import { handleDeferredPickEvent } from './deferred-pick'
import { handleDesktopBridgeEvent } from './desktop-bridge'
import { handleFreeTierEvent } from './free-tier'
import { handleInputRequestEvent } from './input-requests'
@@ -87,6 +88,7 @@ const HANDLERS: GatewayEventHandler[] = [
handleFreeTierEvent,
handleOnboardingEvent,
handleSessionInfoEvent,
+ handleDeferredPickEvent,
handleControlEvent,
handleMessageStreamEvent,
handleToolEvent,
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index 8b29f8b1409..112cd36a3db 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -102,4 +102,10 @@ async def apply_deferred_pick(authority, ref, live):
'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))
if result.get('status') == 'refused':
logger.warning('Deferred model pick on %s not applied: %s', ref.session_id, result.get('reason'))
- live.event_stream.publish(ref.session_id, result, event_type='session.updated')
+ # Named for the viewers that showed "applies from your next message": the target that was
+ # refused, and the committed model they must show again.
+ current = await asyncio.to_thread(authority.db.get_session, ref.session_id) or {}
+ provider = json.loads(current.get('model_config') or '{}').get('provider')
+ live.event_stream.publish(ref.session_id, {
+ **result, 'target_model': pick['payload']['model'], 'model': current.get('model'),
+ **({'provider': provider} if provider else {})}, event_type='session.updated')
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index 8e05605364a..b686041d280 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -286,3 +286,40 @@ async def test_a_guarded_deferred_pick_asks_for_confirmation_instead_of_being_dr
release.set()
await owner.close()
store.close_all_db_handles()
+
+
+async def test_a_refused_deferred_pick_names_the_reason_and_the_committed_model(tmp_path, monkeypatch):
+ from gateway.session_contract import Submission
+ from hermes_cli import model_switch
+ started, release = threading.Event(), asyncio.Event()
+ events = []
+
+ async def handle(event):
+ if event.text == 'RUNNING':
+ started.set()
+ await release.wait()
+ return 'ok'
+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
+ switch = model_switch.switch_model
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=False, new_model='', target_provider='') if k['raw_input'] == 'gone' else switch(**k))
+ stream = authority.sessions[ref.session_id].event_stream
+ publish = stream.publish
+ monkeypatch.setattr(stream, 'publish', lambda sid, payload, **k: (
+ events.append((k.get('event_type'), payload)), publish(sid, payload, **k))[1])
+ try:
+ await authority.submit(owner.actor, Submission('running', ref, {'text': 'RUNNING'}, 'queue'))
+ await async_wait_until(started.is_set, timeout=10, what='the first turn is running')
+ assert (await _mutate(owner, db, ref, 'pick', 'gone'))['result']['status'] == 'deferred'
+ release.set()
+
+ def refused():
+ return [p for t, p in events if t == 'session.updated' and p.get('status') == 'refused']
+ await async_wait_until(lambda: refused(), timeout=10, what='the refusal was announced')
+ assert refused()[0].items() >= {'operation': 'model', 'reason': 'model_resolution_failed',
+ 'target_model': 'gone', 'model': 'frozen'}.items()
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()