Skip to content

The agent that grows with you

fix(cli): ask the owner's model guard; leave the ended session's model alone

unsupportedpastels7bda2a336802
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 2d56f9e9c9b..d1483a4f798 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1048,7 +1048,11 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
):
self._restore_telegram_thread_id_after_split(agent_session_id)
runner._sync_telegram_topic_binding(src, entry, reason="agent-run-compression")
- runner._sync_session_model_from_agent(agent_session_id, agent)
+ from gateway.session_cli_turn import cli_turn
+ if not cli_turn(ctx.inbound_message_id).get("model_override"):
+ # A `/model --once` / `/moa` turn ran another route for this admission only: the row keeps
+ # the session's model, or a /resume would come back on the one-turn model.
+ runner._sync_session_model_from_agent(agent_session_id, agent)
# history_offset=0 whenever the agent's message list lost the original history prefix
# (split OR in-place compaction): the returned `messages` is the compacted set, persist all
# of it; slicing past the pre-compaction length would drop everything.
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 30cb28683fe..7302c8a8d6e 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -677,6 +677,8 @@ class CLIAgentSetupMixin:
openrouter_min_coding_score=self._openrouter_min_coding_score,
session_id=self.session_id, platform="cli", session_db=self._session_db,
clarify_callback=clarify_callback, connection_callback=connection_callback,
+ # The gateway's model-guard refusal is asked like main's own guard; -q cannot answer it.
+ model_confirm_callback=None if single_query_mode else self._confirm_owner_model_switch,
reasoning_callback=self._current_reasoning_callback(),
fallback_model=self._fallback_model, thinking_callback=self._on_thinking,
checkpoints_enabled=self.checkpoints_enabled,
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index c424c503f4b..3783a99ad89 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -199,6 +199,15 @@ def _run_confirm_and_apply(cli, target, *args) -> None:
target(*args)
+def _ask_switch_anyway(cli, title: str, detail: str) -> bool:
+ """The model-guard prompt (switch anyway once, or cancel): True only on an explicit yes."""
+ choices = [
+ ("once", t("cli.model.choice_switch_anyway"), t("cli.model.desc_switch_anyway")),
+ ("cancel", t("cli.model.choice_cancel"), t("cli.model.desc_keep_current_model"))]
+ raw = cli._prompt_text_input_modal(title=f"!!! {title} !!!", detail=detail, choices=choices, timeout=120)
+ return cli._normalize_slash_confirm_choice(raw, choices) == "once"
+
+
# `/model` usage block: (invocation form, description key). Forms are command syntax (never
# translated); descriptions are padded to one column at render time.
_MODEL_USAGE_ROWS = (
@@ -550,6 +559,7 @@ class CLIModelSwitchMixin:
def _confirm_expensive_model_switch(self, result) -> bool:
"""Ask for explicit confirmation before applying costly model switches."""
+ self._confirmed_switch_warning = None
if not getattr(result, "success", False):
return True
try:
@@ -564,12 +574,22 @@ class CLIModelSwitchMixin:
warning = None
if warning is None:
return True
- choices = [
- ("once", t("cli.model.choice_switch_anyway"), t("cli.model.desc_switch_anyway")),
- ("cancel", t("cli.model.choice_cancel"), t("cli.model.desc_keep_current_model"))]
- raw = self._prompt_text_input_modal(
- title=f"!!! {warning.title} !!!", detail=warning.message, choices=choices, timeout=120)
- return self._normalize_slash_confirm_choice(raw, choices) == "once"
+ if not _ask_switch_anyway(self, warning.title, warning.message):
+ return False
+ self._confirmed_switch_warning = warning.message
+ return True
+
+ def _confirm_owner_model_switch(self, refusal) -> bool:
+ """The gateway owner refused a guarded target (``confirmation_required``: cost, data policy,
+ large context; Ink/Desktop/ACP show the same ``confirm_message``): ask in the same prompt as
+ ``_confirm_expensive_model_switch``. Only a yes re-sends with the owner's token. The identical
+ warning the user just confirmed for this switch is not asked twice."""
+ from hermes_cli.gateway_mutations import confirmation_title
+ message = refusal.get("confirm_message") or ""
+ confirmed, self._confirmed_switch_warning = getattr(self, "_confirmed_switch_warning", None), None
+ if message and message == confirmed:
+ return True
+ return _ask_switch_anyway(self, confirmation_title(refusal), message)
def _confirm_and_apply_model_switch_result(
self, result, persist_global: bool, custom_providers=None, reasoning_effort: str = "") -> None:
@@ -601,9 +621,10 @@ class CLIModelSwitchMixin:
def _restore_model_runtime_snapshot(self, snapshot: dict | None) -> None:
"""Restore a model runtime captured before a one-turn override."""
- from cli import logger
+ from cli import _cprint, logger
if not snapshot:
return
+ one_turn = _runtime_fields(self)
for key in _RUNTIME_FIELDS:
if key in snapshot:
setattr(self, key, snapshot.get(key))
@@ -625,15 +646,25 @@ class CLIModelSwitchMixin:
logger.debug("CLI one-turn model restore via primary runtime failed", exc_info=True)
if hasattr(agent, "switch_model"):
try:
- agent.switch_model(
+ restored = agent.switch_model(
new_model=snapshot.get("model", ""), new_provider=snapshot.get("provider", ""),
api_key=snapshot.get("api_key", ""), base_url=snapshot.get("base_url", ""),
api_mode=snapshot.get("api_mode", ""),
capabilities=snapshot.get("capabilities"))
- if "reasoning_config" in snapshot:
- agent.reasoning_config = snapshot["reasoning_config"]
- except Exception as exc:
+ except Exception as exc: # health: allow BLE001 -- runs in the turn's finally; reported below
logger.warning("CLI one-turn model restore failed: %s", exc)
+ restored = exc
+ if restored is False or isinstance(restored, Exception):
+ # The session still runs the one-turn model (the owner's guard prompt was declined, or
+ # nobody can answer it): the CLI follows the session instead of claiming the restore.
+ for key, value in one_turn.items():
+ setattr(self, key, value)
+ notice = t("cli.model.switch_cancelled") if restored is False else t(
+ "cli.model.switch_failed", model=snapshot.get("model", ""), error=restored, old_model=agent.model)
+ _cprint(f" {notice}")
+ return
+ if "reasoning_config" in snapshot:
+ agent.reasoning_config = snapshot["reasoning_config"]
@staticmethod
def _filter_model_picker_entries(entries: list, query: str) -> list:
@@ -676,6 +707,11 @@ class CLIModelSwitchMixin:
rolled back. Returns False after printing the failure (a failed switch is a no-op).
"""
from cli import _cprint
+ if self.agent is None and getattr(self, "_gateway_session_open", False) and not self._init_agent():
+ # Before the first turn: the stand-in built for that turn reads the gateway session's model,
+ # so the switch must commit on the session now; _init_agent printed why it could not.
+ self._confirmed_switch_warning = None
+ return False
_cli_snapshot = _runtime_fields(self)
self.model = result.new_model
self.provider = result.target_provider
@@ -694,10 +730,15 @@ class CLIModelSwitchMixin:
if self.agent is not None:
try:
- self.agent.switch_model(
- new_model=result.new_model, new_provider=result.target_provider,
- api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode,
- capabilities=getattr(result, "runtime_capabilities", None))
+ if self.agent.switch_model(
+ new_model=result.new_model, new_provider=result.target_provider,
+ api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode,
+ capabilities=getattr(result, "runtime_capabilities", None)) is False:
+ # Declined at the gateway owner's guard prompt: nothing was committed.
+ for _k, _v in _cli_snapshot.items():
+ setattr(self, _k, _v)
+ _cprint(f" {t('cli.model.switch_cancelled')}")
+ return False
except Exception as exc:
# The agent rolled itself back to the old working model/client. Roll the CLI's own staged
# fields back too and abort the rest of the commit (note + success print) so a failed switch
@@ -708,6 +749,8 @@ class CLIModelSwitchMixin:
setattr(self, _k, _v)
_cprint(f" {t('cli.model.switch_failed', model=result.new_model, error=exc, old_model=old_model)}")
return False
+ finally:
+ self._confirmed_switch_warning = None # this switch's confirmation only
return True
def _apply_model_switch_result(
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.py
index 5d4dc6b93cb..a180d482662 100644
--- a/hermes_cli/cli_session_mixin.py
+++ b/hermes_cli/cli_session_mixin.py
@@ -87,7 +87,9 @@ def _reset_model_to_config_default(cli, silent: bool) -> None:
explicit_provider=_config_provider or "")
if not r.success:
return
- if cli.agent:
+ # A gateway /new already opened the next session on the profile's default (``session.create``
+ # without a model); the stand-in still points at the ended session, which a switch would rewrite.
+ if cli.agent and not getattr(cli, "_gateway_session_open", False):
cli.agent.switch_model(
new_model=r.new_model, new_provider=r.target_provider, api_key=r.api_key,
base_url=r.base_url, api_mode=r.api_mode,
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 41b285a21c9..ae70d254405 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -77,7 +77,7 @@ class GatewayAgent:
tool_start_callback=None, tool_complete_callback=None, stream_delta_callback=None,
tool_gen_callback=None, notice_callback=None, notice_clear_callback=None,
reaction_callback=None, interim_assistant_callback=None, connection=None,
- push_reasoning=False, **_ignored):
+ push_reasoning=False, model_confirm_callback=None, **_ignored):
conn = connection or getattr(session_db, "connection", None)
if conn is None:
raise GatewayClientError("Gateway session unavailable; no local fallback")
@@ -106,6 +106,8 @@ class GatewayAgent:
self.notice_clear_callback = notice_clear_callback
self.reaction_callback = reaction_callback
self.interim_assistant_callback = interim_assistant_callback
+ # The CLI's confirm prompt for the owner's model-guard refusal; None where nobody can answer (-q).
+ self.model_confirm_callback = model_confirm_callback
self.suppress_status_output = False
self._print_fn = None
# Inert private attributes main's CLI writes (CALLMAP §3.2).
@@ -217,14 +219,16 @@ class GatewayAgent:
logger.debug("session.mutate reasoning failed: %s", exc)
def switch_model(self, new_model, new_provider="", api_key="", base_url="", api_mode="", capabilities=None):
- """Main's in-place swap (``/model``, ``/model --once`` and its restore, /new's reset to the config
- default, /resume) as ``session.mutate model``: the gateway resolves the target with the same
+ """Main's in-place swap (``/model``, ``/model --once`` and its restore, /resume) as
+ ``session.mutate model``: the gateway resolves the target with the same
switch pipeline and commits it to the session's policy, so the next turn runs on it; keys and
- endpoints stay gateway-side. Main's caller already confirmed a guarded target
- (``_confirm_expensive_model_switch``), so the owner's ``confirmation_required`` is answered once
- with its token. A refusal raises: main's callers roll their own fields back."""
+ endpoints stay gateway-side. A guarded target (cost, data policy, large context) the owner refuses
+ with ``confirmation_required`` is re-sent with its token only on the user's yes to
+ ``model_confirm_callback`` (the owner's warning, as Ink/Desktop/ACP show it): a no returns False with
+ nothing written; with no prompt the refusal raises. Any refusal raises: main's callers roll their own
+ fields back."""
if new_model == self.model and (not new_provider or new_provider == self.provider):
- return
+ return True
from hermes_cli.gateway_mutations import model_refusal_text
payload = {"model": new_model, **({"provider": new_provider} if new_provider else {})}
snapshot = self.connection.call("session.resume", session_id=self.session_id)
@@ -232,6 +236,10 @@ class GatewayAgent:
expected_generation=snapshot["execution_generation"])
result = self.connection.call("session.mutate", request_id=uuid.uuid4().hex, payload=payload, **fence) or {}
if result.get("status") == "confirmation_required":
+ if self.model_confirm_callback is None:
+ raise GatewayClientError(model_refusal_text(result))
+ if not self.model_confirm_callback(result):
+ return False
# The refusal wrote nothing: the same fence is re-sent with the owner's token.
result = self.connection.call("session.mutate", request_id=uuid.uuid4().hex,
payload={**payload, "confirm": result["confirm"]}, **fence) or {}
@@ -248,6 +256,7 @@ class GatewayAgent:
state.info = {**(state.info or {}), "model": result.get("model") or new_model,
**({"provider": provider} if provider else {})}
self._apply_info(state.info)
+ return True
# -- session identity ----------------------------------------------------------------------
@property
@@ -757,6 +766,11 @@ class GatewayAgent:
def _on_print(self, payload, stream_callback, starts):
self._emit_print(payload.get("text") or "")
+ def _on_review_summary(self, payload, stream_callback, starts):
+ line = review_summary_line(payload)
+ if line:
+ self._emit_print(line)
+
def _emit_print(self, text):
if self.suppress_status_output:
return
@@ -1001,6 +1015,14 @@ def _rate_limit_state(data):
provider=str(data.get("provider") or ""))
+def review_summary_line(payload):
+ """Main's ``display.review.summary_cli`` line for the gateway's ``review.summary`` frame: the background
+ review's "💾 Self-improvement review: ..." (``/refine``, the post-turn review), which the gateway
+ publishes to a local viewer once the turn settled. None for an empty one."""
+ text = str(payload.get("text") or "").strip() if isinstance(payload, dict) else ""
+ return f" {text}" if text else None
+
+
def _moa_handler(kind):
def handler(agent, payload, stream_callback, starts):
if agent.tool_progress_callback is None:
@@ -1039,6 +1061,7 @@ _HANDLERS = {
"notification.clear": GatewayAgent._on_notice_clear,
"reaction": GatewayAgent._on_reaction,
"agent.print": GatewayAgent._on_print,
+ "review.summary": GatewayAgent._on_review_summary,
"approval.request": GatewayAgent._on_approval,
"clarify.request": GatewayAgent._on_clarify,
}
diff --git a/hermes_cli/gateway_tools_notify.py b/hermes_cli/gateway_tools_notify.py
index 293c23fede6..5e176c2b584 100644
--- a/hermes_cli/gateway_tools_notify.py
+++ b/hermes_cli/gateway_tools_notify.py
@@ -55,8 +55,16 @@ def queue_admitted_turn(cli, store) -> None:
events.put(frame) # the disconnect belongs to the next turn
return
params = frame.get("params") if isinstance(frame, dict) else None
- if (not isinstance(params, dict) or params.get("session_id") != session_id
- or params.get("type") != "message.start" or not params.get("admission_id")):
+ if not isinstance(params, dict) or params.get("session_id") != session_id:
+ continue
+ if params.get("type") == "review.summary":
+ # The background review (/refine, the post-turn review) reports after its turn settled.
+ from hermes_cli.gateway_agent import review_summary_line
+ line = review_summary_line(params.get("payload"))
+ if line:
+ cli._agent_status_print(line)
+ continue
+ if params.get("type") != "message.start" or not params.get("admission_id"):
continue
card = _card(params)
if card is None:
diff --git a/tests/gateway/test_local_viewer_events_submit.py b/tests/gateway/test_local_viewer_events_submit.py
index 19100a19030..c5163cb40b8 100644
--- a/tests/gateway/test_local_viewer_events_submit.py
+++ b/tests/gateway/test_local_viewer_events_submit.py
@@ -239,3 +239,29 @@ def test_a_finite_managed_worker_answers_clarify_headless():
controls._ask = lambda *a: pytest.fail("a finite viewer can never answer")
with finite_turn_scope(True):
assert controls.clarify([{"qid": "q", "question": "?", "choices": [], "multi_select": False}])["outcome"] == "undelivered"
+
+
+def test_a_one_turn_model_never_becomes_the_sessions_stored_model():
+ """``/moa`` and ``/model --once`` run one admission on another route. The turn's post-run sync
+ wrote the executing agent's model to the session row (``default``, the MoA preset), so a /resume
+ right after restored onto the preset. Only a turn on the session's own route records its model."""
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from gateway.session_cli_turn import cli_turn_scope
+ from hermes_cli.model_switch import ModelSwitchResult
+
+ written = []
+ db = SimpleNamespace(get_session=lambda sid: {"model": "session-model", "model_config": "{}"},
+ update_session_meta=lambda sid, config, model=None: written.append((sid, model)))
+ runner = _gateway_runner()
+ runner._session_db = SimpleNamespace(_db=db)
+ runner._sync_session_model_from_agent = (
+ lambda sid, agent: GatewayTurnPrepareMixin._sync_session_model_from_agent(runner, sid, agent))
+ moa = ModelSwitchResult(success=True, new_model="default", target_provider="moa", api_key="",
+ base_url="", api_mode="chat_completions")
+ committed = {"model_override": {"model": "default", "provider": "moa"}}
+ with patch("hermes_cli.model_switch.switch_model", return_value=moa), cli_turn_scope("adm-1", committed):
+ _result, agent = _run_turn(runner)
+ assert agent.model == "default" and written == []
+ with cli_turn_scope("adm-1", committed):
+ _run_turn(runner, admission_id="adm-2")
+ assert [model for _sid, model in written] == ["session-model"]
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index 612fc9c930f..a102c7d8ec9 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -730,19 +730,33 @@ def test_model_switch_is_the_session_model_mutation_and_a_rebuilt_agent_shows_it
assert (rebuilt.model, rebuilt.provider) == ("new-model", "anthropic")
-def test_a_guarded_model_target_is_confirmed_once_with_the_owners_token(make_agent):
- """Main asked before calling switch_model (``_confirm_expensive_model_switch``); the owner's own
- guard refusal is answered with its token once. A second refusal (the session moved) raises, so
- main rolls its fields back and the agent keeps the old model."""
+def test_a_guarded_model_target_commits_only_on_the_users_yes_to_the_owners_warning(make_agent):
+ """The owner's guard refusal (cost, data policy, large context) is the user's to answer: its
+ warning goes to the CLI's prompt and only a yes re-sends with its token. A no commits nothing;
+ with no prompt (-q) the token is never sent. A second refusal after a yes (the session moved)
+ raises, so main rolls its fields back and the agent keeps the old model."""
refusal = {"status": "confirmation_required", "confirm": "tok-1", "confirm_message": "Expensive model"}
- agent, client = make_agent([], model="old-model")
+ asked = []
+ agent, client = make_agent([], model="old-model",
+ model_confirm_callback=lambda r: asked.append(r["confirm_message"]) or True)
client.mutate_replies = [refusal, {"status": "committed", "model": "pricey-model"}]
- agent.switch_model(new_model="pricey-model", new_provider="openrouter")
+ assert agent.switch_model(new_model="pricey-model", new_provider="openrouter") is True
+ assert asked == ["Expensive model"]
sent = [p["payload"] for m, p in client.calls if m == "session.mutate"]
assert sent == [{"model": "pricey-model", "provider": "openrouter"},
{"model": "pricey-model", "provider": "openrouter", "confirm": "tok-1"}]
assert agent.model == "pricey-model"
- other, other_client = make_agent([], model="old-model")
+ declined, declined_client = make_agent([], model="old-model", model_confirm_callback=lambda r: False)
+ unattended, unattended_client = make_agent([], model="old-model")
+ declined_client.mutate_replies, unattended_client.mutate_replies = [refusal], [refusal]
+ assert declined.switch_model(new_model="pricey-model", new_provider="openrouter") is False
+ with pytest.raises(GatewayClientError, match="interactive session"):
+ unattended.switch_model(new_model="pricey-model", new_provider="openrouter")
+ for refused, refused_client in ((declined, declined_client), (unattended, unattended_client)):
+ assert [p["payload"] for m, p in refused_client.calls if m == "session.mutate"] == [
+ {"model": "pricey-model", "provider": "openrouter"}]
+ assert refused.model == "old-model"
+ other, other_client = make_agent([], model="old-model", model_confirm_callback=lambda r: True)
other_client.mutate_replies = [refusal, dict(refusal, confirm="tok-2")]
with pytest.raises(GatewayClientError, match="Model not switched"):
other.switch_model(new_model="pricey-model", new_provider="openrouter")
@@ -797,3 +811,15 @@ def test_a_committed_model_switch_stands_when_the_refresh_after_it_fails(make_ag
assert (agent.model, agent.provider) == ("claude-sonnet-4", "anthropic")
rebuilt = GatewayAgent(connection=agent.connection, session_id=SID, model="old-model", provider="openrouter")
assert (rebuilt.model, rebuilt.provider) == ("claude-sonnet-4", "anthropic")
+
+
+def test_a_background_review_summary_during_a_turn_is_printed_like_mains(make_agent):
+ """``/refine`` (#134889 M3) and the post-turn review run in the gateway, which publishes their
+ summary as a ``review.summary`` frame (no admission). One landing while a turn streams is printed
+ as main's ``display.review.summary_cli`` line, never dropped."""
+ printed = []
+ agent, _ = make_agent([frame("review.summary", {"text": "💾 Self-improvement review: Memory updated"}, admission=None),
+ frame("message.complete", {"text": "ok", "outcome": "completed"})])
+ agent._print_fn = printed.append
+ agent.run_conversation("hi")
+ assert printed == [" 💾 Self-improvement review: Memory updated"]
diff --git a/tests/hermes_cli/test_gateway_model_switch_cli.py b/tests/hermes_cli/test_gateway_model_switch_cli.py
new file mode 100644
index 00000000000..5ab446ff131
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_model_switch_cli.py
@@ -0,0 +1,159 @@
+"""The classic CLI's model switches over the shared gateway session (#134889 M1, review of #138717).
+
+The CLI's agent is a ``GatewayAgent`` stand-in and the gateway session is the source of truth for the
+model a turn runs: ``/new`` must not rewrite the session it just ended, a ``/model`` before the first
+turn must commit on the session that turn runs on, and the owner's model-guard refusal is the user's
+to answer in the CLI's own prompt (never silently confirmed).
+"""
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from hermes_cli.gateway_agent import GatewayAgent
+from hermes_cli.gateway_connection import GatewayConnection
+from hermes_cli.model_switch import ModelSwitchResult
+from tests.hermes_cli.test_gateway_agent import SID, FakeClient, connect_with
+
+REFUSAL = {"status": "confirmation_required", "confirm": "tok-1",
+ "confirm_message": "This session holds ~150,000 tokens of context.",
+ "warnings": [{"kind": "context_cache", "title": "Large Context Switch Warning", "message": "..."}]}
+
+
+def gateway():
+ client = FakeClient([])
+ conn = GatewayConnection(connect=connect_with(client))
+ conn.start(5)
+ conn.state(SID)
+ yield conn, client
+ conn.close()
+
+
+def _mutations(client):
+ return [params for method, params in client.calls if method == "session.mutate"]
+
+
+def _cli(**fields):
+ base = dict(agent=None, _gateway_session_open=True, session_id=SID, model="old-model", provider="openrouter",
+ requested_provider="openrouter", api_key="k", base_url="", api_mode="", _explicit_api_key=None,
+ _explicit_base_url=None, reasoning_config=None)
+ return SimpleNamespace(**{**base, **fields})
+
+
+def _answering(cli, *answers):
+ """Bind main's guard prompt onto ``cli`` with scripted answers; returns what each prompt showed."""
+ from cli import HermesCLI
+ shown, pending = [], list(answers)
+
+ def modal(*, title, detail, choices, timeout):
+ shown.append((title, detail, [choice[0] for choice in choices]))
+ return pending.pop(0)
+ cli._prompt_text_input_modal = modal
+ cli._normalize_slash_confirm_choice = lambda raw, choices: HermesCLI._normalize_slash_confirm_choice(cli, raw, choices)
+ cli._confirm_owner_model_switch = lambda refusal: HermesCLI._confirm_owner_model_switch(cli, refusal)
+ return shown
+
+
+def test_new_after_a_model_switch_leaves_the_ended_session_alone(gateway):
+ """Review item 1: /new reset the model to the config default through the stand-in before it was
+ rebound, so ``session.mutate model`` rewrote the session just ended (a later /resume of it came back
+ on the default). The new session is created on the profile's default and runs it."""
+ from cli import CLI_CONFIG, HermesCLI
+ from hermes_cli.cli_init_mixin import CLIInitMixin
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ conn, client = gateway
+ rpc = client.rpc
+
+ async def create_on_the_default(method, **params):
+ if method != "session.create":
+ return await rpc(method, **params)
+ client.calls.append((method, params))
+ return {"stored_session_id": "local-new", "revision": 1, "execution_generation": 1,
+ "info": {"model": "config-default-model", "provider": "openrouter"}}
+ client.rpc = create_on_the_default
+ agent = GatewayAgent(connection=conn, session_id=SID, model="config-default-model", provider="openrouter")
+ agent.switch_model(new_model="gpt-x", new_provider="openrouter") # /model gpt-x
+ client.calls.clear()
+ cli = _cli(agent=agent, model="gpt-x", _session_db=GatewaySessionStore(connection=conn), conversation_history=[],
+ _pending_title=None, _resumed=False, _notify_session_boundary=MagicMock(),
+ _discard_session_if_empty=MagicMock(), service_tier=None, enabled_toolsets=None, _explicit_toolsets=False)
+ cli._new_session_id = lambda now: CLIInitMixin._new_session_id(cli, now)
+ default = ModelSwitchResult(success=True, new_model="config-default-model", target_provider="openrouter",
+ api_key="k", base_url="", api_mode="chat_completions")
+ with patch.dict(CLI_CONFIG, {"model": {"default": "config-default-model", "provider": "openrouter"}}), \
+ patch("hermes_cli.model_switch.switch_model", return_value=default):
+ HermesCLI.new_session(cli, silent=True)
+ assert _mutations(client) == []
+ assert "model" not in dict(client.calls)["session.create"] # the profile's default
+ assert cli.session_id == agent.session_id == "local-new"
+ assert (cli.model, agent.model) == ("config-default-model", "config-default-model")
+
+
+def test_model_before_the_first_turn_commits_on_the_session_that_turn_runs(gateway, monkeypatch):
+ """Review item 3: before the first turn there is no stand-in, and the one built for that turn read
+ the session's (old) model: "Model switched" was printed and the turn ran the old model. The switch
+ now commits on the gateway session."""
+ from cli import HermesCLI
+ conn, client = gateway
+ conn.state(SID).info.update(model="old-model", provider="openrouter")
+ cli = _cli()
+
+ def init_agent(): # main's _init_agent: the stand-in on this CLI's gateway session
+ cli.agent = GatewayAgent(connection=conn, session_id=SID, model=cli.model, provider=cli.provider)
+ return True
+ cli._init_agent = init_agent
+ monkeypatch.setattr("cli._cprint", lambda *_a, **_k: None)
+ picked = ModelSwitchResult(success=True, new_model="new-model", target_provider="openrouter", api_key="k",
+ base_url="", api_mode="chat_completions")
+ assert HermesCLI._stage_and_swap_model(cli, picked, "old-model") is True
+ [mutation] = _mutations(client)
+ assert (mutation["session_id"], mutation["payload"]["model"]) == (SID, "new-model")
+ first_turn = GatewayAgent(connection=conn, session_id=SID, model="old-model", provider="openrouter")
+ assert first_turn.model == "new-model"
+
+
+def test_the_owners_refusal_is_asked_in_the_clis_model_guard_prompt():
+ """Review item 2: the owner's warning is the prompt's title and body, as Ink/Desktop/ACP show it."""
+ from cli import HermesCLI
+ cli = SimpleNamespace()
+ shown = _answering(cli, "once", "cancel")
+ assert HermesCLI._confirm_owner_model_switch(cli, REFUSAL) is True
+ assert HermesCLI._confirm_owner_model_switch(cli, REFUSAL) is False
+ assert shown == [("!!! Large Context Switch Warning !!!", REFUSAL["confirm_message"], ["once", "cancel"])] * 2
+
+
+def test_a_declined_owner_warning_switches_nothing(gateway, monkeypatch):
+ from cli import HermesCLI
+ conn, client = gateway
+ printed = []
+ monkeypatch.setattr("cli._cprint", lambda text, *_a, **_k: printed.append(str(text)))
+ cli = _cli()
+ shown = _answering(cli, "cancel")
+ cli.agent = GatewayAgent(connection=conn, session_id=SID, model="old-model", provider="openrouter",
+ model_confirm_callback=cli._confirm_owner_model_switch)
+ client.mutate_replies = [REFUSAL]
+ picked = ModelSwitchResult(success=True, new_model="big-model", target_provider="openrouter", api_key="k",
+ base_url="", api_mode="chat_completions")
+ assert HermesCLI._stage_and_swap_model(cli, picked, "old-model") is False
+ assert [title for title, _detail, _choices in shown] == ["!!! Large Context Switch Warning !!!"]
+ assert [m["payload"] for m in _mutations(client)] == [{"model": "big-model", "provider": "openrouter"}]
+ assert (cli.model, cli.agent.model) == ("old-model", "old-model")
+ assert any("Model switch cancelled." in line for line in printed)
+
+
+def test_a_once_restore_nobody_can_confirm_is_not_committed(gateway, monkeypatch):
+ """``/model big --once`` then the restore to the smaller model: the owner can refuse it (large
+ context). Without a prompt (-q) the token is never sent: the session stays on the one-turn model,
+ the CLI says so and follows it instead of claiming the restore."""
+ from cli import HermesCLI
+ conn, client = gateway
+ printed = []
+ monkeypatch.setattr("cli._cprint", lambda text, *_a, **_k: printed.append(str(text)))
+ cli = _cli(model="big-model")
+ cli.agent = GatewayAgent(connection=conn, session_id=SID, model="big-model", provider="openrouter")
+ client.mutate_replies = [REFUSAL]
+ HermesCLI._restore_model_runtime_snapshot(cli, {"model": "small-model", "provider": "openrouter"})
+ assert [m["payload"] for m in _mutations(client)] == [{"model": "small-model", "provider": "openrouter"}]
+ assert (cli.model, cli.agent.model) == ("big-model", "big-model")
+ assert any("Model not switched" in line and "small-model" in line for line in printed)
diff --git a/tests/hermes_cli/test_gateway_tools_notify.py b/tests/hermes_cli/test_gateway_tools_notify.py
index c5307b1c2b6..beec75e5d55 100644
--- a/tests/hermes_cli/test_gateway_tools_notify.py
+++ b/tests/hermes_cli/test_gateway_tools_notify.py
@@ -245,3 +245,20 @@ def test_a_long_subagent_goal_still_admits_its_completion_card():
card = _claim_card(_delegation_completion("audit " * 1000), "model text")
assert card["display_kind"] == "async_delegation_complete"
assert card["display_text"].startswith("Subagent Task Completed: audit")
+
+
+def test_idle_cli_prints_the_gateway_background_review_summary(capsys):
+ """``/refine`` promises "any memory/skill updates will be reported when done" (#134889 M3): the
+ gateway publishes the review's summary to the local session as ``review.summary`` after the turn
+ settled. An idle classic CLI prints it (main's ``display.review.summary_cli`` line) instead of
+ discarding it with the between-turn leftovers."""
+ conn, client = _connected()
+ try:
+ cli = _idle_cli(conn)
+ _play(conn, client, [frame("review.summary", {"text": "💾 Self-improvement review: Memory updated"},
+ admission=None)])
+ cli._drain_process_notifications("cli-idle")
+ assert " 💾 Self-improvement review: Memory updated" in capsys.readouterr().out
+ assert cli._pending_input.empty() # a report, not a turn
+ finally:
+ conn.close()