Skip to content

The agent that grows with you

fix(cli): take the --once pick when the admission is built, inside the submit try

Tekniume1088b565ff8
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.py
index 7894acdf1dd..da41cb7dca9 100644
--- a/hermes_cli/cli_chat_turn_mixin.py
+++ b/hermes_cli/cli_chat_turn_mixin.py
@@ -349,7 +349,10 @@ class CLIChatTurnMixin:
"completed": False, "failed": True, "error": _summary,
}
finally:
- if _one_turn_model_restore:
+ if _one_turn_model_restore and (turn.result or {}).get("failure_reason") == "session_busy":
+ # The owner admitted nothing: the resend is still the one turn the pick was for.
+ self._pending_one_turn_model_restore = _one_turn_model_restore
+ elif _one_turn_model_restore:
self._restore_model_runtime_snapshot(_one_turn_model_restore)
# Credit notices paint cleanly above the prompt here, not behind streamed output.
self._flush_credit_notices()
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index d41aaf66c7a..9e3a1e5744b 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -174,6 +174,7 @@ class GatewayAgent:
# ``/model --once``: chat retires the agent that switch_model touched and builds this one.
# Capture the pick before ``_apply_info`` copies the session model over it.
self._turn_route = self._route_off_session(model, provider) if one_turn else None
+ self._taken_turn_route = None # the pick the admission being sent took (``_take_turn_route``)
# ``/model B --once --reasoning X``: X rides that admission's ``model_override``, never a session pin.
self._turn_reasoning = one_turn_reasoning if one_turn else None
self._apply_info(self._state().info)
@@ -599,18 +600,32 @@ class GatewayAgent:
# Main's batch panel answers the clarify tool's whole question set (one ``clarify`` request).
params["clarify_batch"] = True
info = self._state().info or {}
- pending = self._turn_route
- if pending and self._route_off_session(**pending):
+ pending = self._take_turn_route()
+ if pending:
# /model --once: this admission alone runs the pick. The session row stays put.
- params["model_override"] = dict(pending)
- if self._turn_reasoning:
- params["model_override"]["reasoning"] = self._turn_reasoning
+ params["model_override"] = pending
elif 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
+ def _take_turn_route(self):
+ """The ``/model --once`` pick for the admission being built, consumed here: one admission carries
+ it, even when a later ``run_conversation`` submits while this one's ``prompt.submit`` still blocks.
+ A refusal that admitted nothing (``session_busy``) puts it back with ``_give_back_turn_route``."""
+ pending, reasoning = self._turn_route, self._turn_reasoning
+ self._turn_route = self._turn_reasoning = self._taken_turn_route = None
+ if not pending or not self._route_off_session(**pending):
+ return None
+ self._taken_turn_route = (pending, reasoning)
+ return {**pending, **({"reasoning": reasoning} if reasoning else {})}
+
+ def _give_back_turn_route(self):
+ taken, self._taken_turn_route = getattr(self, "_taken_turn_route", None), None
+ if taken and self._turn_route is None:
+ self._turn_route, self._turn_reasoning = taken
+
def _stage_content_parts(self, parts):
"""``[{type: text}, {type: image_url, image_url: {url: data:...}}]`` -> (text, attachments): each
image is staged on the owner with ``image.attach_bytes`` (bytes read here, locally, by main's
@@ -647,22 +662,23 @@ class GatewayAgent:
receipt = adopted
else:
self._drain_stale()
- params = self._submit_params(user_message, persist_user_message, turn_author)
+ self._taken_turn_route = None
try:
- receipt = self.connection.call("prompt.submit", **params)
+ # Inside the try: staging an image is a gateway call, and its failure is a failed turn.
+ # Building the params consumes a ``/model --once`` pick (``_take_turn_route``).
+ receipt = self.connection.call("prompt.submit", **self._submit_params(
+ user_message, persist_user_message, turn_author))
except GatewayRPCError as exc:
# The owner answered and refused: not a lost connection. Only its own site code
# (session_busy: send again) is a verdict; any other refusal stays unclassified.
busy = str(exc) == "session_busy"
+ if busy:
+ # Nothing was admitted: the resend carries the pick (the CLI keeps its restore).
+ self._give_back_turn_route()
return self._failed(history, user_message, str(exc),
failure_reason="session_busy" if busy else None, retryable=busy)
except GatewayClientError as exc:
return self._failed(history, user_message, str(exc), failure_reason="gateway_connection")
- finally:
- # One admission. A later submit on this agent, including a failed attempt's retry
- # after the CLI restores, must not send the pick again.
- if params.get("model_override") and self._turn_route:
- self._turn_route = None
self._epoch = getattr(self.connection, "epoch", None)
self._admission = (receipt or {}).get("admission_id")
if receipt and receipt.get("execution_generation") is not None:
diff --git a/tests/hermes_cli/test_cli_gateway_model_scope.py b/tests/hermes_cli/test_cli_gateway_model_scope.py
index 0fccd88d8de..4627287bec0 100644
--- a/tests/hermes_cli/test_cli_gateway_model_scope.py
+++ b/tests/hermes_cli/test_cli_gateway_model_scope.py
@@ -320,3 +320,69 @@ def test_once_reasoning_equal_to_the_inherited_level_commits_nothing(monkeypatch
_commit_model_switch(stub, result, persist_global=False, one_turn=True, reasoning_effort="high")
cli.HermesCLI._restore_model_runtime_snapshot(stub, stub._pending_one_turn_model_restore)
assert _reasoning_mutates(conn) == []
+
+
+class BusyOnceConnection(RecordingConnection):
+ """The owner refuses the first ``prompt.submit`` with ``session_busy``: nothing was admitted."""
+
+ def __init__(self, info):
+ super().__init__(info)
+ self.refused = False
+
+ def call(self, method, *, timeout=None, **params):
+ if method == "prompt.submit" and not self.refused:
+ from hermes_cli.gateway_client import GatewayRPCError
+ self.refused = True
+ self.calls.append((method, params))
+ raise GatewayRPCError("session_busy")
+ return super().call(method, timeout=timeout, **params)
+
+
+def test_a_once_pick_refused_as_session_busy_rides_the_resend(monkeypatch):
+ """Review of #140969: the submit's ``finally`` cleared the pick even when the owner refused it with
+ ``session_busy`` (nothing admitted), and the CLI restored its route, so the resend ran on the session
+ model."""
+ conn = BusyOnceConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, _printed = _chat_cli(monkeypatch, conn)
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic --once")
+ stub.chat("refused")
+ assert stub.chat("the resend") == "ok"
+ assert stub.chat("the turn after") == "ok"
+ refused, resend, after = _submits(conn)
+ pick = {"model": "claude-sonnet-4.6", "provider": "anthropic"}
+ assert refused.get("model_override") == pick
+ assert resend.get("model_override") == pick, resend
+ assert "model_override" not in after, after
+ assert (stub.model, stub.agent.model) == ("old/model", "old/model")
+
+
+def test_the_once_pick_is_taken_when_the_admission_is_built(monkeypatch):
+ """dokterdok on #140969: consume the pick when the params are built, not in the call's ``finally``, so
+ a second ``run_conversation`` submitting while the first ``prompt.submit`` is still blocked cannot carry
+ it too."""
+ seen = []
+
+ class Watching(RecordingConnection):
+ def call(self, method, *, timeout=None, **params):
+ if method == "prompt.submit":
+ seen.append(agent._turn_route) # the first submit is "blocked" here
+ return super().call(method, timeout=timeout, **params)
+
+ conn = Watching({"model": "old/model", "provider": "openrouter"})
+ agent = _agent(conn, model="claude-sonnet-4.6", provider="anthropic", one_turn=True)
+ assert agent._turn_route
+ agent.run_conversation("the once turn")
+ assert seen == [None]
+ assert _submits(conn)[0]["model_override"] == {"model": "claude-sonnet-4.6", "provider": "anthropic"}
+
+
+def test_an_image_staging_failure_is_a_failed_turn_not_an_exception():
+ """dokterdok on #140969: ``_submit_params`` stages images over the gateway (``image.attach_bytes``); it
+ moved out of the ``try``, so a lost connection while staging raised out of ``run_conversation``."""
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"}) # attach_bytes is unsupported
+ agent = _agent(conn, model="old/model", provider="openrouter")
+ parts = [{"type": "text", "text": "what is this"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}]
+ result = agent.run_conversation(parts)
+ assert (result.get("failed"), result.get("failure_reason")) == (True, "gateway_connection"), result
+ assert not _submits(conn)