The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): show the switched-to session's usage after /new, /resume or /branch
kshitijk4poor60e3fadd0196
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 269bebe7fc3..ad3c9b0ebdf 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -16,6 +16,7 @@ import queueimport threadingimport timeimport uuid+from contextlib import suppressfrom hermes_cli.gateway_client import GatewayClientError, GatewayRPCErrorfrom hermes_cli.gateway_connection import DISCONNECTED, CallStopped, lost_before@@ -161,25 +162,14 @@ class GatewayAgent:self._primary_runtime = Noneself._interrupt_requested = Falseself._active_children: list = []- self._api_latency_history: list = []- self._api_output_history: list = []- self._turn_base_usage_anchor = None- self._context_tokens = 0- self._turn_calls_base = 0self._turn_ask_index = None- self._turn_api_calls = Noneself._usage_stale = Falseself._current_task_id = self._current_turn_id = self._current_api_request_id = ""self._memory_manager = Noneself._memory_store = Noneself._checkpoint_mgr = None- self.session_api_calls = 0- self.session_total_tokens = 0- self.session_prompt_tokens = self.session_input_tokens = 0- self.session_completion_tokens = self.session_output_tokens = 0- self.session_cache_read_tokens = self.session_cache_write_tokens = 0- self.session_reasoning_tokens = 0self.context_compressor = _CompressorView()+ self._reset_session_figures()self._todo_store = _TodoView()self._generation = Noneself._admission = None@@ -376,6 +366,12 @@ class GatewayAgent:self._session_id = valueif previous is None or value == previous or not value:return+ # The session left behind keeps its own figures: a later frame of its must not repaint this one.+ left = self.connection.state(previous)+ with suppress(ValueError):+ left.usage_listeners.remove(self.apply_session_usage)+ with suppress(ValueError):+ left.request_listeners.remove(self._on_request_withdrawn)store = self._session_dbif store is not None and hasattr(store, "attach"):try:@@ -521,8 +517,27 @@ class GatewayAgent:def _invalidate_system_prompt(self, *a, **k):return None+ def _reset_session_figures(self):+ """Zero the per-session figures main's bar, spinner and /usage read (context length stays)."""+ for attr in _COUNTER_FROM_USAGE:+ setattr(self, attr, 0)+ compressor = self.context_compressor+ compressor.last_prompt_tokens, compressor.last_real_prompt_tokens, compressor.compression_count = 0, None, 0+ self._context_tokens = self._turn_calls_base = 0+ self._turn_base_usage_anchor = self._turn_api_calls = None+ self._api_latency_history, self._api_output_history = [], []+def reset_session_state(self, *a, **k):- return None+ """/new, /resume and /branch, after the ``session_id`` switch: drop the previous session's+ figures, then show the gateway's for this one (``session.stats``, else its cached+ ``session.usage``). A brand-new session (no transcript, no usage yet) reads zero until its+ first turn publishes, without a round trip."""+ self._reset_session_figures()+ state = self._state()+ if not (state.messages or state.usage):+ return+ if not self._refresh_stats() and state.usage:+ self.apply_session_usage(state.usage)def release_clients(self, *a, **k):return Nonediff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex b11599aec61..4a67e01cb7a 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -993,3 +993,39 @@ def test_a_voice_stopped_correction_is_consumed_not_requeued(make_agent, mode):sent = [m for m, _ in client.calls if m.startswith("session.")]assert sent == [{"steer": "session.steer", "interrupt": "session.redirect"}[mode]]assert agent._turn_ask_index == 3, "the running turn's history changed for a consumed stop"+++def test_a_session_switch_drops_the_previous_sessions_figures(make_agent):+ """/new, /resume and /branch repoint ``session_id`` then call ``reset_session_state``: the bar and+ /usage show the target's gateway figures (``session.stats``), never the session left behind, and+ a late frame of the old session does not repaint them."""+ agent, client = make_agent([])+ agent.connection.state(SID).apply_usage(SESSION_USAGE)+ assert agent.session_api_calls == 5 and agent._api_latency_history+ original = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ if method == "session.stats" and params.get("session_id") == "local-other":+ return {"api_calls": 3, "input_tokens": 9}+ return await original(method, _timeout=_timeout, **params)+ client.rpc = rpc+ agent.connection.state("local-other").messages = [{"role": "user", "content": "earlier"}] # resumed+ agent.session_id = "local-other"+ agent.reset_session_state()+ assert (agent.session_api_calls, agent.session_input_tokens, agent.session_output_tokens) == (3, 9, 0)+ assert agent.context_compressor.last_prompt_tokens == 0 and agent._api_latency_history == []+ agent.connection.state(SID).apply_usage(dict(SESSION_USAGE, api_calls=6))+ assert agent.session_api_calls == 3+ assert agent._on_request_withdrawn not in agent.connection.state(SID).request_listeners+++def test_new_session_reads_zero_without_a_stats_round_trip(make_agent):+ """/new lands on a session the gateway just created (no transcript, no usage): its figures are+ known zero, so the reset makes no ``session.stats`` call."""+ agent, client = make_agent([])+ agent.connection.state(SID).apply_usage(SESSION_USAGE)+ agent.session_id = "local-fresh"+ client.calls.clear()+ agent.reset_session_state()+ assert agent.session_api_calls == 0 and agent._api_latency_history == []+ assert [method for method, _ in client.calls] == []