Skip to content

The agent that grows with you

fix(usage-window): switch the TUI limit card's model via session.mutate on canonical connections

Tekniume4a1eb7c27e6
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.usageLimit.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.usageLimit.test.ts
new file mode 100644
index 00000000000..d72164b4410
--- /dev/null
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.usageLimit.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'
+import { getOverlayState, patchOverlayState } from '../app/overlayStore.js'
+import { getUiState, patchUiState } from '../app/uiStore.js'
+
+const ref = <T>(current: T) => ({ current })
+
+const limitEvent = {
+ payload: {
+ error_surface: {
+ code: 'usage_window',
+ usage_limit: {
+ gauge_id: 'day',
+ limit_name: 'daily',
+ message: 'You hit the daily limit.',
+ scope: 'all',
+ suggestions: [{ label: 'Free model', model: 'free/model', note: '', provider: 'nous' }]
+ }
+ },
+ text: 'You hit the daily limit.'
+ },
+ session_id: 'sess-1',
+ type: 'message.complete'
+}
+
+describe('the usage-limit card on a canonical connection', () => {
+ afterEach(() => {
+ patchOverlayState({ confirm: null })
+ })
+
+ it('switches this session with session.mutate (the owner refuses config.set model) and re-sends after it applied', async () => {
+ patchUiState({ info: { model: 'paid/model' } as any, sid: 'sess-1' })
+ const submit = vi.fn()
+
+ const request = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'session.resume') {
+ return { execution_generation: 2, revision: 4 }
+ }
+
+ if (method === 'session.mutate') {
+ return { execution_generation: 2, model: (params?.payload as { model: string }).model, status: 'applied' }
+ }
+
+ throw Object.assign(new Error('use_session_mutation_model'), { data: { reason: 'use_session_mutation_model' } })
+ })
+
+ const ctx = {
+ composer: {
+ dequeue: () => undefined,
+ queueEditRef: ref<null | number>(null),
+ sendQueued: vi.fn(),
+ setInput: vi.fn()
+ },
+ gateway: {
+ gw: { isCanonical: true, request },
+ rpc: (method: string, params?: Record<string, unknown>) => request(method, params)
+ },
+ session: {
+ STARTUP_RESUME_ID: '',
+ colsRef: ref(80),
+ newSession: vi.fn(),
+ resetSession: vi.fn(),
+ resumeById: vi.fn(),
+ setCatalog: vi.fn()
+ },
+ submission: { submitRef: { current: submit } },
+ system: { bellOnComplete: false, sys: vi.fn() },
+ transcript: { appendMessage: vi.fn(), panel: vi.fn(), setHistoryItems: vi.fn() },
+ voice: { setProcessing: vi.fn(), setRecording: vi.fn(), setVoiceEnabled: vi.fn() }
+ } as any
+
+ createGatewayEventHandler(ctx)(limitEvent as any)
+ getOverlayState().confirm!.onConfirm()
+
+ await vi.waitFor(() => expect(submit).toHaveBeenCalledWith('/retry'))
+ expect(request).not.toHaveBeenCalledWith('config.set', expect.anything())
+ expect(request).toHaveBeenCalledWith(
+ 'session.mutate',
+ expect.objectContaining({
+ operation: 'model',
+ payload: { model: 'free/model', provider: 'nous' },
+ session_id: 'sess-1'
+ })
+ )
+ expect(getUiState().info?.model).toBe('free/model')
+ })
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 508bc078804..c4c4c2c55df 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -48,7 +48,11 @@ import { markBubbleShown, newlyStartedRows } from './pendingBubbles.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
import { forgetServerRequest } from './serverRequestStore.js'
import { noteCanonicalCompletion } from './slash/canonicalSessionCommands.js'
-import { mutateCanonicalSession, openModelConfirmation } from './slash/canonicalSessionControls.js'
+import {
+ mutateCanonicalSession,
+ openModelConfirmation,
+ switchCanonicalModel
+} from './slash/canonicalSessionControls.js'
import { loadSlashCatalog, refreshSlashCatalogOnSkillsChange } from './slashCatalog.js'
import { reportStartupLatency } from './startupLatency.js'
import { markNextSubmitVoice } from './submissionCore.js'
@@ -740,7 +744,7 @@ function confirmBillingWall(
/** A window plan's limit: one ask, switch to the plan's recommended model (this session) and re-send,
* or dismiss. The sentence is already in the transcript. */
function confirmUsageLimit(usageLimit: UsageLimit, ctx: GatewayEventHandlerContext): void {
- const { rpc } = ctx.gateway
+ const { gw, rpc } = ctx.gateway
const { sys } = ctx.system
const { submitRef } = ctx.submission
const dialog = usageLimitDialog(usageLimit)
@@ -757,10 +761,21 @@ function confirmUsageLimit(usageLimit: UsageLimit, ctx: GatewayEventHandlerConte
return
}
+ const sid = getUiState().sid
+
+ // The owner refuses `config.set model`: a pick is the session-scoped `session.mutate`.
+ if (gw.isCanonical && sid) {
+ void switchCanonicalModel(gw, sid, dialog.switchValue, sys, () => submitRef.current('/retry')).catch(
+ (e: unknown) => sys(`error: ${rpcErrorMessage(e)}`)
+ )
+
+ return
+ }
+
// Switch first; re-send only once it landed (or was queued for the next turn).
void rpc<{ deferred?: boolean; value?: string }>('config.set', {
key: 'model',
- session_id: getUiState().sid,
+ session_id: sid,
value: dialog.switchValue
})
.then(r => {
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index cfbe3616b1b..ff22c5d03c1 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto'
import { introMsg, toTranscriptMessages } from '../../domain/messages.js'
import { CANONICAL_REASONING_EFFORTS, TUI_SESSION_MODEL_FLAG } from '../../domain/slash.js'
import { t } from '../../i18n/runtime.js'
-import { asRpcResult } from '../../lib/rpc.js'
+import { asRpcResult, rpcErrorMessage } from '../../lib/rpc.js'
import { patchOverlayState } from '../overlayStore.js'
import { getUiState, patchUiState } from '../uiStore.js'
@@ -263,7 +263,7 @@ async function applyBranchResult(result: CanonicalControlResult, arg: string, ct
}
}
-function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {
+function applyModelResult(result: CanonicalControlResult, sys: (text: string) => void) {
if (!result.model) {
throw new Error(t('session.main.invalidModelSwitchResponse'))
}
@@ -271,7 +271,7 @@ function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {
if (result.status === 'deferred') {
// A turn is running: the owner keeps the pick for the next turn, and session.info repaints the
// model when it lands (or a refusal / confirmation follows on session.updated).
- ctx.transcript.sys(t('slashCmd.session.model.switchedDeferred', result.model))
+ sys(t('slashCmd.session.model.switchedDeferred', result.model))
return
}
@@ -286,11 +286,52 @@ function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {
tools: state.info?.tools ?? {}
}
}))
- ctx.transcript.sys(t('session.main.modelSwitched', result.model))
+ sys(t('session.main.modelSwitched', result.model))
if (typeof result.effort === 'string') {
// The level committed in the same selection (a deferred result carries none yet).
- ctx.transcript.sys(t('slashCmd.session.reasoning.current', result.effort))
+ sys(t('slashCmd.session.reasoning.current', result.effort))
+ }
+}
+
+/** A model switch made outside `/model` (a window plan's limit card): the same revision-fenced
+ * `session.mutate` and guarded-target ask. `onApplied` runs only once the switch committed now,
+ * never for a refusal, a declined ask, or a pick deferred behind a running turn. */
+export async function switchCanonicalModel(
+ gw: MutationGateway,
+ sid: string,
+ arg: string,
+ sys: (text: string) => void,
+ onApplied: () => void,
+ confirm?: string
+): Promise<void> {
+ const mutation = await mutateCanonicalSession(gw, sid, 'model', arg, undefined, confirm)
+
+ if (!mutation) {
+ return
+ }
+
+ const { result } = mutation
+
+ if (needsModelConfirmation(result)) {
+ if (confirm) {
+ return sys(t('slashCmd.session.model.confirmStale'))
+ }
+
+ return openModelConfirmation(
+ result.confirm_message,
+ result.target_model ?? arg.trim().split(/\s+/)[0] ?? '',
+ () =>
+ void switchCanonicalModel(gw, sid, arg, sys, onApplied, result.confirm).catch((e: unknown) =>
+ sys(`error: ${rpcErrorMessage(e)}`)
+ )
+ )
+ }
+
+ applyModelResult(result, sys)
+
+ if (result.status !== 'deferred') {
+ onApplied()
}
}
@@ -367,7 +408,7 @@ export async function runCanonicalSessionControl(
} else if (operation === 'branch') {
await applyBranchResult(result, arg, ctx)
} else if (operation === 'model') {
- applyModelResult(result, ctx)
+ applyModelResult(result, ctx.transcript.sys)
} else if (result.status === 'preview') {
// `--preview` is a read-only report; nothing to re-hydrate.
ctx.transcript.sys((result.lines as string[]).join('\n'))
diff --git a/ui-tui/src/lib/billingDialog.ts b/ui-tui/src/lib/billingDialog.ts
index 5844734ebf2..63c8ef2e117 100644
--- a/ui-tui/src/lib/billingDialog.ts
+++ b/ui-tui/src/lib/billingDialog.ts
@@ -41,7 +41,7 @@ export function billingDialogCopy(block: BillingBlock): BillingDialogCopy {
}
export interface UsageLimitDialog extends BillingDialogCopy {
- /** `config.set model` value for the switch (this session only), or null: open /topup instead. */
+ /** `/model` argument for the switch (this session only), or null: open /topup instead. */
switchValue: null | string
}