Skip to content

The agent that grows with you

feat(desktop): a progress chip warns before a subscription hits its usage wall

Brooklyn Nicholson38d19b92e81e
diff --git a/agent/account_usage.py b/agent/account_usage.py
index 477c99d3a1f..ad6f49dbda6 100644
--- a/agent/account_usage.py
+++ b/agent/account_usage.py
@@ -677,13 +677,19 @@ def _call_plugin_usage_hook(profile, base_url: Optional[str], api_key: Optional[
def fetch_account_usage(
provider: Optional[str], *, base_url: Optional[str] = None, api_key: Optional[str] = None,
) -> Optional[AccountUsageSnapshot]:
+ from agent.account_usage_cache import remember_account_usage
+
fetcher = _USAGE_FETCHERS.get(str(provider or "").strip().lower())
try:
if fetcher:
- return fetcher(base_url, api_key)
- from providers import get_provider_profile
+ snapshot = fetcher(base_url, api_key)
+ else:
+ from providers import get_provider_profile
- profile = get_provider_profile(str(provider or "").strip().lower())
- return _call_plugin_usage_hook(profile, base_url, api_key) if profile else None
+ profile = get_provider_profile(str(provider or "").strip().lower())
+ snapshot = _call_plugin_usage_hook(profile, base_url, api_key) if profile else None
except Exception:
return None
+ # Every fetch (``/usage``, the per-turn ``session.usage``) keeps the picker's cache current.
+ remember_account_usage(provider, snapshot)
+ return snapshot
diff --git a/agent/account_usage_cache.py b/agent/account_usage_cache.py
new file mode 100644
index 00000000000..1b57aaa5711
--- /dev/null
+++ b/agent/account_usage_cache.py
@@ -0,0 +1,84 @@
+"""What ``model.options`` knows about subscription usage without waiting on the network.
+
+Usage windows come from a provider API (:func:`agent.account_usage.fetch_account_usage`), so a
+picker reads this cache and asks for a background refresh instead of fetching inline. Every fetch
+lands here, including the one ``session.usage`` runs after each turn, so a picker is at most one
+turn or one refresh interval behind. Keyed per profile home: one process may serve many profiles.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from contextvars import copy_context
+from typing import TYPE_CHECKING, Iterable, Optional
+
+if TYPE_CHECKING:
+ from agent.account_usage import AccountUsageSnapshot
+
+# A picker opened again within this long reuses what it has; usage windows move in minutes, not seconds.
+REFRESH_AFTER_S = 120.0
+
+_lock = threading.Lock()
+_snapshots: dict[tuple[str, str], "AccountUsageSnapshot"] = {}
+_last_try: dict[tuple[str, str], float] = {}
+_inflight: set[tuple[str, str]] = set()
+
+
+def _key(provider: str) -> tuple[str, str]:
+ from hermes_constants import hermes_home_key
+
+ return hermes_home_key(), str(provider or "").strip().lower()
+
+
+def has_account_usage(provider: str) -> bool:
+ """Whether *provider* can report usage windows at all (a built-in fetcher or a plugin hook)."""
+ from agent.account_usage import _USAGE_FETCHERS
+ from providers import get_provider_profile
+ from providers.base import ProviderProfile
+
+ slug = str(provider or "").strip().lower()
+ if slug in _USAGE_FETCHERS:
+ return True
+ profile = get_provider_profile(slug) if slug else None
+ return profile is not None and type(profile).fetch_account_usage is not ProviderProfile.fetch_account_usage
+
+
+def remember_account_usage(provider: Optional[str], snapshot: Optional["AccountUsageSnapshot"]) -> None:
+ if provider and snapshot is not None and snapshot.windows:
+ with _lock:
+ _snapshots[_key(provider)] = snapshot
+
+
+def cached_account_usage(provider: str) -> Optional["AccountUsageSnapshot"]:
+ with _lock:
+ return _snapshots.get(_key(provider))
+
+
+def refresh_account_usage_async(providers: Iterable[str]) -> list[threading.Thread]:
+ """Fetch usage in the background for each provider not tried within ``REFRESH_AFTER_S``. A failed
+ or empty fetch still counts as a try, so a provider with no usage API isn't re-asked every open."""
+ started: list[threading.Thread] = []
+ now = time.monotonic()
+ for provider in dict.fromkeys(providers):
+ key = _key(provider)
+ with _lock:
+ if key in _inflight or now - _last_try.get(key, float("-inf")) < REFRESH_AFTER_S:
+ continue
+ _inflight.add(key)
+ _last_try[key] = now
+ thread = threading.Thread(target=copy_context().run, args=(_refresh, provider, key),
+ name="hermes-account-usage-refresh", daemon=True)
+ thread.start()
+ started.append(thread)
+ return started
+
+
+def _refresh(provider: str, key: tuple[str, str]) -> None:
+ from agent.account_usage import fetch_account_usage
+
+ try:
+ fetch_account_usage(provider) # remembers its own result
+ finally:
+ with _lock:
+ _inflight.discard(key)
diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsx
index 780768eec33..64fc5d80f09 100644
--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx
@@ -14,6 +14,7 @@ import {
useState
} from 'react'
+import { ProviderStatusChip } from '@/components/provider-status-chip'
import { Badge } from '@/components/ui/badge'
import { Codicon } from '@/components/ui/codicon'
import { DisclosureCaret } from '@/components/ui/disclosure-caret'
@@ -792,7 +793,7 @@ export function ModelCatalogMenu({
open={!collapsed}
size="0.625rem"
/>
- <ProviderLimitBadge provider={group.provider} />
+ <ProviderStatusChip className="ml-auto mr-0.5" provider={group.provider} />
</DropdownMenuItem>
{!collapsed &&
group.families.map(family => (
@@ -1235,28 +1236,6 @@ function ModelResetBadge({ time }: { time: null | string }): null | ReactElement
) : null
}
-/** Trailing tag on a provider heading while its whole login is rate-limited.
- * Per-model cooldowns tag their own rows instead. */
-function ProviderLimitBadge({ provider }: { provider: ModelOptionProvider }): null | ReactElement {
- const { t } = useI18n()
- const copy = t.shell.modelMenu
- const resetMs = accountResetMs(provider)
-
- if (resetMs === null) {
- return null
- }
-
- const time = formatReset(resetMs)
-
- return (
- <Tip label={copy.limitedTip(provider.name, time)}>
- <Badge className="ml-auto mr-0.5 shrink-0 normal-case tracking-normal tabular-nums" size="xs" variant="warn">
- {time ? copy.limitedUntil(time) : copy.limited}
- </Badge>
- </Tip>
- )
-}
-
// A model still downloading: visible so the user knows it's coming (and
// where it will land), disabled so it can't be selected early, with the
// same byte progress the Local Models pane shows. Percent is selected HERE,
diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsx
index 40ff9452bfb..332601fb113 100644
--- a/apps/desktop/src/components/model-picker.tsx
+++ b/apps/desktop/src/components/model-picker.tsx
@@ -25,6 +25,7 @@ import type { HermesGateway } from '../hermes'
import { startManualOnboarding } from '../store/onboarding'
import { InlineNotice } from './notifications'
+import { ProviderStatusChip } from './provider-status-chip'
import { Badge } from './ui/badge'
import { Button } from './ui/button'
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from './ui/command'
@@ -612,9 +613,6 @@ function ProviderHeading({ provider }: { provider: ModelOptionProvider }) {
</span>
) : null
- const resetMs = accountResetMs(provider)
- const resetTime = resetMs === null ? null : formatReset(resetMs)
-
return (
<span className="flex min-w-0 items-center gap-2">
<span className="truncate">{provider.name}</span>
@@ -622,16 +620,7 @@ function ProviderHeading({ provider }: { provider: ModelOptionProvider }) {
{provider.slug} · {provider.total_models ?? provider.models?.length ?? 0}
</span>
{tierBadge}
- {resetMs !== null && (
- <Badge
- className="normal-case tracking-normal tabular-nums"
- size="xs"
- title={t.shell.modelMenu.limitedTip(provider.name, resetTime)}
- variant="warn"
- >
- {resetTime ? t.shell.modelMenu.limitedUntil(resetTime) : t.shell.modelMenu.limited}
- </Badge>
- )}
+ <ProviderStatusChip provider={provider} />
</span>
)
}
diff --git a/apps/desktop/src/components/provider-status-chip.tsx b/apps/desktop/src/components/provider-status-chip.tsx
new file mode 100644
index 00000000000..7494be035fa
--- /dev/null
+++ b/apps/desktop/src/components/provider-status-chip.tsx
@@ -0,0 +1,95 @@
+import type { ModelOptionProvider } from '@hermes/shared'
+import type { ReactElement, ReactNode } from 'react'
+
+import { useI18n } from '@/i18n'
+import {
+ accountResetMs,
+ formatReset,
+ USAGE_NOTICE_PERCENT,
+ USAGE_WARN_PERCENT,
+ usageWindows
+} from '@/lib/provider-limit'
+import { cn } from '@/lib/utils'
+
+import { Badge } from './ui/badge'
+import { Tip } from './ui/tooltip'
+
+interface ChipState {
+ label: string
+ remaining: number
+ tip: ReactNode
+ warn: boolean
+}
+
+function useChipState(provider: ModelOptionProvider): ChipState | null {
+ const { t } = useI18n()
+ const copy = t.shell.modelMenu
+ const resetMs = accountResetMs(provider)
+
+ if (resetMs !== null) {
+ const time = formatReset(resetMs)
+
+ return {
+ label: time ? copy.limitedUntil(time) : copy.limited,
+ remaining: 0,
+ tip: copy.limitedTip(provider.name, time),
+ warn: true
+ }
+ }
+
+ const windows = usageWindows(provider)
+ const tightest = windows?.[0]
+
+ if (!windows || !tightest || tightest.remaining > USAGE_NOTICE_PERCENT) {
+ return null
+ }
+
+ const reset = (ms: null | number) => (ms === null ? null : formatReset(ms))
+ const lines = [
+ copy.usageTip(provider.name),
+ ...windows.map(w => copy.usageWindow(w.label, w.remaining, reset(w.resetMs)))
+ ]
+
+ return {
+ label: copy.usageLeft(tightest.remaining, reset(tightest.resetMs)),
+ remaining: tightest.remaining,
+ tip: <span className="whitespace-pre-line">{lines.join('\n')}</span>,
+ warn: tightest.remaining <= USAGE_WARN_PERCENT
+ }
+}
+
+/** The one status slot on a provider heading, a fuel gauge: hidden while there's room, a progress
+ * chip once the tightest usage window is nearly spent (`8% left · resets 4:30 PM`, amber from
+ * 10%), and `Limited until 4:30 PM` once the login is out, so you see the wall coming. */
+export function ProviderStatusChip({
+ className,
+ provider
+}: {
+ className?: string
+ provider: ModelOptionProvider
+}): null | ReactElement {
+ const state = useChipState(provider)
+
+ if (!state) {
+ return null
+ }
+
+ // The bar along the bottom edge is what's LEFT, so it matches the label and empties toward the
+ // wall; a login that's already out says so in words and drops the bar.
+ return (
+ <Tip label={state.tip}>
+ <Badge
+ className={cn('relative shrink-0 overflow-hidden normal-case tracking-normal tabular-nums', className)}
+ size="xs"
+ variant={state.warn ? 'warn' : 'muted'}
+ >
+ {state.remaining > 0 && (
+ <span aria-hidden className="absolute inset-x-0 bottom-0 h-0.5 bg-current/20">
+ <span className="absolute inset-y-0 left-0 bg-current" style={{ width: `${state.remaining}%` }} />
+ </span>
+ )}
+ <span className="relative">{state.label}</span>
+ </Badge>
+ </Tip>
+ )
+}
diff --git a/apps/desktop/src/i18n/ar_chrome.ts b/apps/desktop/src/i18n/ar_chrome.ts
index 9a72f38cc77..e384c63ecb4 100644
--- a/apps/desktop/src/i18n/ar_chrome.ts
+++ b/apps/desktop/src/i18n/ar_chrome.ts
@@ -368,7 +368,12 @@ export const arChrome = {
? `بلغ ${provider} حد الاستخدام. يُعاد ضبطه في ${time}، ويمكنك اختيار نموذج لما بعد ذلك من الآن.`
: `بلغ ${provider} حد الاستخدام. يمكنك اختيار نموذج لما بعد إعادة الضبط من الآن.`,
modelResets: (time: string) => `يعود ${time}`,
- modelLimitedTip: (time: string) => `بلغ هذا النموذج حده الخاص ويعود في ${time}. النماذج الأخرى هنا ما زالت تعمل.`
+ modelLimitedTip: (time: string) => `بلغ هذا النموذج حده الخاص ويعود في ${time}. النماذج الأخرى هنا ما زالت تعمل.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `متبقٍ ${percent}% · يُعاد الضبط ${time}` : `متبقٍ ${percent}%`,
+ usageTip: (provider: string) => `${provider} يقترب من حد الاستخدام.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: متبقٍ ${percent}%، يُعاد الضبط ${time}` : `${label}: متبقٍ ${percent}%`
},
modelOptions: {
noOptions: 'لا توجد خيارات لهذا النموذج',
diff --git a/apps/desktop/src/i18n/de_model_menu.ts b/apps/desktop/src/i18n/de_model_menu.ts
index f0a4ff7b36a..665c80cb4fb 100644
--- a/apps/desktop/src/i18n/de_model_menu.ts
+++ b/apps/desktop/src/i18n/de_model_menu.ts
@@ -21,5 +21,10 @@ export const deModelMenu = {
: `${provider} hat sein Nutzungslimit erreicht. Du kannst schon jetzt ein Modell für die Zeit nach dem Zurücksetzen wählen.`,
modelResets: (time: string) => `wieder ab ${time}`,
modelLimitedTip: (time: string) =>
- `Dieses Modell hat sein eigenes Limit erreicht und ist ab ${time} wieder verfügbar. Andere Modelle hier funktionieren weiterhin.`
+ `Dieses Modell hat sein eigenes Limit erreicht und ist ab ${time} wieder verfügbar. Andere Modelle hier funktionieren weiterhin.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `${percent} % übrig · zurückgesetzt ${time}` : `${percent} % übrig`,
+ usageTip: (provider: string) => `${provider} ist fast am Nutzungslimit.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: ${percent} % übrig, zurückgesetzt ${time}` : `${label}: ${percent} % übrig`
}
diff --git a/apps/desktop/src/i18n/en_model_menu.ts b/apps/desktop/src/i18n/en_model_menu.ts
index bb124c2f4dd..9c266d25b2d 100644
--- a/apps/desktop/src/i18n/en_model_menu.ts
+++ b/apps/desktop/src/i18n/en_model_menu.ts
@@ -22,5 +22,11 @@ export const enModelMenu: Translations['shell']['modelMenu'] = {
? `${provider} hit its usage limit. It resets at ${time}; you can still pick a model for after.`
: `${provider} hit its usage limit. You can still pick a model for after it resets.`,
modelResets: (time: string) => `resets ${time}`,
- modelLimitedTip: (time: string) => `This model hit its own limit and resets at ${time}. Other models here still work.`
+ modelLimitedTip: (time: string) =>
+ `This model hit its own limit and resets at ${time}. Other models here still work.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `${percent}% left · resets ${time}` : `${percent}% left`,
+ usageTip: (provider: string) => `${provider} is close to its usage limit.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: ${percent}% left, resets ${time}` : `${label}: ${percent}% left`
}
diff --git a/apps/desktop/src/i18n/es_model_menu.ts b/apps/desktop/src/i18n/es_model_menu.ts
index 478d49c2f96..ec2f650b05a 100644
--- a/apps/desktop/src/i18n/es_model_menu.ts
+++ b/apps/desktop/src/i18n/es_model_menu.ts
@@ -21,5 +21,10 @@ export const esModelMenu = {
: `${provider} alcanzó su límite de uso. Ya puedes elegir un modelo para cuando se restablezca.`,
modelResets: (time: string) => `vuelve a las ${time}`,
modelLimitedTip: (time: string) =>
- `Este modelo alcanzó su propio límite y vuelve a las ${time}. Los demás modelos de aquí siguen funcionando.`
+ `Este modelo alcanzó su propio límite y vuelve a las ${time}. Los demás modelos de aquí siguen funcionando.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `Queda ${percent} % · se restablece ${time}` : `Queda ${percent} %`,
+ usageTip: (provider: string) => `${provider} está cerca de su límite de uso.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: queda ${percent} %, se restablece ${time}` : `${label}: queda ${percent} %`
}
diff --git a/apps/desktop/src/i18n/fr_model_menu.ts b/apps/desktop/src/i18n/fr_model_menu.ts
index edb40631699..4b6f6feee4f 100644
--- a/apps/desktop/src/i18n/fr_model_menu.ts
+++ b/apps/desktop/src/i18n/fr_model_menu.ts
@@ -21,5 +21,10 @@ export const frModelMenu = {
: `${provider} a atteint sa limite d’utilisation. Vous pouvez déjà choisir un modèle pour après sa réinitialisation.`,
modelResets: (time: string) => `de retour à ${time}`,
modelLimitedTip: (time: string) =>
- `Ce modèle a atteint sa propre limite et revient à ${time}. Les autres modèles ici fonctionnent toujours.`
+ `Ce modèle a atteint sa propre limite et revient à ${time}. Les autres modèles ici fonctionnent toujours.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `${percent} % restant · réinit. ${time}` : `${percent} % restant`,
+ usageTip: (provider: string) => `${provider} approche de sa limite d’utilisation.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label} : ${percent} % restant, réinitialisation ${time}` : `${label} : ${percent} % restant`
}
diff --git a/apps/desktop/src/i18n/ja_model_menu.ts b/apps/desktop/src/i18n/ja_model_menu.ts
index 20ecab5656b..0fc0f0e6d37 100644
--- a/apps/desktop/src/i18n/ja_model_menu.ts
+++ b/apps/desktop/src/i18n/ja_model_menu.ts
@@ -21,5 +21,10 @@ export const jaModelMenu = {
: `${provider} が利用上限に達しました。リセット後に使うモデルは今のうちに選べます。`,
modelResets: (time: string) => `${time} に再開`,
modelLimitedTip: (time: string) =>
- `このモデルは個別の上限に達しており、${time} に再開します。ここにある他のモデルは引き続き使えます。`
+ `このモデルは個別の上限に達しており、${time} に再開します。ここにある他のモデルは引き続き使えます。`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `残り ${percent}% · ${time} にリセット` : `残り ${percent}%`,
+ usageTip: (provider: string) => `${provider} は利用上限に近づいています。`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: 残り ${percent}%、${time} にリセット` : `${label}: 残り ${percent}%`
}
diff --git a/apps/desktop/src/i18n/ru_model_menu.ts b/apps/desktop/src/i18n/ru_model_menu.ts
index 1d4db36e92b..067312a78a1 100644
--- a/apps/desktop/src/i18n/ru_model_menu.ts
+++ b/apps/desktop/src/i18n/ru_model_menu.ts
@@ -21,5 +21,10 @@ export const ruModelMenu = {
: `${provider} исчерпал лимит использования. Модель на время после сброса можно выбрать уже сейчас.`,
modelResets: (time: string) => `снова в ${time}`,
modelLimitedTip: (time: string) =>
- `Эта модель исчерпала собственный лимит и вернётся в ${time}. Остальные модели здесь работают.`
+ `Эта модель исчерпала собственный лимит и вернётся в ${time}. Остальные модели здесь работают.`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `Осталось ${percent}% · сброс в ${time}` : `Осталось ${percent}%`,
+ usageTip: (provider: string) => `${provider} почти исчерпал лимит использования.`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}: осталось ${percent}%, сброс в ${time}` : `${label}: осталось ${percent}%`
}
diff --git a/apps/desktop/src/i18n/types_model_menu.ts b/apps/desktop/src/i18n/types_model_menu.ts
index c6aadbebabb..bac8de05bb8 100644
--- a/apps/desktop/src/i18n/types_model_menu.ts
+++ b/apps/desktop/src/i18n/types_model_menu.ts
@@ -17,4 +17,7 @@ export interface ModelMenuTranslations {
limitedTip: (provider: string, time: null | string) => string
modelResets: (time: string) => string
modelLimitedTip: (time: string) => string
+ usageLeft: (percent: number, time: null | string) => string
+ usageTip: (provider: string) => string
+ usageWindow: (label: string, percent: number, time: null | string) => string
}
diff --git a/apps/desktop/src/i18n/zh-hant_chrome.ts b/apps/desktop/src/i18n/zh-hant_chrome.ts
index 5f7665f00f5..090e4daeefb 100644
--- a/apps/desktop/src/i18n/zh-hant_chrome.ts
+++ b/apps/desktop/src/i18n/zh-hant_chrome.ts
@@ -268,7 +268,12 @@ export const zhHantChrome = {
? `${provider} 已達到用量上限,將於 ${time} 重設;現在就可以先選好之後要用的模型。`
: `${provider} 已達到用量上限;現在就可以先選好重設後要用的模型。`,
modelResets: (time: string) => `${time} 恢復`,
- modelLimitedTip: (time: string) => `此模型已達到自身上限,將於 ${time} 恢復。這裡的其他模型仍可使用。`
+ modelLimitedTip: (time: string) => `此模型已達到自身上限,將於 ${time} 恢復。這裡的其他模型仍可使用。`,
+ usageLeft: (percent: number, time: null | string) =>
+ time ? `剩餘 ${percent}% · ${time} 重設` : `剩餘 ${percent}%`,
+ usageTip: (provider: string) => `${provider} 即將達到用量上限。`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}:剩餘 ${percent}%,${time} 重設` : `${label}:剩餘 ${percent}%`
},
modelOptions: {
noOptions: '此模型沒有可用選項',
diff --git a/apps/desktop/src/i18n/zh_model_menu.ts b/apps/desktop/src/i18n/zh_model_menu.ts
index a58daae80b5..0254beadee5 100644
--- a/apps/desktop/src/i18n/zh_model_menu.ts
+++ b/apps/desktop/src/i18n/zh_model_menu.ts
@@ -20,5 +20,9 @@ export const zhModelMenu = {
? `${provider} 已达到用量上限,将于 ${time} 重置;现在就可以先选好之后要用的模型。`
: `${provider} 已达到用量上限;现在就可以先选好重置后要用的模型。`,
modelResets: (time: string) => `${time} 恢复`,
- modelLimitedTip: (time: string) => `该模型已达到自身上限,将于 ${time} 恢复。这里的其他模型仍可使用。`
+ modelLimitedTip: (time: string) => `该模型已达到自身上限,将于 ${time} 恢复。这里的其他模型仍可使用。`,
+ usageLeft: (percent: number, time: null | string) => (time ? `剩余 ${percent}% · ${time} 重置` : `剩余 ${percent}%`),
+ usageTip: (provider: string) => `${provider} 即将达到用量上限。`,
+ usageWindow: (label: string, percent: number, time: null | string) =>
+ time ? `${label}:剩余 ${percent}%,${time} 重置` : `${label}:剩余 ${percent}%`
}
diff --git a/apps/desktop/src/lib/provider-limit.test.ts b/apps/desktop/src/lib/provider-limit.test.ts
index dca145754ab..8e6ed6b7abb 100644
--- a/apps/desktop/src/lib/provider-limit.test.ts
+++ b/apps/desktop/src/lib/provider-limit.test.ts
@@ -1,7 +1,7 @@
import type { ModelOptionProvider } from '@hermes/shared'
import { describe, expect, it } from 'vitest'
-import { accountResetMs, modelResetMs } from './provider-limit'
+import { accountResetMs, modelResetMs, usageWindows } from './provider-limit'
const NOW = Date.parse('2026-10-05T15:00:00Z')
const iso = (minutes: number) => new Date(NOW + minutes * 60_000).toISOString()
@@ -30,4 +30,25 @@ describe('provider limits', () => {
expect(modelResetMs(limited, 'b', NOW)).toBeNull()
expect(modelResetMs(limited, 'a', NOW + 11 * 60_000)).toBeNull()
})
+
+ it('leads with the usage window closest to the wall and drops windows that rolled over', () => {
+ const windows = usageWindows(
+ {
+ ...provider(null),
+ usage: {
+ windows: [
+ { label: 'Weekly', used_percent: 39, resets_at: iso(60 * 24) },
+ { label: '5-hour', used_percent: 92.4, resets_at: iso(90) },
+ { label: 'Opus week', used_percent: 99, resets_at: iso(-5) }
+ ]
+ }
+ },
+ NOW
+ )
+
+ expect(windows?.map(w => [w.label, w.remaining])).toEqual([
+ ['5-hour', 8],
+ ['Weekly', 61]
+ ])
+ })
})
diff --git a/apps/desktop/src/lib/provider-limit.ts b/apps/desktop/src/lib/provider-limit.ts
index ad3d277d5c0..17d305d4629 100644
--- a/apps/desktop/src/lib/provider-limit.ts
+++ b/apps/desktop/src/lib/provider-limit.ts
@@ -43,6 +43,31 @@ export function modelResetMs(provider: ModelOptionProvider, model: string, nowMs
return limit?.scope === 'models' ? parseMs(limit.models?.[model]) : null
}
+/** Remaining share at or under which a picker shows the usage chip, and turns it amber. */
+export const USAGE_NOTICE_PERCENT = 20
+export const USAGE_WARN_PERCENT = 10
+
+export interface UsageWindowView {
+ label: string
+ remaining: number
+ resetMs: null | number
+}
+
+/** The provider's live usage windows (rolled-over ones dropped), tightest first, or null when it
+ * reports none. The first is the one you'll hit first, so it's the one the chip shows. */
+export function usageWindows(provider: ModelOptionProvider, nowMs = Date.now()): null | UsageWindowView[] {
+ const windows = (provider.usage?.windows ?? [])
+ .map(w => ({
+ label: w.label,
+ remaining: Math.max(0, Math.min(100, Math.round(100 - w.used_percent))),
+ resetMs: parseMs(w.resets_at)
+ }))
+ .filter(w => w.resetMs === null || w.resetMs > nowMs)
+ .sort((a, b) => a.remaining - b.remaining)
+
+ return windows.length > 0 ? windows : null
+}
+
/** `4:30 PM` today, `Oct 6, 9:00 AM` on another day. Infinity = unknown. */
export function formatReset(ms: number, nowMs = Date.now()): null | string {
if (!Number.isFinite(ms)) {
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index f36a7efe451..75bf5c449e0 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -782,6 +782,7 @@ export interface ModelOptionProvider {
free_tier_row?: boolean | null
unavailable_models?: string[] | null
limit?: ProviderLimit | null
+ usage?: ProviderUsage | null
[key: string]: unknown
}
/** ``hermes_cli/inventory.py::_apply_capabilities``. */
@@ -807,6 +808,16 @@ export interface ProviderLimit {
resets_at?: string | null
models?: Record<string, string> | null
}
+/** ``hermes_cli/inventory.py::_apply_usage`` — the provider's account usage windows, from cache. */
+export interface ProviderUsage {
+ windows: ProviderUsageWindow[]
+}
+/** One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour session or the weekly cap, with how much of it is spent and when it rolls over (ISO). */
+export interface ProviderUsageWindow {
+ label: string
+ used_percent: number
+ resets_at?: string | null
+}
export interface ImageGenerateParams {
prompt?: string | null
aspect_ratio?: string | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 0ee777d808d..767807dab45 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -19234,6 +19234,17 @@
}
],
"default": null
+ },
+ "usage": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProviderUsage"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
}
},
"required": [
@@ -26526,6 +26537,56 @@
"title": "ProviderLimit",
"type": "object"
},
+ "ProviderUsage": {
+ "additionalProperties": false,
+ "description": "``hermes_cli/inventory.py::_apply_usage`` \u2014 the provider's account usage windows, from cache.",
+ "properties": {
+ "windows": {
+ "items": {
+ "$ref": "#/components/schemas/ProviderUsageWindow"
+ },
+ "title": "Windows",
+ "type": "array"
+ }
+ },
+ "required": [
+ "windows"
+ ],
+ "title": "ProviderUsage",
+ "type": "object"
+ },
+ "ProviderUsageWindow": {
+ "additionalProperties": false,
+ "description": "One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour\nsession or the weekly cap, with how much of it is spent and when it rolls over (ISO).",
+ "properties": {
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "used_percent": {
+ "title": "Used Percent",
+ "type": "number"
+ },
+ "resets_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Resets At"
+ }
+ },
+ "required": [
+ "label",
+ "used_percent"
+ ],
+ "title": "ProviderUsageWindow",
+ "type": "object"
+ },
"QueuedPrompt": {
"additionalProperties": false,
"properties": {
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.py
index 2ad04d8c71c..ea13fbf4647 100644
--- a/hermes_cli/inventory.py
+++ b/hermes_cli/inventory.py
@@ -247,6 +247,7 @@ def build_model_options_payload(
non_blocking_catalogs=not refresh,
)
_apply_limits(payload["providers"])
+ _apply_usage(payload["providers"])
if not refresh:
_prewarm_pricing_async(payload["providers"], current_provider=ctx.current_provider,
current_base_url=ctx.current_base_url)
@@ -284,6 +285,29 @@ def _apply_limits(rows: list[dict]) -> None:
row["limit"] = {"scope": "models", "models": {m: iso(at) for m, at in state["models"].items()}}
+def _apply_usage(rows: list[dict]) -> None:
+ """Attach ``usage`` (subscription windows: % spent + reset) to signed-in rows that can report it,
+ from the cache only, and ask for a background refresh, so the picker never waits on a usage API
+ and a chip can warn before the wall instead of at it."""
+ from agent.account_usage_cache import cached_account_usage, has_account_usage, refresh_account_usage_async
+
+ wanted: list[str] = []
+ for row in rows:
+ slug = str(row.get("slug") or "")
+ if not slug or row.get("is_user_defined") or row.get("authenticated") is False or not has_account_usage(slug):
+ continue
+ wanted.append(slug)
+ snapshot = cached_account_usage(slug)
+ windows = [
+ {"label": w.label, "used_percent": float(w.used_percent),
+ "resets_at": w.reset_at.isoformat() if w.reset_at else None}
+ for w in (snapshot.windows if snapshot else ()) if w.used_percent is not None
+ ]
+ if windows:
+ row["usage"] = {"windows": windows}
+ refresh_account_usage_async(wanted)
+
+
# ─── Public: auxiliary-task pickers ─────────────────────────────────────
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index f74de9355b0..af69c423da0 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -3946,6 +3946,9 @@
"shell.modelMenu.refreshModels",
"shell.modelMenu.removeFavorite",
"shell.modelMenu.search",
+ "shell.modelMenu.usageLeft",
+ "shell.modelMenu.usageTip",
+ "shell.modelMenu.usageWindow",
"shell.modelOptions.effort",
"shell.modelOptions.fast",
"shell.modelOptions.fastFailed",
diff --git a/tests/hermes_cli/test_model_options_account_usage.py b/tests/hermes_cli/test_model_options_account_usage.py
new file mode 100644
index 00000000000..1f9750665b6
--- /dev/null
+++ b/tests/hermes_cli/test_model_options_account_usage.py
@@ -0,0 +1,51 @@
+"""The model picker shows subscription usage before the wall, without ever waiting on a usage API.
+
+Usage windows come from the provider's API, so ``model.options`` must read them from cache and
+refresh in the background: a slow or hung usage endpoint can't be allowed to stall the picker.
+"""
+
+import threading
+import time
+from datetime import datetime, timedelta, timezone
+
+from agent import account_usage
+from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
+from agent.account_usage_cache import cached_account_usage
+from hermes_cli.inventory import build_model_options_payload, load_picker_context
+
+
+def _snapshot(used: float) -> AccountUsageSnapshot:
+ reset = datetime.now(timezone.utc) + timedelta(hours=2)
+ return AccountUsageSnapshot(
+ provider="openrouter", source="test", fetched_at=datetime.now(timezone.utc),
+ windows=(AccountUsageWindow(label="Current session", used_percent=used, reset_at=reset),))
+
+
+def test_picker_reads_cached_usage_and_refreshes_without_waiting(monkeypatch):
+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key-123")
+ release, called = threading.Event(), threading.Event()
+ answers = iter([_snapshot(92.0)])
+
+ def slow_usage_api(_base_url, _api_key):
+ called.set()
+ release.wait(10)
+ return next(answers)
+
+ monkeypatch.setitem(account_usage._USAGE_FETCHERS, "openrouter", slow_usage_api)
+ ctx = load_picker_context()
+
+ started = time.monotonic()
+ first = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == "openrouter")
+ assert time.monotonic() - started < 5, "the picker waited on the usage API"
+ assert "usage" not in first, "nothing cached yet, so nothing to show"
+ assert called.wait(5), "opening the picker must start a background usage refresh"
+
+ release.set()
+ deadline = time.monotonic() + 5
+ while cached_account_usage("openrouter") is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+
+ row = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == "openrouter")
+ (window,) = row["usage"]["windows"]
+ assert window["label"] == "Current session" and window["used_percent"] == 92.0
+ assert datetime.fromisoformat(window["resets_at"]) > datetime.now(timezone.utc)
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index c3e4c37ab7d..72a58c26591 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -444,6 +444,21 @@ class ProviderLimit(Result):
models: dict[str, str] | None = None
+class ProviderUsageWindow(Result):
+ """One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour
+ session or the weekly cap, with how much of it is spent and when it rolls over (ISO)."""
+
+ label: str
+ used_percent: float
+ resets_at: str | None = None
+
+
+class ProviderUsage(Result):
+ """``hermes_cli/inventory.py::_apply_usage`` — the provider's account usage windows, from cache."""
+
+ windows: list[ProviderUsageWindow]
+
+
class ModelOptionProvider(OpenModel):
"""One ``hermes_cli/inventory.py::build_models_payload`` provider row (the union of every field
the builder sets; ``pricing_pending`` / ``free_tier_pending`` mark the cached-only path)."""
@@ -470,6 +485,7 @@ class ModelOptionProvider(OpenModel):
free_tier_row: bool | None = None
unavailable_models: list[str] | None = None
limit: ProviderLimit | None = None
+ usage: ProviderUsage | None = None
class ModelOptionsResult(Result):