diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 1e4ca5977..445bca9f7 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -33,6 +33,15 @@ export const ModelListRow = memo(function ModelListRow(props: { useProviderScopedLabel?: boolean; useTriggerLabel?: boolean; jumpLabel?: string | null; + /** + * The model's own usage limit, when its account reports one (modelUsageLimitLabel): + * in the row's grey slot, amber near it, red with a grey name once reached. + */ + usageLimit?: { + readonly text: string; + readonly tone: "normal" | "warning" | "reached"; + readonly title: string; + } | null; /** What picking it does when that is not "use this model" (ModelPickerContent rowAction). */ action?: { readonly kind: "add" | "switch"; readonly label: string } | null; /** Set while no model can be picked; the list says why on hover. */ @@ -74,7 +83,14 @@ export const ModelListRow = memo(function ModelListRow(props: {
@@ -100,6 +116,22 @@ export const ModelListRow = memo(function ModelListRow(props: { {props.action.label} ) : null} + {props.usageLimit ? ( + + {props.usageLimit.text} + + ) : null} {props.model.metaLabel ? ( + new Map( + instanceEntries.map((entry) => [ + entry.instanceId, + deriveProviderAccountUsagePresentationForProvider(entry.snapshot), + ]), + ), + [instanceEntries], + ); + const providerTabs = useMemo((): ModelPickerTab[] => { const tabs: ModelPickerTab[] = []; const instanceCountByDriver = new Map(); @@ -430,10 +448,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }); // With more than one account for an agent, each tab says how much room // it has left, the same figure its Settings row shows. + const accountUsage = usageByInstance.get(entry.instanceId) ?? null; const usagePresentation = - (instanceCountByDriver.get(entry.driverKind) ?? 0) > 1 - ? deriveProviderAccountUsagePresentationForProvider(entry.snapshot) - : null; + (instanceCountByDriver.get(entry.driverKind) ?? 0) > 1 ? accountUsage : null; const usage = usagePresentation ? headlineUsageMeter(usagePresentation) : null; tabs.push({ kind: "instance", @@ -452,12 +469,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } : {}), ...(usagePresentation?.notice && !usage ? { usageUnavailable: true } : {}), + ...(isProviderUsageNearLimit(accountUsage, { modelLimits: false }) + ? { nearLimit: true } + : {}), modelCount: sortedModels.length, models: sortedModels, }); } return tabs; - }, [favoritesSet, instanceEntries, isLocked, modelsByInstance]); + }, [favoritesSet, instanceEntries, isLocked, modelsByInstance, usageByInstance]); const showTabList = !lockedToSingleInstance && (!isLocked || providerTabs.length > 1); const tabs = useMemo((): ModelPickerTab[] => { @@ -574,7 +594,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const tabModelCountLabel = (count: number) => `${count} ${count === 1 ? "model" : "models"}`; - const renderTabIcon = (tab: ModelPickerTab) => { + const renderTabIcon = (tab: ModelPickerTab, iconOnly: boolean) => { if (tab.kind === "favorites") { return ; } @@ -592,6 +612,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { style={{ backgroundColor: tab.accentColor }} /> ) : null} + {/* Near the plan's limit, where no figure says so already. */} + {tab.nearLimit && (iconOnly || !tab.usage) ? ( + + ) : null} ); }; @@ -758,6 +786,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }; }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]); + /** The model's own limit, as its row says it, when its account reports one. */ + const ownLimitLabel = (model: ModelPickerItem) => { + const limit = modelOwnUsageLimit(usageByInstance.get(model.instanceId), model.name); + return limit ? modelUsageLimitLabel(limit) : null; + }; + const renderModelRow = (model: ModelPickerItem, modelIndex: number) => { const modelKey = `${model.instanceId}:${model.slug}`; return ( @@ -775,6 +809,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { useProviderScopedLabel useTriggerLabel={lockedToSingleInstance} jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null} + usageLimit={ownLimitLabel(model)} action={props.rowAction ?? null} disabledReason={props.rowsDisabledReason ?? null} onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)} @@ -864,7 +899,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ? [`${tab.usage.label} ${tab.usage.usedPercent}% used`] : tab.usageUnavailable ? ["Usage unavailable"] - : []), + : tab.nearLimit + ? ["Near its plan's limit"] + : []), ].join(" · ")} className={cn( "flex max-w-40 shrink-0 cursor-pointer items-center gap-1.5 rounded-md text-left text-xs font-medium transition-colors", @@ -882,7 +919,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }} > - {renderTabIcon(tab)} + {renderTabIcon(tab, iconOnly)} {iconOnly ? null : {tab.label}} {iconOnly || !tab.usage ? null : ( diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index ebe6ed7b8..e953b3c0a 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -1551,3 +1551,71 @@ describe("ProviderModelPicker", () => { } }); }); + +describe("plan limits", () => { + it("dots a provider near its plan's limit, and says a model's own limit on its row", async () => { + const now = Date.now(); + const resetsAt = now + 3 * 86_400_000 + 16 * 3_600_000 + 30 * 60_000; + const effort = selectDescriptor("effort", "Reasoning", [ + { id: "high", label: "high", isDefault: true }, + ]); + const claudeModel = (slug: string, name: string) => ({ + slug, + name, + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [effort] }), + }); + const claude: ServerProvider = { + ...TEST_PROVIDERS[1]!, + models: [ + claudeModel("claude-opus-5-5", "Claude Opus 5.5"), + claudeModel("claude-fable-5-2", "Claude Fable 5.2"), + ], + accountUsage: { + source: "claude-oauth-usage", + checkedAt: new Date(now).toISOString(), + primaryLimitId: "claude", + limits: [ + { + limitId: "claude", + secondary: { + usedPercent: 84, + remainingPercent: 16, + resetsAt, + windowDurationMins: 10_080, + }, + scoped: [ + { + scopeLabel: "Fable", + usedPercent: 100, + remainingPercent: 0, + resetsAt, + windowDurationMins: 10_080, + }, + ], + }, + ], + }, + }; + const mounted = await mountPicker({ + activeInstanceId: CLAUDE_INSTANCE_ID, + model: "claude-opus-5-5", + lockedProvider: null, + providers: [claude, TEST_PROVIDERS[0]!], + }); + try { + await openModelPicker(); + const tab = (id: string) => + document.querySelector(`[data-model-picker-tab="${id}"]`)!; + expect(tab("claudeAgent").querySelector("[data-model-picker-near-limit]")).not.toBeNull(); + expect(tab("codex").querySelector("[data-model-picker-near-limit]")).toBeNull(); + const limits = Array.from( + getModelPickerListElement().querySelectorAll("[data-model-usage-limit]"), + ).map((element) => [element.dataset.modelUsageLimit, element.textContent]); + // Only Fable has a limit of its own; Opus's row stays as it was. + expect(limits).toEqual([["reached", "Limit · resets in 3d 16h"]]); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/lib/providerUsage.test.ts b/apps/web/src/lib/providerUsage.test.ts index 7d889d35a..48c5c2850 100644 --- a/apps/web/src/lib/providerUsage.test.ts +++ b/apps/web/src/lib/providerUsage.test.ts @@ -12,6 +12,8 @@ import { formatProviderTokenCount, headlineUsageMeter, isProviderUsageNearLimit, + modelOwnUsageLimit, + modelUsageLimitLabel, providerRateLimitResetCreditsExpirationUrgency, providerRateLimitResetCreditExpirationUrgency, providerUsageNearLimitColor, @@ -487,6 +489,7 @@ describe("deriveProviderAccountUsagePresentation", () => { remainingPercent: 22, reachedLimit: false, warning: true, + scope: { name: "Fable", period: "Weekly", resetDetail: "resets in 7d" }, }, ]); expect(presentation?.reachedLimit).toBe(false); @@ -540,6 +543,7 @@ describe("deriveProviderAccountUsagePresentation", () => { remainingPercent: 0, reachedLimit: true, warning: true, + scope: { name: "Fable", period: "Weekly", resetDetail: "resets in 7d" }, }, ]); expect(presentation?.reachedLimit).toBe(true); @@ -1041,6 +1045,79 @@ describe("isProviderUsageNearLimit", () => { }); }); +describe("a model's own usage limit", () => { + const NOW = 1_800_000_000_000; + /** Claude this week: the account at `weekly`%, Fable's own week at `fable`%. */ + const claude = (weekly: number, fable: number) => + deriveProviderAccountUsagePresentation( + { + source: "claude-oauth-usage", + checkedAt: "2026-07-03T00:00:00.000Z", + primaryLimitId: "claude", + limits: [ + { + limitId: "claude", + secondary: { + usedPercent: weekly, + remainingPercent: 100 - weekly, + resetsAt: NOW + 3 * 86_400_000 + 16 * 3_600_000, + windowDurationMins: 10_080, + }, + scoped: [ + { + scopeLabel: "Fable", + usedPercent: fable, + remainingPercent: 100 - fable, + resetsAt: NOW + 3 * 86_400_000 + 16 * 3_600_000, + windowDurationMins: 10_080, + }, + ], + }, + ], + }, + NOW, + ); + + it("matches every model named after the limit, as whole words only", () => { + const usage = claude(40, 64); + expect(modelOwnUsageLimit(usage, "Claude Fable 5.2")?.usedPercent).toBe(64); + expect(modelOwnUsageLimit(usage, "Claude Fable 5.1")?.usedPercent).toBe(64); + expect(modelOwnUsageLimit(usage, "Claude Opus 5.5")).toBeNull(); + expect(modelOwnUsageLimit(usage, "Fablesque 1")).toBeNull(); + }); + + it("reads grey, then amber, then red with when it resets", () => { + const label = (fable: number) => + modelUsageLimitLabel(modelOwnUsageLimit(claude(40, fable), "Claude Fable 5.2")!); + expect(label(64)).toMatchObject({ text: "64% of week", tone: "normal" }); + expect(label(82)).toMatchObject({ text: "82% of week", tone: "warning" }); + expect(label(100)).toMatchObject({ text: "Limit · resets in 3d 16h", tone: "reached" }); + }); + + it("leaves a model's own limit out of the account's near-limit mark", () => { + // Fable's week is used up, the account's is not: only Fable's row says so. + expect(isProviderUsageNearLimit(claude(40, 100), { modelLimits: false })).toBe(false); + expect(isProviderUsageNearLimit(claude(40, 100))).toBe(true); + expect(isProviderUsageNearLimit(claude(84, 10), { modelLimits: false })).toBe(true); + // An account out of its plan, with no windows to say so. + const outOfPlan = deriveProviderAccountUsagePresentation( + { + source: "codex-rate-limits", + checkedAt: "2026-07-03T00:00:00.000Z", + limits: [ + { + limitId: "codex", + rateLimitReachedType: "rate_limit_reached", + primary: { usedPercent: 40, remainingPercent: 60 }, + }, + ], + }, + NOW, + ); + expect(isProviderUsageNearLimit(outOfPlan, { modelLimits: false })).toBe(true); + }); +}); + describe("compactUsageMeters", () => { const window = (key: string, label: string, usedPercent: number, shortLabel?: string) => ({ key, diff --git a/apps/web/src/lib/providerUsage.ts b/apps/web/src/lib/providerUsage.ts index c610c8d4e..8b8080595 100644 --- a/apps/web/src/lib/providerUsage.ts +++ b/apps/web/src/lib/providerUsage.ts @@ -27,6 +27,16 @@ export interface ProviderAccountUsageWindowPresentation { readonly remainingPercent: number; readonly reachedLimit: boolean; readonly warning: boolean; + /** + * Set on a window that caps one model, not the whole account (Claude's + * per-model weekly limits): the name the provider gives it ("Fable"), its + * period ("Weekly"), and when it resets ("resets in 3d 16h"). + */ + readonly scope?: { + readonly name: string; + readonly period: string | null; + readonly resetDetail: string | null; + }; } export interface ProviderAccountUsageSpendControlPresentation { @@ -437,6 +447,7 @@ function formatScopedUsageWindowPresentation( remainingPercent, reachedLimit, warning: reachedLimit || severityWarning || usedPercent >= USAGE_WARNING_THRESHOLD_PERCENT, + scope: { name: window.scopeLabel, period: durationLabel || null, resetDetail }, }; } @@ -801,11 +812,29 @@ export function deriveProviderAccountUsagePresentationForProvider( */ export function isProviderUsageNearLimit( presentation: ProviderAccountUsagePresentation | null, + options: { + /** + * False: only limits on the whole account count, never one model's own + * cap. The model picker's dot on a provider uses this; the model's own + * limit shows on its row (modelOwnUsageLimit). + */ + readonly modelLimits?: boolean; + } = {}, ): boolean { if (!presentation) return false; - if (presentation.reachedLimit) return true; if (presentation.spendControl?.warning) return true; - return presentation.windows.some((window) => window.warning); + // `reachedLimit` also counts a model's own limit, so it decides only when + // those count too; a window reached is a window in warning either way. + if (options.modelLimits !== false) { + return presentation.reachedLimit || presentation.windows.some((window) => window.warning); + } + // Reached with no model's own limit reached: the account itself is out + // (Codex can say so with no windows at all). + const modelLimitReached = presentation.windows.some( + (window) => window.scope !== undefined && window.reachedLimit, + ); + if (presentation.reachedLimit && !modelLimitReached) return true; + return presentation.windows.some((window) => window.scope === undefined && window.warning); } /** @@ -826,3 +855,60 @@ export function providerUsageNearLimitColor( .reduce((max, meter) => Math.max(max, meter.usedPercent), 0); return usageMeterColor(hottestPercent, true); } + +const nameTokens = (name: string) => name.toLowerCase().split(/\s+/).filter(Boolean); + +/** + * The limit a model has of its own, if the account reports one. Providers name + * such a limit, not the model's id ("Fable" for every Fable model), so it + * matches a model whose name holds the limit's name as whole words: "Fable" + * matches "Claude Fable 5.2", while "Opus 5" does not match "Opus 5.5". The + * fullest applies when several do. + */ +export function modelOwnUsageLimit( + usage: Pick | null | undefined, + modelName: string, +): ProviderAccountUsageWindowPresentation | null { + if (!usage) return null; + const model = nameTokens(modelName); + const holds = (scope: ReadonlyArray) => + scope.length > 0 && + model.some((_, start) => scope.every((token, offset) => model[start + offset] === token)); + return usage.windows.reduce((fullest, window) => { + if (window.scope === undefined || !holds(nameTokens(window.scope.name))) return fullest; + return fullest === null || window.usedPercent > fullest.usedPercent ? window : fullest; + }, null); +} + +/** "Weekly" → "week", for "64% of week". Periods with no such word stay as they are. */ +const PERIOD_NOUNS: Readonly> = { + Weekly: "week", + Daily: "day", + Monthly: "month", +}; + +/** + * What a model's row says about its own limit: "40% of week", in the row's + * grey until the warning threshold, then amber; "Limit · resets in 3d 16h", + * in red, once it is reached. The hover has the whole reading. + */ +export function modelUsageLimitLabel(window: ProviderAccountUsageWindowPresentation): { + readonly text: string; + readonly tone: "normal" | "warning" | "reached"; + readonly title: string; +} { + const percent = Math.round(window.usedPercent); + const period = window.scope?.period ?? null; + const reset = window.scope?.resetDetail ?? null; + return { + text: window.reachedLimit + ? reset + ? `Limit · ${reset}` + : "Limit reached" + : period + ? `${percent}% of ${PERIOD_NOUNS[period] ?? period}` + : `${percent}% used`, + tone: window.reachedLimit ? "reached" : window.warning ? "warning" : "normal", + title: `${window.label} · ${window.detail}`, + }; +}