The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): show a refused or guarded next-turn model pick, and restore the committed model
Teknium11c22938cbbc
diff --git a/locales/_keys.tui.json b/locales/_keys.tui.jsonindex df955c31609..78c3258ab11 100644--- a/locales/_keys.tui.json+++ b/locales/_keys.tui.json@@ -1019,6 +1019,7 @@"slashCmd.session.model.cancel","slashCmd.session.model.confirmStale","slashCmd.session.model.confirmTitle",+ "slashCmd.session.model.deferredRefused","slashCmd.session.model.expensiveDetail","slashCmd.session.model.expensiveTitle","slashCmd.session.model.invalidResponse",diff --git a/locales/af.tui.yaml b/locales/af.tui.yamlindex 6e20f0a167d..706b32d837a 100644--- a/locales/af.tui.yaml+++ b/locales/af.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "gebruik: /indicator [{0}]"slashCmd.session.model.cancel: "Kanselleer"slashCmd.session.model.confirmStale: "Model nie gewissel nie: die sessie het verander voordat die bevestiging aangekom het; voer /model weer uit."slashCmd.session.model.confirmTitle: "Bevestig modelwissel na {0}"+slashCmd.session.model.deferredRefused: "modelwissel na {0} het misluk ({1}); die huidige model bly"slashCmd.session.model.expensiveDetail: "Hierdie model se bekende pryse is buitengewoon hoog."slashCmd.session.model.expensiveTitle: "Duur modelkeuse"slashCmd.session.model.invalidResponse: "fout: ongeldige antwoord: modelwisseling"diff --git a/locales/ar.tui.yaml b/locales/ar.tui.yamlindex c8c253c893e..ccfa1d4c84a 100644--- a/locales/ar.tui.yaml+++ b/locales/ar.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "الاستخدام: /indicator [{0}]"slashCmd.session.model.cancel: "إلغاء"slashCmd.session.model.confirmStale: "لم يتم تبديل النموذج: تغيّرت الجلسة قبل وصول التأكيد؛ شغّل /model مرة أخرى."slashCmd.session.model.confirmTitle: "تأكيد تبديل النموذج إلى {0}"+slashCmd.session.model.deferredRefused: "فشل تبديل النموذج إلى {0} ({1})؛ يبقى النموذج الحالي"slashCmd.session.model.expensiveDetail: "لهذا النموذج تسعير معروف مرتفع بشكل غير معتاد."slashCmd.session.model.expensiveTitle: "اختيار نموذج مكلف"slashCmd.session.model.invalidResponse: "خطأ: استجابة غير صالحة: تبديل النموذج"diff --git a/locales/de.tui.yaml b/locales/de.tui.yamlindex 00759897fbf..78d98b35b3c 100644--- a/locales/de.tui.yaml+++ b/locales/de.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "Verwendung: /indicator [{0}]"slashCmd.session.model.cancel: "Abbrechen"slashCmd.session.model.confirmStale: "Modell nicht gewechselt: Die Sitzung hat sich vor der Bestätigung geändert; führe /model erneut aus."slashCmd.session.model.confirmTitle: "Modellwechsel zu {0} bestätigen"+slashCmd.session.model.deferredRefused: "Modellwechsel zu {0} fehlgeschlagen ({1}); das aktuelle Modell bleibt"slashCmd.session.model.expensiveDetail: "Dieses Modell hat ungewöhnlich hohe bekannte Preise."slashCmd.session.model.expensiveTitle: "Teures Modell gewählt"slashCmd.session.model.invalidResponse: "Fehler: ungültige Antwort: Modellwechsel"diff --git a/locales/es.tui.yaml b/locales/es.tui.yamlindex 26bc457c7d5..85d744b7682 100644--- a/locales/es.tui.yaml+++ b/locales/es.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "uso: /indicator [{0}]"slashCmd.session.model.cancel: "Cancelar"slashCmd.session.model.confirmStale: "Modelo no cambiado: la sesión cambió antes de que llegara la confirmación; ejecuta /model de nuevo."slashCmd.session.model.confirmTitle: "Confirmar cambio de modelo a {0}"+slashCmd.session.model.deferredRefused: "el cambio de modelo a {0} falló ({1}); se mantiene el modelo actual"slashCmd.session.model.expensiveDetail: "Este modelo tiene un precio conocido inusualmente alto."slashCmd.session.model.expensiveTitle: "Selección de modelo costoso"slashCmd.session.model.invalidResponse: "error: respuesta no válida: cambio de modelo"diff --git a/locales/fr.tui.yaml b/locales/fr.tui.yamlindex c7e9a9afc0a..f69767f0ca8 100644--- a/locales/fr.tui.yaml+++ b/locales/fr.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "usage : /indicator [{0}]"slashCmd.session.model.cancel: "Annuler"slashCmd.session.model.confirmStale: "Modèle non changé : la session a changé avant l'arrivée de la confirmation ; relancez /model."slashCmd.session.model.confirmTitle: "Confirmer le passage au modèle {0}"+slashCmd.session.model.deferredRefused: "le changement de modèle vers {0} a échoué ({1}) ; le modèle actuel est conservé"slashCmd.session.model.expensiveDetail: "Ce modèle a une tarification connue anormalement élevée."slashCmd.session.model.expensiveTitle: "Sélection d'un modèle coûteux"slashCmd.session.model.invalidResponse: "erreur : réponse invalide : changement de modèle"diff --git a/locales/ga.tui.yaml b/locales/ga.tui.yamlindex 37f3207d77d..bc907b1fa78 100644--- a/locales/ga.tui.yaml+++ b/locales/ga.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "úsáid: /indicator [{0}]"slashCmd.session.model.cancel: "Cealaigh"slashCmd.session.model.confirmStale: "Níor athraíodh an tsamhail: d'athraigh an seisiún sular tháinig an deimhniú; rith /model arís."slashCmd.session.model.confirmTitle: "Deimhnigh athrú samhla go {0}"+slashCmd.session.model.deferredRefused: "theip ar athrú samhla go {0} ({1}); fanann an tsamhail reatha"slashCmd.session.model.expensiveDetail: "Tá praghsáil aitheanta na samhla seo neamhghnách ard."slashCmd.session.model.expensiveTitle: "Samhail chostasach roghnaithe"slashCmd.session.model.invalidResponse: "earráid: freagra neamhbhailí: athrú samhla"diff --git a/locales/hu.tui.yaml b/locales/hu.tui.yamlindex 4ca1296af99..a9ce8a4d079 100644--- a/locales/hu.tui.yaml+++ b/locales/hu.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "használat: /indicator [{0}]"slashCmd.session.model.cancel: "Mégse"slashCmd.session.model.confirmStale: "A modell nem váltott: a munkamenet megváltozott a megerősítés előtt; futtasd újra a /model parancsot."slashCmd.session.model.confirmTitle: "Modellváltás megerősítése erre: {0}"+slashCmd.session.model.deferredRefused: "a modellváltás erre: {0} sikertelen ({1}); a jelenlegi modell marad"slashCmd.session.model.expensiveDetail: "Ennek a modellnek szokatlanul magas az ismert ára."slashCmd.session.model.expensiveTitle: "Drága modell kiválasztása"slashCmd.session.model.invalidResponse: "hiba: érvénytelen válasz: modellváltás"diff --git a/locales/it.tui.yaml b/locales/it.tui.yamlindex 768a5d7949e..e6cf492c2f6 100644--- a/locales/it.tui.yaml+++ b/locales/it.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "uso: /indicator [{0}]"slashCmd.session.model.cancel: "Annulla"slashCmd.session.model.confirmStale: "Modello non cambiato: la sessione è cambiata prima della conferma; esegui di nuovo /model."slashCmd.session.model.confirmTitle: "Conferma il cambio di modello a {0}"+slashCmd.session.model.deferredRefused: "cambio modello a {0} non riuscito ({1}); resta il modello attuale"slashCmd.session.model.expensiveDetail: "Questo modello ha un prezzo noto insolitamente alto."slashCmd.session.model.expensiveTitle: "Selezione di un modello costoso"slashCmd.session.model.invalidResponse: "errore: risposta non valida: cambio modello"diff --git a/locales/ja.tui.yaml b/locales/ja.tui.yamlindex c8f663dd0a3..a8a1fb7869c 100644--- a/locales/ja.tui.yaml+++ b/locales/ja.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "使い方: /indicator [{0}]"slashCmd.session.model.cancel: "キャンセル"slashCmd.session.model.confirmStale: "モデルは切り替わっていません: 確認が届く前にセッションが変更されました。もう一度 /model を実行してください。"slashCmd.session.model.confirmTitle: "{0} へのモデル切り替えを確認"+slashCmd.session.model.deferredRefused: "{0} へのモデル切り替えに失敗しました({1})。現在のモデルを維持します"slashCmd.session.model.expensiveDetail: "このモデルは既知の料金が著しく高額です。"slashCmd.session.model.expensiveTitle: "高額なモデルの選択"slashCmd.session.model.invalidResponse: "エラー: 無効な応答: モデル切り替え"diff --git a/locales/ko.tui.yaml b/locales/ko.tui.yamlindex b21d00c704f..5e74103c681 100644--- a/locales/ko.tui.yaml+++ b/locales/ko.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "사용법: /indicator [{0}]"slashCmd.session.model.cancel: "취소"slashCmd.session.model.confirmStale: "모델이 전환되지 않았습니다: 확인이 도착하기 전에 세션이 변경되었습니다. /model을 다시 실행하세요."slashCmd.session.model.confirmTitle: "{0}(으)로 모델 전환 확인"+slashCmd.session.model.deferredRefused: "{0}(으)로 모델 전환 실패 ({1}); 현재 모델을 유지합니다"slashCmd.session.model.expensiveDetail: "이 모델은 알려진 가격이 유난히 높아요."slashCmd.session.model.expensiveTitle: "고비용 모델 선택"slashCmd.session.model.invalidResponse: "오류: 잘못된 응답: 모델 전환"diff --git a/locales/pt.tui.yaml b/locales/pt.tui.yamlindex 65e8bbe3602..883f8f31aa9 100644--- a/locales/pt.tui.yaml+++ b/locales/pt.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "uso: /indicator [{0}]"slashCmd.session.model.cancel: "Cancelar"slashCmd.session.model.confirmStale: "Modelo não trocado: a sessão mudou antes de a confirmação chegar; execute /model novamente."slashCmd.session.model.confirmTitle: "Confirmar troca de modelo para {0}"+slashCmd.session.model.deferredRefused: "a troca de modelo para {0} falhou ({1}); o modelo atual é mantido"slashCmd.session.model.expensiveDetail: "Este modelo tem um preço conhecido incomumente alto."slashCmd.session.model.expensiveTitle: "Seleção de modelo caro"slashCmd.session.model.invalidResponse: "erro: resposta inválida: troca de modelo"diff --git a/locales/ru.tui.yaml b/locales/ru.tui.yamlindex e2d05eb17c7..e49b0618255 100644--- a/locales/ru.tui.yaml+++ b/locales/ru.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "Использование: /indicator [{0}]"slashCmd.session.model.cancel: "Отмена"slashCmd.session.model.confirmStale: "Модель не переключена: сессия изменилась до подтверждения; выполните /model снова."slashCmd.session.model.confirmTitle: "Подтвердить переключение модели на {0}"+slashCmd.session.model.deferredRefused: "не удалось переключить модель на {0} ({1}); остаётся текущая модель"slashCmd.session.model.expensiveDetail: "У этой модели необычно высокая известная цена."slashCmd.session.model.expensiveTitle: "Выбрана дорогая модель"slashCmd.session.model.invalidResponse: "ошибка: некорректный ответ: смена модели"diff --git a/locales/tr.tui.yaml b/locales/tr.tui.yamlindex bb63b50842c..6498f42bdcb 100644--- a/locales/tr.tui.yaml+++ b/locales/tr.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "kullanım: /indicator [{0}]"slashCmd.session.model.cancel: "İptal"slashCmd.session.model.confirmStale: "Model değiştirilmedi: onay ulaşmadan oturum değişti; /model komutunu yeniden çalıştırın."slashCmd.session.model.confirmTitle: "{0} modeline geçişi onayla"+slashCmd.session.model.deferredRefused: "{0} modeline geçiş başarısız oldu ({1}); mevcut model korunuyor"slashCmd.session.model.expensiveDetail: "Bu modelin bilinen fiyatı alışılmadık derecede yüksek."slashCmd.session.model.expensiveTitle: "Pahalı model seçimi"slashCmd.session.model.invalidResponse: "hata: geçersiz yanıt: model geçişi"diff --git a/locales/uk.tui.yaml b/locales/uk.tui.yamlindex 922203c3891..b7085c6f4b8 100644--- a/locales/uk.tui.yaml+++ b/locales/uk.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "використання: /indicator [{0}]"slashCmd.session.model.cancel: "Скасувати"slashCmd.session.model.confirmStale: "Модель не змінено: сесія змінилася до підтвердження; виконайте /model знову."slashCmd.session.model.confirmTitle: "Підтвердити зміну моделі на {0}"+slashCmd.session.model.deferredRefused: "не вдалося перемкнути модель на {0} ({1}); лишається поточна модель"slashCmd.session.model.expensiveDetail: "Відома вартість цієї моделі незвично висока."slashCmd.session.model.expensiveTitle: "Вибір дорогої моделі"slashCmd.session.model.invalidResponse: "помилка: некоректна відповідь: зміна моделі"diff --git a/locales/zh-hant.tui.yaml b/locales/zh-hant.tui.yamlindex 8d51511d86a..68a7b943041 100644--- a/locales/zh-hant.tui.yaml+++ b/locales/zh-hant.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "用法:/indicator [{0}]"slashCmd.session.model.cancel: "取消"slashCmd.session.model.confirmStale: "未切換模型:確認送達前工作階段已變更;請再次執行 /model。"slashCmd.session.model.confirmTitle: "確認切換模型至 {0}"+slashCmd.session.model.deferredRefused: "切換模型至 {0} 失敗({1});保留目前模型"slashCmd.session.model.expensiveDetail: "此模型的已知定價異常偏高。"slashCmd.session.model.expensiveTitle: "選擇了高價模型"slashCmd.session.model.invalidResponse: "錯誤:無效回應:模型切換"diff --git a/locales/zh.tui.yaml b/locales/zh.tui.yamlindex 400c5762fe1..60d7eb61469 100644--- a/locales/zh.tui.yaml+++ b/locales/zh.tui.yaml@@ -1039,6 +1039,7 @@ slashCmd.session.indicator.usage: "用法:/indicator [{0}]"slashCmd.session.model.cancel: "取消"slashCmd.session.model.confirmStale: "未切换模型:确认送达前会话已更改;请再次运行 /model。"slashCmd.session.model.confirmTitle: "确认切换模型到 {0}"+slashCmd.session.model.deferredRefused: "切换模型至 {0} 失败({1});保留当前模型"slashCmd.session.model.expensiveDetail: "该模型的已知定价异常偏高。"slashCmd.session.model.expensiveTitle: "选择了高价模型"slashCmd.session.model.invalidResponse: "错误:无效响应:模型切换"diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.deferredPick.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.deferredPick.test.tsnew file mode 100644index 00000000000..1844d1c67c7--- /dev/null+++ b/ui-tui/src/__tests__/createGatewayEventHandler.deferredPick.test.ts@@ -0,0 +1,51 @@+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 ctx = (sys = vi.fn()) =>+ ({+ composer: { dequeue: () => undefined, queueEditRef: ref<null | number>(null), sendQueued: vi.fn(), setInput: vi.fn() },+ gateway: { gw: { request: vi.fn(async () => null) }, rpc: vi.fn(async () => null) },+ session: { STARTUP_RESUME_ID: '', colsRef: ref(80), newSession: vi.fn(), resetSession: vi.fn(), resumeById: vi.fn(), setCatalog: vi.fn() },+ submission: { submitRef: { current: vi.fn() } },+ system: { bellOnComplete: false, sys },+ transcript: { appendMessage: vi.fn(), panel: vi.fn(), setHistoryItems: vi.fn() },+ voice: { setProcessing: vi.fn(), setRecording: vi.fn(), setVoiceEnabled: vi.fn() }+ }) as any++describe('a model pick made during a turn that did not apply at the boundary', () => {+ afterEach(() => { patchOverlayState({ confirm: null }) })++ it('names the refusal and shows the committed model again', () => {+ patchUiState({ info: { model: 'picked' } as any, sid: 'sess-1' })+ const sys = vi.fn()++ createGatewayEventHandler(ctx(sys))({ payload: { model: 'frozen', operation: 'model', reason: 'model_resolution_failed',+ session_id: 'sess-1', status: 'refused', target_model: 'picked' }, session_id: 'sess-1', type: 'session.updated' } as any)++ expect(sys).toHaveBeenCalledWith(expect.stringContaining('model_resolution_failed'))+ expect(sys.mock.calls[0][0]).toContain('picked')+ expect(getUiState().info?.model).toBe('frozen')+ })++ it('asks before applying a guarded pick, and the answer re-sends with the owner token', async () => {+ patchUiState({ info: { model: 'frozen' } as any, sid: 'sess-1' })+ const context = ctx()+ context.gateway.gw.request = vi.fn(async (method: string) =>+ method === 'session.resume' ? { execution_generation: 2, revision: 4 } : { model: 'guarded', session_id: 'sess-1' })++ createGatewayEventHandler(context)({ payload: { confirm: 'owner-token', confirm_message: 'Costly', operation: 'model',+ payload: { model: 'guarded' }, session_id: 'sess-1', status: 'confirmation_required', target_model: 'guarded' },+ session_id: 'sess-1', type: 'session.updated' } as any)++ const ask = getOverlayState().confirm+ expect(ask?.detail).toBe('Costly')+ ask?.onConfirm()+ await vi.waitFor(() => expect(context.gateway.gw.request).toHaveBeenCalledTimes(2))+ expect(context.gateway.gw.request.mock.calls.at(-1)[1]).toMatchObject({ operation: 'model', payload: { confirm: 'owner-token', model: 'guarded' } })+ })+})diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex c4eab443162..5fc9297f30f 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -47,6 +47,7 @@ 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 } from './slash/canonicalSessionControls.js'import { loadSlashCatalog } from './slashCatalog.js'import { reportStartupLatency } from './startupLatency.js'import { markNextSubmitVoice } from './submissionCore.js'@@ -575,6 +576,51 @@ function handleErrorEvent(setStatus('ready')}+/** A model pick made during a turn resolves at the next turn boundary. The owner announces a pick+ * that did not apply on `session.updated`: a refusal is named and the committed model shown again;+ * a guarded target asks with the same dialog as `/model`. Applied picks arrive as session.info. */+function applyDeferredPickOutcome(+ update: Record<string, unknown> | undefined,+ sid: null | string | undefined,+ gw: { request: (method: string, params?: Record<string, unknown>) => Promise<unknown> },+ sys: (text: string) => void+): void {+ if (update?.operation !== 'model' || !sid) {+ return+ }++ if (update.status === 'refused') {+ const info = getUiState().info++ if (info && typeof update.model === 'string' && update.model) {+ patchUiState({ info: { ...info, model: update.model, ...(typeof update.provider === 'string' ? { provider: update.provider } : {}) } })+ }++ sys(t('slashCmd.session.model.deferredRefused', String(update.target_model ?? ''), String(update.reason ?? 'refused')))++ return+ }++ if (update.status === 'confirmation_required' && typeof update.confirm === 'string') {+ const pick = (update.payload ?? {}) as { model?: string; provider?: string }+ const arg = `${pick.model ?? ''}${pick.provider ? ` --provider ${pick.provider}` : ''}`++ patchOverlayState({+ confirm: {+ cancelLabel: t('slashCmd.session.model.cancel'),+ confirmLabel: t('slashCmd.session.model.switchAnyway'),+ danger: true,+ detail: (update.confirm_message as string | undefined) || t('slashCmd.session.model.expensiveDetail'),+ onConfirm: () =>+ void mutateCanonicalSession(gw, sid, 'model', arg, undefined, update.confirm as string).catch((error: unknown) =>+ sys(`error: ${error instanceof Error ? error.message : String(error)}`)+ ),+ title: t('slashCmd.session.model.confirmTitle', String(update.target_model ?? pick.model ?? ''))+ }+ })+ }+}+interface SessionInfoSinks {appendMessage: (msg: Msg) => voidsetHistoryItems: GatewayEventHandlerContext['transcript']['setHistoryItems']@@ -1046,6 +1092,11 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:return+ case 'session.updated' as typeof ev.type:+ applyDeferredPickOutcome(ev.payload as Record<string, unknown> | undefined, sid, gw, sys)++ return+case 'session.replay_gap':// The authority retired this subscription (fanout overflow) while the// socket stayed healthy, so no reconnect will ever re-attach it and thediff --git a/ui-tui/src/i18n/en/slashCmd/session.ts b/ui-tui/src/i18n/en/slashCmd/session.tsindex 58d75067b13..ee90611c282 100644--- a/ui-tui/src/i18n/en/slashCmd/session.ts+++ b/ui-tui/src/i18n/en/slashCmd/session.ts@@ -41,6 +41,8 @@ export const slashCmdSessionEn = {cancel: 'Cancel',confirmStale: 'Model not switched: the session changed before the confirmation landed; run /model again.',confirmTitle: (model: string) => `Confirm model switch to ${model}`,+ // {0}=model picked during a turn, {1}=the owner's refusal reason+ deferredRefused: (model: string, reason: string) => `model switch to ${model} failed (${reason}); keeping the current model`,expensiveDetail: 'This model has unusually high known pricing.',expensiveTitle: 'Expensive model selection',invalidResponse: 'error: invalid response: model switch',