Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion apps/web/src/components/chat/ModelListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -74,7 +83,14 @@ export const ModelListRow = memo(function ModelListRow(props: {
<div className="min-w-0 flex-1 text-left">
<div className="flex items-center justify-between gap-2 min-w-0">
<div
className="text-xs font-medium leading-snug flex items-center gap-1.5 min-w-0 group-data-selected:text-primary-readable"
className={cn(
"text-xs font-medium leading-snug flex items-center gap-1.5 min-w-0",
// A model at its own limit reads grey, picked or not; the
// picked row keeps its fill.
props.usageLimit?.tone === "reached"
? "text-muted-foreground"
: "group-data-selected:text-primary-readable",
)}
data-model-picker-model-name
>
<span className="truncate" title={getDisplayModelName(props.model)}>
Expand All @@ -100,6 +116,22 @@ export const ModelListRow = memo(function ModelListRow(props: {
<span className="min-w-0 truncate">{props.action.label}</span>
</span>
) : null}
{props.usageLimit ? (
<span
data-model-usage-limit={props.usageLimit.tone}
className={cn(
"min-w-0 truncate font-mono text-[10px] font-normal",
props.usageLimit.tone === "reached"
? "text-destructive-foreground"
: props.usageLimit.tone === "warning"
? "text-warning"
: "text-muted-foreground/60",
)}
title={props.usageLimit.title}
>
{props.usageLimit.text}
</span>
) : null}
{props.model.metaLabel ? (
<span
className="min-w-0 truncate font-mono text-[10px] font-normal text-muted-foreground/60"
Expand Down
51 changes: 44 additions & 7 deletions apps/web/src/components/chat/ModelPickerContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import { cn } from "~/lib/utils";
import {
deriveProviderAccountUsagePresentationForProvider,
headlineUsageMeter,
isProviderUsageNearLimit,
modelOwnUsageLimit,
modelUsageLimitLabel,
} from "~/lib/providerUsage";
import { ModelListRow } from "./ModelListRow";
import { resolveModelPickerEmptyState } from "./modelPickerEmptyState";
Expand Down Expand Up @@ -77,6 +80,8 @@ type ModelPickerTab = {
usage?: { readonly usedPercent: number; readonly label: string; readonly warning: boolean };
/** This account's usage has nothing to draw right now: the tab shows no figure and says so on hover. */
usageUnavailable?: boolean;
/** The account is near its plan's limit as a whole: an amber dot on the icon (isProviderUsageNearLimit). */
nearLimit?: boolean;
};

/**
Expand Down Expand Up @@ -409,6 +414,19 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return grouped;
}, [eligibleModels]);

// Each account's usage, for the near-limit dot on its tab and each model's
// own limit on its row.
const usageByInstance = useMemo(
() =>
new Map(
instanceEntries.map((entry) => [
entry.instanceId,
deriveProviderAccountUsagePresentationForProvider(entry.snapshot),
]),
),
[instanceEntries],
);

const providerTabs = useMemo((): ModelPickerTab[] => {
const tabs: ModelPickerTab[] = [];
const instanceCountByDriver = new Map<string, number>();
Expand All @@ -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",
Expand All @@ -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[] => {
Expand Down Expand Up @@ -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 <StarIcon className="size-3.5 fill-current text-yellow-500/80" />;
}
Expand All @@ -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) ? (
<span
aria-hidden
data-model-picker-near-limit
className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-warning ring-1 ring-popover"
/>
) : null}
</>
);
};
Expand Down Expand Up @@ -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 (
Expand All @@ -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)}
Expand Down Expand Up @@ -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",
Expand All @@ -882,7 +919,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}}
>
<span className="relative flex size-4 shrink-0 items-center justify-center">
{renderTabIcon(tab)}
{renderTabIcon(tab, iconOnly)}
</span>
{iconOnly ? null : <span className="min-w-0 truncate">{tab.label}</span>}
{iconOnly || !tab.usage ? null : (
Expand Down
68 changes: 68 additions & 0 deletions apps/web/src/components/chat/ProviderModelPicker.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(`[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<HTMLElement>("[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();
}
});
});
77 changes: 77 additions & 0 deletions apps/web/src/lib/providerUsage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
formatProviderTokenCount,
headlineUsageMeter,
isProviderUsageNearLimit,
modelOwnUsageLimit,
modelUsageLimitLabel,
providerRateLimitResetCreditsExpirationUrgency,
providerRateLimitResetCreditExpirationUrgency,
providerUsageNearLimitColor,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading