Skip to content

The agent that grows with you

fix(tui_gateway): ask the large-context confirm when a model is picked mid-turn

jonh-dev20cb63df9e6d
diff --git a/tests/tui_gateway/test_deferred_model_switch_confirm.py b/tests/tui_gateway/test_deferred_model_switch_confirm.py
index fccea5a72ba..849ae4eb674 100644
--- a/tests/tui_gateway/test_deferred_model_switch_confirm.py
+++ b/tests/tui_gateway/test_deferred_model_switch_confirm.py
@@ -15,6 +15,7 @@ possible. The user's pick silently reverted and the confirm was never offered
on this path at all.
"""
+import logging
import threading
import types
@@ -148,3 +149,67 @@ class TestGuardFailureIsNotFatal:
assert result["deferred"] is True
assert running_session["pending_model_switch"]["raw"] == GUARDED_MODEL
+
+LARGE_SESSION = 225_334
+SMALL_SESSION = 40_000
+
+def _live_agent(session, tokens, model="deepseek/deepseek-v4.1-flash"):
+ session["agent"] = types.SimpleNamespace(
+ model=model, context_compressor=types.SimpleNamespace(last_prompt_tokens=tokens))
+
+class TestLargeContextPickAsksBeforeStashing:
+ def test_large_session_is_asked_at_pick_time(self, running_session):
+ _live_agent(running_session, LARGE_SESSION)
+
+ result = _config_set_model(UNGUARDED_MODEL)["result"]
+
+ assert result["confirm_required"] is True, (
+ "the context-cache guard only saw the session size at turn start, where it can no longer "
+ "ask: the pick became an error toast and was dropped"
+ )
+ assert "LARGE CONTEXT MODEL SWITCH" in result["confirm_message"]
+ assert result["deferred"] is False
+ assert "pending_model_switch" not in running_session
+
+ def test_confirming_queues_the_pick(self, running_session):
+ _live_agent(running_session, LARGE_SESSION)
+
+ result = _config_set_model(UNGUARDED_MODEL, confirm_expensive_model=True)["result"]
+
+ assert result["deferred"] is True
+ assert running_session["pending_model_switch"]["confirm_expensive_model"] is True
+
+ def test_small_session_still_defers_without_asking(self, running_session):
+ _live_agent(running_session, SMALL_SESSION)
+
+ result = _config_set_model(UNGUARDED_MODEL)["result"]
+
+ assert result["deferred"] is True
+ assert result["confirm_required"] is False
+
+ def test_reselecting_the_live_model_is_not_a_switch(self, running_session):
+ _live_agent(running_session, LARGE_SESSION, model=UNGUARDED_MODEL)
+
+ result = _config_set_model(UNGUARDED_MODEL)["result"]
+
+ assert result["confirm_required"] is False
+
+class TestDroppedQueuedPickIsLogged:
+ def test_turn_start_drop_leaves_a_server_log_line(self, monkeypatch, caplog):
+ session = _session(pending_model_switch={
+ "raw": UNGUARDED_MODEL, "confirm_expensive_model": False,
+ "display_model": UNGUARDED_MODEL, "display_provider": ""})
+ monkeypatch.setattr(
+ server, "_apply_model_switch",
+ lambda *_a, **_kw: {"confirm_required": True, "confirm_message": "guarded"})
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda *a, **_kw: emitted.append(a))
+
+ with caplog.at_level(logging.WARNING):
+ server._apply_pending_model_switch("sid", session)
+
+ assert "dropped" in caplog.text and UNGUARDED_MODEL in caplog.text, (
+ "a dropped pick used to exist only as a client toast, invisible in server logs"
+ )
+ assert emitted and emitted[0][0] == "error"
+ assert "pending_model_switch" not in session
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index d96fea32de6..286dc3fb72c 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -81,7 +81,8 @@ def _stash_pending_model_switch(rid, key, value, session, confirmed, parsed):
pending_model = str(value)
pending_provider = (getattr(parsed, "explicit_provider", "") or "").strip()
if not confirmed:
- pending_warning = _pending_switch_selection_warning(pending_model, pending_provider)
+ pending_warning = _pending_switch_selection_warning(
+ pending_model, pending_provider, session.get("agent"))
if pending_warning is not None:
return _cfgset_model_ok(rid, key, pending_model, pending_warning, pending_warning, deferred=False)
# display_*: _session_info shows the user's pick while pending, not the live old model.
diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index 93f2572e365..6d22d0135b0 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -496,15 +496,19 @@ def _sync_agent_model_with_config(sid: str, session: dict) -> None:
platform="tui", user_config=getattr(session.get("agent"), "_notification_config", None))
-def _pending_switch_selection_warning(model: str, provider: str) -> str | None:
+def _pending_switch_selection_warning(model: str, provider: str, agent: Any = None) -> str | None:
"""Selection-guard message for a model queued mid-turn, or ``None``. Runs BEFORE the pick is
stashed (the client can still turn the response into a confirm prompt); only pre-resolution
- inputs exist so it can only under-fire — ``_apply_model_switch`` is the backstop."""
+ inputs exist for the model guards, so they can only under-fire — ``_apply_model_switch`` is the
+ backstop. The live ``agent`` supplies the context-cache guard's session size here, since at turn
+ start that guard can no longer ask and would drop the pick."""
if not model:
return None
try:
- from hermes_cli.model_selection_guards import combined_selection_warning
- warning = combined_selection_warning(model, provider=provider or None)
+ from hermes_cli.model_selection_guards import (
+ combined_selection_warning, selection_context_for_agent)
+ warning = combined_selection_warning(
+ model, provider=provider or None, selection_context=selection_context_for_agent(agent))
except Exception:
return None
return warning.message if warning is not None else None
diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.py
index 23b1cbb89a3..9c79c922e94 100644
--- a/tui_gateway/session_compression.py
+++ b/tui_gateway/session_compression.py
@@ -206,6 +206,8 @@ def _apply_pending_model_switch(sid: str, session: dict) -> None:
# Honour the expensive-model confirm: surface the warning and drop the switch rather than spend
# on a model the user never confirmed.
if result.get("confirm_required"):
+ logger.warning("Queued model switch to %s dropped for session %s: selection guard needs a confirm",
+ pending.get("display_model") or pending["raw"], sid)
_emit("error", sid, {"message": result.get("confirm_message") or result.get("warning") or ""})
except Exception as e:
_emit("error", sid, {"message": f"Could not switch model: {e}"})