Skip to content

The agent that grows with you

fix(desktop): guarded model switch asks in a dialog with a real decline

teknium1e1e7eafe853e
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.tsx
index 01bbd96e90c..f132c6fac26 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
@@ -21,6 +21,7 @@ import { deferred } from '../../../test/deferred'
import { useModelControls } from './use-model-controls'
const setGlobalModel = vi.fn()
+const confirmMock = vi.fn()
const notify = vi.fn()
const notifyError = vi.fn()
const dismissNotification = vi.fn()
@@ -40,12 +41,12 @@ vi.mock('@/store/session-states', async importOriginal => {
}
})
-vi.mock('@/i18n', () => ({
+vi.mock('@/i18n', async importOriginal => ({
+ // Keep the real module so the applier's `translateNow` copy is the shipped
+ // string — the assertions below pin the labels a user actually sees.
+ ...(await importOriginal<Record<string, unknown>>()),
useI18n: () => ({
t: {
- common: {
- confirm: 'Confirm'
- },
desktop: {
modelSwitchFailed: 'Model switch failed'
}
@@ -53,6 +54,10 @@ vi.mock('@/i18n', () => ({
})
}))
+vi.mock('@/store/confirm', () => ({
+ confirm: (...args: Parameters<typeof confirmMock>) => confirmMock(...args)
+}))
+
vi.mock('@/store/notifications', () => ({
dismissNotification: (...args: Parameters<typeof dismissNotification>) => dismissNotification(...args),
notify: (...args: Parameters<typeof notify>) => notify(...args),
@@ -80,6 +85,8 @@ function Harness({
describe('useModelControls', () => {
beforeEach(() => {
+ confirmMock.mockReset()
+ notifyError.mockReset()
$activeGatewayProfile.set('default')
$activeSessionId.set(null)
setCurrentModel('')
@@ -332,7 +339,7 @@ describe('useModelControls', () => {
expect(invalidate).toHaveBeenCalled()
})
- it('confirms a guarded model switch before retrying it', async () => {
+ it('asks in a dialog before retrying a guarded model switch, then applies the confirmed one', async () => {
$activeSessionId.set('session-1')
setCurrentModel('gpt-5.6-sol')
setCurrentProvider('openai-codex')
@@ -347,6 +354,12 @@ describe('useModelControls', () => {
})
.mockResolvedValueOnce({ key: 'model', scope: 'global', value: 'muse-spark-1.2-contributor' })
+ // Hold the answer open: nothing may be applied or resent until the user
+ // actually answers the dialog.
+ const answer = deferred<boolean>()
+
+ confirmMock.mockReturnValueOnce(answer.promise)
+
let controls!: Controls
render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)
@@ -357,18 +370,19 @@ describe('useModelControls', () => {
expect($currentModel.get()).toBe('gpt-5.6-sol')
expect($currentProvider.get()).toBe('openai-codex')
- expect(notify).toHaveBeenCalledWith(
+ expect(requestGateway).toHaveBeenCalledTimes(1)
+ expect(confirmMock).toHaveBeenCalledWith(
expect.objectContaining({
- action: expect.objectContaining({ label: 'Confirm' }),
- kind: 'warning',
- message: 'This contributor model trains on your data.'
+ cancelLabel: 'Keep current model',
+ confirmLabel: 'Switch anyway',
+ description: 'This contributor model trains on your data.',
+ destructive: true,
+ title: 'Switch to muse-spark-1.2-contributor?'
})
)
- const action = notify.mock.calls.at(-1)?.[0]?.action
-
await act(async () => {
- await action?.onClick()
+ answer.resolve(true)
})
await waitFor(() => expect(requestGateway).toHaveBeenCalledTimes(2))
@@ -382,6 +396,37 @@ describe('useModelControls', () => {
expect($currentProvider.get()).toBe('opencode-go')
})
+ it('keeps the current model when the guarded switch is declined (#112458)', 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'
+ })
+
+ confirmMock.mockResolvedValueOnce(false)
+
+ 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
+ )
+
+ // Declining is free and silent: no resend, no error toast, the pick is gone.
+ await act(async () => {})
+ expect(confirmMock).toHaveBeenCalledTimes(1)
+ expect(requestGateway).toHaveBeenCalledTimes(1)
+ expect($currentModel.get()).toBe('gpt-5.6-sol')
+ expect($currentProvider.get()).toBe('openai-codex')
+ expect(notifyError).not.toHaveBeenCalled()
+ })
+
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 user
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 99aa536cc61..8f1a6a9ff90 100644
--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts
+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts
@@ -286,15 +286,16 @@ export function useModelControls({
// ONE shared applier for guarded switches (#95293): the same
// confirm flow the Bots editor routes through — never fork this
// logic per surface.
- surfaceModelSwitchConfirm({
- confirmLabel: t.common.confirm,
+ // Not awaited: `selectModel` answers "was the switch applied NOW",
+ // and that answer only exists once the user answers the dialog.
+ void surfaceModelSwitchConfirm({
confirmMessage: result.confirm_message,
failureMessage: copy.modelSwitchFailed,
finish: finishSwitch,
- // Staleness guard — the warning can linger while the user picks
- // a different model or switches sessions. Clicking Confirm must
- // not clobber the newer choice: bail if the live state no longer
- // matches the snapshot this notification was created for.
+ // 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
+ // snapshot this prompt was created for.
isStale: () =>
touchesPrimary
? $activeSessionId.get() !== liveSessionId ||
@@ -303,6 +304,7 @@ export function useModelControls({
: !liveSessionId ||
$sessionStates.get()[liveSessionId]?.model !== prevModel ||
$sessionStates.get()[liveSessionId]?.provider !== prevProvider,
+ model: selection.model,
repaint: () => {
paintSelection()
cacheSelection(selection.provider, selection.model)
@@ -339,7 +341,6 @@ export function useModelControls({
copy.modelSwitchFailed,
queryClient,
requestGateway,
- t.common.confirm,
updateModelOptionsCache
]
)
diff --git a/apps/desktop/src/components/ui/confirm-dialog.tsx b/apps/desktop/src/components/ui/confirm-dialog.tsx
index 4aa4b08bca8..37f5a904617 100644
--- a/apps/desktop/src/components/ui/confirm-dialog.tsx
+++ b/apps/desktop/src/components/ui/confirm-dialog.tsx
@@ -150,7 +150,9 @@ export function ConfirmDialog({
>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
- {description ? <DialogDescription>{description}</DialogDescription> : null}
+ {/* pre-line: a backend-composed description keeps its paragraph
+ breaks instead of collapsing into one run-on line (#112458). */}
+ {description ? <DialogDescription className="whitespace-pre-line">{description}</DialogDescription> : null}
</DialogHeader>
{children}
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index a72fa91e8f8..fa8e083c2be 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -3204,7 +3204,13 @@ export const ar = defineLocale({
cwdChangeFailed: 'فشل تغيير مجلد العمل',
cwdStagedTitle: 'تم تجهيز مجلد العمل',
cwdStagedMessage: 'سيطبق مجلد العمل على الرسالة التالية.',
+ modelSwitchConfirmBody: 'يتطلب تبديل النموذج هذا تأكيدًا.',
+ modelSwitchConfirmLabel: 'التبديل على أي حال',
+ modelSwitchConfirmTitle: (model: string) => `التبديل إلى ${model}؟`,
+ modelSwitchConfirmTitleFallback: 'تبديل النموذج؟',
modelSwitchFailed: 'فشل تبديل النموذج',
+ modelSwitchKeepLabel: 'الاحتفاظ بالنموذج الحالي',
+ modelSwitchStaleNotice: 'تغيّر الاختيار — لم يتم تطبيق تبديل النموذج.',
hydrationSyncing: (profile: string) => `جارٍ مزامنة ${profile}\u2026`,
sessionExported: 'تم تصدير الجلسة',
sessionExportFailed: 'فشل تصدير الجلسة',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 8cd8d089192..fd0d1bd1e9b 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -4438,7 +4438,13 @@ export const en: Translations = {
cwdChangeFailed: 'Working directory change failed',
cwdStagedTitle: 'Working directory staged',
cwdStagedMessage: 'Restart the desktop backend to apply cwd changes to this active session.',
+ modelSwitchConfirmBody: 'This model switch needs confirmation.',
+ modelSwitchConfirmLabel: 'Switch anyway',
+ modelSwitchConfirmTitle: (model: string) => `Switch to ${model}?`,
+ modelSwitchConfirmTitleFallback: 'Switch models?',
modelSwitchFailed: 'Model switch failed',
+ modelSwitchKeepLabel: 'Keep current model',
+ modelSwitchStaleNotice: 'Selection changed — the model switch was not applied.',
hydrationSyncing: (profile: string) => `Syncing ${profile}\u2026`,
sessionExported: 'Session exported',
sessionExportFailed: 'Could not export session',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 2c3a325b80d..59c3056cae0 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -3614,7 +3614,13 @@ export const ja = defineLocale({
cwdStagedTitle: '作業ディレクトリがステージングされました',
cwdStagedMessage:
'このアクティブなセッションへの cwd の変更を適用するにはデスクトップバックエンドを再起動してください。',
+ modelSwitchConfirmBody: 'このモデル切り替えには確認が必要です。',
+ modelSwitchConfirmLabel: 'それでも切り替える',
+ modelSwitchConfirmTitle: (model: string) => `${model} に切り替えますか?`,
+ modelSwitchConfirmTitleFallback: 'モデルを切り替えますか?',
modelSwitchFailed: 'モデルの切り替えに失敗しました',
+ modelSwitchKeepLabel: '現在のモデルを維持',
+ modelSwitchStaleNotice: '選択が変更されたため、モデルの切り替えは適用されませんでした。',
hydrationSyncing: (profile: string) => `${profile} を同期中\u2026`,
sessionExported: 'セッションをエクスポートしました',
sessionExportFailed: 'セッションをエクスポートできませんでした',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index ae2b42447cd..a5c6b850b87 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -3877,7 +3877,13 @@ export const ru = defineLocale({
cwdChangeFailed: 'Изменение рабочего каталога не удалось',
cwdStagedTitle: 'Рабочий каталог поставлен в очередь',
cwdStagedMessage: 'Перезапустите бэкенд desktop, чтобы применить изменения cwd к этому активному сеансу.',
+ modelSwitchConfirmBody: 'Эта смена модели требует подтверждения.',
+ modelSwitchConfirmLabel: 'Всё равно переключить',
+ modelSwitchConfirmTitle: (model: string) => `Переключиться на ${model}?`,
+ modelSwitchConfirmTitleFallback: 'Сменить модель?',
modelSwitchFailed: 'Смена модели не удалась',
+ modelSwitchKeepLabel: 'Оставить текущую модель',
+ modelSwitchStaleNotice: 'Выбор изменился — смена модели не применена.',
sessionExported: 'Сеанс экспортирован',
sessionExportFailed: 'Не удалось экспортировать сеанс',
imageSaved: 'Изображение сохранено',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 37dd3e3be18..2ef07391a9e 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -3796,7 +3796,13 @@ export interface Translations {
cwdChangeFailed: string
cwdStagedTitle: string
cwdStagedMessage: string
+ modelSwitchConfirmBody: string
+ modelSwitchConfirmLabel: string
+ modelSwitchConfirmTitle: (model: string) => string
+ modelSwitchConfirmTitleFallback: string
modelSwitchFailed: string
+ modelSwitchKeepLabel: string
+ modelSwitchStaleNotice: string
hydrationSyncing: (profile: string) => string
sessionExported: string
sessionExportFailed: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index c7ab061d7f1..3cbed17ac25 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -3538,7 +3538,13 @@ export const zhHant = defineLocale({
cwdChangeFailed: '工作目錄變更失敗',
cwdStagedTitle: '工作目錄已暫存',
cwdStagedMessage: '重新啟動桌面後端後,工作目錄變更才會套用至此作用中工作階段。',
+ modelSwitchConfirmBody: '此模型切換需要確認。',
+ modelSwitchConfirmLabel: '仍然切換',
+ modelSwitchConfirmTitle: (model: string) => `切換到 ${model}?`,
+ modelSwitchConfirmTitleFallback: '切換模型?',
modelSwitchFailed: '模型切換失敗',
+ modelSwitchKeepLabel: '保留目前模型',
+ modelSwitchStaleNotice: '選擇已變更 — 未套用模型切換。',
hydrationSyncing: (profile: string) => `正在同步 ${profile}\u2026`,
sessionExported: '工作階段已匯出',
sessionExportFailed: '無法匯出工作階段',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 1af4a731836..b3b5342d677 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -4339,7 +4339,13 @@ export const zh = defineLocale({
cwdChangeFailed: '工作目录更改失败',
cwdStagedTitle: '工作目录已暂存',
cwdStagedMessage: '重启桌面后端后,工作目录更改才会应用到当前活跃会话。',
+ modelSwitchConfirmBody: '此模型切换需要确认。',
+ modelSwitchConfirmLabel: '仍然切换',
+ modelSwitchConfirmTitle: (model: string) => `切换到 ${model}?`,
+ modelSwitchConfirmTitleFallback: '切换模型?',
modelSwitchFailed: '模型切换失败',
+ modelSwitchKeepLabel: '保留当前模型',
+ modelSwitchStaleNotice: '选择已更改 — 未应用模型切换。',
hydrationSyncing: (profile: string) => `正在同步 ${profile}\u2026`,
sessionExported: '会话已导出',
sessionExportFailed: '无法导出会话',
diff --git a/apps/desktop/src/lib/guarded-model-switch.test.tsx b/apps/desktop/src/lib/guarded-model-switch.test.tsx
new file mode 100644
index 00000000000..d528b30ff3b
--- /dev/null
+++ b/apps/desktop/src/lib/guarded-model-switch.test.tsx
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { ConfirmHost } from '@/components/confirm-host'
+
+import { type GuardedModelSwitchResult, surfaceModelSwitchConfirm } from './guarded-model-switch'
+
+vi.mock('@/store/notifications', () => ({
+ notify: vi.fn(),
+ notifyError: vi.fn()
+}))
+
+afterEach(cleanup)
+
+/** Shaped like the gateway's: blank lines separate the guard's paragraphs. */
+const GUARD_MESSAGE =
+ 'This session holds ~206,172 tokens of context.\nSwitching re-reads it.\n\nContext window shrinks (1,000,000 → 256,000).'
+
+type SwitchResult = GuardedModelSwitchResult & { value: string }
+
+function ask() {
+ const requestConfirmed = vi.fn(async (): Promise<SwitchResult> => ({ value: 'perplexity/sonar-deep-research' }))
+
+ const answer = surfaceModelSwitchConfirm({
+ confirmMessage: GUARD_MESSAGE,
+ failureMessage: 'Model switch failed',
+ model: 'perplexity/sonar-deep-research',
+ requestConfirmed
+ })
+
+ return { answer, requestConfirmed }
+}
+
+// The applier through the real `confirm()` atom, the real ConfirmHost mount
+// and the real ConfirmDialog, so the choices a user actually sees are
+// asserted (#112458: the toast it replaced had one "Confirm" and an ✕).
+describe('surfaceModelSwitchConfirm through the shell dialog', () => {
+ it('offers a decline that keeps the current model and keeps the guard paragraphs', async () => {
+ render(<ConfirmHost />)
+
+ const { answer, requestConfirmed } = ask()
+
+ expect(await screen.findByRole('dialog')).toBeTruthy()
+ expect(screen.getByText('Switch to perplexity/sonar-deep-research?')).toBeTruthy()
+
+ // The gateway's line breaks survive: the description is not one run-on line.
+ const description = screen.getByText(/Context window shrinks/)
+
+ expect(description.textContent).toBe(GUARD_MESSAGE)
+ expect(description.className).toMatch(/whitespace-pre-line/)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Keep current model' }))
+
+ await expect(answer).resolves.toBe(false)
+ expect(requestConfirmed).not.toHaveBeenCalled()
+ })
+
+ it('resends with confirmation only after "Switch anyway"', async () => {
+ render(<ConfirmHost />)
+
+ const { answer, requestConfirmed } = ask()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Switch anyway' }))
+
+ await expect(answer).resolves.toBe(true)
+ expect(requestConfirmed).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/src/lib/guarded-model-switch.ts b/apps/desktop/src/lib/guarded-model-switch.ts
index 734cda11bc8..6723ebab38f 100644
--- a/apps/desktop/src/lib/guarded-model-switch.ts
+++ b/apps/desktop/src/lib/guarded-model-switch.ts
@@ -1,4 +1,6 @@
-import { dismissNotification, notify, notifyError } from '@/store/notifications'
+import { translateNow } from '@/i18n'
+import { confirm } from '@/store/confirm'
+import { notify, notifyError } from '@/store/notifications'
/** The gateway's model-switch handshake shape — shared by `config.set model`
* and `profiles.configure` (Bots editor). `confirm_required: true` means the
@@ -11,28 +13,24 @@ export interface GuardedModelSwitchResult {
}
export interface SurfaceModelSwitchConfirmOptions<T extends GuardedModelSwitchResult> {
- /** Label for the confirm action button (and default title). */
- confirmLabel: string
/** The gateway's `confirm_message`, when present. */
confirmMessage?: string
/** Error-toast copy when the confirmed resend still fails. */
failureMessage: string
- /** Message when the gateway sent no `confirm_message`. */
- fallbackMessage?: string
/** Runs after the confirmed resend succeeds (cache invalidation etc.). */
finish?: (result: T | undefined) => void
- /** Staleness guard — the warning can linger while the user picks a
- * different model or switches sessions. Return true to make Confirm a
- * no-op (the notification is dismissed) instead of clobbering the newer
- * choice. */
+ /** Staleness guard — the session/model can move on while the dialog is
+ * open. Return true to make the answered confirm a no-op (with a notice
+ * saying so) instead of clobbering the newer choice. */
isStale?: () => boolean
+ /** The model the switch targets — named in the dialog title when known. */
+ model?: string
/** Optimistically repaint the pending selection before the resend. */
repaint?: () => void
/** Resend the switch WITH `confirm_expensive_model: true`. */
requestConfirmed: () => Promise<T | undefined>
/** Undo the optimistic repaint when the confirmed resend fails. */
rollback?: () => void
- title?: string
}
/**
@@ -42,49 +40,58 @@ export interface SurfaceModelSwitchConfirmOptions<T extends GuardedModelSwitchRe
* it through here so there is exactly one applier and no forked confirm
* logic per surface (#95293).
*
- * Shows a warning notification whose Confirm action resends the switch with
- * `confirm_expensive_model: true`, guarded against stale confirmations. A
- * resend that STILL answers `confirm_required` is treated as a failure — the
- * gateway asked twice, something is wrong; never loop.
+ * A refused switch is a decision, not a notification: it asks through
+ * `confirm()` — the app's ConfirmDialog — so there is a real decline button,
+ * Esc/backdrop/✕ all mean "keep current model", and the dialog owns focus
+ * while it waits (#112458). Declining is free: nothing was applied. Only a
+ * confirmed answer resends with `confirm_expensive_model: true`; a resend
+ * that STILL answers `confirm_required` is treated as a failure — the gateway
+ * asked twice, something is wrong; never loop.
*
- * Returns the notification id.
+ * Resolves `true` when the switch was applied, `false` when it was declined,
+ * went stale, or failed (a failure surfaces its own toast).
*/
-export function surfaceModelSwitchConfirm<T extends GuardedModelSwitchResult>(
+export async function surfaceModelSwitchConfirm<T extends GuardedModelSwitchResult>(
options: SurfaceModelSwitchConfirmOptions<T>
-): string {
- const applyConfirmedSwitch = async () => {
- if (options.isStale?.()) {
- dismissNotification(notificationId)
+): Promise<boolean> {
+ const accepted = await confirm({
+ cancelLabel: translateNow('desktop.modelSwitchKeepLabel'),
+ confirmLabel: translateNow('desktop.modelSwitchConfirmLabel'),
+ description: options.confirmMessage?.trim() || translateNow('desktop.modelSwitchConfirmBody'),
+ destructive: true,
+ title: options.model
+ ? translateNow('desktop.modelSwitchConfirmTitle', options.model)
+ : translateNow('desktop.modelSwitchConfirmTitleFallback')
+ })
- return
- }
+ if (!accepted) {
+ return false
+ }
- dismissNotification(notificationId)
- options.repaint?.()
+ if (options.isStale?.()) {
+ // The session or model moved on under the dialog, so the switch it asked
+ // for no longer exists. Say so — a silent no-op reads as a broken button.
+ notify({ kind: 'info', message: translateNow('desktop.modelSwitchStaleNotice') })
+
+ return false
+ }
- try {
- const result = await options.requestConfirmed()
+ options.repaint?.()
- if (result?.confirm_required) {
- throw new Error(result.confirm_message?.trim() || options.failureMessage)
- }
+ try {
+ const result = await options.requestConfirmed()
- options.finish?.(result)
- } catch (err) {
- options.rollback?.()
- notifyError(err, options.failureMessage)
+ if (result?.confirm_required) {
+ throw new Error(result.confirm_message?.trim() || options.failureMessage)
}
- }
- const notificationId = notify({
- action: {
- label: options.confirmLabel,
- onClick: applyConfirmedSwitch
- },
- kind: 'warning',
- message: options.confirmMessage?.trim() || options.fallbackMessage || 'Confirm this model switch?',
- title: options.title ?? options.confirmLabel
- })
+ options.finish?.(result)
- return notificationId
+ return true
+ } catch (err) {
+ options.rollback?.()
+ notifyError(err, options.failureMessage)
+
+ return false
+ }
}
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts b/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts
index e5876bb87c2..2ddc99494ea 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts
@@ -31,11 +31,12 @@ type AdvancedConfigState = ReturnType<typeof emptyAdvancedState>
interface ModelSwitchConfirmArgs {
confirmMessage: string
finish: () => void
+ model: string
requestConfirmed: () => Promise<{ applied?: Record<string, boolean> } | undefined>
}
const { confirmMock, hostMock, invalidateMock } = vi.hoisted(() => ({
- confirmMock: vi.fn((_args: ModelSwitchConfirmArgs) => 'notification-1'),
+ confirmMock: vi.fn(async (_args: ModelSwitchConfirmArgs) => true),
hostMock: {
getGateway: () => 'ambient-gateway',
request: vi.fn(),
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
index eee01eccd5b..18ab72da5e7 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
@@ -611,18 +611,18 @@ export async function applyAdvancedConfig(bot: RosterRow, state: AdvancedConfigS
// on THIS surface too — `confirm_required` means the model section is
// PENDING the user's confirmation, not failed. Route it through the SAME
// shared confirm handler the core picker uses (one applier, no forked
- // confirm logic per surface): the Confirm action resends ONLY the model
+ // confirm logic per surface): a confirmed answer resends ONLY the model
// section with `confirm_expensive_model: true`.
if (result?.confirm_required && payload.model && payload.provider) {
delete merged.model
- surfaceModelSwitchConfirm({
- confirmLabel: 'Confirm',
+ void surfaceModelSwitchConfirm({
confirmMessage: result.confirm_message,
failureMessage: 'Model switch failed',
finish: () =>
queryClient.invalidateQueries({
queryKey: ROSTER_KEY
}),
+ model: payload.model,
requestConfirmed: () =>
requestForBot(bot, 'profiles.configure', {
name: bot.name,
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index e0e3fdfad36..bb9b39c4900 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1747,8 +1747,9 @@ export { CHAT_EMPTY_AREA, type ChatEmptyContribution, type ChatEmptyProps } from
/** THE confirm flow for guarded model switches — when a gateway model-switch
* RPC answers `confirm_required` (data-policy / expensive-model guard),
* route it through this shared applier instead of forking a per-surface
- * dialog: it shows the warning and resends with
- * `confirm_expensive_model: true` on Confirm (#95293). */
+ * dialog: it asks through the app's ConfirmDialog (Switch anyway / Keep
+ * current model) and only a confirmed answer resends with
+ * `confirm_expensive_model: true` (#95293, #112458). */
export {
type GuardedModelSwitchResult,
surfaceModelSwitchConfirm,