The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(credits): stop desktop reap/resume from re-announcing the same usage band
Brooklyn Nicholsonac80df141002
diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex 9f3359d5cdc..e145eae5f2a 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -380,6 +380,30 @@ def _credits_state_from_account(info) -> Optional[CreditsState]:return None+# Process-lifetime memory of the usage band last shown per session_id: see+# _remember_shown_band. Bounded MRU so a long-lived gateway cannot grow it without limit.+_seen_usage_bands: dict = {}+_SEEN_USAGE_BANDS_MAX = 500+++def _remember_shown_band(session_id, band) -> None:+ """Remember the usage band last evaluated for ``session_id`` (process-lifetime).++ Desktop reap/resume rebuilds the AIAgent per turn, so the in-memory ``_credits_latch``+ (and its ``usage_band``) never survives across messages — every rebuild re-announces the+ current band as a fresh crossing (#101578). ``agent.session_id`` IS stable across those+ rebuilds, so this map lets ``_hydrate_seed_state`` restore the band the user already saw.+ Deliberately NOT durable: a real process restart is a real ``session open`` and the+ cold-start seed should still warn immediately. Bounded (MRU eviction) so a long-lived+ gateway juggling many sessions cannot grow it without limit."""+ if not session_id:+ return+ _seen_usage_bands.pop(session_id, None) # re-insert at the MRU end+ _seen_usage_bands[session_id] = band+ if len(_seen_usage_bands) > _SEEN_USAGE_BANDS_MAX:+ _seen_usage_bands.pop(next(iter(_seen_usage_bands)))++def _hydrate_seed_state(agent, state) -> None:"""Install a seed CreditsState on the agent and fire the notice policy once. Primes the crossing gate:the cold-start snapshot IS the first observation, so a session opening in a band warns immediately."""@@ -389,6 +413,12 @@ def _hydrate_seed_state(agent, state) -> None:latch = getattr(agent, "_credits_latch", None)if isinstance(latch, dict) and state.used_fraction is not None:latch["seen_below_90"] = True # ONLY this gate — priming seen_grant_unspent would revive the steady-state nag+ # Restore the band this logical session already showed (desktop reap/resume rebuilds the+ # agent object but keeps session_id) so an unchanged band is not re-announced per message.+ prior_band = _seen_usage_bands.get(getattr(agent, "session_id", None))+ if prior_band is not None:+ latch["usage_band"] = prior_band+ latch["active"].add(CREDITS_USAGE_KEY)_rerun_notice_policy(agent)diff --git a/agent/rate_limit_credits.py b/agent/rate_limit_credits.pyindex a82543f77f1..c8cfd50996f 100644--- a/agent/rate_limit_credits.py+++ b/agent/rate_limit_credits.py@@ -133,6 +133,7 @@ class RateLimitCreditsMixin:returntry:from agent.credits_tracker import (+ _remember_shown_band,evaluate_credits_notices, is_free_tier_model, new_credits_latch, rewarm_pricing_before_depleted_notice,)latch = getattr(self, "_credits_latch", None)@@ -147,6 +148,12 @@ class RateLimitCreditsMixin:self._emit_notice_clear(key)for notice in to_show:self._emit_notice(notice)+ # Record the band this session last showed so a desktop reap/resume rebuild+ # (fresh agent + fresh latch, SAME session_id) restores it instead of+ # re-announcing the unchanged band as a fresh crossing (#101578). Both the+ # live-header path and the cold-start seed route through here, so this is the+ # single chokepoint.+ _remember_shown_band(getattr(self, "session_id", None), latch.get("usage_band"))except Exception:logger.warning("credits notice evaluation/emit failed", exc_info=True)diff --git a/tests/agent/test_credits_cold_start.py b/tests/agent/test_credits_cold_start.pyindex 3ef2790f33f..470082c29a1 100644--- a/tests/agent/test_credits_cold_start.py+++ b/tests/agent/test_credits_cold_start.py@@ -78,18 +78,21 @@ class _FakeAgent:the real policy against the latch (mirroring run_agent._emit_credits_notices,including the free-model suppression flag)."""- def __init__(self, provider="nous", model="", base_url=""):+ def __init__(self, provider="nous", model="", base_url="", session_id="session-1"): # session_id may be Nonefrom agent.credits_tracker import evaluate_credits_notices, is_free_tier_modelself.provider = providerself.model = modelself.base_url = base_url+ self.session_id = session_idself._credits_state = Noneself._credits_session_start_micros = Noneself._credits_latch = {"active": set(), "seen_below_90": False, "usage_band": None}self.emitted: list = []self._eval = evaluate_credits_noticesself._is_free = is_free_tier_model+ from agent.credits_tracker import _remember_shown_band+ self._remember_band = _remember_shown_banddef _emit_credits_notices(self):if self._credits_state is None:@@ -100,6 +103,9 @@ class _FakeAgent:model_is_free=self._is_free(self.model, self.base_url),)self.emitted.append(([n.key for n in show], clear))+ # Mirrors the post-fix rate_limit_credits chokepoint: the band this session+ # last showed is remembered so a rebuild restores it (#101578).+ self._remember_band(self.session_id, self._credits_latch.get("usage_band"))def _seed(agent, fixture):@@ -160,6 +166,92 @@ def test_seed_skips_non_nous():assert a._credits_state is None+# ── #101578: desktop reap/resume rebuilds must not re-announce the same band ──+#+# Desktop rebuilds the AIAgent (and its _credits_latch) on idle-reap/resume, but+# agent.session_id is stable across those rebuilds. A fresh latch that blindly+# re-primes seen_below_90 re-announces the CURRENT band on every rebuild even+# though the user already saw it moments ago on the previous incarnation.+++def _band_state(used_fraction_of_cap: float) -> CreditsState:+ """A subscription-cap CreditsState at the given used fraction."""+ cap = 20_000_000+ return _state(+ remaining_micros=int(cap * (1 - used_fraction_of_cap)),+ subscription_micros=int(cap * (1 - used_fraction_of_cap)),+ subscription_limit_micros=cap, subscription_limit_usd="20.00",+ denominator_kind="subscription_cap", paid_access=True,+ )+++def test_rebuild_with_same_band_does_not_refire(monkeypatch):+ import agent.credits_tracker as ct++ monkeypatch.setattr(ct, "_seen_usage_bands", {})+ _hydrate = ct._hydrate_seed_state++ # First incarnation: session opens already at 50% — fires once (cold-start seed behavior).+ a1 = _FakeAgent(session_id="desktop-session-1")+ a1._credits_state = _band_state(0.5)+ a1._credits_latch["seen_below_90"] = True+ a1._emit_credits_notices()+ assert a1.emitted == [(["credits.usage"], [])]++ # Desktop idle-reap/resume: a BRAND-NEW agent, fresh empty latch, SAME session_id,+ # usage unchanged (still 50%). Must NOT re-announce the band.+ a2 = _FakeAgent(session_id="desktop-session-1")+ _hydrate(a2, _band_state(0.5))+ assert a2.emitted == [([], [])]+++def test_rebuild_still_fires_on_genuine_band_change(monkeypatch):+ import agent.credits_tracker as ct++ monkeypatch.setattr(ct, "_seen_usage_bands", {})+ _hydrate = ct._hydrate_seed_state++ a1 = _FakeAgent(session_id="desktop-session-2")+ a1._credits_state = _band_state(0.5)+ a1._credits_latch["seen_below_90"] = True+ a1._emit_credits_notices()+ assert a1.emitted == [(["credits.usage"], [])]++ # Usage genuinely climbed to 75% before the next rebuild — must still warn.+ a2 = _FakeAgent(session_id="desktop-session-2")+ _hydrate(a2, _band_state(0.75))+ assert a2.emitted == [(["credits.usage"], ["credits.usage"])]+++def test_unrelated_session_id_not_suppressed(monkeypatch):+ import agent.credits_tracker as ct++ monkeypatch.setattr(ct, "_seen_usage_bands", {})+ _hydrate = ct._hydrate_seed_state++ a1 = _FakeAgent(session_id="desktop-session-a")+ a1._credits_state = _band_state(0.5)+ a1._credits_latch["seen_below_90"] = True+ a1._emit_credits_notices()+ assert a1.emitted == [(["credits.usage"], [])]++ # A different session at the same band has never been shown anything.+ a2 = _FakeAgent(session_id="desktop-session-b")+ _hydrate(a2, _band_state(0.5))+ assert a2.emitted == [(["credits.usage"], [])]+++def test_agent_without_session_id_falls_back_to_prior_behavior(monkeypatch):+ """CLI/plain agents may have no session_id — degrade to the pre-fix behavior+ (cold-start seed warns at open), never raise."""+ import agent.credits_tracker as ct++ monkeypatch.setattr(ct, "_seen_usage_bands", {})+ a = _FakeAgent(session_id=None)+ ct._hydrate_seed_state(a, _band_state(0.5))+ assert a.emitted == [(["credits.usage"], [])]++# ── background seed: the pricing warm the free-model gate depends on ─────────_NOUS_BASE = "https://inference-api.nousresearch.com/v1"