The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(credits): reintroduce grant_spent, gated on an in-session crossing (#73634)
Siddharth Balyan3cedac00b787
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 92d89c8d600..0fafd50bb50 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -887,8 +887,10 @@ def init_agent(# report cumulative micros spent. Surfaced behind HERMES_DEV_CREDITS.agent._credits_state = Noneagent._credits_session_start_micros = None- # Threshold-notice latch (L4): active sticky-notice keys + the warn90 crossing gate.- agent._credits_latch = {"active": set(), "seen_below_90": False, "usage_band": None}+ # Threshold-notice latch (L4): active sticky-notice keys + the crossing gates.+ from agent.credits_tracker import new_credits_latch++ agent._credits_latch = new_credits_latch()# OpenRouter response cache hit counter — incremented when# X-OpenRouter-Cache-Status: HIT is seen in streaming response headers.diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex dfd39e4290f..b47c3f274ed 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -170,6 +170,27 @@ CREDITS_USAGE_BANDS: tuple[tuple[float, str, int], ...] = ()CREDITS_USAGE_KEY = "credits.usage" # single key for the escalating usage notice+# Minimum subscription balance that counts as "grant not yet spent" for the+# grant_spent crossing gate (see evaluate_credits_notices). 1¢: portal-seeded+# states derive micros from float dollars and can carry sub-cent residue where+# the inference headers report exactly 0 — without this floor such a seed+# opens the gate and the first header re-creates the at-open nag.+GRANT_UNSPENT_MIN_MICROS = 10_000+++def new_credits_latch() -> dict:+ """Fresh notice latch in the shape :func:`evaluate_credits_notices` expects.++ The policy owns this schema — every producer (agent build, lazy re-init,+ tests) must build the latch through here so a new gate key lands everywhere+ at once instead of drifting across hand-rolled literals."""+ return {+ "active": set(),+ "seen_below_90": False,+ "usage_band": None,+ "seen_grant_unspent": False,+ }+# ── AgentNotice (out-of-band notice payload; driver-agnostic) ────────────────@@ -250,7 +271,8 @@ def evaluate_credits_notices() -> tuple[list[AgentNotice], list[str]]:"""Reconcile credits notices against the latch. Mutates ``latch`` IN PLACE.- latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int]}.+ latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int],+ "seen_grant_unspent": bool}.``model_is_free``: True when the session's active model is a Nous free-tiermodel (see :func:`is_free_tier_model`). Suppresses the ``credits.depleted``@@ -277,6 +299,18 @@ def evaluate_credits_notices(if uf is not None and uf < _lowest_band:latch["seen_below_90"] = True # gate opened: usage-band notices may now fire+ # Grant-spent crossing gate: grant_spent may fire only after this session+ # has OBSERVED the grant meaningfully unspent (≥1¢ left — see+ # GRANT_UNSPENT_MIN_MICROS). Opening at grant-spent is a steady STATE, not+ # an event — /usage carries it; only a live in-session crossing announces.+ # Unlike seen_below_90, seeds must NOT prime this gate.+ if (+ uf is not None+ and uf < 1.0+ and state.subscription_micros >= GRANT_UNSPENT_MIN_MICROS+ ):+ latch["seen_grant_unspent"] = True+active = latch["active"]# ── Conditions ───────────────────────────────────────────────────────────@@ -288,12 +322,20 @@ def evaluate_credits_notices(current_band = band# Top-up suppression: when the account holds purchased (top-up) credits,# the subscription-cap gauge is the wrong denominator — warning "90% used"- # at a user sitting on $50 of top-up is noise. Suppress the usage band- # entirely; /usage still reports the full balance breakdown. A top-up- # landing mid-session flips current_band → None and the clear path below- # removes any showing band line.+ # at a user sitting on $50 of top-up is noise (and it previously stuck+ # PERMANENTLY alongside grant_spent at >=100%). Suppress the usage band+ # entirely; the cap-reached case is covered by the grant_spent info notice+ # below, which already names the remaining top-up balance. A top-up landing+ # mid-session flips current_band → None and the clear path below removes+ # any showing band line.if state.purchased_micros > 0:current_band = None+ grant_cond = (+ state.denominator_kind == "subscription_cap"+ and uf is not None+ and uf >= 1.0+ and state.purchased_micros > 0+ )depleted_cond = not state.paid_access# ── usage gauge (escalating single notice: 50 → 75 → 90) ──────────────────@@ -332,6 +374,33 @@ def evaluate_credits_notices(active.add(CREDITS_USAGE_KEY)latch["usage_band"] = target_band+ # ── grant_spent ──────────────────────────────────────────────────────────+ # The crossing gate guards only the SHOW and is CONSUMED by it — one+ # announcement per crossing. A header flicker (uf → None → back to 1.0)+ # clears the sticky line via grant_cond but cannot re-announce; only a+ # renewal that re-opens the gate (a fresh ≥1¢ observation) arms the next+ # announcement. .get(): default closed for any hand-built latch missing+ # the key, so a first observation can never fire this notice.+ if (+ grant_cond+ and "credits.grant_spent" not in active+ and latch.get("seen_grant_unspent", False)+ ):+ to_show.append(+ AgentNotice(+ text=f"• Grant spent · ${state.purchased_usd} top-up left",+ level="info",+ kind=CREDITS_NOTICE_KIND,+ key="credits.grant_spent",+ id="credits.grant_spent",+ )+ )+ active.add("credits.grant_spent")+ latch["seen_grant_unspent"] = False+ elif "credits.grant_spent" in active and not grant_cond:+ to_clear.append("credits.grant_spent")+ active.discard("credits.grant_spent")+# ── depleted ─────────────────────────────────────────────────────────────# Suppressed while the active model is free: inference still works there,# so the error banner would just alarm users (free-tier users especially,@@ -603,7 +672,8 @@ _DEV_FIXTURES: dict[str, dict] = {subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",denominator_kind="subscription_cap", paid_access=True,),- "grant_exhausted": dict( # cap reached + purchased>0 → no notice (gauge suppressed by top-up)+ "grant_exhausted": dict( # uf == 1.0 + purchased>0 → SILENT at open (crossing-gated);+ # flip healthy → grant_exhausted via the fixture-file path to see credits.grant_spentremaining_micros=12_340_000, remaining_usd="12.34",subscription_micros=0, subscription_usd="0.00",subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",@@ -717,6 +787,9 @@ def _hydrate_seed_state(agent, state) -> None:agent._credits_session_start_micros = state.remaining_micros_latch = getattr(agent, "_credits_latch", None)if isinstance(_latch, dict) and state.used_fraction is not None:+ # Prime ONLY seen_below_90 (open-high band warnings are wanted at open).+ # Never prime seen_grant_unspent here: a seed observing grant-spent is a+ # steady state, and priming it would revive the every-session nag._latch["seen_below_90"] = Trueemit = getattr(agent, "_emit_credits_notices", None)if callable(emit):diff --git a/apps/desktop/src/app/contrib/dev/credits-notice-demo.ts b/apps/desktop/src/app/contrib/dev/credits-notice-demo.tsindex a2ba8080da1..1766489818b 100644--- a/apps/desktop/src/app/contrib/dev/credits-notice-demo.ts+++ b/apps/desktop/src/app/contrib/dev/credits-notice-demo.ts@@ -25,7 +25,7 @@ interface NoticeStep {}// Walks the same lifecycle the Nous credits tracker drives: usage escalates in-// place (50→75→90, one key), then the depleted/restored pair.+// place (50→75→90, one key), then grant-spent, then the depleted/restored pair.// Wraps around. These are all separate SHOW steps; the stepper auto-clears the// previous notice when the key changes, so the demo shows one toast at a time// (real usage CAN stack these, but that's noise when you're eyeballing a single@@ -34,6 +34,7 @@ const STEPS: readonly NoticeStep[] = [{ key: 'credits.usage', kind: 'sticky', level: 'info', text: "• You've used $110.00 of your $220.00 cap" },{ key: 'credits.usage', kind: 'sticky', level: 'warn', text: "⚠ You've used $165.00 of your $220.00 cap" },{ key: 'credits.usage', kind: 'sticky', level: 'warn', text: "⚠ You've used $198.00 of your $220.00 cap" },+ { key: 'credits.grant_spent', kind: 'sticky', level: 'info', text: '• Grant spent · $12.00 top-up left' },{ key: 'credits.depleted', kind: 'sticky', level: 'error', text: '✕ Credit access paused · run /topup to top up' },{ key: 'credits.restored', kind: 'ttl', level: 'success', text: '✓ Credit access restored', ttl_ms: 8000 }]diff --git a/apps/desktop/src/store/agent-notices.test.ts b/apps/desktop/src/store/agent-notices.test.tsindex 540a3cfad6e..1333969aab4 100644--- a/apps/desktop/src/store/agent-notices.test.ts+++ b/apps/desktop/src/store/agent-notices.test.ts@@ -93,6 +93,11 @@ test('the trailing "· detail" is split off as a secondary meta line, not inlineexpect(paused?.message).toBe('Credit access paused')expect(paused?.meta).toBe('run /topup to top up')+ // grant_spent carries a `· detail` tail too.+ const grant = noticeToToast({ key: 'credits.grant_spent', level: 'info', text: '• Grant spent · $12.00 top-up left' })+ expect(grant?.message).toBe('Grant spent')+ expect(grant?.meta).toBe('$12.00 top-up left')+// The usage line has no middot → whole line is the message, no meta.const plain = noticeToToast(usage())expect(plain?.message).toBe("You've used $110.00 of your $220.00 cap")@@ -104,6 +109,7 @@ test('splitMeta splits on the first space-middot-space only', () => {'Credit access paused','run /topup to top up'])+ expect(splitMeta('Grant spent · $12.00 top-up left')).toEqual(['Grant spent', '$12.00 top-up left'])expect(splitMeta('Credit access restored')).toEqual(['Credit access restored', undefined])// Interior middots after the first split stay in the meta.expect(splitMeta('a · b · c')).toEqual(['a', 'b · c'])@@ -125,7 +131,7 @@ test('usageFraction derives $used / $cap from the notice text', () => {expect(usageFraction("You've used $15.00 of your $20.00 cap")).toBeCloseTo(0.75)expect(usageFraction("You've used $198.00 of your $220.00 cap")).toBeCloseTo(0.9)// Fewer than two amounts, or a zero cap → no fraction.- expect(usageFraction('Credit access restored')).toBeNull()+ expect(usageFraction('Grant spent')).toBeNull()expect(usageFraction("You've used $5.00 of your $0.00 cap")).toBeNull()expect(usageFraction(undefined)).toBeNull()})@@ -146,7 +152,7 @@ test('usage accent stays muted below 75%, then ramps orange → red', () => {test('terminal credit states carry their own accent; others stay default', () => {expect(noticeAccent({ key: 'credits.depleted', text: '✕ paused' })).toBe('var(--ui-red)')expect(noticeAccent({ key: 'credits.restored', text: '✓ restored' })).toBe('var(--ui-green)')- expect(noticeAccent({ key: 'credits.usage', text: '• Credits update' })).toBeUndefined()+ expect(noticeAccent({ key: 'credits.grant_spent', text: '• Grant spent' })).toBeUndefined()expect(noticeAccent(undefined)).toBeUndefined()})@@ -197,7 +203,7 @@ test('clearAgentNotice dismisses only the matching key', () => {test('only credits.depleted and credits.restored map to a native notification', () => {expect(nativeNoticeInput(usage({ key: 'credits.usage' }), 'Credits')).toBeNull()- expect(nativeNoticeInput(usage({ key: 'credits.other' }), 'Credits')).toBeNull()+ expect(nativeNoticeInput(usage({ key: 'credits.grant_spent' }), 'Credits')).toBeNull()expect(nativeNoticeInput({ text: 'x', key: undefined }, 'Credits')).toBeNull()expect(nativeNoticeInput({ text: '', key: 'credits.depleted' }, 'Credits')).toBeNull()})diff --git a/apps/desktop/src/store/agent-notices.ts b/apps/desktop/src/store/agent-notices.tsindex ae6ccfe22bd..683855428ee 100644--- a/apps/desktop/src/store/agent-notices.ts+++ b/apps/desktop/src/store/agent-notices.ts@@ -175,8 +175,8 @@ export function clearAgentNotice(key: string | undefined): void {// Only these two credit notices are urgent enough to break through as a native// OS notification (when Hermes is backgrounded). The escalating usage line-// (`credits.usage`) stays an in-app toast only — it isn't worth interrupting-// the user's OS for.+// (`credits.usage`) and the grant-spent notice stay in-app toasts only — they+// aren't worth interrupting the user's OS for.const NATIVE_NOTICE_KEYS = new Set(['credits.depleted', 'credits.restored'])/**diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 6c492d818a9..e80eb6b77b4 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -1962,7 +1962,7 @@ DEFAULT_CONFIG = {# class of over-claim that otherwise forces users to run# `git status` to verify edits landed. Set false to suppress."file_mutation_verifier": True,- # Nous credits status-bar notices (usage bands, depleted /+ # Nous credits status-bar notices (usage bands, grant-spent, depleted /# restored). When false, no credits notices are emitted — balance data# is still captured and /usage keeps working. Off switch for sub +# top-up users who find the gauge noisy.diff --git a/run_agent.py b/run_agent.pyindex 62032e990c8..dff990eb83e 100644--- a/run_agent.py+++ b/run_agent.py@@ -3569,6 +3569,9 @@ class AIAgent:self._credits_session_start_micros = _fixture.remaining_micros_latch = getattr(self, "_credits_latch", None)if isinstance(_latch, dict):+ # Only seen_below_90 — never seen_grant_unspent (priming it would+ # fire grant_spent on a fixture's first observation, the exact+ # every-session nag the gate exists to prevent)._latch["seen_below_90"] = True # let warn90 fire without a real crossing_used = _fixture.used_fractionlogger.info(@@ -3647,10 +3650,10 @@ class AIAgent:if state is None:returntry:- from agent.credits_tracker import evaluate_credits_notices, is_free_tier_model+ from agent.credits_tracker import evaluate_credits_notices, is_free_tier_model, new_credits_latchlatch = getattr(self, "_credits_latch", None)if latch is None:- latch = self._credits_latch = {"active": set(), "seen_below_90": False, "usage_band": None}+ latch = self._credits_latch = new_credits_latch()# Free-model gate: a depleted account on a free model can still# inference, so the depleted error banner is suppressed. Local-data# only (":free" suffix + pricing-cache peek) — never a network call.diff --git a/tests/agent/test_credits_cold_start.py b/tests/agent/test_credits_cold_start.pyindex 8140eac4af7..620d48ecabe 100644--- a/tests/agent/test_credits_cold_start.py+++ b/tests/agent/test_credits_cold_start.py@@ -49,13 +49,14 @@ def test_cold_start_opens_already_at_90pct_warns():assert "credits.usage" in _cold_start_notices(s)-def test_cold_start_grant_exhausted_no_notice():- """Cap reached but top-up funds remain → NO notice.-- The usage band is suppressed whenever purchased (top-up) credits exist- (the sub-cap gauge is the wrong denominator for an account that can keep- spending), and the old 'Grant spent · $X top-up left' notice was removed —- it camped in the status bar with no action to take."""+def test_cold_start_grant_exhausted_stays_silent():+ """Cap reached but top-up funds remain → NO notice at cold start.++ The usage band is suppressed whenever purchased (top-up) credits exist (the+ sub-cap gauge is the wrong denominator for an account that can keep+ spending). grant_spent is gated on an in-session crossing (seen_grant_unspent)+ — a session that OPENS in this state is observing a steady state, not an+ event, so re-announcing it every session open is noise. /usage carries it."""s = _state(remaining_micros=12_340_000, subscription_micros=0,subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",@@ -194,6 +195,34 @@ def test_seed_healthy_no_notice():assert a.emitted == [([], [])]+def test_seed_grant_exhausted_stays_silent():+ """A session that OPENS with the grant already spent and top-up remaining is a+ steady STATE, not an event. The seed must not re-announce it on every session+ open (/usage carries the balance); only a live in-session crossing may fire+ grant_spent. This is the every-session "Grant spent · $X top-up left" nag fix."""+ a = _FakeAgent()+ assert _seed(a, "grant_exhausted") is True+ assert a._credits_state is not None+ assert a.emitted == [([], [])]+++def test_live_crossing_after_seed_still_fires_grant_spent():+ """The gate opens when the session observes the grant NOT yet spent — a healthy+ seed followed by a grant-exhausted header is a real in-session crossing and must+ still announce grant_spent once."""+ a = _FakeAgent()+ assert _seed(a, "healthy") is True+ a.emitted = []+ a._credits_state = _state( # the grant_exhausted shape, as a live header would carry it+ remaining_micros=12_340_000, subscription_micros=0,+ subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",+ purchased_micros=12_340_000, purchased_usd="12.34",+ denominator_kind="subscription_cap", paid_access=True,+ )+ a._emit_credits_notices()+ assert a.emitted == [(["credits.grant_spent"], [])]++def test_seed_is_idempotent():a = _FakeAgent()_seed(a, "sub_90pct")diff --git a/tests/agent/test_credits_policy.py b/tests/agent/test_credits_policy.pyindex 81c72527115..6c89602446f 100644--- a/tests/agent/test_credits_policy.py+++ b/tests/agent/test_credits_policy.py@@ -1,7 +1,8 @@"""Tests for evaluate_credits_notices — pure threshold reconciliation policy (L4.1).-All tests use fresh latch = {"active": set(), "seen_below_90": False, "usage_band": None} per scenario.-CreditsState is constructed directly (not parsed from headers).+All tests use a fresh latch (new_credits_latch(), the shape every production+caller builds) per scenario. CreditsState is constructed directly (not parsed+from headers)."""from __future__ import annotations@@ -14,6 +15,7 @@ from agent.credits_tracker import (AgentNotice,CreditsState,evaluate_credits_notices,+ new_credits_latch,)@@ -21,7 +23,7 @@ from agent.credits_tracker import (def fresh_latch() -> dict:- return {"active": set(), "seen_below_90": False, "usage_band": None}+ return new_credits_latch()def state_with_fraction(@@ -163,10 +165,11 @@ class TestBoundaryFractions:assert "credits.usage" in keysassert "credits.usage" not in to_clear- def test_just_below_1_0_boundary_no_notices_with_topup(self):- """subscription_micros = 1 (used_fraction just under 1.0) with top-up- funds → nothing fires: gauge suppressed by purchased>0, and the old- grant_spent notice no longer exists at any fraction.+ def test_just_below_1_0_does_not_fire_grant_spent(self):+ """subscription_micros = limit - 1 (used_fraction just under 1.0) must NOT fire grant_spent.++ Locks the boundary so a future used_fraction clamp refactor cannot fire+ grant_spent a micro early."""latch = fresh_latch()limit = 20_000_000@@ -181,43 +184,107 @@ class TestBoundaryFractions:)assert s.used_fraction is not None and s.used_fraction < 1.0to_show, to_clear = evaluate_credits_notices(s, latch)- assert to_show == []- assert to_clear == []-+ assert all(n.key != "credits.grant_spent" for n in to_show)+ assert "credits.grant_spent" not in to_clear-# ── Scenario 4: grant_spent removed ──────────────────────────────────────────+# ── Scenario 4: grant_spent ───────────────────────────────────────────────────-class TestGrantSpentRemoved:- """The 'Grant spent · $X top-up left' notice was removed (July 2026) — it- camped in the status bar for every sub+top-up user and carried no action.- The policy must never emit or clear the key, even for the state that used- to fire it (cap reached + purchased top-up funds)."""- def _old_trigger_state(self) -> CreditsState:+class TestGrantSpent:+ def _grant_state(self, purchased_micros: int = 12_340_000) -> CreditsState:return state_with_fraction(1.0,denominator_kind="subscription_cap",- purchased_micros=12_340_000,+ purchased_micros=purchased_micros,purchased_usd="12.34",)- def test_never_fires_on_old_trigger_state(self):+ def test_grant_spent_silent_on_first_obs(self):+ """Crossing gate: a fresh latch that OPENS already at grant-spent (the+ every-session cold-start case) must NOT fire — only a live in-session+ crossing announces grant_spent."""latch = fresh_latch()- to_show, to_clear = evaluate_credits_notices(self._old_trigger_state(), latch)+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)assert all(n.key != "credits.grant_spent" for n in to_show)assert "credits.grant_spent" not in to_clear- assert "credits.grant_spent" not in latch["active"]- def test_stale_active_key_is_left_alone(self):- """A latch persisted from an older build may still hold the key; the- policy neither re-fires nor clears it (frontends drop unknown keys)."""+ def test_grant_spent_fires_on_live_crossing(self):+ """Observing the grant NOT yet spent (uf < 1.0) opens the gate; the later+ crossing to >= 1.0 with top-up remaining announces once."""+ latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.75), latch)+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)+ assert "credits.grant_spent" in [n.key for n in to_show]++ def test_grant_spent_no_refire(self):latch = fresh_latch()- latch["active"].add("credits.grant_spent")- to_show, to_clear = evaluate_credits_notices(self._old_trigger_state(), latch)+ evaluate_credits_notices(state_with_fraction(0.75), latch) # open the gate+ evaluate_credits_notices(self._grant_state(), latch)+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)assert all(n.key != "credits.grant_spent" for n in to_show)assert "credits.grant_spent" not in to_clear+ def test_grant_spent_flicker_does_not_reannounce(self):+ """The gate is CONSUMED by the announcement. A header flicker+ (uf → None → back to 1.0) clears the sticky line but must not+ re-announce — one crossing, one announcement."""+ latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.75), latch) # open the gate+ evaluate_credits_notices(self._grant_state(), latch) # announce + consume+ to_show, to_clear = evaluate_credits_notices(+ state_with_fraction(None, purchased_micros=12_340_000, purchased_usd="12.34"),+ latch,+ )+ assert "credits.grant_spent" in to_clear # sticky line drops on flicker+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)+ assert all(n.key != "credits.grant_spent" for n in to_show)++ def test_grant_spent_reannounces_after_renewal_crossing(self):+ """A renewal (grant meaningfully unspent again) re-opens the gate, so the+ NEXT exhaustion is a fresh crossing and announces again."""+ latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.75), latch)+ evaluate_credits_notices(self._grant_state(), latch) # first crossing+ evaluate_credits_notices(state_with_fraction(0.10), latch) # renewal: clears + re-opens+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)+ assert "credits.grant_spent" in [n.key for n in to_show]++ def test_sub_cent_residual_does_not_open_gate(self):+ """A float-derived portal seed can report a sub-cent grant residual where+ the inference headers say exactly spent. Below GRANT_UNSPENT_MIN_MICROS+ the observation must NOT open the gate — otherwise the first header+ after such a seed re-creates the at-open nag."""+ latch = fresh_latch()+ s = CreditsState(+ subscription_limit_micros=20_000_000,+ subscription_limit_usd="20.00",+ subscription_micros=4_000, # $0.004 left — sub-cent residue+ denominator_kind="subscription_cap",+ purchased_micros=12_340_000,+ purchased_usd="12.34",+ paid_access=True,+ )+ assert s.used_fraction is not None and s.used_fraction < 1.0+ evaluate_credits_notices(s, latch)+ to_show, to_clear = evaluate_credits_notices(self._grant_state(), latch)+ assert all(n.key != "credits.grant_spent" for n in to_show)++ def test_grant_spent_clears_when_purchased_zero(self):+ latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.75), latch) # open the gate+ evaluate_credits_notices(self._grant_state(), latch)+ # Now purchased → 0: grant_cond becomes False+ s_no_purchase = state_with_fraction(+ 1.0,+ denominator_kind="subscription_cap",+ purchased_micros=0,+ purchased_usd="0.00",+ )+ to_show, to_clear = evaluate_credits_notices(s_no_purchase, latch)+ assert "credits.grant_spent" in to_clear+ assert all(n.key != "credits.grant_spent" for n in to_show)+# ── Scenario 5: depleted + recovery ──────────────────────────────────────────@@ -443,10 +510,9 @@ class TestNoticeCopy:assert "$20.00" in warn_notice.textassert "cap" in warn_notice.text- def test_grant_spent_never_emitted(self):- """Old grant_spent trigger state produces no notice at all — the gauge- is suppressed by top-up and the grant_spent notice is gone."""+ def test_grant_spent_contains_verbatim_purchased_usd(self):latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.10), latch) # open the crossing gates = state_with_fraction(1.0,denominator_kind="subscription_cap",@@ -454,7 +520,9 @@ class TestNoticeCopy:purchased_usd="12.34",)to_show, _ = evaluate_credits_notices(s, latch)- assert to_show == []+ grant_notice = next(n for n in to_show if n.key == "credits.grant_spent")+ assert "$12.34" in grant_notice.text+ assert "top-up left" in grant_notice.textdef test_depleted_mentions_credits_command(self):latch = fresh_latch()@@ -468,11 +536,19 @@ class TestNoticeCopy:class TestSeverityOrder:- def test_depleted_only_notice_with_topup_at_cap(self):- """With top-up funds and cap reached while unpaid, only depleted fires:- the usage gauge is suppressed by purchased>0 and grant_spent is gone."""- latch = {"active": set(), "seen_below_90": True, "usage_band": None}+ def test_multiple_new_notices_ordered_ascending_severity(self):+ """grant_spent < depleted in to_show when both fire in one call.++ (usage is suppressed here: purchased>0 — see TestTopUpSuppression.+ usage + grant_spent are now mutually exclusive by design.)+ """+ latch = {"active": set(), "seen_below_90": True, "usage_band": None,+ "seen_grant_unspent": True}+ # Build state: subscription_cap, uf >= 1.0, purchased_micros > 0, NOT paid_access+ # grant_cond: subscription_cap + uf >= 1.0 + purchased > 0 ✓+ # depleted_cond: not paid_access ✓+ # usage band: suppressed (purchased > 0)s = CreditsState(subscription_limit_micros=20_000_000,subscription_limit_usd="20.00",@@ -484,7 +560,11 @@ class TestSeverityOrder:)to_show, _ = evaluate_credits_notices(s, latch)keys = [n.key for n in to_show]- assert keys == ["credits.depleted"]+ assert "credits.usage" not in keys+ assert "credits.grant_spent" in keys+ assert "credits.depleted" in keys+ # Ascending severity: grant_spent before depleted+ assert keys.index("credits.grant_spent") < keys.index("credits.depleted")def test_usage_before_depleted_without_topup(self):"""With no top-up funds, usage fires and precedes depleted."""@@ -554,10 +634,11 @@ class TestTopUpSuppression:assert "$19.00" in n.textassert latch["usage_band"] == 90- def test_no_notice_at_cap_with_topup(self):- """Cap reached with top-up funds → nothing fires: gauge suppressed,- grant_spent removed."""+ def test_grant_spent_still_fires_with_topup(self):+ """Suppression only affects the gauge — grant_spent (which NEEDS purchased>0)+ is untouched."""latch = fresh_latch()+ evaluate_credits_notices(state_with_fraction(0.10), latch) # open the crossing gates = state_with_fraction(1.0,denominator_kind="subscription_cap",@@ -565,7 +646,9 @@ class TestTopUpSuppression:purchased_usd="12.34",)to_show, _ = evaluate_credits_notices(s, latch)- assert to_show == []+ keys = [n.key for n in to_show]+ assert "credits.grant_spent" in keys+ assert "credits.usage" not in keysdef test_depleted_unaffected_by_topup_suppression(self):latch = fresh_latch()diff --git a/tests/gateway/test_notice_rendering.py b/tests/gateway/test_notice_rendering.pyindex 292155f1408..8625b263fc4 100644--- a/tests/gateway/test_notice_rendering.py+++ b/tests/gateway/test_notice_rendering.py@@ -63,7 +63,10 @@ def test_real_policy_notices_render_without_doubling():from agent.credits_tracker import CreditsState, evaluate_credits_noticesdef _emitted(uf=None, paid=True, purchased=0):- latch = {"active": set(), "seen_below_90": True, "usage_band": None}+ # Both crossing gates pre-opened: this test's subject is RENDERING of+ # every notice the policy can emit, not the gating.+ latch = {"active": set(), "seen_below_90": True, "usage_band": None,+ "seen_grant_unspent": True}if uf is None:st = CreditsState(subscription_limit_micros=None, subscription_micros=0,@@ -84,10 +87,12 @@ def test_real_policy_notices_render_without_doubling():notices = (_emitted(uf=0.9) # band 90 (warn)+ _emitted(uf=0.5) # band 50 (info)- + _emitted(uf=1.0, purchased=5_000_000) # top-up at cap → no notices (empty)+ + _emitted(uf=1.0, purchased=5_000_000) # grant_spent (band suppressed by top-up)+ _emitted(uf=None, paid=False) # depleted)- assert notices, "policy produced no notices to check"+ # Every leg above must actually produce its notice — a gate regression that+ # silences one leg must fail here, not silently shrink the coverage.+ assert len(notices) == 4, [n.key for n in notices]for n in notices:assert render_notice_line(n) == n.text # verbatim — no prepended glyphdiff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.tsindex 3c373ac5df8..91380466487 100644--- a/ui-tui/src/app/turnController.ts+++ b/ui-tui/src/app/turnController.ts@@ -989,12 +989,12 @@ class TurnController {this.interrupted = falsethis.persistedToolLabels.clear()// "Flash and yield" notices clear when a new turn starts: a usage-band heads-up- // (credits.usage, 50/75/90%) should show once, then get out of the way — not- // camp the bar. Depletion (credits.depleted) and other notices stay — they're- // explicitly sticky until the policy clears them. The Python `active` latch- // retains the key, so a yielded notice won't re-fire on the next turn.- // (credits.grant_spent is also cleared here for back-compat with older- // backends that still emit it — the notice was removed in July 2026.)+ // (credits.usage, 50/75/90%) and the one-time "grant spent" transition+ // (credits.grant_spent) should show once, then get out of the way — not camp the+ // bar (e.g. "Grant spent · $990 top-up left" sitting there with plenty of top-up+ // left). Depletion (credits.depleted) and other notices stay — they're explicitly+ // sticky until the policy clears them. The Python `active` latch retains the key,+ // so a yielded notice won't re-fire on the next turn.const yieldingNoticeKey = getUiState().notice?.keyif (yieldingNoticeKey === 'credits.usage' || yieldingNoticeKey === 'credits.grant_spent') {diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex b02be8eb77f..da0cf2adb9c 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1542,7 +1542,7 @@ display:enabled: falsefields: ["model", "context_pct", "cwd"]file_mutation_verifier: true # Append an advisory footer when write_file/patch calls failed this turn- credits_notices: true # Nous credits status-bar notices (usage bands, depleted). false = silence them; /usage still works+ credits_notices: true # Nous credits status-bar notices (usage bands, grant-spent, depleted). false = silence them; /usage still workslanguage: en # UI language for static messages (approval prompts, some gateway replies). en | zh | zh-hant | ja | de | es | fr | tr | uk | af | ko | it | ga | pt | ru | hu```