Skip to content

The agent that grows with you

PR review comments

rob-maroncafa03f7f431
diff --git a/agent/account_usage.py b/agent/account_usage.py
index 4f56bc7630f..5512d180eee 100644
--- a/agent/account_usage.py
+++ b/agent/account_usage.py
@@ -27,6 +27,7 @@ _DEPLETED_LINE = "Status: access depleted — top up to restore"
_WINDOW_TOP_TIER_USED_UP = "Monthly large-model usage is used up."
_WINDOW_PAUSED_LINE = ("Status: included usage paused. Your subscription payment failed. Update your card to restore it. "
"Until then, Hermes uses your credits.")
+_WINDOW_PAUSED_OTHER_LINE = "Status: included usage paused. See Billing in the Portal. Until then, Hermes uses your credits."
def _utc_now() -> datetime:
@@ -250,7 +251,8 @@ def _usage_window_rows(gauges: Any, *, paused_reason: Any,
if top_full:
lines.append(_window_top_tier_line(top_row.reset_at if top_row else None, keep_going_on_credits))
if isinstance(paused_reason, str) and paused_reason:
- lines.append(_WINDOW_PAUSED_LINE)
+ from agent.usage_gauges import paused_for_payment
+ lines.append(_WINDOW_PAUSED_LINE if paused_for_payment(paused_reason) else _WINDOW_PAUSED_OTHER_LINE)
elif keep_going_on_credits is False:
lines.append(_WINDOW_KEEP_GOING_OFF_LINE)
elif keep_going_on_credits is True:
@@ -431,6 +433,17 @@ def nous_credits_view(*, markdown: bool = False, timeout: float = 10.0, credits_
return [], False
+def nous_credits_usage_fields(agent: Any = None) -> dict[str, Any]:
+ """The ``session.usage`` fields for the Nous credits block: ``credits_lines`` (when there are any) and
+ ``credits_usage_window`` for the usage-window layout. Reads *agent*'s live credits headers. Never raises."""
+ try:
+ lines, is_window = nous_credits_view(credits_state=getattr(agent, "_credits_state", None) if agent else None)
+ except Exception:
+ logger.debug("credits ▸ /usage fields unavailable", exc_info=True)
+ return {}
+ return ({"credits_lines": lines} | ({"credits_usage_window": True} if is_window else {})) if lines else {}
+
+
def _snapshot_from_credits_state(state) -> Optional[AccountUsageSnapshot]:
"""Header-shaped CreditsState (dev fixture) → /usage snapshot, same shape as the portal path. *_usd strings
are display-only; the % comes from CreditsState.used_fraction. Fail-open → None."""
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 6c1c09a9099..1d8e485170d 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1054,12 +1054,8 @@ def recover_with_credential_pool(
# Pass classified semantics, not just the status: a billing 403 and an edge-throttle 403
# need opposite cooldowns.
if effective_reason is not None:
- failure_reason = "usage_window" if (error_context or {}).get("usage_window") else effective_reason.value
- if effective_reason == FailoverReason.billing and billing_unverified:
- # Ambiguous billing body: size the cooldown as transient, not a 1-hour bench.
- from agent.credential_pool import FAILURE_REASON_BILLING_UNVERIFIED
- failure_reason = FAILURE_REASON_BILLING_UNVERIFIED
- kwargs["failure_reason"] = failure_reason
+ from agent.credential_pool_model_cooldowns import pool_failure_reason
+ kwargs["failure_reason"] = pool_failure_reason(effective_reason, error_context, billing_unverified)
model = getattr(agent, "model", None)
if isinstance(model, str) and model.strip():
kwargs["model"] = model
diff --git a/agent/chat_completion_headers.py b/agent/chat_completion_headers.py
index 16f4154f419..7bf461aac85 100644
--- a/agent/chat_completion_headers.py
+++ b/agent/chat_completion_headers.py
@@ -13,8 +13,8 @@ def _chat_completion_capturing_headers(agent, client, api_kwargs: dict):
The parsed ``ChatCompletion`` drops headers, so without this a non-streaming turn never
observes ``x-nous-credits-*`` (usage-window ``spend_source`` / gauges go stale). The SDK's
- ``with_raw_response`` returns the same request with headers attached; test doubles
- (``Mock`` clients, namespaces without the attribute) keep the plain call. Usage-window plans
+ ``with_raw_response`` returns the same request with headers attached; a client without it keeps
+ the plain call. Usage-window plans
only: every other provider, and a Nous session not yet known to be on a window plan (the
session-start seed or a stream header establishes it), keep the plain call; headers are
captured only when the response itself is the usage-window kind. A capture failure never
@@ -25,9 +25,7 @@ def _chat_completion_capturing_headers(agent, client, api_kwargs: dict):
if getattr(agent, "provider", "") != "nous" or getattr(state, "is_usage_window", False) is not True:
return client.chat.completions.create(**api_kwargs)
raw_api = getattr(getattr(getattr(client, "chat", None), "completions", None), "with_raw_response", None)
- # Test doubles (unittest.mock) invent every attribute; checked by module so production never
- # imports unittest.
- if raw_api is None or any(cls.__module__ == "unittest.mock" for cls in type(client).__mro__):
+ if raw_api is None:
return client.chat.completions.create(**api_kwargs)
raw = raw_api.create(**api_kwargs)
from agent.credits_tracker import response_is_usage_window
diff --git a/agent/credential_pool_model_cooldowns.py b/agent/credential_pool_model_cooldowns.py
index e4f902850a7..9e511868562 100644
--- a/agent/credential_pool_model_cooldowns.py
+++ b/agent/credential_pool_model_cooldowns.py
@@ -22,6 +22,18 @@ MODEL_ENTITLEMENT_BENCH_SECONDS = 365 * 24 * 60 * 60
FAILURE_REASON_USAGE_WINDOW = "usage_window"
+def pool_failure_reason(reason: Any, error_context: Optional[dict[str, Any]], billing_unverified: bool) -> str:
+ """The pool's failure reason for a rotation (*reason* is a ``FailoverReason``). A usage-window 402
+ benches only the refused model; an ambiguous billing body is sized as transient, not a 1-hour bench."""
+ from agent.error_classifier import FailoverReason
+ if reason == FailoverReason.billing and (error_context or {}).get("usage_window"):
+ return FAILURE_REASON_USAGE_WINDOW
+ if reason == FailoverReason.billing and billing_unverified:
+ from agent.credential_pool import FAILURE_REASON_BILLING_UNVERIFIED
+ return FAILURE_REASON_BILLING_UNVERIFIED
+ return reason.value
+
+
def model_cooldown_until(entry: PooledCredential, model: Optional[str]) -> Optional[float]:
"""Active cooldown blocking *entry* for *model*, or ``None``.
diff --git a/agent/credits_tracker.py b/agent/credits_tracker.py
index 26f3b49da3e..9f997257b28 100644
--- a/agent/credits_tracker.py
+++ b/agent/credits_tracker.py
@@ -25,6 +25,7 @@ from agent.usage_gauges import (
binding_gauge,
gauge_limit_name,
parse_gauges,
+ paused_for_payment,
top_tier_gauge,
)
@@ -184,6 +185,7 @@ CREDITS_RESTORED_KEY = "credits.restored"
CREDITS_GRANT_SPENT_KEY = "credits.grant_spent"
_DEPLETED_TEXT = "✕ Credit access paused · run /topup to top up"
_PAUSED_TEXT = "✕ Included usage paused · your subscription payment failed · update your card, or add credits in /topup to keep going"
+_PAUSED_OTHER_TEXT = "✕ Included usage paused · see Billing in the Portal, or add credits in /topup to keep going"
_TOP_TIER_LIMIT = "You've hit your monthly large-model limit"
_AUTO_TOP_UP_SUFFIX = " · auto top-up is on"
@@ -246,18 +248,18 @@ def _window_hard_stop(state: CreditsState, *, model_is_free: bool) -> Optional[s
then: payment paused with no credits (credits keep a paused plan going whatever the setting says; a
card update restores included usage), the large-model allowance used with no pay path, the window used with no
pay path. A free model keeps inferencing, so only the payment-paused line survives it.
- With Keep going on credits off, a balance is not a pay path: the way on is that account setting, so
- the copy names it instead of adding credits."""
+ The credits step comes from :func:`agent.plan_limits.credits_action`, the rule every limit surface reads."""
purchased = state.purchased_micros
if state.paused_reason and purchased <= 0:
- return _PAUSED_TEXT
+ return _PAUSED_TEXT if paused_for_payment(state.paused_reason) else _PAUSED_OTHER_TEXT
if not state.paid_access:
return None if model_is_free else _DEPLETED_TEXT
if model_is_free or state.credits_pay:
return None
if state.unmetered:
return None
- action = _KEEP_GOING_OFF_ACTION if state.keep_going_on_credits is False else _ADD_CREDITS_ACTION
+ from agent.plan_limits import credits_action
+ action = _CREDITS_STEP[credits_action(state.keep_going_on_credits, purchased)]
# The large-model allowance ran out AND the last response was a block: the API stamps ``spend-source`` on every
# admitted request and never on a 402, so header-sourced + no source = this model was refused. An
# ``included`` source means the current model is not top-tier (still admitted) and a seed cannot know
@@ -281,8 +283,12 @@ def window_stop_resets_at_ms(state: CreditsState) -> Optional[int]:
# "Keep going on credits": the account setting (/topup or Portal billing), off by default on a window plan.
-_KEEP_GOING_OFF_ACTION = "turn on Keep going in /topup"
_ADD_CREDITS_ACTION = "/topup to add credits"
+_CREDITS_STEP = { # keyed by agent.plan_limits.credits_action
+ "use_credits": "turn on Keep going in /topup",
+ "add_credits": _ADD_CREDITS_ACTION,
+ "add_credits_and_keep_going": "add credits and turn on Keep going in /topup",
+}
def _window_payg_text(state: CreditsState) -> Optional[str]:
@@ -343,7 +349,7 @@ def _evaluate_window_notices(state: CreditsState, latch: dict, *, model_is_free:
active.discard(CREDITS_GRANT_SPENT_KEY)
stop = _window_hard_stop(state, model_is_free=model_is_free)
- limit = stop is not None and stop not in (_PAUSED_TEXT, _DEPLETED_TEXT)
+ limit = stop is not None and stop not in (_PAUSED_TEXT, _PAUSED_OTHER_TEXT, _DEPLETED_TEXT)
was_stopped = CREDITS_DEPLETED_KEY in active or CREDITS_WINDOW_LIMIT_KEY in active
_reconcile_sticky(CREDITS_WINDOW_LIMIT_KEY, stop if limit else None, "error", latch, to_show, to_clear)
_reconcile_sticky(CREDITS_DEPLETED_KEY, None if limit else stop, "error", latch, to_show, to_clear)
@@ -773,6 +779,24 @@ def restore_window_notices(session_id, latch: dict) -> None:
logger.debug("window notice restore failed", exc_info=True)
+def apply_keep_going_change(agent, enabled: bool) -> None:
+ """The user just changed "Keep going on credits": the agent's state takes the new value now (the next
+ reply's headers confirm it) and the notice policy re-runs, so a "turn on Keep going" line clears at once.
+ The account snapshot the pickers read is refreshed in the background. Never raises."""
+ try:
+ from dataclasses import replace
+ state = getattr(agent, "_credits_state", None)
+ if state is None or not state.is_usage_window:
+ return
+ agent._credits_state = replace(state, keep_going_on_credits=enabled)
+ _rerun_notice_policy(agent)
+ from agent.memory_provider import spawn_context_thread
+ from hermes_cli.nous_account import get_nous_portal_account_info
+ spawn_context_thread(lambda: get_nous_portal_account_info(force_fresh=True), name="keep-going-refresh").start()
+ except Exception:
+ logger.debug("keep going ▸ local refresh failed", exc_info=True)
+
+
def forget_window_notices(session_id) -> None:
"""The session is no longer on a window plan: drop its saved lines. Never raises."""
_seen_window_notices.pop(session_id, None)
diff --git a/agent/error_classifier.py b/agent/error_classifier.py
index 8c60df7a546..5a6e60b5efb 100644
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@ -128,7 +128,9 @@ _XAI_SPENDING_LIMIT_ERROR_CODE = "personal-team-blocked:spending-limit"
# Nous usage-window plan: included usage (or the large-model allowance) is spent AND
# there are no top-up credits. Billing so the pool may rotate to a key the user
-# owns; the message names the reset, so it must never read as transient.
+# owns; the message names the reset, so it must never read as transient. Honoured
+# only on a Nous 402 (``_classify_402`` behind ``_is_nous_route``), never via
+# _BILLING_ERROR_CODES, so any other status or upstream keeps main's rules.
_NOUS_USAGE_WINDOW_402_CODE = "usage_window_and_credits_exhausted"
# Structured codes meaning the account cannot serve paid traffic.
@@ -143,7 +145,6 @@ _BILLING_ERROR_CODES = frozenset({
"organization_usage_limit_exceeded", "project_spend_limit_exceeded",
# Nous paid model behind an empty credit balance arrives as a 404 (#115702).
"insufficient_credits_for_paid_model",
- _NOUS_USAGE_WINDOW_402_CODE,
})
# Transient rate limiting. Bedrock "Throttling error: Too many tokens" also
diff --git a/agent/plan_limits.py b/agent/plan_limits.py
index 99a8ffca4c1..969a04fd479 100644
--- a/agent/plan_limits.py
+++ b/agent/plan_limits.py
@@ -31,6 +31,11 @@ _MAX_SUGGESTIONS = 2
NOTE_FREE = "free"
NOTE_INCLUDED = "included"
+# Past a limit, the credits step (:func:`credits_action`).
+USE_CREDITS = "use_credits" # Keep going off, balance: turn it on
+ADD_CREDITS = "add_credits" # Keep going on/unknown, no balance: top up
+ADD_CREDITS_AND_KEEP_GOING = "add_credits_and_keep_going" # Keep going off, no balance: both
+
@dataclass(frozen=True)
class ModelSuggestion:
@@ -45,13 +50,10 @@ class ModelSuggestion:
@dataclass(frozen=True)
class CreditsOption:
- """The second way on, past a limit: spend top-up credits.
-
- ``use_credits``: Keep going on credits is off and there is a balance, so turning it on lets the
- request through. ``add_credits``: no balance (or the setting is already on), so the way on is a
- top-up. Interactive surfaces render it as a button; messaging points at the Portal (a chat button
- could spend the owner's money for anyone in the room)."""
- action: str # "use_credits" | "add_credits"
+ """The second way on, past a limit: spend top-up credits (the action comes from :func:`credits_action`).
+ Interactive surfaces render it as a button; messaging points at the Portal (a chat button could spend
+ the owner's money for anyone in the room)."""
+ action: str # USE_CREDITS | ADD_CREDITS | ADD_CREDITS_AND_KEEP_GOING
def to_payload(self) -> dict[str, str]:
return {"action": self.action}
@@ -80,10 +82,13 @@ class LimitHit:
# ── catalog reads ────────────────────────────────────────────────────────────────────────────────
-def cached_pricing(base_url: str) -> dict:
+def cached_pricing(base_url: str = "") -> dict:
+ """The calling profile's own cached Nous catalog (never fetches); ``base_url`` is not needed for it. Only
+ the profile-keyed read: a process serving several profiles holds their catalogs side by side, and a
+ usage level (Large / Free) is per plan, so another profile's catalog must never answer."""
try:
- from hermes_cli.models_pricing import peek_cached_pricing
- return peek_cached_pricing(base_url) or {}
+ from hermes_cli.models_pricing import get_pricing_for_provider
+ return get_pricing_for_provider(PROVIDER, cached_only=True) or {}
except Exception:
logger.debug("Cached pricing unavailable", exc_info=True)
return {}
@@ -113,11 +118,16 @@ def is_free(model: str, pricing: Optional[dict]) -> bool:
def is_top_tier(model: str, pricing: Optional[dict]) -> bool:
- """The gateway's ``top_tier`` mark. Unmarked or no catalog: not top tier."""
- entry = (pricing or {}).get(model) if model else None
- if is_free(model, pricing):
+ """The gateway marks the model top tier (``usage_level: top_tier``, or an older gateway's ``top_tier:
+ true``), read by the same rule as the picker tags. Unmarked or no catalog: not top tier."""
+ if not model:
+ return False
+ try:
+ from hermes_cli.model_picker_usage import usage_levels
+ return usage_levels([model], pricing).get(model) == "top_tier"
+ except Exception:
+ logger.debug("Usage level lookup failed", exc_info=True)
return False
- return isinstance(entry, dict) and entry.get("top_tier") is True
def model_label(model: str, pricing: Optional[dict]) -> str:
@@ -207,15 +217,23 @@ def suggest_models(
return tuple(out)
+def credits_action(keep_going_on_credits: Optional[bool], purchased_micros: Optional[int]) -> str:
+ """The credits step past a limit; every surface's copy reads this one rule. With Keep going on credits
+ off, the gateway refuses whatever the balance, so a balance alone is not enough and neither is the
+ setting alone: off with no balance needs both steps. An unknown balance counts as none."""
+ has_balance = int(purchased_micros or 0) > 0
+ if keep_going_on_credits is False:
+ return USE_CREDITS if has_balance else ADD_CREDITS_AND_KEEP_GOING
+ return ADD_CREDITS
+
+
def credits_option(state: Any) -> Optional[CreditsOption]:
- """How credits could carry on past the limit (see :class:`CreditsOption`). None while paused (a card
+ """How credits could carry on past the limit (see :func:`credits_action`). None while paused (a card
update restores included usage; the paused copy says so)."""
if state is None or getattr(state, "paused_reason", None):
return None
- purchased = int(getattr(state, "purchased_micros", 0) or 0)
- if getattr(state, "keep_going_on_credits", None) is False and purchased > 0:
- return CreditsOption("use_credits")
- return CreditsOption("add_credits")
+ return CreditsOption(credits_action(getattr(state, "keep_going_on_credits", None),
+ getattr(state, "purchased_micros", 0)))
def limit_hit(agent: Any, *, message: str, needed_tokens: Optional[int] = None) -> Optional[LimitHit]:
@@ -257,10 +275,27 @@ def limit_hit(agent: Any, *, message: str, needed_tokens: Optional[int] = None)
def portal_wording(text: str) -> str:
"""A refusal line for a surface without ``/topup`` (messaging): point its credits steps at the Portal."""
return (text.replace("turn on Keep going in /topup", "turn on Keep going in the Portal")
+ .replace("(turn on in /topup)", "(turn on in the Portal)")
.replace("/topup to add credits", "add credits in the Portal")
.replace("add credits in /topup", "add credits in the Portal"))
+def chat_refusal_wording(text: str, resets_at: Any = None) -> str:
+ """A refusal sent to a chat: credits steps point at the Portal (:func:`portal_wording`), and the reset
+ reads as a duration ("resets in 3h"), since the gateway's clock is not the reader's time zone."""
+ text = portal_wording(text)
+ if isinstance(resets_at, (int, float)) and not isinstance(resets_at, bool) and resets_at > 0:
+ try:
+ from agent.credits_tracker import format_window_reset
+ from hermes_cli.model_picker_usage import compact_duration
+ ms = round(resets_at * 1000) # the epoch seconds came from these ms: round, never truncate
+ if left := compact_duration(ms):
+ text = text.replace(f"resets {format_window_reset(ms)}", f"resets in {left}")
+ except Exception:
+ logger.debug("chat reset wording failed", exc_info=True)
+ return text
+
+
def suggestion_phrase(s: ModelSuggestion) -> str:
"""``Model A (free)``."""
return f"{s.label} ({s.note})"
@@ -277,12 +312,13 @@ def next_steps_text(hit: LimitHit, *, model_command: str = "/model", topup_comma
else:
parts.append(f"Pick another model with {model_command}")
if hit.credits is not None:
- if portal or not topup_command:
- parts.append("turn on Keep going in the Portal to use credits" if hit.credits.action == "use_credits"
- else "add credits in the Portal")
+ where = "the Portal" if portal or not topup_command else topup_command
+ if hit.credits.action == USE_CREDITS:
+ parts.append(f"turn on Keep going in {where} to use credits")
+ elif hit.credits.action == ADD_CREDITS_AND_KEEP_GOING:
+ parts.append(f"add credits and turn on Keep going in {where}")
else:
- parts.append(f"turn on Keep going in {topup_command} to use credits" if hit.credits.action == "use_credits"
- else f"add credits with {topup_command}")
+ parts.append(f"add credits {'in' if where == 'the Portal' else 'with'} {where}")
return ", or ".join(parts) + "."
diff --git a/agent/plan_snapshot_sync.py b/agent/plan_snapshot_sync.py
index 4f0e088171f..672a94c8858 100644
--- a/agent/plan_snapshot_sync.py
+++ b/agent/plan_snapshot_sync.py
@@ -16,10 +16,16 @@ from typing import Any, Optional
logger = logging.getLogger(__name__)
_lock = threading.Lock()
-_inflight = False
+# Both keyed by Hermes home: one process can serve several profiles, each with its own account.
+_inflight: set[str] = set()
# What the headers said the last time a refresh ran. The portal can trail the gateway by a few minutes
# (usage is ingested in batches), so the same mismatch is refreshed once, not on every reply meanwhile.
-_last_attempt: Optional[tuple[bool, frozenset[str]]] = None
+_last_attempt: dict[str, tuple[bool, frozenset[str]]] = {}
+
+
+def _profile_key() -> str:
+ from hermes_constants import hermes_home_key
+ return hermes_home_key()
def _snapshot_full_ids(snapshot: Any) -> Optional[frozenset[str]]:
@@ -47,8 +53,7 @@ def plan_snapshot_is_stale(state: Any, snapshot: Any) -> bool:
return frozenset(g.id for g in getattr(state, "gauges", ()) if g.full) != full_ids
-def _refresh(plan_changed: bool) -> None:
- global _inflight
+def _refresh(plan_changed: bool, key: str) -> None:
try:
from hermes_cli.nous_account import get_nous_portal_account_info
get_nous_portal_account_info(force_fresh=True)
@@ -58,42 +63,45 @@ def _refresh(plan_changed: bool) -> None:
get_pricing_for_provider("nous", force_refresh=True)
except Exception:
logger.debug("plan sync ▸ refresh failed (fail-open)", exc_info=True)
- global _last_attempt
- _last_attempt = None # a transient portal error must not block the next re-sync
+ _last_attempt.pop(key, None) # a transient portal error must not block the next re-sync
finally:
with _lock:
- _inflight = False
+ _inflight.discard(key)
def sync_plan_snapshot(state: Any) -> bool:
"""Start one background refresh when *state* (a fresh ``CreditsState`` from reply headers) says the
cached plan is out of date. Returns True iff a refresh started. Never raises, never blocks."""
- global _inflight, _last_attempt
+ key = ""
try:
+ key = _profile_key()
if not getattr(state, "is_usage_window", False):
# Non-window reply: only a cached window snapshot (a downgrade / cancel) can be stale. Peek the
# raw cache first so every other account pays no auth-state read per reply.
from hermes_cli import nous_account
cached = nous_account._account_info_cache
if cached is None or _snapshot_full_ids(cached[2]) is None:
- _last_attempt = None
+ _last_attempt.pop(key, None)
return False
from hermes_cli.nous_account import cached_nous_portal_account_info
snapshot = cached_nous_portal_account_info(any_age=True)
if not plan_snapshot_is_stale(state, snapshot):
- _last_attempt = None # in step again: the next mismatch gets its own refresh
+ _last_attempt.pop(key, None) # in step again: the next mismatch gets its own refresh
return False
on_window = bool(getattr(state, "is_usage_window", False))
seen = (on_window, frozenset(g.id for g in getattr(state, "gauges", ()) if g.full))
plan_changed = on_window != (_snapshot_full_ids(snapshot) is not None)
with _lock:
- if _inflight or seen == _last_attempt:
+ if key in _inflight or _last_attempt.get(key) == seen:
return False
- _inflight, _last_attempt = True, seen
- threading.Thread(target=_refresh, args=(plan_changed,), name="nous-plan-sync", daemon=True).start()
+ _inflight.add(key)
+ _last_attempt[key] = seen
+ # Under this profile's contextvars (its Hermes home and auth store), as the credits seed thread does.
+ from agent.memory_provider import spawn_context_thread
+ spawn_context_thread(_refresh, args=(plan_changed, key), name="nous-plan-sync").start()
return True
except Exception:
logger.debug("plan sync ▸ check failed (fail-open)", exc_info=True)
with _lock:
- _inflight = False
+ _inflight.discard(key)
return False
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index caefd4e497d..79ca27ef2ab 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -617,7 +617,29 @@ def _reject_all_turns(agent: Any, api_error: Exception) -> bool:
return bool(reject(api_error)) if callable(reject) else False
-# health: allow CC -- usage-window 402: skip the credential refresh and hand the pool a model-scoped bench context; this recovery ladder was over target on main
+def _pool_error_context(agent, classified: Any, error_context: Any) -> Any:
+ """What the credential pool sees: a plan limit (usage-window 402) benches only the refused model on the
+ credential, until its reset; every other failure passes the error context through unchanged."""
+ if not (getattr(classified, "error_context", None) or {}).get("usage_window"):
+ return error_context
+ return {**(error_context if isinstance(error_context, dict) else {}), "usage_window": True,
+ **_usage_window_reset_context(agent)}
+
+
+def _usage_window_reset_context(agent) -> dict[str, float]:
+ """``{"reset_at": epoch s}`` for a usage-window 402: when the refused allowance frees up, from the usage
+ headers the 402 carried (the API's error body has no reset). Empty when the state names none, so the
+ pool keeps its default bench."""
+ try:
+ from agent.credits_tracker import window_stop_resets_at_ms
+ state = getattr(agent, "_credits_state", None)
+ resets_ms = window_stop_resets_at_ms(state) if state is not None else None
+ except Exception:
+ logger.debug("usage-window reset unavailable for the pool", exc_info=True)
+ return {}
+ return {"reset_at": resets_ms / 1000} if isinstance(resets_ms, (int, float)) and resets_ms > 0 else {}
+
+
def recover_after_classification(
agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState, *,
status_code: Optional[int], error_context: Any, messages: list[dict[str, Any]],
@@ -663,13 +685,9 @@ def recover_after_classification(
_vlines(agent, "🔐 Nous paid access verified — refreshed runtime credentials and retrying request...")
return True, False
- _pool_context = error_context
- if (getattr(classified, "error_context", None) or {}).get("usage_window"):
- # A plan limit benches only the refused model on the credential, until its reset.
- _pool_context = {**(error_context if isinstance(error_context, dict) else {}), "usage_window": True}
recovered_with_pool, _retry.has_retried_429 = agent._recover_with_credential_pool(
status_code=status_code, has_retried_429=_retry.has_retried_429,
- classified_reason=classified.reason, error_context=_pool_context,
+ classified_reason=classified.reason, error_context=_pool_error_context(agent, classified, error_context),
billing_unverified=classified.billing_unverified,
)
if recovered_with_pool:
@@ -850,6 +868,8 @@ def _print_nonretryable_auth_guidance(
agent: Any, classified: Any, *, status_code: Optional[int], provider: Any, base_url: Any, model: Any,
) -> None:
"""Actionable guidance for a terminal auth / billing error."""
+ if (getattr(classified, "error_context", None) or {}).get("usage_window"):
+ return # a plan limit's refusal line and limit panel are its guidance: no second copy, no portal fetch
from agent.conversation_loop import _print_billing_or_entitlement_guidance, _print_nous_entitlement_guidance
if classified.reason == FailoverReason.billing and _print_billing_or_entitlement_guidance(
@@ -1162,8 +1182,10 @@ def max_retries_exhausted_result(
capability="model access", provider=provider, base_url=str(base_url), model=model,
unverified=classified.billing_unverified,
)
- _billing_guidance = _billing_or_entitlement_message(**_billing_kw)
- _print_billing_or_entitlement_guidance(agent, **_billing_kw)
+ # A plan limit (usage-window 402) carries its own refusal line: no portal fetch, no second copy.
+ if not (classified.error_context or {}).get("usage_window"):
+ _billing_guidance = _billing_or_entitlement_message(**_billing_kw)
+ _print_billing_or_entitlement_guidance(agent, **_billing_kw)
elif is_rate_limited:
_reset = reset_hint(api_error)
agent._emit_diagnostic_status(
diff --git a/agent/usage_gauges.py b/agent/usage_gauges.py
index d74520adeb5..c11dbd102de 100644
--- a/agent/usage_gauges.py
+++ b/agent/usage_gauges.py
@@ -12,6 +12,7 @@ any other id shows the server's ``label``.
from __future__ import annotations
import json
+import time
from dataclasses import dataclass
from typing import Any, Iterable, Optional
@@ -19,6 +20,13 @@ BP_FULL = 10_000
SCOPE_ALL = "all"
SCOPE_TOP_TIER = "top_tier"
_SCOPES = frozenset({SCOPE_ALL, SCOPE_TOP_TIER})
+# The pause reasons that mean the subscription payment failed. Any other reason (including "unknown",
+# sent for a malformed one) is still a pause, with copy that does not claim a payment failed.
+PAYMENT_PAUSE_REASONS = frozenset({"payment_past_due"})
+
+
+def paused_for_payment(reason: Any) -> bool:
+ return reason in PAYMENT_PAUSE_REASONS
@dataclass(frozen=True)
@@ -61,8 +69,7 @@ def parse_gauges(value: Any) -> Optional[tuple[WindowGauge, ...]]:
continue
if isinstance(bp, bool) or not isinstance(bp, int) or not 0 <= bp <= BP_FULL:
continue
- reset = item.get("resets_at_ms")
- reset = reset if isinstance(reset, int) and not isinstance(reset, bool) and reset > 0 else None
+ reset = _plausible_reset_ms(item.get("resets_at_ms"))
label = item.get("label")
seen.add(gid)
out.append(WindowGauge(gid, scope, label.strip() if isinstance(label, str) and label.strip() else gid,
@@ -70,6 +77,17 @@ def parse_gauges(value: Any) -> Optional[tuple[WindowGauge, ...]]:
return tuple(out) or None
+# A reset more than a year ahead is a bad stamp (the longest allowance is a month): shown as unknown, never
+# as a date or a duration decades away. A past stamp needs no bound: it already reads "shortly".
+_RESET_MAX_AHEAD_MS = 366 * 86_400_000
+
+
+def _plausible_reset_ms(value: Any) -> Optional[int]:
+ if not isinstance(value, int) or isinstance(value, bool):
+ return None
+ return value if 0 < value <= time.time() * 1000 + _RESET_MAX_AHEAD_MS else None
+
+
def all_scope(gauges: Iterable[WindowGauge]) -> tuple[WindowGauge, ...]:
return tuple(g for g in gauges if g.scope == SCOPE_ALL)
diff --git a/apps/desktop/src/app/settings/billing/fixtures.test-util.ts b/apps/desktop/src/app/settings/billing/fixtures.test-util.ts
index a7b2b7017d1..c4220815ad2 100644
--- a/apps/desktop/src/app/settings/billing/fixtures.test-util.ts
+++ b/apps/desktop/src/app/settings/billing/fixtures.test-util.ts
@@ -88,7 +88,7 @@ function windowPlan(
featured_model_ids: ['example/model-a', 'example/model-c'],
top_tier_model_ids: ['example/model-c'],
kind: 'usage_window',
- paused_reason: paused ? 'payment_failed' : null,
+ paused_reason: paused ? 'payment_past_due' : null,
plan: 'Window Plan'
},
usage: { available: false }
diff --git a/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.test.tsx b/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.test.tsx
index 019edea0611..bc58c9b108d 100644
--- a/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.test.tsx
+++ b/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.test.tsx
@@ -138,3 +138,27 @@ describe('KeepGoingOnCreditsRow after an approval', () => {
await waitFor(() => expect(screen.queryByText(/didn't save/)).toBeNull())
})
})
+
+describe('KeepGoingOnCreditsRow with overlapping attempts', () => {
+ it('a cancelled approval that resolves late never snaps back the newer attempt', async () => {
+ const resolvers: ((value: unknown) => void)[] = []
+ apiMocks.updateKeepGoingOnCredits.mockResolvedValue(NEEDS_APPROVAL)
+ apiMocks.stepUp.mockImplementation(() => new Promise(resolve => resolvers.push(resolve)))
+
+ renderRow(false)
+ fireEvent.click(screen.getByRole('switch'))
+ expect(await screen.findByText(/Approve Remote Spending in your browser/)).toBeTruthy()
+
+ fireEvent.click(screen.getByText('Cancel'))
+ await waitFor(() => expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false'))
+
+ fireEvent.click(screen.getByRole('switch'))
+ await waitFor(() => expect(apiMocks.updateKeepGoingOnCredits).toHaveBeenCalledTimes(2))
+ expect(await screen.findByText(/Approve Remote Spending in your browser/)).toBeTruthy()
+
+ // The first (cancelled) approval comes back now: the second attempt keeps its switch and its prompt.
+ await act(async () => resolvers[0]?.({ data: { granted: false, ok: true }, ok: true }))
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true')
+ expect(screen.getByText(/Approve Remote Spending in your browser/)).toBeTruthy()
+ })
+})
diff --git a/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.tsx b/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.tsx
index 7c4b6e708d7..aa3fd83262b 100644
--- a/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.tsx
+++ b/apps/desktop/src/app/settings/billing/keep-going-on-credits-row.tsx
@@ -1,5 +1,5 @@
import { useQueryClient } from '@tanstack/react-query'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { useI18n } from '@/i18n'
@@ -35,50 +35,66 @@ export function KeepGoingOnCreditsRow({ enabled }: { enabled: boolean }) {
// Approved, yet the change was still refused (e.g. an older backend replayed the pre-approval token).
const [retryValue, setRetryValue] = useState<boolean | null>(null)
const checked = optimistic ?? enabled
+ // Each click / cancel / retry is a new attempt; an older one that resolves late (an approval cancelled,
+ // then the switch flipped again) must not snap the switch back or touch the newer attempt's state.
+ const attempt = useRef(0)
- const settle = async () => {
+ const settle = async (run = attempt.current) => {
await queryClient.invalidateQueries({ queryKey: ['billing', 'state'] })
- setOptimistic(null)
+
+ if (run === attempt.current) {
+ setOptimistic(null)
+ }
}
- const apply = async (next: boolean, afterApproval = false): Promise<void> => {
+ const apply = async (next: boolean, afterApproval = false, run = attempt.current): Promise<void> => {
const result = await api.updateKeepGoingOnCredits(next)
+ if (run !== attempt.current) {
+ return
+ }
+
if (result.ok) {
setRetryValue(null)
- return settle()
+ return settle(run)
}
if (result.refusal.kind === 'insufficient_scope' && afterApproval) {
// Never the generic "start a top-up" copy here: the user just approved. Offer a plain retry.
setRetryValue(next)
- return settle()
+ return settle(run)
}
if (result.refusal.kind === 'insufficient_scope') {
// Needs Remote Spending: approve, then apply the SAME change (the switch keeps the requested position).
setApproving(true)
const granted = await stepUp.start()
+
+ if (run !== attempt.current) {
+ return
+ }
+
setApproving(false)
if (granted) {
stepUp.dismiss() // the change itself is the confirmation; no extra "Verification complete" line
- return apply(next, true)
+ return apply(next, true, run)
}
// Denied / failed / cancelled: the switch goes back; a denial keeps its one-line reason below.
- return settle()
+ return settle(run)
}
setRefusal(result.refusal)
- return settle()
+ return settle(run)
}
const onChange = (next: boolean) => {
+ attempt.current += 1
setOptimistic(next)
setRefusal(null)
setRetryValue(null)
@@ -104,6 +120,7 @@ export function KeepGoingOnCreditsRow({ enabled }: { enabled: boolean }) {
<Button
onClick={() => {
// dismiss() makes the pending start() return early, so put the switch back here.
+ attempt.current += 1
stepUp.dismiss()
setApproving(false)
void settle()
@@ -123,6 +140,7 @@ export function KeepGoingOnCreditsRow({ enabled }: { enabled: boolean }) {
<Button
onClick={() => {
const next = retryValue
+ attempt.current += 1
setRetryValue(null)
setOptimistic(next)
void apply(next, true)
diff --git a/apps/desktop/src/app/settings/billing/use-billing-state.test.ts b/apps/desktop/src/app/settings/billing/use-billing-state.test.ts
index b7869da9659..b15723c4cb8 100644
--- a/apps/desktop/src/app/settings/billing/use-billing-state.test.ts
+++ b/apps/desktop/src/app/settings/billing/use-billing-state.test.ts
@@ -135,6 +135,22 @@ describe('deriveBillingView (usage-window plans)', () => {
}
})
+ it('a pause for any other reason does not claim a payment failed', () => {
+ const fixture = windowFixtures['window-paused']
+ const billing = fixture.billing.ok ? fixture.billing.data : undefined
+ const subscription = fixture.subscription.ok ? fixture.subscription.data : undefined
+ const planUsage = { ...billing!.plan_usage!, paused_reason: 'unknown' }
+
+ const view = deriveBillingView(
+ okBilling({ ...billing!, plan_usage: planUsage }),
+ okSubscription({ ...subscription!, plan_usage: planUsage })
+ )
+
+ for (const row of view.usageRows.slice(0, 3)) {
+ expect(row.caption).toBe('Paused: see Billing in the Portal')
+ }
+ })
+
it('names the window plan on the Usage section, and nothing on a credit-grant plan', () => {
const win = windowFixtures['window-healthy']
expect(deriveBillingView(win.billing, win.subscription).usagePlanName).toBe('Window Plan')
diff --git a/apps/desktop/src/app/settings/billing/use-billing-state.ts b/apps/desktop/src/app/settings/billing/use-billing-state.ts
index 3f84208d5de..dbd2c8fc8f9 100644
--- a/apps/desktop/src/app/settings/billing/use-billing-state.ts
+++ b/apps/desktop/src/app/settings/billing/use-billing-state.ts
@@ -1,4 +1,4 @@
-import { gaugeScope, gaugeTitle } from '@hermes/shared'
+import { gaugeScope, gaugeTitle, PAYMENT_PAUSE_REASON } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
@@ -909,7 +909,9 @@ function deriveWindowRows(
value: used
},
caption: paused
- ? copy.captionPaused
+ ? planUsage.paused_reason === PAYMENT_PAUSE_REASON
+ ? copy.captionPaused
+ : copy.captionPausedOther
: gaugeScope(gauge) === 'top_tier' && exhausted
? keepGoingOff
? copy.captionTopTierUsedUpKeepGoingOff
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
index 3db3f59a322..3b6b40bdd93 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
@@ -433,19 +433,19 @@ describe("a window plan's limit: one-click switch and credits (no silent switch)
expect(executeSlash).toHaveBeenCalledWith('/model example/model-free:free --provider nous --session', 'rt-1')
// No balance: the credits way on is Billing, labelled for what it does.
expect(screen.getByRole('button', { name: 'Open billing settings' })).toBeTruthy()
- expect(screen.queryByRole('button', { name: 'Use credits' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Turn on Keep going on credits' })).toBeNull()
// The generic provider menu is replaced by the one-click switch.
expect(screen.queryByRole('button', { name: 'Switch provider' })).toBeNull()
})
- it('with a balance and Keep going off, offers Use credits', async () => {
+ it('with a balance and Keep going off, offers to turn on Keep going (a lasting setting)', async () => {
render(
<MemoryRouter>
<Harness assistant={limitMessage('use_credits')} />
</MemoryRouter>
)
- expect(await screen.findByRole('button', { name: 'Use credits' })).toBeTruthy()
+ expect(await screen.findByRole('button', { name: 'Turn on Keep going on credits' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'Switch to Model Free (free)' })).toBeTruthy()
})
diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsx
index f2805ac3905..f6b9f1c58ec 100644
--- a/apps/desktop/src/components/model-picker.tsx
+++ b/apps/desktop/src/components/model-picker.tsx
@@ -1,5 +1,13 @@
import type { ModelOptionProvider, ModelPricing, PlanUsage, PlanUsageGauge } from '@hermes/shared'
-import { gaugeTitle, hasTopTier, planBlocks, planLimit, splitRecommended, usageTag } from '@hermes/shared'
+import {
+ gaugeTitle,
+ hasTopTier,
+ PAYMENT_PAUSE_REASON,
+ planBlocks,
+ planLimit,
+ splitRecommended,
+ usageTag
+} from '@hermes/shared'
import { fuzzyRank, modelSearchText } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
@@ -717,7 +725,9 @@ function PlanUsageSummary({ provider, usage }: { provider: ModelOptionProvider;
) : (
<div>
{copy.included}
- {usage.paused_reason ? ` · ${copy.pausedRenewal}` : ''}
+ {usage.paused_reason
+ ? ` · ${usage.paused_reason === PAYMENT_PAUSE_REASON ? copy.pausedRenewal : copy.pausedOther}`
+ : ''}
</div>
)}
{windowGauges.map(g => {
diff --git a/apps/desktop/src/i18n/ar_assistant.ts b/apps/desktop/src/i18n/ar_assistant.ts
index 7fe9b0e76e0..10e53bda6a6 100644
--- a/apps/desktop/src/i18n/ar_assistant.ts
+++ b/apps/desktop/src/i18n/ar_assistant.ts
@@ -69,7 +69,7 @@ export const arAssistant = {
errorRetry: 'إعادة المحاولة',
errorSwitchToModel: (model, note) => (note ? `التبديل إلى ${model} (${note})` : `التبديل إلى ${model}`),
errorSwitchModelFailed: 'تعذر تبديل النموذج',
- errorUseCredits: 'استخدام الرصيد',
+ errorUseCredits: 'تفعيل الاستمرار بالرصيد',
errorUseCreditsFailed: 'تعذر تفعيل الاستمرار بالرصيد',
errorAddCredits: 'إضافة رصيد',
errorOpenBillingSettings: 'فتح إعدادات الفوترة',
diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.ts
index 0c75ff083d9..17827c02c6e 100644
--- a/apps/desktop/src/i18n/ar_settings.ts
+++ b/apps/desktop/src/i18n/ar_settings.ts
@@ -32,6 +32,7 @@ export const arSettings = {
topTier: 'النماذج الكبيرة (شهريًا)',
barLabel: title => `المستخدم من الاستخدام المضمّن: ${title}`,
captionPaused: 'متوقف مؤقتًا: فشل دفع الاشتراك',
+ captionPausedOther: 'متوقف مؤقتًا: راجع الفوترة في البوابة',
captionTopTierUsedUp: 'نفدت الحصة الشهرية، ويغطي الرصيد الباقي',
captionTopTierUsedUpKeepGoingOff: 'نفدت الحصة الشهرية، ولا تزال النماذج المضمّنة الأخرى تعمل',
captionResetsIn: duration => `يُعاد التعيين خلال ${duration}`,
@@ -970,6 +971,7 @@ export const arSettings = {
topTier: 'النماذج الكبيرة (شهري)',
included: 'كل النماذج أدناه مشمولة',
pausedRenewal: 'متوقف: التجديد غير مدفوع',
+ pausedOther: 'متوقف',
includedUsedUp: 'نفد الاستخدام المضمن',
limitReached: name => `تم بلوغ الحد ${name}`,
limitNames: { day: 'اليومي', month: 'الشهري', top_tier: 'الشهري للنماذج الكبيرة', week: 'الأسبوعي' },
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 009b44615ce..bf65fd80801 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -2138,6 +2138,7 @@ export const deOverrides = {
topTier: 'Große Modelle (monatlich)',
barLabel: (title: string) => `${title}: genutztes Inklusivvolumen`,
captionPaused: 'Pausiert: Abo-Zahlung fehlgeschlagen',
+ captionPausedOther: 'Pausiert: siehe Abrechnung im Portal',
captionTopTierUsedUp: 'Monatskontingent aufgebraucht, Credits decken den Rest',
captionTopTierUsedUpKeepGoingOff:
'Monatskontingent aufgebraucht, andere enthaltene Modelle funktionieren weiter',
@@ -4508,6 +4509,7 @@ export const deOverrides = {
topTier: 'Große Modelle (monatlich)',
included: 'Alle Modelle unten sind enthalten',
pausedRenewal: 'pausiert: Verlängerung unbezahlt',
+ pausedOther: 'pausiert',
includedUsedUp: 'Inklusivvolumen aufgebraucht',
limitReached: (name: string) => `${name} erreicht`,
limitNames: {
@@ -5156,7 +5158,7 @@ export const deOverrides = {
errorRetry: 'Erneut versuchen',
errorSwitchToModel: (model, note) => (note ? `Zu ${model} wechseln (${note})` : `Zu ${model} wechseln`),
errorSwitchModelFailed: 'Modell konnte nicht gewechselt werden',
- errorUseCredits: 'Guthaben nutzen',
+ errorUseCredits: 'Mit Guthaben weitermachen aktivieren',
errorUseCreditsFailed: 'Mit Guthaben weitermachen konnte nicht aktiviert werden',
errorAddCredits: 'Guthaben aufladen',
errorOpenBillingSettings: 'Abrechnungseinstellungen öffnen',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index d2e57fa770c..3c9b400f2fb 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1786,6 +1786,7 @@ export const en: Translations = {
topTier: 'Large models (monthly)',
barLabel: title => `${title} included usage used`,
captionPaused: 'Paused: subscription payment failed',
+ captionPausedOther: 'Paused: see Billing in the Portal',
captionTopTierUsedUp: 'Monthly allowance used up, credits cover the rest',
captionTopTierUsedUpKeepGoingOff: 'Monthly allowance used up, other included models still work',
captionResetsIn: duration => `Resets in ${duration}`,
@@ -4073,6 +4074,7 @@ export const en: Translations = {
topTier: 'Large models (monthly)',
included: 'Every model below is included',
pausedRenewal: 'paused: renewal unpaid',
+ pausedOther: 'paused',
includedUsedUp: 'Included usage used up',
limitReached: name => `${name.charAt(0).toUpperCase()}${name.slice(1)} limit reached`,
limitNames: { day: 'daily', month: 'monthly', top_tier: 'monthly large-model', week: 'weekly' },
@@ -4716,7 +4718,7 @@ export const en: Translations = {
errorChooseModel: 'Choose a model',
errorSwitchToModel: (model, note) => (note ? `Switch to ${model} (${note})` : `Switch to ${model}`),
errorSwitchModelFailed: 'Could not switch model',
- errorUseCredits: 'Use credits',
+ errorUseCredits: 'Turn on Keep going on credits',
errorUseCreditsFailed: 'Could not turn on Keep going on credits',
errorAddCredits: 'Add credits',
errorOpenBillingSettings: 'Open billing settings',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index f1661d973db..9f4a125fbdc 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -2129,6 +2129,7 @@ export const esOverrides = {
topTier: 'Modelos grandes (mensual)',
barLabel: (title: string) => `${title}: uso incluido consumido`,
captionPaused: 'En pausa: falló el pago de la suscripción',
+ captionPausedOther: 'En pausa: consulta Facturación en el Portal',
captionTopTierUsedUp: 'Cuota mensual agotada, los créditos cubren el resto',
captionTopTierUsedUpKeepGoingOff: 'Cuota mensual agotada, los demás modelos incluidos siguen funcionando',
captionResetsIn: (duration: string) => `Se restablece en ${duration}`,
@@ -4500,6 +4501,7 @@ export const esOverrides = {
topTier: 'Modelos grandes (mensual)',
included: 'Todos los modelos de abajo están incluidos',
pausedRenewal: 'en pausa: renovación impagada',
+ pausedOther: 'en pausa',
includedUsedUp: 'Uso incluido agotado',
limitReached: (name: string) => `Límite ${name} alcanzado`,
limitNames: { day: 'diario', month: 'mensual', top_tier: 'mensual de modelos grandes', week: 'semanal' },
@@ -5141,7 +5143,7 @@ export const esOverrides = {
errorRetry: 'Reintentar',
errorSwitchToModel: (model, note) => (note ? `Cambiar a ${model} (${note})` : `Cambiar a ${model}`),
errorSwitchModelFailed: 'No se pudo cambiar de modelo',
- errorUseCredits: 'Usar créditos',
+ errorUseCredits: 'Activar Seguir con créditos',
errorUseCreditsFailed: 'No se pudo activar Seguir con créditos',
errorAddCredits: 'Añadir créditos',
errorOpenBillingSettings: 'Abrir ajustes de facturación',
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index 81946e49ed1..71ec9db3999 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -2142,6 +2142,7 @@ export const frOverrides = {
topTier: 'Grands modèles (mensuel)',
barLabel: (title: string) => `${title} : usage inclus consommé`,
captionPaused: "En pause : échec du paiement de l'abonnement",
+ captionPausedOther: 'En pause : voir Facturation dans le Portail',
captionTopTierUsedUp: 'Quota mensuel épuisé, les crédits couvrent le reste',
captionTopTierUsedUpKeepGoingOff: 'Quota mensuel épuisé, les autres modèles inclus fonctionnent toujours',
captionResetsIn: (duration: string) => `Réinitialisation dans ${duration}`,
@@ -4515,6 +4516,7 @@ export const frOverrides = {
topTier: 'Grands modèles (mensuel)',
included: 'Tous les modèles ci-dessous sont inclus',
pausedRenewal: 'en pause : renouvellement impayé',
+ pausedOther: 'en pause',
includedUsedUp: 'Usage inclus épuisé',
limitReached: (name: string) => `Limite ${name} atteinte`,
limitNames: {
@@ -5161,7 +5163,7 @@ export const frOverrides = {
errorRetry: 'Réessayer',
errorSwitchToModel: (model, note) => (note ? `Passer à ${model} (${note})` : `Passer à ${model}`),
errorSwitchModelFailed: 'Impossible de changer de modèle',
- errorUseCredits: 'Utiliser les crédits',
+ errorUseCredits: 'Activer Continuer avec les crédits',
errorUseCreditsFailed: 'Impossible d’activer Continuer avec les crédits',
errorAddCredits: 'Ajouter des crédits',
errorOpenBillingSettings: 'Ouvrir les réglages de facturation',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 913c224081d..69827f2dbd4 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -257,6 +257,7 @@ export const jaOverrides = {
topTier: '大型モデル(月間)',
barLabel: title => `${title}の含まれる利用量の使用率`,
captionPaused: '一時停止中: サブスクリプションの支払いに失敗しました',
+ captionPausedOther: '一時停止中: ポータルの請求をご確認ください',
captionTopTierUsedUp: '月間の枠を使い切りました。残りはクレジットで支払われます',
captionTopTierUsedUpKeepGoingOff: '月間の枠を使い切りました。他の含まれるモデルは引き続き使えます',
captionResetsIn: duration => `${duration}後にリセット`,
@@ -2903,6 +2904,7 @@ export const jaOverrides = {
topTier: '大型モデル(月間)',
included: '以下のモデルはすべて含まれます',
pausedRenewal: '一時停止: 未払い',
+ pausedOther: '一時停止',
includedUsedUp: '含まれる利用量を使い切りました',
limitReached: name => `${name}の上限に達しました`,
limitNames: { day: '1日', month: '月間', top_tier: '大型モデルの月間', week: '週間' },
@@ -3440,7 +3442,7 @@ export const jaOverrides = {
errorRetry: '再試行',
errorSwitchToModel: (model, note) => (note ? `${model} に切り替え(${note})` : `${model} に切り替え`),
errorSwitchModelFailed: 'モデルを切り替えられませんでした',
- errorUseCredits: 'クレジットを使う',
+ errorUseCredits: 'クレジットで続行を有効にする',
errorUseCreditsFailed: 'クレジットで続行を有効にできませんでした',
errorAddCredits: 'クレジットを追加',
errorOpenBillingSettings: '請求設定を開く',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 2bc554088d3..9444d9cef4d 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -367,6 +367,7 @@ export const ruOverrides = {
topTier: 'Крупные модели (месяц)',
barLabel: title => `${title}: использовано включённого объёма`,
captionPaused: 'Приостановлено: платёж по подписке не прошёл',
+ captionPausedOther: 'Приостановлено: см. раздел «Оплата» на портале',
captionTopTierUsedUp: 'Месячный лимит исчерпан, остальное оплачивается кредитами',
captionTopTierUsedUpKeepGoingOff: 'Месячный лимит исчерпан, другие включённые модели работают',
captionResetsIn: duration => `Сброс через ${duration}`,
@@ -3204,6 +3205,7 @@ export const ruOverrides = {
topTier: 'Крупные модели (в месяц)',
included: 'Все модели ниже включены',
pausedRenewal: 'пауза: оплата не прошла',
+ pausedOther: 'пауза',
includedUsedUp: 'Включённый объём исчерпан',
limitReached: name => `Достигнут ${name}`,
limitNames: {
@@ -3622,7 +3624,7 @@ export const ruOverrides = {
errorSwitchToModel: (model: string, note?: string) =>
note ? `Переключиться на ${model} (${note})` : `Переключиться на ${model}`,
errorSwitchModelFailed: 'Не удалось переключить модель',
- errorUseCredits: 'Использовать кредиты',
+ errorUseCredits: 'Включить «Продолжать за кредиты»',
errorUseCreditsFailed: 'Не удалось включить «Продолжать за кредиты»',
errorAddCredits: 'Пополнить кредиты',
errorOpenBillingSettings: 'Открыть настройки оплаты',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 3c81ca18a54..a003a9699d2 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1632,6 +1632,7 @@ catalog: CatalogTranslations
topTier: string
barLabel: (title: string) => string
captionPaused: string
+ captionPausedOther: string
captionTopTierUsedUp: string
captionTopTierUsedUpKeepGoingOff: string
captionResetsIn: (duration: string) => string
@@ -3513,6 +3514,7 @@ catalog: CatalogTranslations
topTier: string
included: string
pausedRenewal: string
+ pausedOther: string
includedUsedUp: string
/** Row note: past its included usage, this model bills top-up credits (pay as you go). */
/** "Weekly limit reached" from a limit name ("weekly"). */
diff --git a/apps/desktop/src/i18n/zh-hant_assistant.ts b/apps/desktop/src/i18n/zh-hant_assistant.ts
index b4d246b1f28..307a6685dbe 100644
--- a/apps/desktop/src/i18n/zh-hant_assistant.ts
+++ b/apps/desktop/src/i18n/zh-hant_assistant.ts
@@ -120,7 +120,7 @@ export const zhHantAssistant = {
errorRetry: '重試',
errorSwitchToModel: (model, note) => (note ? `切換到 ${model}(${note})` : `切換到 ${model}`),
errorSwitchModelFailed: '無法切換模型',
- errorUseCredits: '使用額度',
+ errorUseCredits: '開啟用額度繼續',
errorUseCreditsFailed: '無法開啟用額度繼續',
errorAddCredits: '新增額度',
errorOpenBillingSettings: '開啟帳單設定',
diff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.ts
index ceaffa632a2..0e32877cace 100644
--- a/apps/desktop/src/i18n/zh-hant_settings.ts
+++ b/apps/desktop/src/i18n/zh-hant_settings.ts
@@ -1382,6 +1382,7 @@ export const zhHantSettings = {
topTier: '大型模型(每月)',
barLabel: title => `${title}已用包含用量`,
captionPaused: '已暫停:訂閱付款失敗',
+ captionPausedOther: '已暫停:請在 Portal 的帳單頁查看',
captionTopTierUsedUp: '每月額度已用完,剩餘部分由你的額度支付',
captionTopTierUsedUpKeepGoingOff: '每月額度已用完,其他包含的模型仍可使用',
captionResetsIn: duration => `${duration}後重設`,
@@ -1625,6 +1626,7 @@ export const zhHantSettings = {
topTier: '大型模型(每月)',
included: '下列模型均已包含',
pausedRenewal: '已暫停:續費未到帳',
+ pausedOther: '已暫停',
includedUsedUp: '包含用量已用完',
limitReached: name => `已達${name}上限`,
limitNames: { day: '每日', month: '每月', top_tier: '每月大型模型', week: '每週' },
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index c2edbb4d008..d2e45b005a3 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1802,6 +1802,7 @@ export const zhOverrides = {
topTier: '大型模型(每月)',
barLabel: title => `${title}已用包含用量`,
captionPaused: '已暂停:订阅付款失败',
+ captionPausedOther: '已暂停:请在 Portal 的账单页查看',
captionTopTierUsedUp: '每月额度已用完,剩余部分由你的额度支付',
captionTopTierUsedUpKeepGoingOff: '每月额度已用完,其他包含的模型仍可使用',
captionResetsIn: duration => `${duration}后重置`,
@@ -3921,6 +3922,7 @@ export const zhOverrides = {
topTier: '大型模型(每月)',
included: '下列模型均已包含',
pausedRenewal: '已暂停:续费未到账',
+ pausedOther: '已暂停',
includedUsedUp: '包含用量已用完',
limitReached: name => `已达${name}上限`,
limitNames: { day: '每日', month: '每月', top_tier: '每月大型模型', week: '每周' },
@@ -4452,7 +4454,7 @@ export const zhOverrides = {
errorRetry: '重试',
errorSwitchToModel: (model, note) => (note ? `切换到 ${model}(${note})` : `切换到 ${model}`),
errorSwitchModelFailed: '无法切换模型',
- errorUseCredits: '使用额度',
+ errorUseCredits: '开启用额度继续',
errorUseCreditsFailed: '无法开启用额度继续',
errorAddCredits: '添加额度',
errorOpenBillingSettings: '打开账单设置',
diff --git a/apps/desktop/src/lib/error-surface.test.ts b/apps/desktop/src/lib/error-surface.test.ts
index 04676290376..b8e4a311b32 100644
--- a/apps/desktop/src/lib/error-surface.test.ts
+++ b/apps/desktop/src/lib/error-surface.test.ts
@@ -272,6 +272,19 @@ describe('usage-window refusal', () => {
expect(add.openBilling).toBe(true)
expect(add.useCredits || add.switchToModel || add.switchProvider).toBe(false)
+
+ // Keep going off and no balance: both steps live on the Billing page, so Open billing (not Use credits).
+ const both = errorRecoveryPlan(
+ parseErrorSurface({
+ code: 'usage_window',
+ layer: 'billing',
+ retryable: true,
+ usage_limit: { credits: { action: 'add_credits_and_keep_going' }, suggestions: [] }
+ })
+ )
+
+ expect(both.openBilling).toBe(true)
+ expect(both.useCredits || both.switchToModel || both.switchProvider).toBe(false)
})
it('falls back to its own table body when an older backend sent no sentence', () => {
diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.ts
index 0fb19ee5e71..04509f5bb9b 100644
--- a/apps/desktop/src/lib/error-surface.ts
+++ b/apps/desktop/src/lib/error-surface.ts
@@ -119,8 +119,9 @@ export interface UsageLimitSuggestion {
export interface UsageLimitSurface {
suggestions: UsageLimitSuggestion[]
- /** use_credits: Keep going is off and there is a balance. add_credits: top up. */
- credits?: 'add_credits' | 'use_credits'
+ /** agent/plan_limits.py::credits_action. use_credits: Keep going is off and there is a balance; add_credits:
+ * top up; add_credits_and_keep_going: both. Only use_credits gets its own button, the others open billing. */
+ credits?: 'add_credits' | 'add_credits_and_keep_going' | 'use_credits'
}
function parseUsageLimit(value: unknown): UsageLimitSurface | undefined {
@@ -146,7 +147,9 @@ function parseUsageLimit(value: unknown): UsageLimitSurface | undefined {
})
const action = raw.credits?.action
- const credits = action === 'use_credits' || action === 'add_credits' ? action : undefined
+
+ const credits =
+ action === 'use_credits' || action === 'add_credits' || action === 'add_credits_and_keep_going' ? action : undefined
return suggestions.length || credits ? { suggestions, ...(credits ? { credits } : {}) } : undefined
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 4ae5ce6e838..6b302280bec 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -5703,7 +5703,7 @@ export interface UsageLimitSuggestion {
note: string
provider?: string
}
-/** ``agent/plan_limits.py::CreditsOption`` — ``use_credits`` (turn on Keep going) or ``add_credits``. */
+/** ``agent/plan_limits.py::CreditsOption`` — ``use_credits`` (turn on Keep going), ``add_credits``, or ``add_credits_and_keep_going`` (both: Keep going is off and there is no balance). */
export interface UsageLimitCredits {
action: string
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 913c8f77b1b..9d75f208ecd 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -45236,7 +45236,7 @@
},
"UsageLimitCredits": {
"additionalProperties": false,
- "description": "``agent/plan_limits.py::CreditsOption`` \u2014 ``use_credits`` (turn on Keep going) or ``add_credits``.",
+ "description": "``agent/plan_limits.py::CreditsOption`` \u2014 ``use_credits`` (turn on Keep going), ``add_credits``, or\n``add_credits_and_keep_going`` (both: Keep going is off and there is no balance).",
"properties": {
"action": {
"title": "Action",
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index 68e6ed48103..058010e4055 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -106,6 +106,7 @@ export {
gaugeScope,
gaugeTitle,
hasTopTier,
+ PAYMENT_PAUSE_REASON,
planBlocks,
planLimit,
sectionAt,
diff --git a/apps/shared/src/plan-usage.ts b/apps/shared/src/plan-usage.ts
index 534578e9afb..78575849064 100644
--- a/apps/shared/src/plan-usage.ts
+++ b/apps/shared/src/plan-usage.ts
@@ -94,6 +94,10 @@ export function sectionAt(
*/
export type KnownGaugeId = 'day' | 'month' | 'top_tier' | 'week'
+/** The pause reason that means the subscription payment failed (agent/usage_gauges.py
+ * `PAYMENT_PAUSE_REASONS`). Any other reason, `unknown` included, is a pause with neutral copy. */
+export const PAYMENT_PAUSE_REASON = 'payment_past_due'
+
const KNOWN_GAUGE_IDS = new Set<string>(['day', 'month', 'top_tier', 'week'])
export function knownGaugeId(gauge: Pick<PlanUsageGauge, 'label'>): KnownGaugeId | null {
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 96d90752bd6..2d90b818f57 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1,4 +1,3 @@
-# health: allow FILE_LINES -- usage-window plans: two delivery hooks only (Portal wording on chat platforms, then the limit offer after the reply); the logic lives in agent/plan_limits.py and gateway/slash_commands_model.py
"""Agent-turn execution for GatewayRunner: _handle_message_with_agent, _run_agent*, proxy path,
background tasks, MCP reload. Bound onto ``GatewayRunner`` via the MRO; ``gateway.run`` internals
are imported lazily inside method bodies (import cycle) so ``patch("gateway.run.X")`` still works.
@@ -309,11 +308,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
persist_user_display_kind=prepared.persist_user_display_kind,
reply_expected=event.reply_expected,
)
- response = self._hmwa_prepend_reasoning(agent_result, response, source, _intentional_silence)
- if agent_result.get("usage_window_message") and response:
- # A chat has no /topup Keep going control: the plan's credits settings live in the Portal.
- from agent.plan_limits import portal_wording
- response = portal_wording(response)
+ response = self._usage_window_chat_wording(agent_result, self._hmwa_prepend_reasoning(agent_result, response, source, _intentional_silence))
_footer_line = self._hmwa_runtime_footer_line(agent_result, source, _turn_seconds)
# Streaming already delivered the body: the footer goes out as a trailing send instead.
if _footer_line and response and not agent_result.get("already_sent") and not _intentional_silence:
@@ -335,15 +330,10 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
hidden_reasoning_incomplete=hidden_reasoning_incomplete,
is_context_overflow_failure=is_context_overflow_failure,
)
- delivered = await self._hmwa_deliver_turn_response(
+ return await self._deliver_turn_response_then_limit_offer(
event, source, session_entry, session_key, run_generation,
agent_result, agent_messages, response, _footer_line, _intentional_silence,
)
- if isinstance(agent_result.get("usage_limit"), dict):
- # After the reply lands: the limit sentence is the reply; the button follows it.
- self._schedule_usage_limit_offer(event, agent_result["usage_limit"], session_key=session_key,
- generation=run_generation)
- return delivered
except Exception as e:
return await self._hmwa_agent_error_reply(e, event, source, session_entry, session_key, prepared)
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index a4f108979ab..b4fe66fd31f 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -524,6 +524,31 @@ class GatewayTurnPersistenceMixin:
# trigger a rebuild next turn (destroying prompt caching).
await self._refresh_agent_cache_message_count(session_key, sid)
+ @staticmethod
+ def _usage_window_chat_wording(agent_result: dict, response: str) -> str:
+ """A usage-window refusal sent to a chat: credits steps point at the Portal (a chat's /topup has no
+ Keep going control) and the reset reads as a duration (the gateway's clock is not the reader's).
+ Every other reply is returned unchanged."""
+ if not (agent_result.get("usage_window_message") and response):
+ return response
+ from agent.plan_limits import chat_refusal_wording
+ return chat_refusal_wording(response, agent_result.get("failure_resets_at"))
+
+ async def _deliver_turn_response_then_limit_offer(
+ self, event, source, session_entry, session_key, run_generation,
+ agent_result, agent_messages, response, footer_line, intentional_silence,
+ ):
+ """``_hmwa_deliver_turn_response``, then, for a usage-window refusal, the limit offer: the limit
+ sentence is the reply, and the button follows it once it lands."""
+ delivered = await self._hmwa_deliver_turn_response(
+ event, source, session_entry, session_key, run_generation,
+ agent_result, agent_messages, response, footer_line, intentional_silence,
+ )
+ if isinstance(agent_result.get("usage_limit"), dict):
+ self._schedule_usage_limit_offer(event, agent_result["usage_limit"], session_key=session_key,
+ generation=run_generation)
+ return delivered
+
async def _hmwa_deliver_turn_response(
self, event, source, session_entry, session_key, run_generation,
agent_result, agent_messages, response, _footer_line, _intentional_silence,
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index a7ab198c715..235df213cf0 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -336,6 +336,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
def present():
try:
line = render_notice_line(notice)
+ if key.startswith("credits."):
+ # Window plans (e.g. a paused plan's line): a chat's /topup has no credits settings.
+ from agent.plan_limits import portal_wording
+ line = portal_wording(line)
except Exception:
logger.debug("render_notice_line failed", exc_info=True)
return
diff --git a/gateway/slash_commands_status.py b/gateway/slash_commands_status.py
index 7c30a7a8cd1..90f3e8667a2 100644
--- a/gateway/slash_commands_status.py
+++ b/gateway/slash_commands_status.py
@@ -607,6 +607,9 @@ class GatewayStatusCommandsMixin:
lambda: asyncio.to_thread(nous_credits_lines, markdown=True, credits_state=credits_state),
[],
)
+ # Window plans: a chat's /topup has no Keep going control, so point the setting at the Portal.
+ from agent.plan_limits import portal_wording
+ credits_lines = [portal_wording(line) for line in credits_lines]
def _with_account_blocks(lines: list[str]) -> str:
# Each block is preceded by a blank divider only when something precedes it.
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index d1ef5172e59..bc0a96fef96 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -1677,7 +1677,7 @@ def _login_nous(args, pconfig: ProviderConfig) -> None:
_save_model_choice(selected_model)
print(f"Default model set to: {selected_model}")
from hermes_cli.model_picker_usage import large_model_notice
- if _notice := large_model_notice(selected_model, "nous", base_url=inference_base_url or ""):
+ if _notice := large_model_notice(selected_model, "nous"):
print(f" ⚠ {_notice}") # window plans only (a Large mark exists only on their catalog)
print(f" Config updated: {config_path} (model.provider=nous)")
except KeyboardInterrupt:
diff --git a/hermes_cli/cli_billing_mixin.py b/hermes_cli/cli_billing_mixin.py
index 91afc30aa45..b11047de939 100644
--- a/hermes_cli/cli_billing_mixin.py
+++ b/hermes_cli/cli_billing_mixin.py
@@ -1134,6 +1134,8 @@ class CLIBillingMixin:
self._billing_render_charge_error(state, exc)
return
print(f" {t('cli.billing.keep_going_turned_on' if turn_on else 'cli.billing.keep_going_turned_off')}")
+ from agent.credits_tracker import apply_keep_going_change
+ apply_keep_going_change(getattr(self, "agent", None), turn_on)
def _billing_auto_reload_disable(self, state):
"""PATCH ``enabled:false``; the endpoint still requires threshold/topUpAmount → echo current (or 0)."""
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.py
index 4f3e5ecad31..274a2213936 100644
--- a/hermes_cli/inventory.py
+++ b/hermes_cli/inventory.py
@@ -3,7 +3,6 @@
from __future__ import annotations
-import contextlib
import logging
from contextvars import copy_context
from dataclasses import dataclass, replace
@@ -1003,9 +1002,7 @@ def _apply_pricing(rows: list[dict], *, force_fresh_nous_tier: bool = False, cac
# The gateway's per-plan word per model (free / low / medium / top_tier).
row["usage_levels"] = usage_levels(list(models), raw_pricing)
# Top-tier marks from the gateway (it decides, not the client).
- with contextlib.suppress(Exception):
- row["plan_usage"] = plan_usage.with_pricing(
- {m: raw_pricing.get(m) for m in models}).to_payload()
+ row["plan_usage"] = plan_usage.with_pricing({m: raw_pricing.get(m) for m in models}).to_payload()
# Window plans: the picker shows the usage word, not per-token prices.
row.pop("pricing", None)
diff --git a/hermes_cli/model_picker_usage.py b/hermes_cli/model_picker_usage.py
index 61bb9030ca0..7efe8252a25 100644
--- a/hermes_cli/model_picker_usage.py
+++ b/hermes_cli/model_picker_usage.py
@@ -103,9 +103,9 @@ class PickerUsage:
"""A copy that reads the gateway's ``top_tier`` marks from *pricing* (picker pricing shape)."""
if not pricing:
return self
- from agent.plan_limits import is_free
- free = frozenset(m for m in pricing if is_free(m, pricing))
- marked = frozenset(m for m, p in pricing.items() if p and p.get("top_tier") is True and m not in free)
+ levels = usage_levels(list(pricing), pricing) # same rule as the tags and agent.plan_limits.is_top_tier
+ free = frozenset(m for m, level in levels.items() if level == "free")
+ marked = frozenset(m for m, level in levels.items() if level == "top_tier")
from dataclasses import replace
return replace(self, top_tier_ids=marked, free_ids=free)
@@ -405,22 +405,18 @@ def nous_picker_usage(*, warm: bool = False, any_age: bool = False) -> Optional[
return None
-def _nous_catalog(base_url: str = "", *, fetch: bool = False) -> dict[str, dict[str, Any]]:
- """The caller's Nous ``/v1/models`` rows: resident cache first, one fetch only when ``fetch``."""
- from hermes_cli.models_pricing import get_pricing_for_provider, peek_cached_pricing
+def _nous_catalog(*, fetch: bool = False) -> dict[str, dict[str, Any]]:
+ """This profile's Nous ``/v1/models`` rows: its resident cache, one fetch only when ``fetch``. Never a
+ catalog cached for another credential (another profile's plan marks different models Large)."""
+ from hermes_cli.models_pricing import get_pricing_for_provider
rows = get_pricing_for_provider("nous", cached_only=True) or {}
- if not rows:
- if not base_url:
- from hermes_cli.auth import DEFAULT_NOUS_INFERENCE_URL, _nous_inference_env_override
- base_url = _nous_inference_env_override() or DEFAULT_NOUS_INFERENCE_URL
- rows = peek_cached_pricing(base_url) or {}
if not rows and fetch:
rows = get_pricing_for_provider("nous") or {}
return rows
def large_model_notice(
- model_id: str, provider: str, *, base_url: str = "", fetch: bool = False, lang: Optional[str] = None,
+ model_id: str, provider: str, *, fetch: bool = False, lang: Optional[str] = None,
) -> Optional[str]:
"""Warning line for a switch to a Large model, or None. Window plans only. The gateway decides "Large"
(``usage_level: top_tier``; older gateways ``top_tier: true``) and stamps it ONLY on a usage-window
@@ -432,7 +428,7 @@ def large_model_notice(
return None
fresh = nous_picker_usage()
usage = fresh or nous_picker_usage(any_age=True)
- rows = _nous_catalog(base_url, fetch=fetch and usage is not None)
+ rows = _nous_catalog(fetch=fetch and usage is not None)
row = rows.get(model_id)
if not row:
return None
@@ -475,7 +471,9 @@ def _gauge_name(g: UsageGauge) -> str:
def plan_gauge_lines(usage: PickerUsage) -> list[str]:
"""Stacked plan summary: one line per server allowance, in the server's order, so the picker header
stays readable at a normal terminal width."""
- head = (usage.plan or "Hermes plan") + (" (paused: renewal unpaid)" if usage.paused_reason else "")
+ from agent.usage_gauges import paused_for_payment
+ paused = (" (paused: renewal unpaid)" if paused_for_payment(usage.paused_reason) else " (paused)") if usage.paused_reason else ""
+ head = (usage.plan or "Hermes plan") + paused
label_w = max((len(_gauge_name(g)) for g in usage.gauges), default=4)
return [head, *(
f"{_gauge_name(g):<{label_w}} {g.bar} {g.percent_used + ' used':<9} {format_resets_in(g.resets_at_ms)}"
diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.py
index f7993abb845..8ed772442e7 100644
--- a/hermes_cli/model_setup_flows.py
+++ b/hermes_cli/model_setup_flows.py
@@ -360,7 +360,7 @@ def _model_flow_nous(config, current_model="", args=None):
print(f"Default model set to: {selected} (via Nous Portal)")
if _usage is not None:
from hermes_cli.model_picker_usage import large_model_notice
- if _notice := large_model_notice(selected, "nous", base_url=creds.get("base_url", "")):
+ if _notice := large_model_notice(selected, "nous"):
print(f"⚠ {_notice}")
# Offer Tool Gateway enablement for paid subscribers
prompt_enable_tool_gateway(config)
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index 60993b45131..7e1c683b313 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1731,8 +1731,7 @@ def _build_switch_result(st: _Switch) -> ModelSwitchResult:
warnings = [w for w in (st.validation.get("message"), _check_hermes_model_warning(st.new_model)) if w]
from hermes_cli.model_picker_usage import large_model_notice
- usage_notice = large_model_notice(
- st.new_model, st.target_provider, base_url=str(st.base_url or ""), fetch=True) or ""
+ usage_notice = large_model_notice(st.new_model, st.target_provider, fetch=True) or ""
# Carry the switched provider's request_overrides (custom_providers ``extra_body`` such as
# chat_template_kwargs) so the gateway applies them like the default-provider path does.
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index e97ee8652f0..ac3356231cd 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -1428,13 +1428,7 @@ def _attach_window_model_notes(providers: list[dict]) -> None:
if usage is None:
return
from agent.plan_limits import cached_pricing
- base_url = str(nous.get("api_url") or "")
- if not base_url:
- # Cache-only: the env override, else the default URL; never a credential refresh here.
- from hermes_cli.auth import _nous_inference_env_override
- from hermes_cli.auth_constants import DEFAULT_NOUS_INFERENCE_URL
- base_url = _nous_inference_env_override() or DEFAULT_NOUS_INFERENCE_URL
- pricing = cached_pricing(base_url)
+ pricing = cached_pricing() # this profile's catalog only (cache-only, no credential refresh)
models = [str(m) for m in nous.get("models", [])]
labels = {m: label for m, lv in usage_levels(models, pricing).items() if (label := usage_level_label(lv))}
if labels:
diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.py
index 0fdd9aa9146..adfbc3de8e3 100644
--- a/hermes_cli/nous_account.py
+++ b/hermes_cli/nous_account.py
@@ -200,21 +200,29 @@ def nous_portal_topup_url(account_info: Optional[NousPortalAccountInfo] = None)
def format_usage_window_block_guidance(account_info: Optional[NousPortalAccountInfo]) -> Optional[str]:
- """Next step after a usage-window 402 (included usage spent, no credits): the add-credits link,
- plus the auto top-up nudge when it is off. None for every account not on a usage-window plan, so
- the credit-grant guidance is unchanged. A paused plan points at the card, not at a top-up."""
+ """Next step after a usage-window 402: the credits step from :func:`agent.plan_limits.credits_action`
+ (turn on Keep going, add credits, or both), plus the auto top-up nudge when it is off. None for every
+ account not on a usage-window plan, so the credit-grant guidance is unchanged. A paused plan points
+ at the card, not at a top-up."""
window = getattr(account_info, "usage_window", None) if account_info is not None else None
# A partial/empty block is not a window plan (same completeness rule as the credits seed).
from agent.credits_tracker import _window_seed_fields
if _window_seed_fields(window) is None:
return None
- if getattr(window, "paused_reason", None):
+ if paused := getattr(window, "paused_reason", None):
# A paused plan bills credits whatever the setting says: no credits is why this 402 came.
- return ("Update your card to restore included usage, or add credits to keep going now: "
- f"{nous_portal_billing_url(account_info)}")
- if getattr(window, "keep_going_on_credits", None) is False:
- # A balance doesn't unlock Hermes here: the account setting does.
+ from agent.usage_gauges import paused_for_payment
+ fix = "Update your card to restore included usage" if paused_for_payment(paused) else "Included usage is paused"
+ return f"{fix}, or add credits to keep going now: {nous_portal_billing_url(account_info)}"
+ from agent.plan_limits import ADD_CREDITS_AND_KEEP_GOING, USE_CREDITS, credits_action
+ purchased = getattr(account_info.paid_service_access_info, "purchased_credits_remaining", None)
+ action = credits_action(getattr(window, "keep_going_on_credits", None),
+ int(purchased * 1_000_000) if isinstance(purchased, (int, float)) else None)
+ if action == USE_CREDITS:
return f"Turn on Keep going in /topup to use your credits now: {nous_portal_billing_url(account_info)}"
+ if action == ADD_CREDITS_AND_KEEP_GOING:
+ # With the setting off the gateway refuses whatever the balance, so a top-up alone won't do.
+ return f"Add credits and turn on Keep going in /topup to keep going now: {nous_portal_billing_url(account_info)}"
lines = [f"Add credits to keep going now: {nous_portal_topup_url(account_info)}"]
if getattr(window, "auto_top_up_enabled", None) is False:
lines.append("Turn on auto top-up in the same place so this doesn't stop you next time.")
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 330a86b54fd..1069b2f35c2 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -2135,6 +2135,7 @@
"modelPicker.month",
"modelPicker.noAuthenticatedProviders",
"modelPicker.noModels",
+ "modelPicker.pausedOther",
"modelPicker.pausedRenewal",
"modelPicker.percentUsed",
"modelPicker.priceTitle",
@@ -3082,6 +3083,7 @@
"settings.billing.state.usage.window.barLabel",
"settings.billing.state.usage.window.captionIncluded",
"settings.billing.state.usage.window.captionPaused",
+ "settings.billing.state.usage.window.captionPausedOther",
"settings.billing.state.usage.window.captionResetsIn",
"settings.billing.state.usage.window.captionTopTierUsedUp",
"settings.billing.state.usage.window.captionTopTierUsedUpKeepGoingOff",
diff --git a/locales/_keys.tui.json b/locales/_keys.tui.json
index 58a066873af..b2f96f9e5e8 100644
--- a/locales/_keys.tui.json
+++ b/locales/_keys.tui.json
@@ -553,6 +553,12 @@
"libText.agentRows.starting",
"libText.attachments.imageToken",
"libText.billingDialog.dismiss",
+ "libText.billingDialog.limitCreditsAdd",
+ "libText.billingDialog.limitCreditsBoth",
+ "libText.billingDialog.limitCreditsUse",
+ "libText.billingDialog.limitOpenTopup",
+ "libText.billingDialog.limitSwitchTo",
+ "libText.billingDialog.limitTitle",
"libText.billingDialog.nousDetail",
"libText.billingDialog.nousTitle",
"libText.billingDialog.openBillingPage",
diff --git a/locales/af.tui.yaml b/locales/af.tui.yaml
index b17cbf24467..17e7e6faf62 100644
--- a/locales/af.tui.yaml
+++ b/locales/af.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "resultaat gereed"
libText.agentRows.starting: "Begin…"
libText.attachments.imageToken: "[[ Beeld {0} ]]"
libText.billingDialog.dismiss: "Maak toe"
+libText.billingDialog.limitCreditsAdd: "Of voeg krediete by met /topup."
+libText.billingDialog.limitCreditsBoth: "Of voeg krediete by en skakel Gaan voort op krediete aan in /topup."
+libText.billingDialog.limitCreditsUse: "Of skakel Gaan voort op krediete aan in /topup om jou krediete te gebruik."
+libText.billingDialog.limitOpenTopup: "Maak /topup oop"
+libText.billingDialog.limitSwitchTo: "Skakel oor na {0}"
+libText.billingDialog.limitTitle: "Limiet bereik"
libText.billingDialog.nousDetail: "Jou Nous-kredietsaldo is op — laai op om voort te gaan."
libText.billingDialog.nousTitle: "Nous-krediete is op"
libText.billingDialog.openBillingPage: "Open faktureringsblad"
diff --git a/locales/ar.tui.yaml b/locales/ar.tui.yaml
index eac964f9bdb..4c3dd7d6405 100644
--- a/locales/ar.tui.yaml
+++ b/locales/ar.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "النتيجة جاهزة"
libText.agentRows.starting: "جارٍ البدء…"
libText.attachments.imageToken: "[[ صورة {0} ]]"
libText.billingDialog.dismiss: "تجاهل"
+libText.billingDialog.limitCreditsAdd: "أو أضف رصيدًا عبر /topup."
+libText.billingDialog.limitCreditsBoth: "أو أضف رصيدًا وفعّل الاستمرار بالرصيد في /topup."
+libText.billingDialog.limitCreditsUse: "أو فعّل الاستمرار بالرصيد في /topup لاستخدام رصيدك."
+libText.billingDialog.limitOpenTopup: "افتح /topup"
+libText.billingDialog.limitSwitchTo: "التبديل إلى {0}"
+libText.billingDialog.limitTitle: "تم بلوغ الحد"
libText.billingDialog.nousDetail: "نفد رصيد Nous لديك — أعد تعبئة الرصيد لمواصلة العمل."
libText.billingDialog.nousTitle: "نفد رصيد Nous"
libText.billingDialog.openBillingPage: "فتح صفحة الفوترة"
diff --git a/locales/de.tui.yaml b/locales/de.tui.yaml
index 996024371c0..2131ee454c0 100644
--- a/locales/de.tui.yaml
+++ b/locales/de.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "Ergebnis bereit"
libText.agentRows.starting: "Startet…"
libText.attachments.imageToken: "[[ Bild {0} ]]"
libText.billingDialog.dismiss: "Schließen"
+libText.billingDialog.limitCreditsAdd: "Oder Credits mit /topup aufladen."
+libText.billingDialog.limitCreditsBoth: "Oder Credits aufladen und „Mit Credits weitermachen“ in /topup aktivieren."
+libText.billingDialog.limitCreditsUse: "Oder „Mit Credits weitermachen“ in /topup aktivieren, um Ihre Credits zu nutzen."
+libText.billingDialog.limitOpenTopup: "/topup öffnen"
+libText.billingDialog.limitSwitchTo: "Zu {0} wechseln"
+libText.billingDialog.limitTitle: "Limit erreicht"
libText.billingDialog.nousDetail: "Ihr Nous-Guthaben ist aufgebraucht — laden Sie auf, um weiterzumachen."
libText.billingDialog.nousTitle: "Kein Nous-Guthaben mehr"
libText.billingDialog.openBillingPage: "Abrechnungsseite öffnen"
diff --git a/locales/es.tui.yaml b/locales/es.tui.yaml
index 8ce26396aaf..906c418a4e7 100644
--- a/locales/es.tui.yaml
+++ b/locales/es.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "resultado listo"
libText.agentRows.starting: "Iniciando…"
libText.attachments.imageToken: "[[ Imagen {0} ]]"
libText.billingDialog.dismiss: "Descartar"
+libText.billingDialog.limitCreditsAdd: "O añade créditos con /topup."
+libText.billingDialog.limitCreditsBoth: "O añade créditos y activa Seguir con créditos en /topup."
+libText.billingDialog.limitCreditsUse: "O activa Seguir con créditos en /topup para usar tus créditos."
+libText.billingDialog.limitOpenTopup: "Abrir /topup"
+libText.billingDialog.limitSwitchTo: "Cambiar a {0}"
+libText.billingDialog.limitTitle: "Límite alcanzado"
libText.billingDialog.nousDetail: "Tu saldo de créditos de Nous se agotó — recarga para seguir."
libText.billingDialog.nousTitle: "Sin créditos de Nous"
libText.billingDialog.openBillingPage: "Abrir página de facturación"
diff --git a/locales/fr.tui.yaml b/locales/fr.tui.yaml
index 4ef2a41c1e6..d6ccad4ff3e 100644
--- a/locales/fr.tui.yaml
+++ b/locales/fr.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "résultat prêt"
libText.agentRows.starting: "Démarrage…"
libText.attachments.imageToken: "[[ Image {0} ]]"
libText.billingDialog.dismiss: "Ignorer"
+libText.billingDialog.limitCreditsAdd: "Ou ajoutez des crédits avec /topup."
+libText.billingDialog.limitCreditsBoth: "Ou ajoutez des crédits et activez Continuer avec les crédits dans /topup."
+libText.billingDialog.limitCreditsUse: "Ou activez Continuer avec les crédits dans /topup pour utiliser vos crédits."
+libText.billingDialog.limitOpenTopup: "Ouvrir /topup"
+libText.billingDialog.limitSwitchTo: "Passer à {0}"
+libText.billingDialog.limitTitle: "Limite atteinte"
libText.billingDialog.nousDetail: "Votre solde de crédits Nous est épuisé — rechargez pour continuer."
libText.billingDialog.nousTitle: "Plus de crédits Nous"
libText.billingDialog.openBillingPage: "Ouvrir la page de facturation"
diff --git a/locales/ga.tui.yaml b/locales/ga.tui.yaml
index f0d9568d9a1..be53196964e 100644
--- a/locales/ga.tui.yaml
+++ b/locales/ga.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "toradh réidh"
libText.agentRows.starting: "Ag tosú…"
libText.attachments.imageToken: "[[ Íomhá {0} ]]"
libText.billingDialog.dismiss: "Ruaig"
+libText.billingDialog.limitCreditsAdd: "Nó cuir creidmheasanna leis le /topup."
+libText.billingDialog.limitCreditsBoth: "Nó cuir creidmheasanna leis agus cas air Lean ar aghaidh le creidmheasanna in /topup."
+libText.billingDialog.limitCreditsUse: "Nó cas air Lean ar aghaidh le creidmheasanna in /topup chun do chreidmheasanna a úsáid."
+libText.billingDialog.limitOpenTopup: "Oscail /topup"
+libText.billingDialog.limitSwitchTo: "Athraigh go {0}"
+libText.billingDialog.limitTitle: "Teorainn bainte amach"
libText.billingDialog.nousDetail: "Tá d'iarmhéid creidmheasa Nous ídithe — cuir breis leis chun leanúint ar aghaidh."
libText.billingDialog.nousTitle: "Creidmheas Nous ídithe"
libText.billingDialog.openBillingPage: "Oscail leathanach billeála"
diff --git a/locales/hu.tui.yaml b/locales/hu.tui.yaml
index 836fb004bc7..d8d1f5e9cc4 100644
--- a/locales/hu.tui.yaml
+++ b/locales/hu.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "eredmény kész"
libText.agentRows.starting: "Indul…"
libText.attachments.imageToken: "[[ Kép {0} ]]"
libText.billingDialog.dismiss: "Bezárás"
+libText.billingDialog.limitCreditsAdd: "Vagy tölts fel kreditet a /topup paranccsal."
+libText.billingDialog.limitCreditsBoth: "Vagy tölts fel kreditet, és kapcsold be a Folytatás kreditekkel opciót a /topup alatt."
+libText.billingDialog.limitCreditsUse: "Vagy kapcsold be a Folytatás kreditekkel opciót a /topup alatt a kreditjeid használatához."
+libText.billingDialog.limitOpenTopup: "/topup megnyitása"
+libText.billingDialog.limitSwitchTo: "Váltás erre: {0}"
+libText.billingDialog.limitTitle: "Korlát elérve"
libText.billingDialog.nousDetail: "A Nous kreditegyenleged elfogyott — tölts fel a folytatáshoz."
libText.billingDialog.nousTitle: "Elfogytak a Nous kreditek"
libText.billingDialog.openBillingPage: "Számlázási oldal megnyitása"
diff --git a/locales/it.tui.yaml b/locales/it.tui.yaml
index d2eb7377e08..723f59eb165 100644
--- a/locales/it.tui.yaml
+++ b/locales/it.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "risultato pronto"
libText.agentRows.starting: "Avvio…"
libText.attachments.imageToken: "[[ Immagine {0} ]]"
libText.billingDialog.dismiss: "Ignora"
+libText.billingDialog.limitCreditsAdd: "Oppure aggiungi crediti con /topup."
+libText.billingDialog.limitCreditsBoth: "Oppure aggiungi crediti e attiva Continua con i crediti in /topup."
+libText.billingDialog.limitCreditsUse: "Oppure attiva Continua con i crediti in /topup per usare i tuoi crediti."
+libText.billingDialog.limitOpenTopup: "Apri /topup"
+libText.billingDialog.limitSwitchTo: "Passa a {0}"
+libText.billingDialog.limitTitle: "Limite raggiunto"
libText.billingDialog.nousDetail: "Il tuo saldo crediti Nous è esaurito — ricarica per continuare."
libText.billingDialog.nousTitle: "Crediti Nous esauriti"
libText.billingDialog.openBillingPage: "Apri la pagina di fatturazione"
diff --git a/locales/ja.tui.yaml b/locales/ja.tui.yaml
index 06eb2ca3c2a..841a694719d 100644
--- a/locales/ja.tui.yaml
+++ b/locales/ja.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "結果あり"
libText.agentRows.starting: "起動中…"
libText.attachments.imageToken: "[[ 画像 {0} ]]"
libText.billingDialog.dismiss: "閉じる"
+libText.billingDialog.limitCreditsAdd: "または /topup でクレジットを追加してください。"
+libText.billingDialog.limitCreditsBoth: "または /topup でクレジットを追加し、「クレジットで続行」をオンにしてください。"
+libText.billingDialog.limitCreditsUse: "または /topup で「クレジットで続行」をオンにしてクレジットを使ってください。"
+libText.billingDialog.limitOpenTopup: "/topup を開く"
+libText.billingDialog.limitSwitchTo: "{0} に切り替え"
+libText.billingDialog.limitTitle: "上限に達しました"
libText.billingDialog.nousDetail: "Nous のクレジット残高がなくなりました — 続けるにはチャージしてください。"
libText.billingDialog.nousTitle: "Nous クレジットが不足しています"
libText.billingDialog.openBillingPage: "請求ページを開く"
diff --git a/locales/ko.tui.yaml b/locales/ko.tui.yaml
index 75275110fa8..62c8515351e 100644
--- a/locales/ko.tui.yaml
+++ b/locales/ko.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "결과 준비됨"
libText.agentRows.starting: "시작 중…"
libText.attachments.imageToken: "[[ 이미지 {0} ]]"
libText.billingDialog.dismiss: "닫기"
+libText.billingDialog.limitCreditsAdd: "또는 /topup으로 크레딧을 충전하세요."
+libText.billingDialog.limitCreditsBoth: "또는 /topup에서 크레딧을 충전하고 '크레딧으로 계속하기'를 켜세요."
+libText.billingDialog.limitCreditsUse: "또는 /topup에서 '크레딧으로 계속하기'를 켜서 크레딧을 사용하세요."
+libText.billingDialog.limitOpenTopup: "/topup 열기"
+libText.billingDialog.limitSwitchTo: "{0}(으)로 전환"
+libText.billingDialog.limitTitle: "한도에 도달했습니다"
libText.billingDialog.nousDetail: "Nous 크레딧 잔액을 모두 사용했어요 — 계속하려면 충전하세요."
libText.billingDialog.nousTitle: "Nous 크레딧 소진"
libText.billingDialog.openBillingPage: "결제 페이지 열기"
diff --git a/locales/pt.tui.yaml b/locales/pt.tui.yaml
index 5dd5dfc0213..f6610fb43d1 100644
--- a/locales/pt.tui.yaml
+++ b/locales/pt.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "resultado pronto"
libText.agentRows.starting: "Iniciando…"
libText.attachments.imageToken: "[[ Imagem {0} ]]"
libText.billingDialog.dismiss: "Fechar"
+libText.billingDialog.limitCreditsAdd: "Ou adicione créditos com /topup."
+libText.billingDialog.limitCreditsBoth: "Ou adicione créditos e ative Continuar com créditos em /topup."
+libText.billingDialog.limitCreditsUse: "Ou ative Continuar com créditos em /topup para usar seus créditos."
+libText.billingDialog.limitOpenTopup: "Abrir /topup"
+libText.billingDialog.limitSwitchTo: "Mudar para {0}"
+libText.billingDialog.limitTitle: "Limite atingido"
libText.billingDialog.nousDetail: "Seu saldo de créditos Nous acabou — recarregue para continuar."
libText.billingDialog.nousTitle: "Créditos Nous esgotados"
libText.billingDialog.openBillingPage: "Abrir página de cobrança"
diff --git a/locales/ru.tui.yaml b/locales/ru.tui.yaml
index 211b8afa1b7..e02416bf677 100644
--- a/locales/ru.tui.yaml
+++ b/locales/ru.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "результат готов"
libText.agentRows.starting: "Запуск…"
libText.attachments.imageToken: "[[ Изображение {0} ]]"
libText.billingDialog.dismiss: "Закрыть"
+libText.billingDialog.limitCreditsAdd: "Или пополните кредиты через /topup."
+libText.billingDialog.limitCreditsBoth: "Или пополните кредиты и включите «Продолжать за кредиты» в /topup."
+libText.billingDialog.limitCreditsUse: "Или включите «Продолжать за кредиты» в /topup, чтобы использовать кредиты."
+libText.billingDialog.limitOpenTopup: "Открыть /topup"
+libText.billingDialog.limitSwitchTo: "Переключиться на {0}"
+libText.billingDialog.limitTitle: "Лимит исчерпан"
libText.billingDialog.nousDetail: "Баланс кредитов Nous исчерпан — пополните его, чтобы продолжить."
libText.billingDialog.nousTitle: "Кредиты Nous закончились"
libText.billingDialog.openBillingPage: "Открыть страницу оплаты"
diff --git a/locales/tr.tui.yaml b/locales/tr.tui.yaml
index e33166faa6b..c046a31f4e8 100644
--- a/locales/tr.tui.yaml
+++ b/locales/tr.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "sonuç hazır"
libText.agentRows.starting: "Başlatılıyor…"
libText.attachments.imageToken: "[[ Görüntü {0} ]]"
libText.billingDialog.dismiss: "Kapat"
+libText.billingDialog.limitCreditsAdd: "Ya da /topup ile kredi ekleyin."
+libText.billingDialog.limitCreditsBoth: "Ya da kredi ekleyip /topup içinde Kredilerle devam et seçeneğini açın."
+libText.billingDialog.limitCreditsUse: "Ya da kredilerinizi kullanmak için /topup içinde Kredilerle devam et seçeneğini açın."
+libText.billingDialog.limitOpenTopup: "/topup aç"
+libText.billingDialog.limitSwitchTo: "{0} modeline geç"
+libText.billingDialog.limitTitle: "Limite ulaşıldı"
libText.billingDialog.nousDetail: "Nous kredi bakiyeniz tükendi — devam etmek için bakiye yükleyin."
libText.billingDialog.nousTitle: "Nous kredisi bitti"
libText.billingDialog.openBillingPage: "Faturalandırma sayfasını aç"
diff --git a/locales/uk.tui.yaml b/locales/uk.tui.yaml
index 94da3a57203..4357cc81c09 100644
--- a/locales/uk.tui.yaml
+++ b/locales/uk.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "результат готовий"
libText.agentRows.starting: "Запуск…"
libText.attachments.imageToken: "[[ Зображення {0} ]]"
libText.billingDialog.dismiss: "Закрити"
+libText.billingDialog.limitCreditsAdd: "Або поповніть кредити через /topup."
+libText.billingDialog.limitCreditsBoth: "Або поповніть кредити й увімкніть «Продовжувати за кредити» в /topup."
+libText.billingDialog.limitCreditsUse: "Або увімкніть «Продовжувати за кредити» в /topup, щоб використати кредити."
+libText.billingDialog.limitOpenTopup: "Відкрити /topup"
+libText.billingDialog.limitSwitchTo: "Перейти на {0}"
+libText.billingDialog.limitTitle: "Ліміт вичерпано"
libText.billingDialog.nousDetail: "Баланс кредитів Nous вичерпано — поповніть його, щоб продовжити."
libText.billingDialog.nousTitle: "Кредити Nous вичерпано"
libText.billingDialog.openBillingPage: "Відкрити сторінку оплати"
diff --git a/locales/zh-hant.tui.yaml b/locales/zh-hant.tui.yaml
index e63f7400e21..5f1a2d87378 100644
--- a/locales/zh-hant.tui.yaml
+++ b/locales/zh-hant.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "結果就緒"
libText.agentRows.starting: "正在啟動…"
libText.attachments.imageToken: "[[ 圖片 {0} ]]"
libText.billingDialog.dismiss: "關閉"
+libText.billingDialog.limitCreditsAdd: "或使用 /topup 儲值。"
+libText.billingDialog.limitCreditsBoth: "或在 /topup 儲值並開啟「用額度繼續」。"
+libText.billingDialog.limitCreditsUse: "或在 /topup 開啟「用額度繼續」以使用你的額度。"
+libText.billingDialog.limitOpenTopup: "開啟 /topup"
+libText.billingDialog.limitSwitchTo: "切換到 {0}"
+libText.billingDialog.limitTitle: "已達上限"
libText.billingDialog.nousDetail: "你的 Nous 額度餘額已用盡 — 儲值後即可繼續。"
libText.billingDialog.nousTitle: "Nous 額度已用盡"
libText.billingDialog.openBillingPage: "開啟帳務頁面"
diff --git a/locales/zh.tui.yaml b/locales/zh.tui.yaml
index a541edd9fbf..584c8d98eff 100644
--- a/locales/zh.tui.yaml
+++ b/locales/zh.tui.yaml
@@ -567,6 +567,12 @@ libText.agentRows.resultReady: "结果就绪"
libText.agentRows.starting: "正在启动…"
libText.attachments.imageToken: "[[ 图片 {0} ]]"
libText.billingDialog.dismiss: "关闭"
+libText.billingDialog.limitCreditsAdd: "或使用 /topup 充值。"
+libText.billingDialog.limitCreditsBoth: "或在 /topup 充值并开启「用额度继续」。"
+libText.billingDialog.limitCreditsUse: "或在 /topup 开启「用额度继续」以使用你的额度。"
+libText.billingDialog.limitOpenTopup: "打开 /topup"
+libText.billingDialog.limitSwitchTo: "切换到 {0}"
+libText.billingDialog.limitTitle: "已达上限"
libText.billingDialog.nousDetail: "你的 Nous 额度余额已用完 — 充值后即可继续。"
libText.billingDialog.nousTitle: "Nous 额度已用完"
libText.billingDialog.openBillingPage: "打开账单页面"
diff --git a/tests/agent/test_credits_usage_window.py b/tests/agent/test_credits_usage_window.py
index 6b24f4d734a..cdba31d3d27 100644
--- a/tests/agent/test_credits_usage_window.py
+++ b/tests/agent/test_credits_usage_window.py
@@ -261,6 +261,13 @@ class TestDerivedState:
assert not _state(window_top_tier_used_bp=None).top_tier_exhausted # not listed ≠ used
assert not _state(paused_reason="payment_past_due").window_exhausted # paused is not spent
+ def test_an_implausible_reset_stamp_reads_as_unknown(self):
+ """More than a year ahead is a bad stamp (the longest allowance is a month): no date decades away."""
+ far = int(time.time() * 1000) + 10 * 366 * 86_400_000
+ gauges = ct.parse_gauges([{"id": "day", "scope": "all", "used_bp": 100, "resets_at_ms": far},
+ {"id": "week", "scope": "all", "used_bp": 100, "resets_at_ms": WEEK_RESET}])
+ assert gauges[0].resets_at_ms is None and gauges[1].resets_at_ms == WEEK_RESET
+
def test_no_gauges_is_not_a_usage_window(self):
s = _state(gauges=())
assert not s.is_usage_window and s.used_fraction is None and s.binding_gauge is None
@@ -444,6 +451,21 @@ class TestHardStops:
assert "payment failed" in text and "update your card" in text and "add credits in /topup" in text
assert "Keep going on credits" not in text # the setting doesn't gate a paused plan
+ def test_a_pause_for_another_reason_never_claims_a_payment_failed(self):
+ """The server may send any reason (\"unknown\" for a malformed one): still a pause, neutral copy."""
+ from agent import account_usage
+ from hermes_cli import nous_account
+ show, _ = _run(_state(paid_access=False, paused_reason="unknown", spend_source=None), new_credits_latch())
+ assert [k for k, _l, _t in show] == [CREDITS_DEPLETED_KEY]
+ assert "payment" not in show[0][2] and "add credits in /topup" in show[0][2]
+ window = SimpleNamespace(gauges=ct.parse_gauges(_gauges(100, 50)), auto_top_up_enabled=False,
+ paused_reason="unknown", keep_going_on_credits=None)
+ info = SimpleNamespace(logged_in=True, paid_service_access=True, usage_window=window, portal_base_url=None,
+ paid_service_access_info=SimpleNamespace(purchased_credits_remaining=0.0), subscription=None)
+ lines = account_usage.render_account_usage_lines(account_usage.build_nous_credits_snapshot(info))
+ assert account_usage._WINDOW_PAUSED_OTHER_LINE in lines and account_usage._WINDOW_PAUSED_LINE not in lines
+ assert nous_account.format_usage_window_block_guidance(info).startswith("Included usage is paused, or add credits")
+
def test_payment_paused_wins_over_exhausted_and_survives_a_free_model(self):
s = _state(paid_access=False, paused_reason="payment_past_due", window_day_used_bp=10_000, spend_source=None)
show, _ = _run(s, new_credits_latch())
@@ -635,6 +657,7 @@ _PLAN_STATES = {
"week_90pct": lambda: _plan_state(3_000, 9_100, source="included"), # the week's 90% heads-up
# window used up, $5.00 top-up but top-up for Hermes turned off → the stop names the setting
"keep_going_off": lambda: _plan_state(10_000, 6_000, purchased="5.00", keep_going=False),
+ "keep_going_off_no_balance": lambda: _plan_state(10_000, 6_000, keep_going=False),
# window used up, $5.00 top-up → PAYG one-shot
"payg": lambda: _plan_state(10_000, 6_000, purchased="5.00", source="payg"),
"payg_autotopup": lambda: _plan_state(10_000, 6_000, purchased="5.00", source="payg", auto_top_up=True),
@@ -661,6 +684,8 @@ class TestPlanStates:
("exhausted", [CREDITS_WINDOW_LIMIT_KEY], "/topup to add credits"),
# A balance, but top-up for Hermes is off: the stop names the account setting, not /topup.
("keep_going_off", [CREDITS_WINDOW_LIMIT_KEY], "turn on Keep going in /topup"),
+ # No balance and the setting off (the default): the gateway refuses either way, so both steps.
+ ("keep_going_off_no_balance", [CREDITS_WINDOW_LIMIT_KEY], "add credits and turn on Keep going in /topup"),
("paused", [CREDITS_DEPLETED_KEY], "payment failed"),
])
def test_every_window_state_drives_its_notice(self, name, expect_keys, must_contain):
@@ -926,6 +951,16 @@ class TestClassifier:
provider="example", model="m", base_url="https://example.invalid/v1")
assert c.reason == FailoverReason.rate_limit and not c.error_context.get("usage_window")
+ def test_window_code_on_a_429_from_another_upstream_keeps_main_rules(self):
+ """The code is honoured only through the gated 402 path: on any other status (a 429 from another
+ provider or a custom endpoint) it is not a billing code, so the turn backs off and retries as on main."""
+ from agent.error_classifier import FailoverReason, classify_api_error
+ for provider, base_url in (("example", "https://example.invalid/v1"), ("custom", "https://custom.example.invalid/v1")):
+ c = classify_api_error(self._err(429, "usage_window_and_credits_exhausted", "Too many requests"),
+ provider=provider, model="m", base_url=base_url)
+ assert c.reason == FailoverReason.rate_limit and c.retryable
+ assert not c.error_context.get("usage_window")
+
def test_a_plain_403_still_classifies_as_before(self):
from agent.error_classifier import FailoverReason, classify_api_error
c = classify_api_error(self._err(403, "forbidden", "Forbidden"), provider="nous", model="m")
@@ -977,8 +1012,6 @@ class TestBlockedResponseCapture:
def test_non_streaming_success_feeds_the_header_capture(self):
"""A non-streaming 200 must observe x-nous-credits-* like a stream open does
(spend_source / window gauges otherwise go stale until the next stream or 402)."""
- from unittest.mock import MagicMock
-
from agent.chat_completion_headers import _chat_completion_capturing_headers
seen = []
@@ -1014,11 +1047,11 @@ class TestBlockedResponseCapture:
assert _chat_completion_capturing_headers(
SimpleNamespace(provider="example"), other, {"model": "m"}) is plain
- # Test doubles without the raw surface keep the plain call and capture nothing.
+ # A client without the raw surface keeps the plain call and captures nothing.
seen.clear()
agent._capture_rate_limits = lambda r: seen.append(("rl", r))
- mock_client = MagicMock()
- assert _chat_completion_capturing_headers(agent, mock_client, {"model": "m"}) is mock_client.chat.completions.create.return_value
+ bare = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=lambda **kw: plain)))
+ assert _chat_completion_capturing_headers(agent, bare, {"model": "m"}) is plain
assert seen == []
def test_non_streaming_non_window_keeps_mains_behaviour(self):
@@ -1130,6 +1163,42 @@ class TestRefusalReadsAsTheStopLine:
assert resets_at == DAY_RESET / 1000
assert limit["gauge_id"] == "day" and limit["scope"] == "all" and limit["message"] == text
assert limit["credits"] == {"action": "use_credits"} and limit["current_model"] == "example/model-b"
+
+ def test_only_a_billing_refusal_with_the_window_mark_benches_one_model(self):
+ """The model-scoped bench applies to the usage-window 402 alone, and wins over the unverified-billing
+ sizing; any other reason keeps the pool's own handling."""
+ from agent.credential_pool import FAILURE_REASON_BILLING_UNVERIFIED
+ from agent.credential_pool_model_cooldowns import FAILURE_REASON_USAGE_WINDOW, pool_failure_reason
+ from agent.error_classifier import FailoverReason
+ window = {"usage_window": True}
+ assert pool_failure_reason(FailoverReason.billing, window, True) == FAILURE_REASON_USAGE_WINDOW
+ assert pool_failure_reason(FailoverReason.rate_limit, window, False) == FailoverReason.rate_limit.value
+ assert pool_failure_reason(FailoverReason.billing, {}, True) == FAILURE_REASON_BILLING_UNVERIFIED
+ assert pool_failure_reason(FailoverReason.billing, None, False) == FailoverReason.billing.value
+
+ def test_the_pool_bench_lasts_until_the_refused_allowance_resets(self):
+ """The 402's own headers are captured before recovery, so the pool gets the window's reset (not its
+ default 60 s / 1 h bench); a state naming no reset leaves the default."""
+ from agent.turn_recovery import _usage_window_reset_context
+ assert _usage_window_reset_context(self._agent()) == {"reset_at": DAY_RESET / 1000}
+ assert _usage_window_reset_context(SimpleNamespace(_credits_state=None)) == {}
+
+ def test_keep_going_off_with_no_balance_says_both_steps_everywhere(self):
+ """A new subscriber's first limit (setting off by default, no top-up): the stop line, the next-steps
+ payload and the 402 guidance all name both steps, since either one alone is still refused."""
+ from agent.conversation_loop import _usage_window_refusal
+ from hermes_cli import nous_account
+ agent = self._agent(purchased_micros=0, keep_going_on_credits=False)
+ text, _resets_at, limit = _usage_window_refusal(agent, SimpleNamespace(error_context={"usage_window": True}))
+ assert text.endswith(" · add credits and turn on Keep going in /topup")
+ assert limit["credits"] == {"action": "add_credits_and_keep_going"}
+ window = SimpleNamespace(gauges=ct.parse_gauges(_gauges(100, 50)), auto_top_up_enabled=False,
+ paused_reason=None, keep_going_on_credits=False)
+ for purchased in (0.0, None):
+ info = SimpleNamespace(logged_in=True, paid_service_access=True, usage_window=window, portal_base_url=None,
+ paid_service_access_info=SimpleNamespace(purchased_credits_remaining=purchased))
+ guidance = nous_account.format_usage_window_block_guidance(info)
+ assert guidance.startswith("Add credits and turn on Keep going in /topup")
# Any other billing failure keeps its own copy and carries no limit.
assert _usage_window_refusal(agent, SimpleNamespace(error_context={})) == ("", None, None)
diff --git a/tests/agent/test_plan_limits.py b/tests/agent/test_plan_limits.py
index 8a812069753..7dfa48cb938 100644
--- a/tests/agent/test_plan_limits.py
+++ b/tests/agent/test_plan_limits.py
@@ -66,6 +66,13 @@ class TestTheRule:
assert not pl.is_top_tier("unknown/model", PRICING)
assert not pl.is_top_tier("example/model-c", {})
+ def test_the_usage_level_word_marks_top_tier_too(self):
+ """Today's gateway sends both marks; either one alone is enough, and a free row never is."""
+ level_only = {"example/model-d": {"prompt": "0.000005", "completion": "0.000025", "usage_level": "top_tier"}}
+ assert pl.is_top_tier("example/model-d", level_only)
+ free_marked = {"example/model-e:free": {"prompt": "0", "completion": "0", "usage_level": "top_tier"}}
+ assert not pl.is_top_tier("example/model-e:free", free_marked)
+
def test_nothing_full_blocks_nothing(self):
assert not any(pl.is_blocked(m, HEALTHY, PRICING) for m in PRICING)
@@ -126,11 +133,16 @@ class TestCreditsOption:
assert pl.credits_option(state).action == "use_credits"
def test_no_balance_or_setting_on_offers_add_credits(self):
- for state in (SimpleNamespace(paused_reason=None, purchased_micros=0, keep_going_on_credits=False),
- SimpleNamespace(paused_reason=None, purchased_micros=5_000_000, keep_going_on_credits=True),
+ for state in (SimpleNamespace(paused_reason=None, purchased_micros=5_000_000, keep_going_on_credits=True),
SimpleNamespace(paused_reason=None, purchased_micros=0, keep_going_on_credits=None)):
assert pl.credits_option(state).action == "add_credits"
+ def test_keep_going_off_and_no_balance_needs_both_steps(self):
+ """The gateway refuses with Keep going off whatever the balance: a top-up alone would still be refused."""
+ state = SimpleNamespace(paused_reason=None, purchased_micros=0, keep_going_on_credits=False)
+ assert pl.credits_option(state).action == "add_credits_and_keep_going"
+ assert pl.credits_action(False, None) == "add_credits_and_keep_going" # unknown balance counts as none
+
def test_paused_offers_nothing(self):
state = SimpleNamespace(paused_reason="payment_past_due", purchased_micros=5_000_000, keep_going_on_credits=False)
assert pl.credits_option(state) is None
@@ -199,11 +211,27 @@ class TestNextSteps:
text = pl.limit_next_steps_from_payload(self._payload(credits={"action": "use_credits"}))
assert text.endswith("or turn on Keep going in /topup to use credits.")
+ def test_keep_going_off_with_no_balance_names_both_steps(self):
+ both = self._payload(credits={"action": "add_credits_and_keep_going"})
+ assert pl.limit_next_steps_from_payload(both).endswith("or add credits and turn on Keep going in /topup.")
+ assert pl.limit_next_steps_from_payload(both, topup_command=None, portal=True).endswith(
+ "or add credits and turn on Keep going in the Portal.")
+
def test_messaging_points_at_the_portal_and_uses_the_platform_prefix(self):
text = pl.limit_next_steps_from_payload(self._payload(), model_command="!model", topup_command=None, portal=True)
assert text == "Switch to Model Free (free) with !model, or add credits in the Portal."
assert "/topup" not in text
+ def test_a_chat_refusal_points_at_the_portal_and_reads_the_reset_as_a_duration(self):
+ """A gateway's clock is not the reader's time zone: the reset reads "resets in 3h" in a chat."""
+ import time
+
+ from agent.credits_tracker import format_window_reset
+ resets_at = time.time() + 3 * 3600 + 30
+ text = f"You've hit your daily limit · resets {format_window_reset(int(resets_at * 1000))} · /topup to add credits"
+ assert pl.chat_refusal_wording(text, resets_at) == "You've hit your daily limit · resets in 3h · add credits in the Portal"
+ assert pl.chat_refusal_wording("Limit · /topup to add credits") == "Limit · add credits in the Portal"
+
def test_no_suggestion_still_says_how_to_change_model(self):
text = pl.limit_next_steps_from_payload(self._payload(suggestions=[], credits=None))
assert text == "Pick another model with /model."
diff --git a/tests/agent/test_plan_snapshot_sync.py b/tests/agent/test_plan_snapshot_sync.py
index 8601dbd6239..013ed88f1bd 100644
--- a/tests/agent/test_plan_snapshot_sync.py
+++ b/tests/agent/test_plan_snapshot_sync.py
@@ -47,8 +47,8 @@ def wired(monkeypatch):
monkeypatch.setattr(na, "get_nous_portal_account_info", lambda force_fresh=False: calls.append("account"))
monkeypatch.setattr(mp, "get_pricing_for_provider",
lambda provider, force_refresh=False: calls.append(("catalog", provider, force_refresh)))
- monkeypatch.setattr(sync, "_last_attempt", None)
- monkeypatch.setattr(sync, "_inflight", False)
+ monkeypatch.setattr(sync, "_last_attempt", {})
+ monkeypatch.setattr(sync, "_inflight", set())
class _Thread: # run inline: deterministic, no sleeps
def __init__(self, target, args=(), **kw):
@@ -86,6 +86,22 @@ def test_back_in_step_rearms(wired):
assert sync.sync_plan_snapshot(_state(True)) is True
+def test_each_profile_refreshes_its_own_account_under_its_own_home(wired, tmp_path, monkeypatch):
+ """One process, two profiles: the refresh runs with the asking profile's Hermes home, and one
+ profile's pending mismatch never blocks another's."""
+ from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override
+ import hermes_cli.nous_account as na
+ homes = []
+ monkeypatch.setattr(na, "get_nous_portal_account_info", lambda force_fresh=False: homes.append(str(get_hermes_home())))
+ for name in ("a", "b"):
+ token = set_hermes_home_override(tmp_path / name)
+ try:
+ assert sync.sync_plan_snapshot(_state(True)) is True
+ finally:
+ reset_hermes_home_override(token)
+ assert homes == [str(tmp_path / "a"), str(tmp_path / "b")]
+
+
def test_an_ordinary_reply_costs_nothing(wired):
calls, box = wired
box["snap"] = ON_PLAN
diff --git a/tests/gateway/test_usage_limit_offer.py b/tests/gateway/test_usage_limit_offer.py
index 39fe73950ad..74a9faffded 100644
--- a/tests/gateway/test_usage_limit_offer.py
+++ b/tests/gateway/test_usage_limit_offer.py
@@ -228,3 +228,23 @@ def test_a_messaging_refusal_points_at_the_portal_not_topup():
assert portal_wording("You've hit your daily limit · resets 15:56 · turn on Keep going in /topup") == (
"You've hit your daily limit · resets 15:56 · turn on Keep going in the Portal")
assert "/topup" not in portal_wording("You've hit your weekly limit · /topup to add credits")
+
+
+def test_a_chat_refusal_is_worded_for_the_chat_and_other_replies_are_untouched():
+ runner = _runner(_TextAdapter())
+ refusal = {"usage_window_message": "x", "failure_resets_at": None}
+ assert runner._usage_window_chat_wording(refusal, "Limit · /topup to add credits") == "Limit · add credits in the Portal"
+ assert runner._usage_window_chat_wording({}, "use /topup to add credits") == "use /topup to add credits"
+
+
+async def test_the_limit_offer_follows_the_delivered_reply_only_for_a_limit():
+ runner = _runner(_TextAdapter())
+ runner._hmwa_deliver_turn_response = AsyncMock(return_value="sent")
+ offers = []
+ runner._schedule_usage_limit_offer = lambda event, limit, **kw: offers.append((limit, kw))
+ args = ("src", "entry", "chat:c1", 7)
+ for result in ({"usage_limit": LIMIT}, {}):
+ assert await runner._deliver_turn_response_then_limit_offer(
+ _event(), *args, result, [], "reply", "", False) == "sent"
+ assert offers == [(LIMIT, {"session_key": "chat:c1", "generation": 7})]
diff --git a/tests/hermes_cli/test_cli_billing_keep_going_on_credits.py b/tests/hermes_cli/test_cli_billing_keep_going_on_credits.py
index 59f52175570..f197531b7f6 100644
--- a/tests/hermes_cli/test_cli_billing_keep_going_on_credits.py
+++ b/tests/hermes_cli/test_cli_billing_keep_going_on_credits.py
@@ -92,3 +92,25 @@ def test_a_declined_step_up_sends_nothing_more(monkeypatch):
monkeypatch.setattr(cli, "_step_up_remote_spending", lambda **_kw: False, raising=False)
cli._billing_keep_going_on_credits_flow(SimpleNamespace(keep_going_on_credits=False))
assert calls == [{"enabled": True}]
+
+
+def test_turning_on_updates_the_session_state_at_once(sent, monkeypatch):
+ """The "turn on Keep going" line must not wait for the next reply: the agent's state takes the new
+ value and the notice policy re-runs; the account snapshot refreshes in the background."""
+ import hermes_cli.nous_account as na
+ from agent.credits_tracker import CreditsState
+ from agent.usage_gauges import SCOPE_ALL, WindowGauge
+ refreshed, emitted = [], []
+ monkeypatch.setattr(na, "get_nous_portal_account_info", lambda force_fresh=False: refreshed.append(force_fresh))
+ cli = _Cli("agree")
+ cli.agent = SimpleNamespace(_credits_state=CreditsState(version=1, denominator_kind="usage_window",
+ gauges=(WindowGauge("day", SCOPE_ALL, "Today", 10_000),),
+ keep_going_on_credits=False),
+ _emit_credits_notices=lambda: emitted.append(cli.agent._credits_state.keep_going_on_credits))
+ cli._billing_keep_going_on_credits_flow(SimpleNamespace(keep_going_on_credits=False))
+ assert cli.agent._credits_state.keep_going_on_credits is True and emitted == [True]
+ import threading
+ for th in threading.enumerate():
+ if th.name == "keep-going-refresh":
+ th.join(timeout=5)
+ assert refreshed == [True]
diff --git a/tests/hermes_cli/test_model_picker_usage.py b/tests/hermes_cli/test_model_picker_usage.py
index c78dba1e1b8..a8d6cf7a4bc 100644
--- a/tests/hermes_cli/test_model_picker_usage.py
+++ b/tests/hermes_cli/test_model_picker_usage.py
@@ -4,7 +4,7 @@ from dataclasses import replace
from types import SimpleNamespace
from hermes_cli.auth_model_picker import _ModelPickerRows
-from tests.usage_window_fixtures import usage_window
+from tests.usage_window_fixtures import FAR, usage_window
from hermes_cli.model_picker_usage import (
GAUGE_MONTH,
GAUGE_TODAY,
@@ -129,7 +129,7 @@ def test_window_plan_gauges_stack_on_separate_lines():
logged_in=True, subscription=SimpleNamespace(plan="Window Plan"),
usage_window=SimpleNamespace(**usage_window(
day_used_bp=0, week_used_bp=0, top_tier_used_bp=0,
- day_resets_at_ms=int(1e13), week_resets_at_ms=int(1e13), paused_reason=None,
+ day_resets_at_ms=FAR, week_resets_at_ms=FAR, paused_reason=None,
)),
))
stacked = plan_gauge_lines(usage)
@@ -154,7 +154,7 @@ def test_window_gauges_for_model_omit_top_tier_on_regular_ids():
def _window_usage(**window):
"""A window plan where the gateway marked Model B top tier."""
base = dict(day_used_bp=0, week_used_bp=0, top_tier_used_bp=0,
- day_resets_at_ms=int(1e13), week_resets_at_ms=int(1e13), paused_reason=None)
+ day_resets_at_ms=FAR, week_resets_at_ms=FAR, paused_reason=None)
usage = picker_usage_from_account(SimpleNamespace(
logged_in=True, subscription=SimpleNamespace(plan="Window Plan"),
usage_window=SimpleNamespace(**usage_window(**{**base, **window})),
@@ -178,7 +178,7 @@ def test_picker_draws_whatever_allowances_the_server_lists():
usage = picker_usage_from_account(SimpleNamespace(
logged_in=True, subscription=SimpleNamespace(plan="Window Plan"),
usage_window=SimpleNamespace(gauges=[
- {"id": "five_hour", "scope": "all", "label": "Next 5 hours", "used_bp": 10_000, "resets_at_ms": int(1e13)},
+ {"id": "five_hour", "scope": "all", "label": "Next 5 hours", "used_bp": 10_000, "resets_at_ms": FAR},
*usage_window()["gauges"],
], featured_model_ids=()),
))
@@ -263,7 +263,7 @@ def test_a_free_model_is_never_used_up():
def test_the_note_names_the_allowance_that_frees_up_last():
"""Day and week both spent: the day's reset alone lets nothing through, so the note waits for the week."""
- usage = _window_usage(day_used_bp=10_000, week_used_bp=10_000, day_resets_at_ms=1_000, week_resets_at_ms=int(1e13))
+ usage = _window_usage(day_used_bp=10_000, week_used_bp=10_000, day_resets_at_ms=1_000, week_resets_at_ms=FAR)
assert usage.exhausted_gauge("paid/m").label == GAUGE_WEEK
@@ -458,7 +458,7 @@ def test_messaging_pickers_get_large_free_labels_and_the_limit_line(monkeypatch)
from agent import plan_limits as pl
monkeypatch.setattr(mpu, "nous_picker_usage", lambda **kw: _window_usage(top_tier_used_bp=10_000))
- monkeypatch.setattr(pl, "cached_pricing", lambda base_url: dict(_LEVELS))
+ monkeypatch.setattr(pl, "cached_pricing", lambda base_url="": dict(_LEVELS))
providers = [{"slug": "nous", "api_url": "https://x/v1", "models": ["example/model-b", "example/model-a"]},
{"slug": "example", "models": ["example/model-b"]}]
msp._attach_window_model_notes(providers)
@@ -486,7 +486,7 @@ def test_messaging_pickers_get_large_free_labels_and_the_limit_line(monkeypatch)
def test_large_model_notice_window_plans_only(monkeypatch):
from dataclasses import replace as _replace
from hermes_cli import model_picker_usage as mpu
- monkeypatch.setattr(mpu, "_nous_catalog", lambda base_url="", fetch=False: dict(_LEVELS))
+ monkeypatch.setattr(mpu, "_nous_catalog", lambda fetch=False: dict(_LEVELS))
monkeypatch.setattr(mpu, "nous_picker_usage", lambda **kw: _window_usage())
note = mpu.large_model_notice("example/model-b", "nous")
assert note.startswith("Large model: uses more of your plan's usage per message.") and "Monthly large-model limit:" in note
@@ -502,11 +502,24 @@ def test_large_model_notice_window_plans_only(monkeypatch):
# Any other account: its catalog carries no marks (None), and it is never fetched.
seen = []
monkeypatch.setattr(mpu, "_nous_catalog",
- lambda base_url="", fetch=False: seen.append(fetch) or {"example/model-b": {"prompt": "0.000001"}})
+ lambda fetch=False: seen.append(fetch) or {"example/model-b": {"prompt": "0.000001"}})
assert mpu.large_model_notice("example/model-b", "nous", fetch=True) is None
assert seen == [False]
+def test_catalog_reads_never_answer_from_another_profiles_cache(monkeypatch):
+ """One process, several profiles: tags and the Large notice read only this profile's catalog, never the
+ newest catalog cached for any credential (another plan can mark different models Large)."""
+ import hermes_cli.models_pricing as mp
+ from agent import plan_limits as pl
+ from hermes_cli import model_picker_usage as mpu
+ monkeypatch.setattr(mp, "peek_cached_pricing", lambda base_url: dict(_LEVELS)) # another profile's catalog
+ monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider, **kw: {}) # this profile: cold
+ monkeypatch.setattr(mpu, "nous_picker_usage", lambda **kw: None) # this profile: no window plan
+ assert pl.cached_pricing("https://inference-api.nousresearch.com/v1") == {}
+ assert mpu.large_model_notice("example/model-b", "nous") is None
+
+
def test_picker_words_follow_the_display_language(monkeypatch):
"""Pickers main translates read the catalog: English stays byte-identical, other languages translate."""
from hermes_cli import model_picker_usage as mpu
diff --git a/tests/usage_window_fixtures.py b/tests/usage_window_fixtures.py
index d626460ad6e..7e6e4bf426b 100644
--- a/tests/usage_window_fixtures.py
+++ b/tests/usage_window_fixtures.py
@@ -6,9 +6,12 @@ week 40%, top tier full", so this maps those names onto the list, in the server'
from __future__ import annotations
+import time
from typing import Any, Optional
-_FAR = int(1e13)
+# A reset well inside parse_gauges' plausible range (no more than a year ahead).
+FAR = int(time.time() * 1000) + 30 * 86_400_000
+_FAR = FAR
def gauges(*, day_used_bp: int = 0, week_used_bp: int = 0, top_tier_used_bp: Optional[int] = 0,
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 204d38fb55a..1d9603953cf 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -201,7 +201,8 @@ class UsageLimitSuggestion(Payload):
class UsageLimitCredits(Payload):
- """``agent/plan_limits.py::CreditsOption`` — ``use_credits`` (turn on Keep going) or ``add_credits``."""
+ """``agent/plan_limits.py::CreditsOption`` — ``use_credits`` (turn on Keep going), ``add_credits``, or
+ ``add_credits_and_keep_going`` (both: Keep going is off and there is no balance)."""
action: str
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 29c0bbdadde..29847639d07 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1,4 +1,3 @@
-# health: allow FILE_LINES -- usage-window plans: /usage marks the window view, plus one billing write route (keep going on credits) beside its siblings; data building lives in agent/account_usage.py
"""Session / delegation / spawn-tree / billing / pet JSON-RPC handlers.
Bodies are rebound onto server.py's globals at install time (method_ctx.py), so they use server
@@ -1452,16 +1451,8 @@ def _(rid, params: dict, session: dict) -> dict:
if session.get("agent") is None and not usage:
usage = {"calls": 0, "input": 0, "output": 0, "total": 0}
# Nous credits are agent-independent (portal fetch); fail-open when absent.
- with contextlib.suppress(Exception):
- from agent.account_usage import nous_credits_view
- agent = session.get("agent")
- credits, is_window = nous_credits_view(
- credits_state=getattr(agent, "_credits_state", None) if agent else None,
- )
- if credits:
- usage["credits_lines"] = credits
- if is_window:
- usage["credits_usage_window"] = True
+ from agent.account_usage import nous_credits_usage_fields # never raises (fail-open inside)
+ usage.update(nous_credits_usage_fields(session.get("agent")))
return _ok(rid, usage)
@@ -1920,14 +1911,8 @@ def _auto_reload(nb, p: dict, _key) -> dict:
_billing_route("billing.auto_reload", _auto_reload, message="threshold and top_up_amount are required",
invalid=lambda p: p.get("threshold") is None or p.get("top_up_amount") is None)
-# PATCH /api/billing/keep-going-on-credits (window plans). `invalid` below guarantees a bool.
-def _keep_going_on_credits(nb, p: dict, _key) -> dict:
- nb.patch_keep_going_on_credits(enabled=p["enabled"])
- return {"ok": True}
-
-
-_billing_route("billing.keep_going_on_credits", _keep_going_on_credits,
- invalid=lambda p: not isinstance(p.get("enabled"), bool), message="enabled (bool) is required")
+_billing_route("billing.keep_going_on_credits", lambda nb, p, _k: _billing_pick(nb.patch_keep_going_on_credits(enabled=p["enabled"])),
+ invalid=lambda p: not isinstance(p.get("enabled"), bool), message="enabled (bool) is required") # window plans
@method("billing.step_up")
diff --git a/ui-tui/src/__tests__/usagePanel.test.ts b/ui-tui/src/__tests__/usagePanel.test.ts
new file mode 100644
index 00000000000..3f0160f3b5e
--- /dev/null
+++ b/ui-tui/src/__tests__/usagePanel.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+
+import { planUsageLines } from '../app/slash/usagePanel.js'
+
+const plan = (left_fraction: number) =>
+ ({ gauges: [{ label: 'day', left_fraction, style: 'bar', title: 'Today' }], kind: 'usage_window' }) as never
+
+describe('planUsageLines', () => {
+ it('a nearly full allowance reads 99% beside its 9 cells, like the CLI and Desktop', () => {
+ expect(planUsageLines(plan(0.00004))).toEqual(['Today [||||||||| ] 99% used'])
+ })
+
+ it('100% only once the allowance is spent', () => {
+ expect(planUsageLines(plan(0))).toEqual(['Today [||||||||||] 100% used'])
+ })
+})
diff --git a/ui-tui/src/app/slash/usagePanel.ts b/ui-tui/src/app/slash/usagePanel.ts
index 586aac0b8a7..23529c4ee67 100644
--- a/ui-tui/src/app/slash/usagePanel.ts
+++ b/ui-tui/src/app/slash/usagePanel.ts
@@ -70,7 +70,10 @@ export function planUsageLines(plan: BillingStateResponse['plan_usage'], nowMs:
const used = Math.max(0, Math.min(1, 1 - left))
// Same cells as `render_bar`: any use shows one, only a full allowance fills all ten.
const filled = Math.min(used < 1 ? 9 : 10, Math.max(used > 0 ? 1 : 0, Math.round(used * 10)))
- const bp = Math.round(used * 10_000)
+ // Same percent as the CLI / Desktop (`format_percent_used` / `formatPercentUsed`): floor, so a nearly
+ // full allowance reads 99% beside its 9 cells; 100% only once it is spent. Micro-rounded first:
+ // `1 - left` can land a hair under an exact basis point.
+ const bp = Math.floor(Math.round(used * 10_000 * 1e6) / 1e6)
const pct = bp <= 0 ? '0%' : bp < 100 ? '<1%' : `${Math.floor(bp / 100)}%`
const when = formatResetsIn(g.resets_at_ms, nowMs)
const reset = when === 'soon' ? 'resets soon' : when ? `resets in ${when}` : ''
diff --git a/ui-tui/src/i18n/en/libText.ts b/ui-tui/src/i18n/en/libText.ts
index 22c55b7c3fa..e72589f59e1 100644
--- a/ui-tui/src/i18n/en/libText.ts
+++ b/ui-tui/src/i18n/en/libText.ts
@@ -79,7 +79,15 @@ export const libTextEn = {
/** {0} = provider label */
providerDetail: (label: string) => `${label} reports your credits or billing are exhausted.`,
/** {0} = provider label */
- providerTitle: (label: string) => `Out of credits · ${label}`
+ providerTitle: (label: string) => `Out of credits · ${label}`,
+ // A usage-window plan's limit (usageLimitDialog).
+ limitTitle: 'Limit reached',
+ limitOpenTopup: 'Open /topup',
+ /** {0} = model label (with its note) */
+ limitSwitchTo: (label: string) => `Switch to ${label}`,
+ limitCreditsAdd: 'Or add credits with /topup.',
+ limitCreditsBoth: 'Or add credits and turn on Keep going in /topup.',
+ limitCreditsUse: 'Or turn on Keep going in /topup to use your credits.'
},
// lib/subagentTree.ts — the `d2 · 7 agents · 124 tools · 2m 14s` summary chip.
diff --git a/ui-tui/src/lib/billingDialog.ts b/ui-tui/src/lib/billingDialog.ts
index 89ec153ae5d..5844734ebf2 100644
--- a/ui-tui/src/lib/billingDialog.ts
+++ b/ui-tui/src/lib/billingDialog.ts
@@ -45,6 +45,13 @@ export interface UsageLimitDialog extends BillingDialogCopy {
switchValue: null | string
}
+// agent/plan_limits.py::credits_action → the dialog's credits line.
+const CREDITS_STEP: Record<string, () => string> = {
+ add_credits: () => t('libText.billingDialog.limitCreditsAdd'),
+ add_credits_and_keep_going: () => t('libText.billingDialog.limitCreditsBoth'),
+ use_credits: () => t('libText.billingDialog.limitCreditsUse')
+}
+
/**
* A usage-window plan's limit (error_surface.usage_limit, agent/plan_limits.py): the confirm button
* switches THIS session to the plan's recommended model and re-sends the message; the detail names the
@@ -55,30 +62,26 @@ export function usageLimitDialog(limit: UsageLimit): UsageLimitDialog {
const suggestion = limit.suggestions?.[0]
const sentence = (limit.message || '').trim()
- const credits =
- limit.credits?.action === 'use_credits'
- ? 'Or turn on Keep going in /topup to use your credits.'
- : limit.credits?.action === 'add_credits'
- ? 'Or add credits with /topup.'
- : ''
+ const action = limit.credits?.action
+ const credits = action && Object.hasOwn(CREDITS_STEP, action) ? CREDITS_STEP[action]!() : ''
if (!suggestion) {
return {
- cancelLabel: 'Dismiss',
- confirmLabel: 'Open /topup',
+ cancelLabel: t('libText.billingDialog.dismiss'),
+ confirmLabel: t('libText.billingDialog.limitOpenTopup'),
switchValue: null,
detail: [sentence, credits].filter(Boolean).join('\n'),
- title: 'Limit reached'
+ title: t('libText.billingDialog.limitTitle')
}
}
const note = suggestion.note ? ` (${suggestion.note})` : ''
return {
- cancelLabel: 'Dismiss',
- confirmLabel: `Switch to ${suggestion.label}${note}`,
+ cancelLabel: t('libText.billingDialog.dismiss'),
+ confirmLabel: t('libText.billingDialog.limitSwitchTo', `${suggestion.label}${note}`),
detail: [sentence, credits].filter(Boolean).join('\n'),
switchValue: `${suggestion.model} --provider ${suggestion.provider || 'nous'} --session`,
- title: 'Limit reached'
+ title: t('libText.billingDialog.limitTitle')
}
}
diff --git a/ui-tui/src/lib/usageLimit.test.ts b/ui-tui/src/lib/usageLimit.test.ts
index cc08ffc7555..4b13d01d251 100644
--- a/ui-tui/src/lib/usageLimit.test.ts
+++ b/ui-tui/src/lib/usageLimit.test.ts
@@ -132,6 +132,12 @@ describe('usageLimitDialog', () => {
expect(dialog.detail.endsWith('Or turn on Keep going in /topup to use your credits.')).toBe(true)
})
+ it('names both steps when Keep going is off and there is no balance', () => {
+ const dialog = usageLimitDialog({ ...limit, credits: { action: 'add_credits_and_keep_going' } } as never)
+
+ expect(dialog.detail.endsWith('Or add credits and turn on Keep going in /topup.')).toBe(true)
+ })
+
it('without a model to offer, the confirm opens /topup', () => {
const dialog = usageLimitDialog({ ...limit, suggestions: [] } as never)