Skip to content

The agent that grows with you

fix(usage-window): the limit card re-runs the turn only after the model switch applied

Teknium403ae95de1ce
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index a5ce8adddb1..b3fa07674db 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -24,6 +24,7 @@ vi.mock('@/hermes', async importActual => ({
getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: '' })),
getSession: vi.fn()
}))
+vi.mock('@/store/confirm', () => ({ confirm: vi.fn(async () => false) }))
vi.mock('@/store/gateway', async importActual => ({
...(await importActual<Record<string, unknown>>()),
requestGatewayForAgent: vi.fn(),
@@ -32,6 +33,7 @@ vi.mock('@/store/gateway', async importActual => ({
const { getLatestSessionMessages, getSession, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } = await import('@/hermes')
const { requestGatewayForAgent, requestGatewayForProfile } = await import('@/store/gateway')
+const { confirm } = await import('@/store/confirm')
const row = (over: Partial<SessionInfo>): SessionInfo =>
({
@@ -685,6 +687,28 @@ describe('useSessionTileDelegate resumeTile', () => {
})
})
+describe('useSessionTileDelegate switchSessionModel', () => {
+ it('answers applied only after a guarded target is confirmed, and never on "keep current model"', async () => {
+ const asked = { key: 'model', session_id: 'rt-1', value: 'example/model-a --provider nous --session' }
+
+ const requestGateway = vi.fn(async (_method: string, params: Record<string, unknown>) =>
+ params.confirm_expensive_model ? {} : { confirm_message: 'Large model', confirm_required: true }
+ )
+
+ renderTile(requestGateway)
+ const switchSessionModel = sessionTileDelegate()!.switchSessionModel!
+
+ vi.mocked(confirm).mockResolvedValueOnce(false)
+ await expect(switchSessionModel('rt-1', 'example/model-a', 'nous')).resolves.toBe(false)
+ expect(requestGateway).toHaveBeenCalledTimes(1)
+ expect(requestGateway).toHaveBeenCalledWith('config.set', asked)
+
+ vi.mocked(confirm).mockResolvedValueOnce(true)
+ await expect(switchSessionModel('rt-1', 'example/model-a', 'nous')).resolves.toBe(true)
+ expect(requestGateway).toHaveBeenLastCalledWith('config.set', { ...asked, confirm_expensive_model: true })
+ })
+})
+
describe('useSessionTileDelegate retireBusyClaim', () => {
it('retires a stale busy claim through the session-state write path (#93059)', () => {
const busyState = {
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index be476e72427..a1effde9c31 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -14,6 +14,7 @@ import {
import { translateNow } from '@/i18n/runtime'
import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
import { markReasoningEffortPending } from '@/lib/chat-runtime'
+import { type GuardedModelSwitchResult, surfaceModelSwitchConfirm } from '@/lib/guarded-model-switch'
import { noteMessageSent } from '@/store/desktop-metrics'
import { notify } from '@/store/notifications'
import {
@@ -268,6 +269,39 @@ export function useSessionTileDelegate({
executeSlash: async (rawCommand, sessionId, options) => {
await executeSlashCommand(rawCommand, { sessionId, ...options })
},
+ // The picker's wire (config.set model), always --session (never the profile default), with a
+ // guarded target asked through the ONE shared confirm flow and awaited: true only once the switch
+ // applied (or is queued for the next turn start), so a caller can safely re-run a turn on it;
+ // false when the user kept the current model. A refused switch throws.
+ switchSessionModel: async (runtimeId, model, provider) => {
+ const storedSessionId = storedSessionIdForRuntime(runtimeId)
+
+ const request = (confirmExpensiveModel: boolean) => {
+ const params = {
+ key: 'model',
+ session_id: runtimeId,
+ value: `${model} --provider ${provider} --session`,
+ ...(confirmExpensiveModel ? { confirm_expensive_model: true } : {})
+ }
+
+ return storedSessionId
+ ? requestForStoredSession<GuardedModelSwitchResult>(storedSessionId, 'config.set', params)
+ : requestGateway<GuardedModelSwitchResult>('config.set', params)
+ }
+
+ const result = await request(false)
+
+ if (!result?.confirm_required) {
+ return true
+ }
+
+ return surfaceModelSwitchConfirm({
+ confirmMessage: result.confirm_message,
+ failureMessage: translateNow('desktop.modelSwitchFailed'),
+ model,
+ requestConfirmed: () => request(true)
+ })
+ },
// Gateway reconnect (sleep/wake, backend respawn): every stored→runtime
// binding recorded pre-reconnect points at a runtime id the respawned
// backend no longer knows. Drop the map so resumeTile's warm path can't
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
index 3b6b40bdd93..c2cfe5ccde2 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
@@ -416,9 +416,9 @@ describe("a window plan's limit: one-click switch and credits (no silent switch)
})
it('switches THIS session to the recommended model, then re-runs the turn', async () => {
- const executeSlash = vi.fn(async () => {})
+ const switchSessionModel = vi.fn(async () => true)
const onReload = vi.fn(async () => {})
- setSessionTileDelegate({ executeSlash } as unknown as SessionTileDelegate)
+ setSessionTileDelegate({ switchSessionModel } as unknown as SessionTileDelegate)
$activeSessionId.set('rt-1')
render(
@@ -430,7 +430,7 @@ describe("a window plan's limit: one-click switch and credits (no silent switch)
fireEvent.click(await screen.findByRole('button', { name: 'Switch to Model Free (free)' }))
await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))
- expect(executeSlash).toHaveBeenCalledWith('/model example/model-free:free --provider nous --session', 'rt-1')
+ expect(switchSessionModel).toHaveBeenCalledWith('rt-1', 'example/model-free:free', 'nous')
// No balance: the credits way on is Billing, labelled for what it does.
expect(screen.getByRole('button', { name: 'Open billing settings' })).toBeTruthy()
expect(screen.queryByRole('button', { name: 'Turn on Keep going on credits' })).toBeNull()
@@ -438,6 +438,28 @@ describe("a window plan's limit: one-click switch and credits (no silent switch)
expect(screen.queryByRole('button', { name: 'Switch provider' })).toBeNull()
})
+ it('re-runs nothing while the switch is unconfirmed or the user keeps the current model', async () => {
+ // The gateway asked to confirm a guarded target and the user kept the current model.
+ const switchSessionModel = vi.fn(async () => false)
+ const executeSlash = vi.fn(async () => {})
+ const onReload = vi.fn(async () => {})
+ setSessionTileDelegate({ executeSlash, switchSessionModel } as unknown as SessionTileDelegate)
+ $activeSessionId.set('rt-1')
+
+ render(
+ <MemoryRouter>
+ <Harness assistant={limitMessage('add_credits')} onReload={onReload} />
+ </MemoryRouter>
+ )
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Switch to Model Free (free)' }))
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0))
+ })
+
+ expect(onReload).not.toHaveBeenCalled()
+ })
+
it('with a balance and Keep going off, offers to turn on Keep going (a lasting setting)', async () => {
render(
<MemoryRouter>
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index 21a5b0ce3cf..f5904a1722d 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -754,9 +754,10 @@ const CompressConversationAction: FC<{ label: string }> = ({ label }) => {
// usage_window: "Switch to Model A" — the plan's recommended model that
// still works past the limit (agent/plan_limits.py picked it). Switches THIS
-// session through the same slash path a typed `/model <id> --provider nous
-// --session` takes (session.info repaints the composer), then re-runs the
-// refused turn. Session-only on purpose: the user's default stays put.
+// session (session.info repaints the composer), then re-runs the refused turn
+// only once the switch applied: a guarded target waits for the user's answer,
+// and keeping the current model re-runs nothing. Session-only on purpose: the
+// user's default stays put.
const SwitchToModelAction: FC<{ suggestion: UsageLimitSuggestion }> = ({ suggestion }) => {
const { t } = useI18n()
const copy = t.assistant.thread
@@ -766,10 +767,10 @@ const SwitchToModelAction: FC<{ suggestion: UsageLimitSuggestion }> = ({ suggest
const [busy, setBusy] = useState(false)
const switchAndRetry = useCallback(async () => {
- const delegate = sessionTileDelegate()
+ const switchSessionModel = sessionTileDelegate()?.switchSessionModel
- if (!sessionId || !delegate) {
- notifyError(new Error('slash delegate unavailable'), copy.errorSwitchModelFailed)
+ if (!sessionId || !switchSessionModel) {
+ notifyError(new Error('session delegate unavailable'), copy.errorSwitchModelFailed)
return
}
@@ -778,8 +779,9 @@ const SwitchToModelAction: FC<{ suggestion: UsageLimitSuggestion }> = ({ suggest
setBusy(true)
try {
- await delegate.executeSlash(`/model ${suggestion.model} --provider ${suggestion.provider} --session`, sessionId)
- aui.message().reload()
+ if (await switchSessionModel(sessionId, suggestion.model, suggestion.provider)) {
+ aui.message().reload()
+ }
} catch (error) {
notifyError(error, copy.errorSwitchModelFailed)
} finally {
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index c1e8c8094d7..c5b38a21bce 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -2179,11 +2179,11 @@ export interface SessionTileDelegate {
branchSessionAtMessage(storedSessionId: string, runtimeId: string, messageId: string): Promise<boolean>
/** Delete a stored session (the sidebar's delete, incl. tile cleanup). */
deleteSession(storedSessionId: string): Promise<void>
- /** Run a slash command against a tile's session (app-level effects — e.g.
- * branch/handoff — act on the main surface, as they should). */
+ /** Run a slash command against a tile's session (app-level effects, e.g. branch/handoff, act on the main surface). */
executeSlash(rawCommand: string, sessionId: string, options?: { typed?: boolean }): Promise<void>
/** Interrupt a tile's running turn. */
interruptSession(runtimeId: string): Promise<void>
+ switchSessionModel?(runtimeId: string, model: string, provider: string): Promise<boolean>
/** Drop the wiring cache's stored→runtime bindings. Called on gateway
* reconnect: a respawned backend re-mints runtime ids, so every binding
* recorded before the reconnect is suspect — without this, `resumeTile`'s