Skip to content

The agent that grows with you

fix(desktop): a declined deferred pick repaints the committed model; foreign-profile outcomes stay off the composer

Teknium2964a152f220
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
index 21f6b7cb329..9128ab44589 100644
--- 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
@@ -11,12 +11,13 @@ 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>) {
+function context(payload: Record<string, unknown>, overrides: Record<string, unknown> = {}) {
const states: Record<string, Record<string, unknown>> = { s: { model: 'picked', provider: 'custom' } }
const ctx = {
deps: {
activeGatewayProfile: 'default',
+ activeSessionIdRef: { current: 's' },
queryClient: { invalidateQueries: vi.fn(async () => undefined) },
updateSessionState: (sid: string, updater: (state: never) => never) => (states[sid] = updater(states[sid] as never))
},
@@ -27,7 +28,8 @@ function context(payload: Record<string, unknown>) {
occurredAt: 0,
payload,
scheduleConfigRefresh: vi.fn(),
- sessionId: 's'
+ sessionId: 's',
+ ...overrides
} as unknown as GatewayEventContext
return { ctx, states }
@@ -62,4 +64,49 @@ describe('handleDeferredPickEvent', () => {
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)
})
+
+ it('declining a guarded next-turn pick paints the committed model again', async () => {
+ setCurrentModelTransient('guarded')
+ setCurrentProviderTransient('custom')
+ surfaceModelSwitchConfirm.mockResolvedValueOnce(false)
+
+ const { ctx, states } = context({ committed_model: 'frozen', committed_provider: 'openrouter', confirm: 'token',
+ operation: 'model', payload: { model: 'guarded', provider: 'custom' }, session_id: 's',
+ status: 'confirmation_required', target_model: 'guarded' })
+
+ states.s = { model: 'guarded', provider: 'custom' }
+ expect(handleDeferredPickEvent(ctx)).toBe(true)
+ await vi.waitFor(() => expect($currentModel.get()).toBe('frozen'))
+ expect($currentProvider.get()).toBe('openrouter')
+ expect(states.s).toMatchObject({ model: 'frozen', provider: 'openrouter' })
+ })
+
+ it('a decline never rewinds a newer pick or another session', async () => {
+ setCurrentModelTransient('guarded')
+ let answer: (value: boolean) => void = () => undefined
+ surfaceModelSwitchConfirm.mockReturnValueOnce(new Promise<boolean>(resolve => (answer = resolve)))
+
+ const { ctx } = context({ committed_model: 'frozen', confirm: 'token', operation: 'model',
+ payload: { model: 'guarded' }, session_id: 's', status: 'confirmation_required', target_model: 'guarded' })
+
+ handleDeferredPickEvent(ctx)
+ setCurrentModelTransient('newer')
+ answer(false)
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect($currentModel.get()).toBe('newer')
+ })
+
+ it("another profile's same-ID refusal leaves the active composer and its cache alone", () => {
+ setCurrentModelTransient('picked')
+ setCurrentProviderTransient('custom')
+
+ const { ctx, states } = context({ model: 'other-profile-model', operation: 'model', provider: 'openrouter',
+ reason: 'model_resolution_failed', session_id: 's', status: 'refused', target_model: 'picked' },
+ { event: { payload: {}, profile: 'other', session_id: 's', type: 'session.updated' }, fromActiveSource: () => false })
+
+ expect(handleDeferredPickEvent(ctx)).toBe(true)
+ expect([$currentModel.get(), $currentProvider.get()]).toEqual(['picked', 'custom'])
+ expect(states.s).toMatchObject({ model: 'picked', provider: 'custom' })
+ expect((ctx.deps.queryClient.invalidateQueries as any).mock.calls[0][0].queryKey).toContain('other')
+ })
})
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
index 7f2fdb180b0..bd05260234f 100644
--- 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
@@ -14,7 +14,27 @@ import type { GatewayEventContext } from './types'
* - `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 {
+/** Paint the committed selection back over a pick that did not apply. Only for the active profile's
+ * own session, and only while the composer still shows that pick (a newer pick or a navigation wins). */
+function repaintCommitted(
+ { deps, sessionId }: Pick<GatewayEventContext, 'deps' | 'sessionId'>,
+ target: unknown,
+ model: string,
+ provider: string
+) {
+ deps.updateSessionState(sessionId!, state => ({ ...state, model, ...(provider ? { provider } : {}) }))
+
+ if (deps.activeSessionIdRef.current === sessionId && $currentModel.get() === target) {
+ setCurrentModelTransient(model)
+
+ if (provider) {
+ setCurrentProviderTransient(provider)
+ }
+ }
+}
+
+export function handleDeferredPickEvent(ctx: GatewayEventContext): boolean {
+ const { deps, event, payload, sessionId, fromActiveSource } = ctx
const update = payload as Record<string, unknown> | undefined
// Receipt broadcasts are not in the generated event map; the dispatch fence passes them through.
@@ -22,24 +42,19 @@ export function handleDeferredPickEvent({ deps, event, payload, sessionId, isAct
return false
}
+ // Another profile's session can share this id (imports): its outcome is not this composer's.
+ const ownSource = fromActiveSource()
+ const profile = event.profile ?? deps.activeGatewayProfile
+ const invalidate = () => void deps.queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(profile, sessionId) })
+
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)
- }
- }
+ if (model && ownSource) {
+ repaintCommitted(ctx, update.target_model, model, typeof update.provider === 'string' ? update.provider : '')
}
- void deps.queryClient.invalidateQueries({ queryKey: modelOptionsQueryKey(deps.activeGatewayProfile, sessionId) })
+ invalidate()
notifyError(new Error(String(update.reason ?? 'refused')), translateNow('desktop.modelSwitchFailed'))
return true
@@ -48,15 +63,16 @@ export function handleDeferredPickEvent({ deps, event, payload, sessionId, isAct
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() }
+ const target = String(update.target_model ?? pick.model ?? '')
+ const committed = typeof update.committed_model === 'string' ? update.committed_model : ''
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 ?? ''),
+ model: target,
// The protocol attaches the owner's token (kept from this event) to the same target's resend.
requestConfirmed: () =>
requestGatewayForAgent(
@@ -67,7 +83,13 @@ export function handleDeferredPickEvent({ deps, event, payload, sessionId, isAct
? { 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) })
+ finish: invalidate
+ }).then(applied => {
+ // Declined, or the confirmed resend failed: the committed model is still the session's.
+ if (!applied && committed && ownSource) {
+ repaintCommitted(ctx, target, committed, typeof update.committed_provider === 'string' ? update.committed_provider : '')
+ invalidate()
+ }
})
return true
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index 0b046acf253..81372e864ea 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -114,8 +114,12 @@ async def apply_deferred_pick(authority, ref, live):
await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(
'UPDATE state_meta SET value=? WHERE key=? AND value=?',
(_json({**pick, 'awaiting_confirm': result['confirm']}), key, stored[0])))
- live.event_stream.publish(ref.session_id, {**result, 'payload': pick['payload']},
- event_type='session.updated')
+ current = await asyncio.to_thread(authority.db.get_session, ref.session_id) or {}
+ provider = json.loads(current.get('model_config') or '{}').get('provider')
+ # The committed selection rides along, so a viewer that declines paints it back.
+ live.event_stream.publish(ref.session_id, {
+ **result, 'payload': pick['payload'], 'committed_model': current.get('model'),
+ **({'committed_provider': provider} if provider else {})}, event_type='session.updated')
return
await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(
'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index 6828bc2312b..972f0c8030c 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -270,6 +270,7 @@ async def test_a_guarded_deferred_pick_asks_for_confirmation_instead_of_being_dr
await async_wait_until(lambda: asks(), timeout=10, what='the guarded pick asked for confirmation')
ask = asks()[0]
assert ask['target_model'] == 'guarded' and ask['payload'] == {'model': 'guarded'}
+ assert ask['committed_model'] == 'frozen', ask
assert not [p for t, p in events if p.get('status') == 'refused']
assert _running_model(authority, ref) == 'frozen'
# The user confirms: the canonical resend carries the owner's token and commits.