Skip to content

The agent that grows with you

fix(desktop): wire the canonical model confirmation into the shared model-switch dialog

Tekniumf19df95e4170
diff --git a/apps/desktop/src/api/canonical-model-confirm.test.tsx b/apps/desktop/src/api/canonical-model-confirm.test.tsx
new file mode 100644
index 00000000000..6f5d0191a6c
--- /dev/null
+++ b/apps/desktop/src/api/canonical-model-confirm.test.tsx
@@ -0,0 +1,98 @@
+import { QueryClient } from '@tanstack/react-query'
+import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { useModelControls } from '@/app/session/hooks/use-model-controls'
+import { $activeSessionId, $currentModel, setCurrentModel, setCurrentProvider } from '@/store/session'
+
+import { CanonicalDesktopProtocol } from './canonical-protocol'
+
+const confirmMock = vi.fn()
+
+vi.mock('@/store/confirm', () => ({ confirm: (...args: unknown[]) => confirmMock(...args) }))
+vi.mock('@/store/notifications', () => ({ dismissNotification: vi.fn(), notify: vi.fn(), notifyError: vi.fn() }))
+vi.mock('@/hermes', () => ({ getGlobalModelInfo: vi.fn(), setApiRequestProfile: vi.fn(), setGlobalModel: vi.fn() }))
+
+// The canonical owner: a guarded target answers `confirmation_required` + a one-time token and
+// writes nothing; only that token in `payload.confirm` applies it.
+function owner() {
+ const state = { model: 'old', revision: 3, generation: 2 }
+ const mutations: Record<string, unknown>[] = []
+ const protocol = new CanonicalDesktopProtocol()
+ protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 3, execution_generation: 2 })
+
+ const request = async <T,>(method: string, params: Record<string, unknown> = {}): Promise<T> => {
+ const prepared = protocol.prepare(method, params)
+ expect(protocol.wire(method, prepared)).toBe('session.mutate')
+ const payload = prepared.payload as Record<string, unknown>
+ mutations.push(payload)
+
+ const value = payload.confirm === 'tok-1'
+ ? (Object.assign(state, { model: payload.model, revision: 4, generation: 3 }),
+ { session_id: 's', operation: 'model', revision: 4, execution_generation: 3, model: payload.model })
+ : { session_id: 's', operation: 'model', status: 'confirmation_required', confirm: 'tok-1',
+ confirm_message: 'This session holds ~5,000 tokens.', target_model: payload.model }
+
+ return protocol.result(method, prepared, value) as T
+ }
+
+ return { mutations, protocol, request, state }
+}
+
+function Picker({ onReady, request }: { onReady: (c: ReturnType<typeof useModelControls>) => void; request: ReturnType<typeof owner>['request'] }) {
+ onReady(useModelControls({ queryClient: new QueryClient(), requestGateway: request }))
+
+ return null
+}
+
+afterEach(() => {
+ cleanup()
+ confirmMock.mockReset()
+ $activeSessionId.set(null)
+})
+
+test('a guarded canonical picker switch asks; yes applies once with the owner token, no changes nothing', async () => {
+ for (const accept of [false, true]) {
+ const gateway = owner()
+ $activeSessionId.set('s')
+ setCurrentModel('old')
+ setCurrentProvider('custom')
+ confirmMock.mockResolvedValueOnce(accept)
+ let controls!: ReturnType<typeof useModelControls>
+ render(<Picker onReady={value => (controls = value)} request={gateway.request} />)
+
+ await act(async () => {
+ await controls.selectModel({ model: 'pricey', provider: 'custom' })
+ })
+ await waitFor(() => expect(confirmMock).toHaveBeenCalledWith(expect.objectContaining({
+ description: 'This session holds ~5,000 tokens.' })))
+ await act(async () => {})
+
+ expect(gateway.mutations).toEqual(accept
+ ? [{ model: 'pricey', provider: 'custom' }, { model: 'pricey', provider: 'custom', confirm: 'tok-1' }]
+ : [{ model: 'pricey', provider: 'custom' }])
+ expect(gateway.state.model).toBe(accept ? 'pricey' : 'old')
+ expect($currentModel.get()).toBe(accept ? 'pricey' : 'old')
+ cleanup()
+ confirmMock.mockReset()
+ }
+})
+
+test('a typed /model on a canonical session answers the same handshake and its resend carries the token once', () => {
+ const protocol = new CanonicalDesktopProtocol()
+ protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 3, execution_generation: 2 })
+ const typed = protocol.prepare('slash.exec', { session_id: 's', command: 'model pricey' })
+
+ const refused = protocol.result('slash.exec', typed, { session_id: 's', operation: 'model', status: 'confirmation_required',
+ confirm: 'tok-1', confirm_message: 'pricey IS EXPENSIVE' })
+
+ expect(refused).toMatchObject({ confirm_required: true, confirm_message: 'pricey IS EXPENSIVE' })
+ expect(refused).not.toHaveProperty('model')
+ const resend = protocol.prepare('slash.exec', { session_id: 's', command: 'model pricey', confirm_expensive_model: true })
+ expect(resend.payload).toEqual({ model: 'pricey', confirm: 'tok-1' })
+ expect(resend.request_id).not.toBe(typed.request_id)
+ // Consumed: a second refusal is never auto-confirmed with the spent token.
+ protocol.result('slash.exec', resend, { session_id: 's', operation: 'model', status: 'confirmation_required', confirm: 'tok-2', confirm_message: 'again' })
+ protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 3, execution_generation: 2 })
+ expect(protocol.prepare('slash.exec', { session_id: 's', command: 'model pricey' }).payload).toEqual({ model: 'pricey' })
+})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index d969505e866..50eb51e68da 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -89,6 +89,11 @@ export class CanonicalDesktopProtocol {
// (owner died mid-turn). Only these rows may be acknowledged, and only with
// the generation the authority stamped on them, never the live one.
private unknownAdmissions = new Map<string, { session_id: string; profile: string; generation: number }>()
+ // [owner, model payload] → the owner's one-time token from a `confirmation_required` model
+ // answer (a guarded target: cost / data policy / large context; nothing was written). The
+ // dialog's resend (`confirm_expensive_model: true`, the legacy handshake every Desktop surface
+ // speaks) carries it as `payload.confirm`; consumed once, so a re-refusal is never auto-confirmed.
+ private modelConfirmations = new Map<string, string>()
failure(params: Record<string, unknown>, error: unknown) {
if ((error as { data?: { reason?: string } })?.data?.reason !== 'revision_conflict') { return }
@@ -198,18 +203,40 @@ export class CanonicalDesktopProtocol {
if (method === 'config.set' && params.key === 'model') {
const pick = pickerModelMutation(params.value)
- if (pick) { return this.retainedMutation(params.session_id, params.profile, 'model', pick, true) }
+ if (pick) { return this.retainedMutation(params.session_id, params.profile, 'model', this.confirmedModel(params, pick), true) }
}
if (method === 'slash.exec') {
const directive = slashMutation(String(params.command ?? ''))
- if (directive) { return this.retainedMutation(params.session_id, params.profile, directive.operation, directive.payload, true) }
+ if (directive) {
+ const payload = directive.operation === 'model' ? this.confirmedModel(params, directive.payload) : directive.payload
+
+ return this.retainedMutation(params.session_id, params.profile, directive.operation, payload, true)
+ }
}
return null
}
+ private modelConfirmationKey(params: Record<string, unknown>, payload: Record<string, unknown>): string {
+ const { confirm: _token, ...target } = payload
+
+ return JSON.stringify([canonicalSessionKey(params.session_id, params.profile), target])
+ }
+
+ // A user-confirmed resend of a guarded model target presents the owner's token once.
+ private confirmedModel(params: Record<string, unknown>, payload: Record<string, unknown>): Record<string, unknown> {
+ if (!params.confirm_expensive_model) { return payload }
+ const key = this.modelConfirmationKey(params, payload)
+ const token = this.modelConfirmations.get(key)
+
+ if (!token) { return payload }
+ this.modelConfirmations.delete(key)
+
+ return { ...payload, confirm: token }
+ }
+
private prepareCreate(params: Record<string, unknown>): Record<string, unknown> {
const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config'])
const unsupported = Object.keys(params).filter(key => !allowed.has(key) && !(key === 'fast' && params[key] === false))
@@ -341,6 +368,15 @@ export class CanonicalDesktopProtocol {
for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }
+ if (params.operation === 'model' && value.status === 'confirmation_required' && typeof value.confirm === 'string') {
+ // The owner wrote nothing: answer in the legacy handshake (`confirm_required` +
+ // `confirm_message`) so the shared confirm dialog asks, and keep the token for its resend.
+ this.modelConfirmations.set(this.modelConfirmationKey(params, params.payload as Record<string, unknown>), value.confirm)
+ const refusal = { ...value, confirm_required: true }
+
+ return method === 'slash.exec' ? { ...refusal, type: 'exec', output: value.confirm_message } : refusal
+ }
+
if (BRANCH_METHODS.has(method)) {
return { ...value, session_id: value.branched_session_id, stored_session_id: value.branched_session_id, parent_session_id: params.session_id, message_count: value.copied_messages }
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index 9f5992462a3..d776289e3c5 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@ -20,6 +20,7 @@ import {
resolveDesktopCommand
} from '@/lib/desktop-slash-commands'
import { isMissingRpcMethod } from '@/lib/gateway-rpc'
+import { type GuardedModelSwitchResult, surfaceModelSwitchConfirm } from '@/lib/guarded-model-switch'
import { applyReasoningSlashResult, reasoningSlashParams } from '@/lib/reasoning-slash'
import { setSessionYolo } from '@/lib/yolo-session'
import { openCommandPalettePage } from '@/store/command-palette'
@@ -486,10 +487,28 @@ export function useSlashCommand(deps: SlashCommandDeps) {
}
try {
- const result = await requestGateway<unknown>('slash.exec', {
- session_id: sessionId,
- command: command.replace(/^\/+/, '')
- })
+ const execParams = { session_id: sessionId, command: command.replace(/^\/+/, '') }
+ const result = await requestGateway<unknown>('slash.exec', execParams)
+
+ if (name === 'model' && (result as GuardedModelSwitchResult | null)?.confirm_required) {
+ // A guarded target (cost / data policy / large context) was NOT applied: ask with the
+ // shared model-switch dialog (the picker's), resend once on "switch anyway".
+ const refusal = result as GuardedModelSwitchResult & { target_model?: string }
+
+ void surfaceModelSwitchConfirm<GuardedModelSwitchResult & SlashExecResponse>({
+ confirmMessage: refusal.confirm_message,
+ failureMessage: copy.modelSwitchFailed,
+ finish: confirmed => renderSlashOutput(confirmed?.output || `/${name}: no output`),
+ model: refusal.target_model,
+ requestConfirmed: () =>
+ requestGateway<GuardedModelSwitchResult & SlashExecResponse>('slash.exec', {
+ ...execParams,
+ confirm_expensive_model: true
+ })
+ })
+
+ return
+ }
const dispatch = parseCommandDispatch(result)