Skip to content

The agent that grows with you

fix(cli): keep the ~ context estimate after Ctrl+C before the first response

Tekniumdc7e3d83ca51
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 39dc0190e33..1565322a535 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -1145,7 +1145,11 @@ class GatewayAgent:
return out
self._session_messages = out["messages"]
calls = stored.get("api_calls")
- self._turn_api_calls = calls if isinstance(calls, int) and not isinstance(calls, bool) else None
+ # An interrupted turn's own count includes the attempt Ctrl-C cut off (the agent counts a call
+ # before the request goes out). Only a response prices the ask: fall back to the gateway's
+ # cumulative count, which moves per response, so an unanswered ask stays main's ``~`` estimate.
+ counted = isinstance(calls, int) and not isinstance(calls, bool) and not out.get("interrupted")
+ self._turn_api_calls = calls if counted else None
self._apply_usage(stored, usage, turn)
return out
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index a3d21d30337..fff0878e521 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -899,3 +899,26 @@ def test_a_withdrawal_for_another_request_leaves_the_panel_open(make_agent):
assert closed == []
agent._on_request_withdrawn({"id": "srq-mine", "method": "clarify", "reason": "resolved"})
assert closed == ["clarify"]
+
+
+def test_ctrl_c_during_the_first_api_call_keeps_mains_estimate_marker(make_agent):
+ """T4: Ctrl+C while the turn's first request is in flight. The gateway agent counted the attempt
+ (``api_calls: 1`` in the turn result) but no response priced the ask, so main's in-process bar kept
+ the previous turn's anchor and estimated the ask (``~``). The stand-in must not anchor after the ask."""
+ from agent.usage_anchor import anchored_context_tokens
+ usage = dict(SESSION_USAGE, context_tokens=700, api_calls=2) # no response: cumulative calls unchanged
+ agent, client = make_agent([frame("message.complete", {"text": "", "outcome": "cancelled", "status": "interrupted"})],
+ result={"final_response": "", "api_calls": 1, "interrupted": True, "messages": []})
+ original = client.rpc
+
+ async def rpc(method, *, _timeout=None, **params):
+ if method == "session.stats":
+ return usage
+ return await original(method, _timeout=_timeout, **params)
+ client.rpc = rpc
+ agent.session_api_calls = 2
+ agent.run_conversation("story", conversation_history=[{"role": "user", "content": "a"},
+ {"role": "assistant", "content": "b"}])
+ anchor = agent._turn_base_usage_anchor
+ assert anchor["base_count"] == 2 # the unanswered ask is the estimated delta: main's `~`
+ assert anchored_context_tokens(agent._session_messages, anchor, charge_stale_thinking=False) == 700