Skip to content

The agent that grows with you

fix(desktop): Bots-mode picker routes guarded model switches through the shared confirm handler

Teknium61b6788dd494
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 418c1ba5150..46db8a1c6d3 100644
--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts
+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts
@@ -5,8 +5,9 @@ import type { ModelSelection } from '@/app/shell/model-menu-panel'
import { getGlobalModelInfo } from '@/hermes'
import { useI18n } from '@/i18n'
import { isBusySessionModelSwitch } from '@/lib/gateway-rpc'
+import { surfaceModelSwitchConfirm } from '@/lib/guarded-model-switch'
import { manualPickRemoved, modelOptionsQueryKey } from '@/lib/model-options'
-import { dismissNotification, notify, notifyError } from '@/store/notifications'
+import { notifyError } from '@/store/notifications'
import { $activeGatewayProfile } from '@/store/profile'
import {
$activeSessionId,
@@ -282,63 +283,37 @@ export function useModelControls({ queryClient, requestGateway }: ModelControlsO
}
}
- let confirmNotificationId: string | null = null
-
- const applyConfirmedSwitch = async () => {
- // 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 and dismiss if the live state no
- // longer matches the snapshot this notification was created for.
- const isStale = touchesPrimary
- ? $activeSessionId.get() !== liveSessionId ||
- $currentModel.get() !== prevModel ||
- $currentProvider.get() !== prevProvider
- : !liveSessionId ||
- $sessionStates.get()[liveSessionId]?.model !== prevModel ||
- $sessionStates.get()[liveSessionId]?.provider !== prevProvider
-
- if (isStale) {
- if (confirmNotificationId) {
- dismissNotification(confirmNotificationId)
- }
-
- return
- }
-
- if (confirmNotificationId) {
- dismissNotification(confirmNotificationId)
- }
-
- paintSelection()
- cacheSelection(selection.provider, selection.model)
-
- try {
- const result = await requestSwitch(true)
-
- if (result?.confirm_required) {
- throw new Error(result.confirm_message?.trim() || copy.modelSwitchFailed)
- }
-
- finishSwitch(result)
- } catch (err) {
- rollbackSelection()
- notifyError(err, copy.modelSwitchFailed)
- }
- }
-
try {
const result = await requestSwitch()
if (result?.confirm_required) {
rollbackSelection()
- confirmNotificationId = notify({
- action: {
- label: t.common.confirm,
- onClick: applyConfirmedSwitch
+ // 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,
+ 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.
+ isStale: () =>
+ touchesPrimary
+ ? $activeSessionId.get() !== liveSessionId ||
+ $currentModel.get() !== prevModel ||
+ $currentProvider.get() !== prevProvider
+ : !liveSessionId ||
+ $sessionStates.get()[liveSessionId]?.model !== prevModel ||
+ $sessionStates.get()[liveSessionId]?.provider !== prevProvider,
+ repaint: () => {
+ paintSelection()
+ cacheSelection(selection.provider, selection.model)
},
- kind: 'warning',
- message: result.confirm_message?.trim() || 'Confirm this model switch?',
- title: t.common.confirm
+ requestConfirmed: () => requestSwitch(true),
+ rollback: rollbackSelection
})
return false
diff --git a/apps/desktop/src/app/shell/model-menu-panel.test.tsx b/apps/desktop/src/app/shell/model-menu-panel.test.tsx
index 39e11b66407..c0fddaf532a 100644
--- a/apps/desktop/src/app/shell/model-menu-panel.test.tsx
+++ b/apps/desktop/src/app/shell/model-menu-panel.test.tsx
@@ -1,13 +1,25 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useState } from 'react'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useModelControls } from '@/app/session/hooks/use-model-controls'
import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu'
import { $collapsedProviders, toggleCollapsedProvider } from '@/store/provider-collapse'
import { $activeSessionId, $currentModel, $currentProvider } from '@/store/session'
import { ModelMenuPanel } from './model-menu-panel'
+const notify = vi.fn(() => 'confirm-toast-1')
+const notifyError = vi.fn()
+const dismissNotification = vi.fn()
+
+vi.mock('@/store/notifications', () => ({
+ dismissNotification: (...args: unknown[]) => dismissNotification(...args),
+ notify: (...args: unknown[]) => notify(...args),
+ notifyError: (...args: unknown[]) => notifyError(...args)
+}))
+
// Radix calls these on open; jsdom doesn't implement them.
beforeAll(() => {
Element.prototype.scrollIntoView = vi.fn()
@@ -446,3 +458,94 @@ describe('ModelMenuPanel provider collapse', () => {
expect(onSelectModel).not.toHaveBeenCalled()
})
})
+
+describe('ModelMenuPanel refresh reconcile × guarded-switch confirm handshake', () => {
+ // #95446 fix (reconcile after Refresh Models) composes with the
+ // confirm-handshake guard: when the reconcile target is itself a GUARDED
+ // model (contributor tier / expensive), the switch must surface the confirm
+ // flow — one config.set, a warning with a Confirm action, rollback until
+ // confirmed — never a silent retry loop and never a silently-painted pick.
+ function ConfirmHarness({
+ requestGateway
+ }: {
+ requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>
+ }) {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }))
+ const controls = useModelControls({ queryClient: client, requestGateway })
+
+ return (
+ <QueryClientProvider client={client}>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <ModelMenuPanel onSelectModel={controls.selectModel} requestGateway={requestGateway as never} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </QueryClientProvider>
+ )
+ }
+
+ it('reconcile-triggered switch to a guarded model surfaces confirm, not a silent retry', async () => {
+ $activeSessionId.set('runtime-1')
+ $currentProvider.set('zhipu')
+ $currentModel.set('glm-4.5-air')
+ getGlobalModelOptions
+ .mockResolvedValueOnce({
+ providers: [{ models: ['glm-4.5-air'], name: 'Zhipu', slug: 'zhipu' }, MOA_PROVIDER]
+ })
+ // Refresh drops the current pick; the only remaining model is guarded.
+ .mockResolvedValueOnce({
+ providers: [{ models: ['muse-spark-1.2-contributor'], name: 'OpenCode', slug: 'opencode-go' }, MOA_PROVIDER]
+ })
+
+ const requestGateway = vi
+ .fn()
+ .mockResolvedValueOnce({
+ confirm_message: 'CONTRIBUTOR TIER: this model may train on your data.',
+ confirm_required: true,
+ key: 'model',
+ value: 'muse-spark-1.2-contributor'
+ })
+ .mockResolvedValueOnce({ key: 'model', scope: 'global', value: 'muse-spark-1.2-contributor' })
+
+ const content = render(<ConfirmHarness requestGateway={requestGateway as never} />)
+
+ await content.findByText(/Glm 4\.5 Air/i)
+ fireEvent.click(await content.findByText('Refresh Models'))
+
+ // The reconcile fired exactly ONE switch attempt and it came back
+ // confirm_required → the confirm toast is up, nothing retried silently.
+ await vi.waitFor(() => {
+ expect(notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: expect.objectContaining({ label: expect.any(String) }),
+ kind: 'warning',
+ message: 'CONTRIBUTOR TIER: this model may train on your data.'
+ })
+ )
+ })
+
+ const configSetCalls = requestGateway.mock.calls.filter(([method]) => method === 'config.set')
+ expect(configSetCalls).toHaveLength(1)
+ expect(configSetCalls[0][1]).not.toHaveProperty('confirm_expensive_model')
+
+ // Pending confirmation = rolled back, not silently painted.
+ expect($currentModel.get()).toBe('glm-4.5-air')
+ expect($currentProvider.get()).toBe('zhipu')
+
+ // User confirms → ONE resend carrying confirm_expensive_model: true.
+ const action = notify.mock.calls.at(-1)?.[0]?.action as { onClick: () => Promise<void> }
+
+ await act(async () => {
+ await action.onClick()
+ })
+
+ await vi.waitFor(() => {
+ const resend = requestGateway.mock.calls.filter(([method]) => method === 'config.set')
+ expect(resend).toHaveLength(2)
+ expect(resend[1][1]).toMatchObject({ confirm_expensive_model: true, session_id: 'runtime-1' })
+ })
+ expect($currentModel.get()).toBe('muse-spark-1.2-contributor')
+ expect($currentProvider.get()).toBe('opencode-go')
+ expect(notifyError).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/lib/guarded-model-switch.ts b/apps/desktop/src/lib/guarded-model-switch.ts
new file mode 100644
index 00000000000..734cda11bc8
--- /dev/null
+++ b/apps/desktop/src/lib/guarded-model-switch.ts
@@ -0,0 +1,90 @@
+import { dismissNotification, 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
+ * switch was intentionally NOT applied and the gateway is waiting for a
+ * resend that carries `confirm_expensive_model: true`. */
+export interface GuardedModelSwitchResult {
+ confirm_message?: string
+ confirm_required?: boolean
+ deferred?: boolean
+}
+
+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. */
+ isStale?: () => boolean
+ /** 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
+}
+
+/**
+ * THE confirm flow for guarded model switches — every surface that can
+ * receive `confirm_required` from a model switch (core picker via
+ * `config.set`, Bots editor via `profiles.configure`, future surfaces) routes
+ * 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.
+ *
+ * Returns the notification id.
+ */
+export function surfaceModelSwitchConfirm<T extends GuardedModelSwitchResult>(
+ options: SurfaceModelSwitchConfirmOptions<T>
+): string {
+ const applyConfirmedSwitch = async () => {
+ if (options.isStale?.()) {
+ dismissNotification(notificationId)
+
+ return
+ }
+
+ dismissNotification(notificationId)
+ options.repaint?.()
+
+ try {
+ const result = await options.requestConfirmed()
+
+ if (result?.confirm_required) {
+ throw new Error(result.confirm_message?.trim() || options.failureMessage)
+ }
+
+ options.finish?.(result)
+ } catch (err) {
+ options.rollback?.()
+ notifyError(err, 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
+ })
+
+ return notificationId
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 63e99bb2b08..ce355f700a8 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -58,6 +58,7 @@ import {
SelectTrigger,
SelectValue,
Switch,
+ surfaceModelSwitchConfirm,
Textarea,
Tip,
useQuery,
@@ -9808,6 +9809,29 @@ async function applyAdvancedConfig(bot, state) {
const result = await requestForBot(bot, 'profiles.configure', payload)
const merged = { ...applied, ...(result?.applied || {}) }
+ // #95293 remainder: the gateway now guards data-policy / expensive models
+ // 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
+ // section with `confirm_expensive_model: true`.
+ if (result?.confirm_required && payload.model && payload.provider) {
+ delete merged.model
+ surfaceModelSwitchConfirm({
+ confirmLabel: 'Confirm',
+ confirmMessage: result.confirm_message,
+ failureMessage: 'Model switch failed',
+ finish: () => queryClient.invalidateQueries({ queryKey: ROSTER_KEY }),
+ requestConfirmed: () =>
+ requestForBot(bot, 'profiles.configure', {
+ name: bot.name,
+ model: payload.model,
+ provider: payload.provider,
+ confirm_expensive_model: true
+ })
+ })
+ }
+
return { ...result, ok: Object.values(merged).every(Boolean), applied: merged }
}
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjs
new file mode 100644
index 00000000000..1ae57f0966d
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjs
@@ -0,0 +1,188 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// #95293 remainder: a GUARDED model switch made from the Bots surface must
+// surface the SAME confirm flow the core picker uses, then resend with
+// `confirm_expensive_model: true` once the user confirms.
+//
+// The Bots editor's switch path is `applyAdvancedConfig` → `profiles.configure`
+// (it does NOT route through use-model-controls). The gateway now answers
+// `confirm_required` + `confirm_message` for guarded picks on this surface too
+// (same handshake as `config.set model`); the plugin must:
+//
+// 1. route that response through the shared confirm handler
+// (`surfaceModelSwitchConfirm` from the plugin SDK — one applier, no
+// forked confirm logic per surface),
+// 2. NOT count the pending model section as a failed section, and
+// 3. resend ONLY the model section with `confirm_expensive_model: true`
+// when the user clicks Confirm.
+//
+// Pre-fix, the confirm_required response matched no branch: the pick silently
+// dropped (no confirm, no resend) — exactly issue #95293 on the Bots surface.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadHarness({ request }) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = {
+ get: () => values.get(slot),
+ set: value => values.set(slot, value),
+ listen: () => undefined
+ }
+ values.set(slot, initial)
+ return slot
+ }
+ const jsx = (type, props = {}) => ({ type, props })
+ const routed = []
+ const confirms = []
+ const invalidated = []
+ const context = {
+ atom,
+ Checkbox: 'Checkbox',
+ GlyphSpinner: 'GlyphSpinner',
+ Input: 'Input',
+ ScrollArea: 'ScrollArea',
+ Textarea: 'Textarea',
+ document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },
+ host: {
+ getGateway: () => 'ambient-gateway',
+ request: async (method, params) => {
+ routed.push([method, params])
+
+ return request(method, params)
+ },
+ requestProfile: async (route, method, params) => {
+ routed.push([method, params])
+
+ return request(method, params)
+ },
+ state: {
+ gateway: { get: () => 'open', listen: () => undefined },
+ profile: { get: () => 'default', listen: () => undefined }
+ }
+ },
+ jsx,
+ jsxs: jsx,
+ queryClient: { invalidateQueries: key => invalidated.push(key) },
+ sdk: {},
+ // The shared confirm handler the core picker uses, exported through the
+ // plugin SDK. The stub records the options so the test can drive the
+ // Confirm action exactly like a user click would.
+ surfaceModelSwitchConfirm: options => {
+ confirms.push(options)
+
+ return 'notification-1'
+ },
+ useQuery: () => ({ data: undefined, isLoading: false, error: null }),
+ useState: initial => [initial, () => undefined],
+ window: { setTimeout, clearTimeout }
+ }
+ const code = source
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__applyAdvancedConfig = applyAdvancedConfig;')
+ vm.runInNewContext(code, context, { filename: 'plugin.js' })
+
+ return { applyAdvancedConfig: context.__applyAdvancedConfig, confirms, invalidated, routed }
+}
+
+const bot = { name: 'zeta' }
+
+const dirtyModelState = {
+ loaded: true,
+ provider: 'opencode-go',
+ model: 'muse-spark-1.2-contributor',
+ soul: '',
+ skills: [],
+ toolsets: [],
+ mcp: [],
+ dirtyModel: true,
+ dirtySoul: false,
+ dirtySkills: false,
+ dirtyToolsets: false,
+ dirtyMcp: false
+}
+
+test('guarded Bots-mode switch surfaces the shared confirm flow instead of silently dropping', async () => {
+ const { applyAdvancedConfig, confirms, routed } = loadHarness({
+ request: async () => ({
+ ok: true,
+ applied: {},
+ confirm_required: true,
+ confirm_message: 'CONTRIBUTOR TIER: this model may train on your data.'
+ })
+ })
+
+ const res = await applyAdvancedConfig(bot, { ...dirtyModelState })
+
+ // The first request is the normal (unconfirmed) configure call.
+ assert.equal(routed.length, 1)
+ assert.equal(routed[0][0], 'profiles.configure')
+ assert.equal(routed[0][1].model, 'muse-spark-1.2-contributor')
+ assert.ok(!routed[0][1].confirm_expensive_model, 'first attempt must NOT pre-confirm')
+
+ // The confirm flow was surfaced through the SHARED handler with the
+ // gateway's message — not swallowed, not a forked local dialog.
+ assert.equal(confirms.length, 1, 'confirm_required must surface the shared confirm handler')
+ assert.match(String(confirms[0].confirmMessage || ''), /CONTRIBUTOR TIER/)
+
+ // Pending-confirmation is NOT a failed section: the editor must not toast
+ // "Some sections failed: model" while the confirm toast is up.
+ assert.notEqual(res?.applied?.model, false)
+ assert.equal(res?.ok, true)
+})
+
+test('Confirm resends ONLY the model section with confirm_expensive_model: true', async () => {
+ let calls = 0
+ const { applyAdvancedConfig, confirms, routed } = loadHarness({
+ request: async () => {
+ calls += 1
+
+ if (calls === 1) {
+ return { ok: true, applied: {}, confirm_required: true, confirm_message: 'guarded' }
+ }
+
+ return { ok: true, applied: { model: true } }
+ }
+ })
+
+ await applyAdvancedConfig(bot, { ...dirtyModelState })
+ assert.equal(confirms.length, 1)
+
+ // Drive the confirmed resend exactly as the shared handler's Confirm
+ // action does.
+ const confirmed = await confirms[0].requestConfirmed()
+
+ assert.equal(routed.length, 2)
+ const [method, params] = routed[1]
+ assert.equal(method, 'profiles.configure')
+ assert.equal(params.confirm_expensive_model, true)
+ assert.equal(params.model, 'muse-spark-1.2-contributor')
+ assert.equal(params.provider, 'opencode-go')
+ assert.equal(params.name, 'zeta')
+ // Only the model section rides the resend — no soul/skills/toolsets replay.
+ assert.deepEqual(
+ Object.keys(params).sort(),
+ ['confirm_expensive_model', 'model', 'name', 'provider']
+ )
+ assert.equal(confirmed?.applied?.model, true)
+})
+
+test('unguarded saves keep the existing single-shot behavior', async () => {
+ const { applyAdvancedConfig, confirms, routed } = loadHarness({
+ request: async () => ({ ok: true, applied: { model: true } })
+ })
+
+ const res = await applyAdvancedConfig(bot, { ...dirtyModelState })
+
+ assert.equal(routed.length, 1)
+ assert.equal(confirms.length, 0)
+ assert.equal(res?.ok, true)
+ assert.equal(res?.applied?.model, true)
+})
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index f1cf9d23f7a..c39b6fd32f7 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1488,6 +1488,16 @@ export { type BudgetedLoop, type BudgetedLoopOptions, createBudgetedLoop } from
/** THE compact-number formatter — every user-facing count/token figure goes
* through here (1230 → "1.2k", 1_500_000 → "1.5M"). Don't hand-roll `/1000`. */
export { compactNumber } from '@/lib/format'
+/** 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). */
+export {
+ type GuardedModelSwitchResult,
+ surfaceModelSwitchConfirm,
+ type SurfaceModelSwitchConfirmOptions
+} from '@/lib/guarded-model-switch'
export { triggerHaptic as haptic } from '@/lib/haptics'
export type { HermesOpenTarget } from '@/lib/hermes-open-target'
/** The app's lucide icon set (RefreshCw, LayoutDashboard, Activity, …). */
diff --git a/tests/tui_gateway/test_profiles_configure_model_guard.py b/tests/tui_gateway/test_profiles_configure_model_guard.py
new file mode 100644
index 00000000000..51cd8f21c8e
--- /dev/null
+++ b/tests/tui_gateway/test_profiles_configure_model_guard.py
@@ -0,0 +1,111 @@
+"""profiles.configure honours the model selection guard (#95293 remainder).
+
+The Bots-mode editor writes a profile's default model through
+``profiles.configure`` — a surface that historically bypassed the
+data-policy / expensive-model selection guard every other model-switch path
+enforces (``config.set model`` answers ``confirm_required`` and waits for a
+``confirm_expensive_model`` resend). A guarded pick made from the Bots
+surface was therefore applied silently, with no confirm flow anywhere.
+
+These tests pin the same handshake contract on ``profiles.configure``:
+
+* a guarded model WITHOUT ``confirm_expensive_model`` answers
+ ``confirm_required`` + ``confirm_message`` and writes NOTHING;
+* the confirmed resend (``confirm_expensive_model: true``) writes;
+* unguarded models keep writing exactly as before.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+import hermes_cli.model_selection_guards as guards
+import tui_gateway.server as srv
+
+GUARDED_MODEL = "muse-spark-1.2-contributor"
+GUARD_MESSAGE = "CONTRIBUTOR TIER: this model may train on your data."
+
+
+def home(tmp_path, monkeypatch):
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ return hermes_home
+
+
+def contributor_guard(monkeypatch):
+ """Fire the selection guard for GUARDED_MODEL only, like the real
+ data-policy guard fires for ``-contributor`` ids."""
+
+ def fake_combined_selection_warning(model_name, **_kwargs):
+ if model_name == GUARDED_MODEL:
+ return SimpleNamespace(message=GUARD_MESSAGE, kind="data_policy")
+ return None
+
+ monkeypatch.setattr(guards, "combined_selection_warning", fake_combined_selection_warning)
+
+
+def _configure(params):
+ return srv._methods["profiles.configure"]("configure", {"name": "default", **params})["result"]
+
+
+def _profile_model(home: Path):
+ cfg_path = home / "config.yaml"
+ if not cfg_path.is_file():
+ return None
+ cfg = yaml.safe_load(cfg_path.read_text()) or {}
+ model_cfg = cfg.get("model") or {}
+ return model_cfg.get("default")
+
+
+def test_guarded_model_answers_confirm_required_and_writes_nothing(home, contributor_guard):
+ result = _configure({"model": GUARDED_MODEL, "provider": "opencode-go"})
+
+ assert result.get("confirm_required") is True
+ assert GUARD_MESSAGE in (result.get("confirm_message") or "")
+ # The model section is PENDING confirmation, not failed — it must not
+ # poison ``ok`` (the Bots editor toasts "Some sections failed" on False).
+ assert result["applied"].get("model") is not False
+ assert _profile_model(home) != GUARDED_MODEL
+
+
+def test_confirmed_resend_writes_the_guarded_model(home, contributor_guard):
+ result = _configure(
+ {
+ "model": GUARDED_MODEL,
+ "provider": "opencode-go",
+ "confirm_expensive_model": True,
+ }
+ )
+
+ assert not result.get("confirm_required")
+ assert result["applied"].get("model") is True
+ assert _profile_model(home) == GUARDED_MODEL
+
+
+def test_unguarded_model_still_writes_without_confirmation(home, contributor_guard):
+ result = _configure({"model": "hermes-4.5-405b", "provider": "nous"})
+
+ assert not result.get("confirm_required")
+ assert result["applied"].get("model") is True
+ assert _profile_model(home) == "hermes-4.5-405b"
+
+
+def test_other_sections_still_apply_while_model_awaits_confirmation(home, contributor_guard):
+ result = _configure(
+ {
+ "model": GUARDED_MODEL,
+ "provider": "opencode-go",
+ "soul": "# SOUL\nBe kind.",
+ }
+ )
+
+ assert result.get("confirm_required") is True
+ assert result["applied"].get("soul") is True
+ assert _profile_model(home) != GUARDED_MODEL
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index aa63a96d522..2ceb2e89bb5 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -884,14 +884,34 @@ def _(rid, params: dict) -> dict:
model = str(params.get("model") or "").strip()
provider = str(params.get("provider") or "").strip()
+ confirm_message = None
if model and provider:
- try:
- from hermes_cli.web_routers.profiles import _write_profile_model
+ # #95293 remainder: this is the Bots editor's model-switch path,
+ # and it used to write guarded (data-policy / expensive) models
+ # silently — the ONE surface that bypassed the selection guard
+ # every other switch path enforces. Same handshake contract as
+ # ``config.set model``: without ``confirm_expensive_model`` a
+ # guarded pick answers ``confirm_required`` + ``confirm_message``
+ # and writes NOTHING; the client resends with
+ # ``confirm_expensive_model: true`` once the user confirms. A
+ # misbehaving guard must never break the save (treated as "no
+ # warning"), matching ``_apply_model_switch``.
+ if not is_truthy_value(params.get("confirm_expensive_model", False)):
+ try:
+ from hermes_cli.model_selection_guards import combined_selection_warning
- _write_profile_model(profile_dir, provider, model)
- applied["model"] = True
- except Exception:
- applied["model"] = False
+ warning = combined_selection_warning(model, provider=provider or None)
+ confirm_message = warning.message if warning is not None else None
+ except Exception:
+ confirm_message = None
+ if confirm_message is None:
+ try:
+ from hermes_cli.web_routers.profiles import _write_profile_model
+
+ _write_profile_model(profile_dir, provider, model)
+ applied["model"] = True
+ except Exception:
+ applied["model"] = False
needs_cfg = (
isinstance(params.get("disabled_skills"), list)
@@ -987,7 +1007,13 @@ def _(rid, params: dict) -> dict:
finally:
reset_hermes_home_override(token)
- return _ok(rid, {"ok": all(applied.values()) if applied else True, "applied": applied})
+ result = {"ok": all(applied.values()) if applied else True, "applied": applied}
+ if confirm_message is not None:
+ # Model write pending user confirmation — same shape config.set
+ # returns, so clients reuse one confirm handler for both surfaces.
+ result["confirm_required"] = True
+ result["confirm_message"] = confirm_message
+ return _ok(rid, result)
except Exception as e:
return _err(rid, 5064, str(e))