The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): a rate-limited provider says why and until when in the model pickers
Brooklyn Nicholson8ab6d6404367
diff --git a/agent/credential_pool_model_cooldowns.py b/agent/credential_pool_model_cooldowns.pyindex d74d1ded1bf..cc02a882620 100644--- a/agent/credential_pool_model_cooldowns.py+++ b/agent/credential_pool_model_cooldowns.py@@ -9,7 +9,7 @@ auth, billing and payment failures keep benching the whole credential with.from __future__ import annotationsimport time-from typing import Any, Dict, Optional, TYPE_CHECKING+from typing import Any, Dict, Iterable, Optional, TYPE_CHECKINGif TYPE_CHECKING:from agent.credential_pool import PooledCredential@@ -102,3 +102,30 @@ class CredentialPoolModelCooldownMixin:cooldowns = merge_model_cooldowns(scoped.model_cooldowns, {model: until})self._adopt(scoped, persist=False, model_cooldowns=cooldowns)self._persist()++ def limit_state(self, models: Iterable[str]) -> Optional[Dict[str, Any]]:+ """What a picker should say about this pool's rate limits, or ``None`` when nothing is limited.++ ``{"scope": "account", "resets_at": epoch}`` when every live entry is benched credential-wide+ (the whole login is out; another model won't help), else ``{"scope": "models", "models":+ {model: epoch}}`` for the given *models* no usable entry can serve until a model cooldown+ ends. Entitlement benches (a year: the plan lacks the model) aren't windows that reset, so+ they're left out. Read-only: never clears or persists a cooldown.+ """+ from agent.credential_pool import STATUS_DEAD, _exhausted_until++ now = time.time()+ with self._lock:+ live = [entry for entry in self._entries if entry.last_status != STATUS_DEAD]+ sole = len(live) <= 1+ benched = {entry.id: until for entry in live+ if (until := _exhausted_until(entry, sole_credential=sole)) and until > now}+ if live and len(benched) == len(live):+ return {"scope": "account", "resets_at": min(benched.values())}+ usable = [entry for entry in live if entry.id not in benched]+ cooled: Dict[str, float] = {}+ for model in models:+ waits = [model_cooldown_until(entry, model) for entry in usable]+ if waits and all(waits) and min(waits) - now < MODEL_ENTITLEMENT_BENCH_SECONDS / 2:+ cooled[model] = min(waits)+ return {"scope": "models", "models": cooled} if cooled else Nonediff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsxindex de6309903b0..47378e148e8 100644--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx@@ -37,6 +37,7 @@ import { triggerHaptic } from '@/lib/haptics'import { isSubmitEnter } from '@/lib/ime'import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'+import { accountResetMs, formatReset, modelResetMs } from '@/lib/provider-limit'import { reasoningEffortLabel } from '@/lib/reasoning-effort'import { foldIncludes, normalize } from '@/lib/text'import { cn } from '@/lib/utils'@@ -791,6 +792,7 @@ export function ModelCatalogMenu({open={!collapsed}size="0.625rem"/>+ <ProviderLimitBadge provider={group.provider} /></DropdownMenuItem>{!collapsed &&group.families.map(family => (@@ -1008,6 +1010,12 @@ function ModelFamilyRow({const { name, tag } = modelDisplayParts(family.id)const decoration = useModelMenuRowDecoration({ label: name, model: family.id, provider: provider.slug })const caps = provider.capabilities?.[family.id]+ // A limited provider stays pickable: the account-wide case dims every row+ // (the group heading says why), the per-model case tags only the rows that+ // are cooling down, so a sibling model reads as the way to keep working.+ const accountLimited = accountResetMs(provider) !== null+ const modelReset = modelResetMs(provider, family.id) ?? (family.fastId ? modelResetMs(provider, family.fastId) : null)+ const modelResetLabel = modelReset === null ? null : formatReset(modelReset)// Live per-model $/Mtok pricing (Nous Portal and other providers that ship// it). A `-fast` sibling shares the base id's price: the collapsed row@@ -1118,7 +1126,12 @@ function ModelFamilyRow({<Codicon name={favorite ? 'star-full' : 'star-empty'} size="0.75rem" /></button></Tip>- <span className="flex min-w-0 flex-1 items-center gap-1.5">+ <span+ className={cn(+ 'flex min-w-0 flex-1 items-center gap-1.5',+ (accountLimited || modelResetLabel) && !isCurrent && 'text-(--ui-text-tertiary)'+ )}+ >{decoration.icon !== undefined ? <ModelMenuRowIcon icon={decoration.icon} /> : null}<span className="min-w-0 truncate"><HighlightMatches foldSeparators query={search} text={name} />@@ -1130,6 +1143,13 @@ function ModelFamilyRow({</Badge>) : null}</span>+ {modelResetLabel ? (+ <Tip label={copy.modelLimitedTip(modelResetLabel)}>+ <Badge className="shrink-0 tabular-nums" size="xs" variant="warn">+ {copy.modelResets(modelResetLabel)}+ </Badge>+ </Tip>+ ) : null}{loadProgress ? (<span className="flex shrink-0 items-center gap-1.5" title={copyPicker.loadingIntoMemory}><span className="h-1 w-14 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">@@ -1202,6 +1222,28 @@ function ModelChip({ children, setting = false }: { children: ReactNode; setting)}+/** 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.tsxindex 785787d60ba..40ff9452bfb 100644--- a/apps/desktop/src/components/model-picker.tsx+++ b/apps/desktop/src/components/model-picker.tsx@@ -7,6 +7,7 @@ import { type ReactElement, useMemo, useRef, useState } from 'react'import { useI18n } from '@/i18n'import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'import { currentPickerSelection } from '@/lib/model-status-label'+import { accountResetMs, formatReset, modelResetMs } from '@/lib/provider-limit'import { foldIncludes, normalize } from '@/lib/text'import { cn } from '@/lib/utils'import { $customModels, addCustomModel, customModelCandidate, withCustomModels } from '@/store/custom-models'@@ -24,6 +25,7 @@ import type { HermesGateway } from '../hermes'import { startManualOnboarding } from '../store/onboarding'import { InlineNotice } from './notifications'+import { Badge } from './ui/badge'import { Button } from './ui/button'import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from './ui/command'import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog'@@ -340,6 +342,7 @@ function ModelResults({}const unavailable = new Set(provider.unavailable_models ?? [])+ const accountLimited = accountResetMs(provider) !== nullreturn (<CommandGroup heading={<ProviderHeading provider={provider} />} key={provider.slug}>@@ -354,6 +357,9 @@ function ModelResults({const isCurrent = model === currentModel && catalogProviderMatches(provider, currentProvider)const price = provider.pricing?.[model]const locked = unavailable.has(model)+ const resetMs = modelResetMs(provider, model)+ const resetLabel = resetMs === null ? null : formatReset(resetMs)+ const dimmed = !locked && (accountLimited || resetLabel !== null)// Managed local model loading into memory right now: show the// real load percent inline (keyed by exact model id — remote// providers never match).@@ -376,7 +382,7 @@ function ModelResults({}}value={`${provider.slug}:${model}`}>- <span className="min-w-0 flex-1 truncate">+ <span className={cn('min-w-0 flex-1 truncate', dimmed && !isCurrent && 'text-muted-foreground')}><HighlightMatches foldSeparators query={search} text={model} /></span>{loadProgress && (@@ -393,6 +399,16 @@ function ModelResults({{locked && (<span className="shrink-0 text-[0.62rem] uppercase tracking-wide opacity-80">{copy.pro}</span>)}+ {resetLabel && (+ <Badge+ className="font-sans tabular-nums"+ size="xs"+ title={t.shell.modelMenu.modelLimitedTip(resetLabel)}+ variant="warn"+ >+ {t.shell.modelMenu.modelResets(resetLabel)}+ </Badge>+ )}<ModelPrice isCurrent={isCurrent} price={price} /></CommandItem>)@@ -596,6 +612,9 @@ 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>@@ -603,6 +622,16 @@ 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>+ )}</span>)}diff --git a/apps/desktop/src/i18n/ar_chrome.ts b/apps/desktop/src/i18n/ar_chrome.tsindex 9d4c8d0588c..9a72f38cc77 100644--- a/apps/desktop/src/i18n/ar_chrome.ts+++ b/apps/desktop/src/i18n/ar_chrome.ts@@ -360,7 +360,15 @@ export const arChrome = {free: 'مجاني',cacheRead: 'قراءة من الذاكرة المؤقتة',priceTitle: (input: string, output: string, cache: string) =>- `الإدخال ${input}/Mtok · الإخراج ${output}/Mtok` + (cache ? ` · قراءة من الذاكرة المؤقتة ${cache}/Mtok` : '')+ `الإدخال ${input}/Mtok · الإخراج ${output}/Mtok` + (cache ? ` · قراءة من الذاكرة المؤقتة ${cache}/Mtok` : ''),+ limited: 'محدود',+ limitedUntil: (time: string) => `محدود حتى ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `بلغ ${provider} حد الاستخدام. يُعاد ضبطه في ${time}، ويمكنك اختيار نموذج لما بعد ذلك من الآن.`+ : `بلغ ${provider} حد الاستخدام. يمكنك اختيار نموذج لما بعد إعادة الضبط من الآن.`,+ modelResets: (time: string) => `يعود ${time}`,+ modelLimitedTip: (time: string) => `بلغ هذا النموذج حده الخاص ويعود في ${time}. النماذج الأخرى هنا ما زالت تعمل.`},modelOptions: {noOptions: 'لا توجد خيارات لهذا النموذج',diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 5b9974ac767..4be48d9e487 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -5063,7 +5063,16 @@ export const deOverrides = {free: 'kostenlos',cacheRead: 'Cache-Lesung',priceTitle: (input: string, output: string, cache: string) =>- `Eingabe ${input}/Mtok · Ausgabe ${output}/Mtok` + (cache ? ` · Cache-Lesung ${cache}/Mtok` : '')+ `Eingabe ${input}/Mtok · Ausgabe ${output}/Mtok` + (cache ? ` · Cache-Lesung ${cache}/Mtok` : ''),+ limited: 'Limitiert',+ limitedUntil: (time: string) => `Limitiert bis ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} hat sein Nutzungslimit erreicht. Es wird um ${time} zurückgesetzt; du kannst schon jetzt ein Modell für danach wählen.`+ : `${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.`},modelOptions: {noOptions: 'Keine Optionen für dieses Modell',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0ea0dd309f4..f5cd7a262db 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4625,7 +4625,16 @@ export const en: Translations = {free: 'free',cacheRead: 'cached read',priceTitle: (input: string, output: string, cache: string) =>- `Input ${input}/Mtok · Output ${output}/Mtok` + (cache ? ` · Cached read ${cache}/Mtok` : '')+ `Input ${input}/Mtok · Output ${output}/Mtok` + (cache ? ` · Cached read ${cache}/Mtok` : ''),+ limited: 'Limited',+ limitedUntil: (time: string) => `Limited until ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${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.`},modelOptions: {noOptions: 'No options for this model',diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 52820897243..dffb0a670de 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -5055,7 +5055,16 @@ export const esOverrides = {free: 'gratis',cacheRead: 'lectura en caché',priceTitle: (input: string, output: string, cache: string) =>- `Entrada ${input}/Mtok · Salida ${output}/Mtok` + (cache ? ` · Lectura en caché ${cache}/Mtok` : '')+ `Entrada ${input}/Mtok · Salida ${output}/Mtok` + (cache ? ` · Lectura en caché ${cache}/Mtok` : ''),+ limited: 'Limitado',+ limitedUntil: (time: string) => `Limitado hasta las ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} alcanzó su límite de uso. Se restablece a las ${time}; ya puedes elegir un modelo para después.`+ : `${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.`},modelOptions: {noOptions: 'No hay opciones para este modelo',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex f0e40f7d7d1..ab88cdb7e13 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -5077,7 +5077,16 @@ export const frOverrides = {free: 'gratuit',cacheRead: 'lecture en cache',priceTitle: (input: string, output: string, cache: string) =>- `Entrée ${input}/Mtok · Sortie ${output}/Mtok` + (cache ? ` · Lecture en cache ${cache}/Mtok` : '')+ `Entrée ${input}/Mtok · Sortie ${output}/Mtok` + (cache ? ` · Lecture en cache ${cache}/Mtok` : ''),+ limited: 'Limité',+ limitedUntil: (time: string) => `Limité jusqu’à ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} a atteint sa limite d’utilisation. Elle se réinitialise à ${time} ; vous pouvez déjà choisir un modèle pour après.`+ : `${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.`},modelOptions: {noOptions: 'Aucune option pour ce modèle',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 3790eb502c9..2a0350928f9 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3364,7 +3364,16 @@ export const ja = defineLocale({free: '無料',cacheRead: 'キャッシュ読み取り',priceTitle: (input: string, output: string, cache: string) =>- `入力 ${input}/Mtok · 出力 ${output}/Mtok` + (cache ? ` · キャッシュ読み取り ${cache}/Mtok` : '')+ `入力 ${input}/Mtok · 出力 ${output}/Mtok` + (cache ? ` · キャッシュ読み取り ${cache}/Mtok` : ''),+ limited: '制限中',+ limitedUntil: (time: string) => `${time} まで制限中`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} が利用上限に達しました。${time} にリセットされます。リセット後に使うモデルは今のうちに選べます。`+ : `${provider} が利用上限に達しました。リセット後に使うモデルは今のうちに選べます。`,+ modelResets: (time: string) => `${time} に再開`,+ modelLimitedTip: (time: string) =>+ `このモデルは個別の上限に達しており、${time} に再開します。ここにある他のモデルは引き続き使えます。`},modelOptions: {noOptions: 'このモデルにはオプションがありません',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 311ab4741c0..1385a085b8c 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -3585,7 +3585,16 @@ export const ru = defineLocale({free: 'бесплатно',cacheRead: 'чтение из кэша',priceTitle: (input: string, output: string, cache: string) =>- `Вход ${input}/Mtok · Выход ${output}/Mtok` + (cache ? ` · Чтение из кэша ${cache}/Mtok` : '')+ `Вход ${input}/Mtok · Выход ${output}/Mtok` + (cache ? ` · Чтение из кэша ${cache}/Mtok` : ''),+ limited: 'Лимит',+ limitedUntil: (time: string) => `Лимит до ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} исчерпал лимит использования. Он сбросится в ${time}; модель на потом можно выбрать уже сейчас.`+ : `${provider} исчерпал лимит использования. Модель на время после сброса можно выбрать уже сейчас.`,+ modelResets: (time: string) => `снова в ${time}`,+ modelLimitedTip: (time: string) =>+ `Эта модель исчерпала собственный лимит и вернётся в ${time}. Остальные модели здесь работают.`},modelOptions: {noOptions: 'Для этой модели нет опций',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 3851fce23e3..2151282440a 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3873,6 +3873,11 @@ export interface Translations {free: stringcacheRead: stringpriceTitle: (input: string, output: string, cache: string) => string+ limited: string+ limitedUntil: (time: string) => string+ limitedTip: (provider: string, time: null | string) => string+ modelResets: (time: string) => string+ modelLimitedTip: (time: string) => string}modelOptions: {noOptions: stringdiff --git a/apps/desktop/src/i18n/zh-hant_chrome.ts b/apps/desktop/src/i18n/zh-hant_chrome.tsindex 7beb55f51ee..5f7665f00f5 100644--- a/apps/desktop/src/i18n/zh-hant_chrome.ts+++ b/apps/desktop/src/i18n/zh-hant_chrome.ts@@ -260,7 +260,15 @@ export const zhHantChrome = {free: '免費',cacheRead: '快取讀取',priceTitle: (input: string, output: string, cache: string) =>- `輸入 ${input}/Mtok · 輸出 ${output}/Mtok` + (cache ? ` · 快取讀取 ${cache}/Mtok` : '')+ `輸入 ${input}/Mtok · 輸出 ${output}/Mtok` + (cache ? ` · 快取讀取 ${cache}/Mtok` : ''),+ limited: '已限額',+ limitedUntil: (time: string) => `限額至 ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} 已達到用量上限,將於 ${time} 重設;現在就可以先選好之後要用的模型。`+ : `${provider} 已達到用量上限;現在就可以先選好重設後要用的模型。`,+ modelResets: (time: string) => `${time} 恢復`,+ modelLimitedTip: (time: string) => `此模型已達到自身上限,將於 ${time} 恢復。這裡的其他模型仍可使用。`},modelOptions: {noOptions: '此模型沒有可用選項',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex e0e708de334..b6c30eb9680 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4319,7 +4319,15 @@ export const zh = defineLocale({free: '免费',cacheRead: '缓存读取',priceTitle: (input: string, output: string, cache: string) =>- `输入 ${input}/Mtok · 输出 ${output}/Mtok` + (cache ? ` · 缓存读取 ${cache}/Mtok` : '')+ `输入 ${input}/Mtok · 输出 ${output}/Mtok` + (cache ? ` · 缓存读取 ${cache}/Mtok` : ''),+ limited: '已限额',+ limitedUntil: (time: string) => `限额至 ${time}`,+ limitedTip: (provider: string, time: null | string) =>+ time+ ? `${provider} 已达到用量上限,将于 ${time} 重置;现在就可以先选好之后要用的模型。`+ : `${provider} 已达到用量上限;现在就可以先选好重置后要用的模型。`,+ modelResets: (time: string) => `${time} 恢复`,+ modelLimitedTip: (time: string) => `该模型已达到自身上限,将于 ${time} 恢复。这里的其他模型仍可使用。`},modelOptions: {noOptions: '此模型没有可用选项',diff --git a/apps/desktop/src/lib/provider-limit.test.ts b/apps/desktop/src/lib/provider-limit.test.tsnew file mode 100644index 00000000000..dca145754ab--- /dev/null+++ b/apps/desktop/src/lib/provider-limit.test.ts@@ -0,0 +1,33 @@+import type { ModelOptionProvider } from '@hermes/shared'+import { describe, expect, it } from 'vitest'++import { accountResetMs, modelResetMs } from './provider-limit'++const NOW = Date.parse('2026-10-05T15:00:00Z')+const iso = (minutes: number) => new Date(NOW + minutes * 60_000).toISOString()++const provider = (limit: ModelOptionProvider['limit']): ModelOptionProvider => ({+ slug: 'anthropic',+ name: 'Anthropic',+ models: ['a', 'b'],+ limit+})++describe('provider limits', () => {+ it('reports an account-wide limit until its reset, then clears without a refetch', () => {+ const limited = provider({ scope: 'account', resets_at: iso(30) })++ expect(accountResetMs(limited, NOW)).toBe(NOW + 30 * 60_000)+ expect(modelResetMs(limited, 'a', NOW)).toBeNull()+ expect(accountResetMs(limited, NOW + 31 * 60_000)).toBeNull()+ })++ it('tags only the cooled-down models, each until its own reset', () => {+ const limited = provider({ scope: 'models', models: { a: iso(10) } })++ expect(accountResetMs(limited, NOW)).toBeNull()+ expect(modelResetMs(limited, 'a', NOW)).toBe(NOW + 10 * 60_000)+ expect(modelResetMs(limited, 'b', NOW)).toBeNull()+ expect(modelResetMs(limited, 'a', NOW + 11 * 60_000)).toBeNull()+ })+})diff --git a/apps/desktop/src/lib/provider-limit.ts b/apps/desktop/src/lib/provider-limit.tsnew file mode 100644index 00000000000..ad3d277d5c0--- /dev/null+++ b/apps/desktop/src/lib/provider-limit.ts@@ -0,0 +1,55 @@+import type { ModelOptionProvider, ProviderLimit } from '@hermes/shared'++import { DAY, fmtClock, fmtDayTime, startOfLocalDay } from '@/lib/time'++function parseMs(value: null | string | undefined): null | number {+ const ms = value ? Date.parse(value) : NaN++ return Number.isFinite(ms) ? ms : null+}++/** The provider's rate limit (`account`: the whole login is out, another model+ * won't help; `models`: only those models are), or null when it has none or+ * every reset has already passed, so a stale catalog clears itself. */+export function providerLimit(provider: ModelOptionProvider, nowMs = Date.now()): null | ProviderLimit {+ const limit = provider.limit++ if (!limit) {+ return null+ }++ if (limit.scope === 'account') {+ const resetMs = parseMs(limit.resets_at)++ return resetMs === null || resetMs > nowMs ? limit : null+ }++ const live = Object.entries(limit.models ?? {}).filter(([, at]) => (parseMs(at) ?? 0) > nowMs)++ return live.length > 0 ? { ...limit, models: Object.fromEntries(live) } : null+}++/** Account-wide reset time (ms) while the whole provider is limited. */+export function accountResetMs(provider: ModelOptionProvider, nowMs = Date.now()): null | number {+ const limit = providerLimit(provider, nowMs)++ return limit?.scope === 'account' ? (parseMs(limit.resets_at) ?? Number.POSITIVE_INFINITY) : null+}++/** This model's own reset time (ms) when only it is cooling down. */+export function modelResetMs(provider: ModelOptionProvider, model: string, nowMs = Date.now()): null | number {+ const limit = providerLimit(provider, nowMs)++ return limit?.scope === 'models' ? parseMs(limit.models?.[model]) : 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)) {+ return null+ }++ return startOfLocalDay(ms) === startOfLocalDay(nowMs) || ms - nowMs < DAY / 4+ ? fmtClock.format(ms)+ : fmtDayTime.format(ms)+}diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 3f68c2dfc12..f36a7efe451 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -781,6 +781,7 @@ export interface ModelOptionProvider {free_tier_pending?: boolean | nullfree_tier_row?: boolean | nullunavailable_models?: string[] | null+ limit?: ProviderLimit | null[key: string]: unknown}/** ``hermes_cli/inventory.py::_apply_capabilities``. */@@ -800,6 +801,12 @@ export interface ModelPricing {was_input?: string | nullwas_output?: string | null}+/** ``hermes_cli/inventory.py::_apply_limits`` — ``account``: the whole login is rate-limited until ``resets_at`` (ISO, absent when unknown); ``models``: only these models are, each until its time. */+export interface ProviderLimit {+ scope: 'account' | 'models'+ resets_at?: string | null+ models?: Record<string, string> | null+}export interface ImageGenerateParams {prompt?: string | nullaspect_ratio?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 8cf27e31454..0ee777d808d 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -19223,6 +19223,17 @@],"default": null,"title": "Unavailable Models"+ },+ "limit": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ProviderLimit"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"required": [@@ -26469,6 +26480,52 @@"title": "PromptSubmitStatus","type": "string"},+ "ProviderLimit": {+ "additionalProperties": false,+ "description": "``hermes_cli/inventory.py::_apply_limits`` \u2014 ``account``: the whole login is rate-limited until\n``resets_at`` (ISO, absent when unknown); ``models``: only these models are, each until its time.",+ "properties": {+ "scope": {+ "enum": [+ "account",+ "models"+ ],+ "title": "Scope",+ "type": "string"+ },+ "resets_at": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Resets At"+ },+ "models": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Models"+ }+ },+ "required": [+ "scope"+ ],+ "title": "ProviderLimit",+ "type": "object"+ },"QueuedPrompt": {"additionalProperties": false,"properties": {diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex cc41e49f342..1e6de63db05 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -246,12 +246,42 @@ def build_model_options_payload(refresh=refresh, probe_custom_providers=refresh, probe_current_custom_provider=not refresh,non_blocking_catalogs=not refresh,)+ _apply_limits(payload["providers"])if not refresh:_prewarm_pricing_async(payload["providers"], current_provider=ctx.current_provider,current_base_url=ctx.current_base_url)return payload+def _apply_limits(rows: list[dict]) -> None:+ """Attach ``limit`` to rows whose credential pool is rate-limited, so a picker can say why and until+ when instead of the row just looking broken. Only providers with a persisted pool are read (no+ seeding), and a pool that fails to load says nothing rather than failing the whole catalog."""+ from datetime import datetime, timezone++ from agent.credential_pool import load_pool+ from hermes_cli.auth import read_credential_pool++ def iso(epoch: float) -> str:+ return datetime.fromtimestamp(epoch, timezone.utc).isoformat()++ pooled = {slug for slug, entries in read_credential_pool().items() if entries}+ for row in rows:+ slug = str(row.get("slug") or "")+ if slug not in pooled or row.get("is_user_defined"):+ continue+ try:+ state = load_pool(slug).limit_state(row.get("models") or [])+ except Exception:+ continue+ if state is None:+ continue+ if state["scope"] == "account":+ row["limit"] = {"scope": "account", "resets_at": iso(state["resets_at"])}+ else:+ row["limit"] = {"scope": "models", "models": {m: iso(at) for m, at in state["models"].items()}}++# ─── Public: auxiliary-task pickers ─────────────────────────────────────diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 4b5afdec013..f74de9355b0 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -3936,6 +3936,11 @@"shell.modelMenu.favorites","shell.modelMenu.followDefault","shell.modelMenu.free",+ "shell.modelMenu.limited",+ "shell.modelMenu.limitedTip",+ "shell.modelMenu.limitedUntil",+ "shell.modelMenu.modelLimitedTip",+ "shell.modelMenu.modelResets","shell.modelMenu.noModels","shell.modelMenu.priceTitle","shell.modelMenu.refreshModels",diff --git a/tests/hermes_cli/test_model_options_rate_limited_pool.py b/tests/hermes_cli/test_model_options_rate_limited_pool.pyindex ac48988e27e..b985bb4f5fc 100644--- a/tests/hermes_cli/test_model_options_rate_limited_pool.py+++ b/tests/hermes_cli/test_model_options_rate_limited_pool.py@@ -9,13 +9,14 @@ real payload builder against a real ``auth.json`` pool in a temp home.import jsonimport time+from datetime import datetimeimport pytestfrom hermes_cli.inventory import build_model_options_payload, load_picker_context-def _pool_entry(provider: str, cooldown: str) -> dict:+def _pool_entry(provider: str, cooldown: str, model: str = "some-model") -> dict:now = time.time()oauth = provider == "anthropic"entry = {@@ -29,8 +30,8 @@ def _pool_entry(provider: str, cooldown: str) -> dict:if cooldown == "exhausted":entry.update(last_status="exhausted", last_status_at=now, last_error_code=429,last_error_reset_at=now + 3 * 3600)- else:- entry["model_cooldowns"] = {"some-model": now + 3 * 3600}+ elif cooldown == "model_cooldown":+ entry["model_cooldowns"] = {model: now + 3 * 3600}return entry@@ -43,10 +44,12 @@ def pooled_home(tmp_path, monkeypatch):(home / "config.yaml").write_text("model:\n provider: nous\n default: test-model\nauth:\n adopt_external_logins: false\n")- def write(provider: str, cooldown: str) -> None:+ def write(provider: str, cooldown: str, model: str = "some-model") -> dict:+ entry = _pool_entry(provider, cooldown, model)(home / "auth.json").write_text(json.dumps({"version": 1, "providers": {},- "credential_pool": {provider: [_pool_entry(provider, cooldown)]}}))+ "credential_pool": {provider: [entry]}}))+ return entryreturn write@@ -65,6 +68,29 @@ def test_rate_limited_pool_keeps_its_provider_row(pooled_home, provider, cooldowassert row["models"], "the kept row must still offer the provider's models"[email protected]("provider", ["anthropic", "gemini"])+def test_kept_row_says_which_limit_and_when_it_resets(pooled_home, provider):+ """The row names the limit's scope and the pool's own reset time, and a healthy pool says nothing."""+ ctx = load_picker_context()+ pooled_home(provider, "ok")+ healthy = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == provider)+ assert "limit" not in healthy+ model, sibling = healthy["models"][0], healthy["models"][1]++ entry = pooled_home(provider, "exhausted")+ row = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == provider)+ assert row["limit"]["scope"] == "account"+ assert datetime.fromisoformat(row["limit"]["resets_at"]).timestamp() == pytest.approx(+ entry["last_error_reset_at"], abs=1)++ entry = pooled_home(provider, "model_cooldown", model)+ row = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == provider)+ assert row["limit"]["scope"] == "models"+ assert set(row["limit"]["models"]) == {model}, f"{sibling} still works and must not be tagged"+ assert datetime.fromisoformat(row["limit"]["models"][model]).timestamp() == pytest.approx(+ entry["model_cooldowns"][model], abs=1)++def test_picker_visibility_keeps_the_full_custom_probe_budget(monkeypatch):"""Keeping cooldown rows visible must not shorten the current custom endpoint's live probe."""monkeypatch.setattr("hermes_cli.models.cached_provider_model_ids", lambda *_a, **_kw: [])diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.pyindex 6a5a570098a..c3e4c37ab7d 100644--- a/tui_gateway/contracts/config_free_tier_control.py+++ b/tui_gateway/contracts/config_free_tier_control.py@@ -435,6 +435,15 @@ class ModelCapabilities(Result):can_disable_reasoning: bool | None = None+class ProviderLimit(Result):+ """``hermes_cli/inventory.py::_apply_limits`` — ``account``: the whole login is rate-limited until+ ``resets_at`` (ISO, absent when unknown); ``models``: only these models are, each until its time."""++ scope: Literal["account", "models"]+ resets_at: str | None = None+ models: dict[str, str] | None = None++class ModelOptionProvider(OpenModel):"""One ``hermes_cli/inventory.py::build_models_payload`` provider row (the union of every fieldthe builder sets; ``pricing_pending`` / ``free_tier_pending`` mark the cached-only path)."""@@ -460,6 +469,7 @@ class ModelOptionProvider(OpenModel):free_tier_pending: bool | None = Nonefree_tier_row: bool | None = Noneunavailable_models: list[str] | None = None+ limit: ProviderLimit | None = Noneclass ModelOptionsResult(Result):