Skip to content

The agent that grows with you

fix(cli): show a gateway /review result in an idle CLI; keep committed model switches

unsupportedpastels8ddf92ff8309
diff --git a/gateway/response_filters.py b/gateway/response_filters.py
index ce10af4b1c3..7b97674e7c5 100644
--- a/gateway/response_filters.py
+++ b/gateway/response_filters.py
@@ -33,7 +33,7 @@ _BRACKETED_SILENCE_MARKERS = tuple(
INTERNAL_NOTIFICATION_DISPLAY_KIND = "internal_notification"
# Async-result cards a gateway producer may name on its own internal event (with a display_text),
# the same rows the in-process TUI persisted. A closed set: never a client-chosen presentation.
-PRODUCER_NOTICE_DISPLAY_KINDS = frozenset({"process_complete"})
+PRODUCER_NOTICE_DISPLAY_KINDS = frozenset({"process_complete", "async_delegation_complete"})
MACHINERY_DISPLAY_KINDS = frozenset({INTERNAL_NOTIFICATION_DISPLAY_KIND, *PRODUCER_NOTICE_DISPLAY_KINDS})
# Longer than any marker could plausibly be, even with stray punctuation.
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 87378a51c8e..6a16787b69e 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -106,6 +106,21 @@ def _raw_process_event_session_id(evt: dict) -> str:
return str(evt.get("origin_session_id") or session_key or "").strip()
+def _local_completion_card(evt: dict) -> dict[str, str]:
+ """The async-result card main's in-process TUI wrote for a completion; the claim's
+ ``message.start`` carries it, and an idle classic CLI only opens a turn that has one (a
+ gateway-side ``/review`` reports as an async delegation). ``{}`` for a watch event."""
+ from tools.process_registry_notifications import (
+ PROCESS_COMPLETE_DISPLAY_KIND, async_delegation_display_text, process_completion_display_text)
+ evt_type = evt.get("type", "completion")
+ if evt_type == "completion":
+ return {"display_kind": PROCESS_COMPLETE_DISPLAY_KIND,
+ "display_text": evt.get("_display_text") or process_completion_display_text([evt])}
+ if evt_type == "async_delegation":
+ return {"display_kind": "async_delegation_complete", "display_text": async_delegation_display_text(evt)}
+ return {}
+
+
def _watch_notification_metadata(evt: dict, source) -> dict[str, Any]:
"""Synthetic-event metadata for a watch/completion notification: routing pins, proof ids,
automation identities, and the local async-result card."""
@@ -121,13 +136,10 @@ def _watch_notification_metadata(evt: dict, source) -> dict[str, Any]:
metadata["gateway_session_id"] = parent_session_id
if evt.get('_automation_identities'):
metadata['automation_identities'] = evt['_automation_identities']
- if source.platform == Platform.LOCAL and evt.get("type", "completion") == "completion":
+ if source.platform == Platform.LOCAL:
# A local completion persists as the async-result card the in-process TUI wrote;
# messaging rows stay internal_notification, as on main.
- from tools.process_registry_notifications import (
- PROCESS_COMPLETE_DISPLAY_KIND, process_completion_display_text)
- metadata["display_kind"] = PROCESS_COMPLETE_DISPLAY_KIND
- metadata["display_text"] = evt.get("_display_text") or process_completion_display_text([evt])
+ metadata.update(_local_completion_card(evt))
proven_session_id = str(evt.get("proven_session_id") or "").strip()
if proven_session_id:
metadata["gateway_proven_session_id"] = proven_session_id
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 011afe4ae5a..41b285a21c9 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -238,9 +238,15 @@ class GatewayAgent:
if result.get("status") == "confirmation_required":
raise GatewayClientError(model_refusal_text(result, confirmed=True))
state = self._state()
- state.adopt_snapshot(self.connection.call("session.resume", session_id=self.session_id))
+ try:
+ state.adopt_snapshot(self.connection.call("session.resume", session_id=self.session_id))
+ except (GatewayClientError, KeyError, TypeError) as exc:
+ # Committed: the next turn runs on the new model, so main must not roll its fields back.
+ logger.warning("session.resume after the committed model switch failed: %s", exc)
# A rebuilt stand-in reads the session's info: it must show the committed model.
- state.info.update(model=result.get("model") or new_model, **({"provider": new_provider} if new_provider else {}))
+ provider = result.get("provider") or new_provider
+ state.info = {**(state.info or {}), "model": result.get("model") or new_model,
+ **({"provider": provider} if provider else {})}
self._apply_info(state.info)
# -- session identity ----------------------------------------------------------------------
@@ -518,8 +524,10 @@ class GatewayAgent:
if self.clarify_callback is not None:
# Main's batch panel answers the clarify tool's whole question set (one ``clarify`` request).
params["clarify_batch"] = True
- if self._moa_preset and (self._state().info or {}).get("provider") != "moa":
- # /moa one-shot: this admission alone runs the preset; the session's route is untouched.
+ info = self._state().info or {}
+ if self._moa_preset and (info.get("provider"), info.get("model")) != ("moa", self._moa_preset):
+ # /moa one-shot: this admission alone runs the preset (unless it is the session's own
+ # route); the session's route is untouched.
params["model_override"] = {"model": self._moa_preset, "provider": "moa"}
return params
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index 56cadd80a42..612fc9c930f 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -764,3 +764,36 @@ def test_moa_one_shot_preset_rides_this_turns_submit_as_its_model_override(make_
regular = GatewayAgent(connection=agent.connection, session_id=SID, model="claude-sonnet", provider="anthropic")
regular.run_conversation("next")
assert "model_override" not in dict(client.calls)["prompt.submit"]
+
+
+def test_moa_one_shot_overrides_a_moa_session_running_another_preset(make_agent):
+ """A session already on the MoA provider runs ITS preset; ``/moa`` with another preset must still
+ send that preset as the turn's override. Only the same preset is the session's own route."""
+ done = [frame("message.complete", {"text": "ok", "outcome": "completed"})]
+ agent, client = make_agent(done)
+ agent.connection.state(SID).info.update(model="fast", provider="moa")
+ GatewayAgent(connection=agent.connection, session_id=SID, model="deep", provider="moa").run_conversation("go")
+ assert dict(client.calls)["prompt.submit"]["model_override"] == {"model": "deep", "provider": "moa"}
+ client.calls.clear()
+ GatewayAgent(connection=agent.connection, session_id=SID, model="fast", provider="moa").run_conversation("again")
+ assert "model_override" not in dict(client.calls)["prompt.submit"]
+
+
+def test_a_committed_model_switch_stands_when_the_refresh_after_it_fails(make_agent):
+ """Once ``session.mutate`` commits, the gateway runs the next turn on the new model. A failed
+ ``session.resume`` refresh after that must not raise: main's caller would roll its fields back to
+ a model the session no longer has. The agent shows the model and provider the gateway committed."""
+ agent, client = make_agent([], model="old-model", provider="openrouter")
+ client.mutate_replies = [{"status": "committed", "model": "claude-sonnet-4", "provider": "anthropic"}]
+ rpc = client.rpc
+
+ async def refresh_fails(method, **params):
+ if method == "session.resume" and any(m == "session.mutate" for m, _ in client.calls):
+ raise GatewayClientError(DISCONNECTED)
+ return await rpc(method, **params)
+ client.rpc = refresh_fails
+ agent.switch_model(new_model="sonnet")
+ assert len([m for m, _ in client.calls if m == "session.mutate"]) == 1
+ 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")
diff --git a/tests/hermes_cli/test_gateway_tools_notify.py b/tests/hermes_cli/test_gateway_tools_notify.py
index a0e586f113d..c5307b1c2b6 100644
--- a/tests/hermes_cli/test_gateway_tools_notify.py
+++ b/tests/hermes_cli/test_gateway_tools_notify.py
@@ -180,3 +180,68 @@ def test_claim_stamp_carries_the_automation_card_on_message_start():
assert admission_display(diagnostic)["notification_category"] == "diagnostic"
assert admission_display({"text": "typed by the user"}) == {}
assert admission_display({"text": "x", "local_automation_v1": {"identity": "i"}}) == {}
+
+
+def _delegation_completion(goal):
+ return {"type": "async_delegation", "delegation_id": "deleg_1", "parent_session_id": SID,
+ "goals": [goal], "results": [{"task_index": 0, "status": "completed", "summary": "Two nits.",
+ "api_calls": 3, "duration_seconds": 12}]}
+
+
+def _claim_card(evt, text):
+ """The ``message.start`` card the gateway publishes for this LOCAL completion's admission: the
+ producer's metadata, validated as ``snapshot_local_automation`` does, read back at the claim."""
+ from gateway.config import Platform
+ from gateway.run_notifications import _watch_notification_metadata
+ from gateway.session import SessionSource
+ from gateway.session_automation import admission_display, automation_display_metadata
+ metadata = _watch_notification_metadata(evt, SessionSource(platform=Platform.LOCAL, chat_id=SID))
+ descriptor = {"identity": "i", "owner": SID, "route": "r", "target": SID,
+ **automation_display_metadata(metadata)}
+ return admission_display({"text": text, "local_automation_v1": descriptor})
+
+
+def test_idle_cli_shows_a_gateway_review_subagents_completion(capsys):
+ """``/review`` runs its reviewer as a gateway-side async delegation (#134889 M4/CLI-6). Its
+ completion turn must reach an idle classic CLI as main's ``◈ Subagent Task ...`` header plus the
+ streamed reply; a claim without the card was skipped and the result never shown."""
+ from tools.process_registry_notifications import format_process_notification
+ evt = _delegation_completion("Review the work just discussed")
+ text = format_process_notification(evt)
+ card = _claim_card(evt, text)
+ conn, client = _connected()
+ try:
+ cli = _idle_cli(conn)
+ _play(conn, client, [frame("message.start", card, generation=9, admission="adm-9"),
+ frame("message.delta", {"text": "Review: two nits."}, generation=9, admission="adm-9"),
+ frame("message.complete", {"text": "Review: two nits.", "status": "complete"},
+ generation=9, admission="adm-9")])
+ cli._drain_process_notifications("cli-idle")
+ queued = cli._pending_input.get_nowait()
+ assert queued.display_kind == "async_delegation_complete"
+ assert queued.display_text == "Subagent Task Completed: Review the work just discussed"
+ assert str(queued) == text
+ for attr, value in {"_pending_resume_sessions": [], "_typed_voice_stop": lambda t: False,
+ "handle_bang_shell": lambda t: False, "_turn_summary_begin": lambda: None,
+ "_tui_after_turn": lambda: None, "_app": SimpleNamespace(invalidate=lambda: None),
+ "chat": Mock()}.items():
+ setattr(cli, attr, value)
+ cli._tui_process_one_input(queued)
+ assert f"◈ {queued.display_text}" in capsys.readouterr().out
+ deltas = []
+ agent = GatewayAgent(connection=conn, session_id=SID, stream_delta_callback=deltas.append)
+ cli.conversation_history = []
+ cli._chat_stage_user_message(agent, queued)
+ result = agent.run_conversation(str(queued), conversation_history=[])
+ assert "prompt.submit" not in [method for method, _ in client.calls]
+ assert deltas == ["Review: two nits."] and result["final_response"] == "Review: two nits."
+ finally:
+ conn.close()
+
+
+def test_a_long_subagent_goal_still_admits_its_completion_card():
+ """The card's title is bounded by the admission's display-text limit: an over-long goal must not
+ turn the completion into an ``invalid_params`` refusal (a delivery that never lands)."""
+ 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")
diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py
index 757febc1ce9..8da8679edba 100644
--- a/tools/process_registry_notifications.py
+++ b/tools/process_registry_notifications.py
@@ -335,10 +335,15 @@ def async_delegation_display_text(evt: dict) -> str:
goal = goals[index] if 0 <= index < len(goals) else result.get("goal", "")
titles.append(" ".join(str(goal or "Background task").split()))
if len(results) == 1:
- return f"Subagent Task {labels[0]}: {titles[0]}"
+ return f"Subagent Task {labels[0]}: {_short_title(titles[0])}"
outcome = labels[0] if len(set(labels)) == 1 else "Finished with Issues"
title = " ".join(str(evt.get("group") or "").split()) or "; ".join(titles)
- return f"Subagent Tasks {outcome}: {title} ({len(results)} tasks)"
+ return f"Subagent Tasks {outcome}: {_short_title(title)} ({len(results)} tasks)"
+
+
+def _short_title(title: str) -> str:
+ # A goal is free text: the card's title stays one line (and within an admission's display limit).
+ return title[:197] + "..." if len(title) > 200 else title
PROCESS_COMPLETE_DISPLAY_KIND = "process_complete"