feat: Add usage prediction and pace to usage dropdown and settings (#372)

This commit is contained in:
gsxdsm
2026-02-09 17:32:41 +02:00
committed by GitHub
parent 3fff7a1475
commit 5deb851a75
9 changed files with 553 additions and 84 deletions
+105 -46
View File
@@ -30,11 +30,13 @@ import { cn, getModifierLabel, hasModifier } from '@/lib/utils';
import { useDiffFileCount } from '@/components/views/DiffView'; import { useDiffFileCount } from '@/components/views/DiffView';
import { McpDropdown, McpDropdownContent } from '@/components/mcp/McpDropdown'; import { McpDropdown, McpDropdownContent } from '@/components/mcp/McpDropdown';
import { ProviderLogo } from '@/components/ui/ProviderLogo'; import { ProviderLogo } from '@/components/ui/ProviderLogo';
import { formatPercent, formatWindowLabel, QUOTA_PROVIDERS } from '@/lib/quota'; import { formatPercent, formatWindowLabel, QUOTA_PROVIDERS, calculatePace, calculateExpectedUsagePercent } from '@/lib/quota';
import { UsageProgressBar } from '@/components/sections/usage/UsageProgressBar'; import { UsageProgressBar } from '@/components/sections/usage/UsageProgressBar';
import { PaceIndicator } from '@/components/sections/usage/PaceIndicator';
import { updateDesktopSettings } from '@/lib/persistence'; import { updateDesktopSettings } from '@/lib/persistence';
import { import {
getAllModelFamilies, getAllModelFamilies,
getDisplayModelName,
groupModelsByFamily, groupModelsByFamily,
sortModelFamilies, sortModelFamilies,
} from '@/lib/quota/model-families'; } from '@/lib/quota/model-families';
@@ -216,6 +218,7 @@ export const Header: React.FC = () => {
providerId: string; providerId: string;
providerName: string; providerName: string;
entries: Array<[string, UsageWindow]>; entries: Array<[string, UsageWindow]>;
error?: string;
modelFamilies?: Array<{ modelFamilies?: Array<{
familyId: string | null; familyId: string | null;
familyLabel: string; familyLabel: string;
@@ -239,14 +242,15 @@ export const Header: React.FC = () => {
providerId: provider.id, providerId: provider.id,
providerName: provider.name, providerName: provider.name,
entries, entries,
error: (result && !result.ok && result.configured) ? result.error : undefined,
}; };
// Add model families if provider has per-model quotas // Add model families if provider has per-model quotas
if (models && Object.keys(models).length > 0) { if (models && Object.keys(models).length > 0) {
const providerSelectedModels = selectedModels[provider.id] ?? []; const providerSelectedModels = selectedModels[provider.id] ?? [];
// hasExplicitSelection = true means user touched the selection (even if empty) // hasExplicitSelection = true means user has selected specific models to show
// hasExplicitSelection = false means no preference (key missing) → show all by default // If the array exists but is empty, treat as "show all" (user cleared selection)
const hasExplicitSelection = provider.id in selectedModels; const hasExplicitSelection = providerSelectedModels.length > 0;
const modelGroups = groupModelsByFamily(models, provider.id); const modelGroups = groupModelsByFamily(models, provider.id);
const families = getAllModelFamilies(provider.id); const families = getAllModelFamilies(provider.id);
const sortedFamilies = sortModelFamilies(families); const sortedFamilies = sortModelFamilies(families);
@@ -310,7 +314,7 @@ export const Header: React.FC = () => {
} }
} }
if (entries.length > 0 || (group.modelFamilies && group.modelFamilies.length > 0)) { if (entries.length > 0 || (group.modelFamilies && group.modelFamilies.length > 0) || group.error) {
groups.push(group); groups.push(group);
} }
} }
@@ -826,7 +830,10 @@ export const Header: React.FC = () => {
<p>Instance / Usage / MCP</p> <p>Instance / Usage / MCP</p>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
<DropdownMenuContent align="end" className="w-[min(30rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0"> <DropdownMenuContent
align="end"
className="w-[min(30rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0"
>
<div className="sticky top-0 z-20 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2"> <div className="sticky top-0 z-20 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2">
<AnimatedTabs<'instance' | 'usage' | 'mcp'> <AnimatedTabs<'instance' | 'usage' | 'mcp'>
value={desktopServicesTab} value={desktopServicesTab}
@@ -856,7 +863,7 @@ export const Header: React.FC = () => {
{desktopServicesTab === 'usage' && ( {desktopServicesTab === 'usage' && (
<div className="overflow-x-hidden"> <div className="overflow-x-hidden">
<div className="sticky top-0 z-20 bg-[var(--surface-elevated)] border-b border-[var(--interactive-border)]"> <div className="bg-[var(--surface-elevated)] border-b border-[var(--interactive-border)]">
<DropdownMenuLabel className="flex items-center justify-between gap-3 py-2.5"> <DropdownMenuLabel className="flex items-center justify-between gap-3 py-2.5">
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<span className="typography-ui-header font-semibold text-foreground">Rate limits</span> <span className="typography-ui-header font-semibold text-foreground">Rate limits</span>
@@ -901,7 +908,7 @@ export const Header: React.FC = () => {
return ( return (
<React.Fragment key={group.providerId}> <React.Fragment key={group.providerId}>
<DropdownMenuLabel className="sticky top-[44px] z-10 flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground"> <DropdownMenuLabel className="flex items-center gap-2 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] typography-ui-label text-foreground">
<ProviderLogo providerId={group.providerId} className="h-4 w-4" /> <ProviderLogo providerId={group.providerId} className="h-4 w-4" />
{group.providerName} {group.providerName}
</DropdownMenuLabel> </DropdownMenuLabel>
@@ -912,23 +919,27 @@ export const Header: React.FC = () => {
className="cursor-default hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent" className="cursor-default hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent"
onSelect={(event) => event.preventDefault()} onSelect={(event) => event.preventDefault()}
> >
<span className="typography-ui-label text-muted-foreground">No rate limits reported.</span> <span className="typography-ui-label text-muted-foreground">
{group.error ?? 'No rate limits reported.'}
</span>
</DropdownMenuItem> </DropdownMenuItem>
) : ( ) : (
<> <>
{group.entries.map(([label, window]) => ( {group.entries.map(([label, window]) => {
const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent
: window.usedPercent;
const paceInfo = calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, label);
const expectedMarker = paceInfo?.dailyAllocationPercent != null
? calculateExpectedUsagePercent(paceInfo.elapsedRatio)
: null;
return (
<DropdownMenuItem <DropdownMenuItem
key={`${group.providerId}-${label}`} key={`${group.providerId}-${label}`}
className="cursor-default items-start hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent" className="cursor-default items-start hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent"
onSelect={(event) => event.preventDefault()} onSelect={(event) => event.preventDefault()}
> >
<span className="flex min-w-0 flex-1 flex-col gap-2"> <span className="flex min-w-0 flex-1 flex-col gap-2">
{(() => {
const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent
: window.usedPercent;
return (
<>
<span className="flex min-w-0 items-center justify-between gap-3"> <span className="flex min-w-0 items-center justify-between gap-3">
<span className="min-w-0 flex items-center gap-2"> <span className="min-w-0 flex items-center gap-2">
<span className="truncate typography-ui-label text-foreground">{formatWindowLabel(label)}</span> <span className="truncate typography-ui-label text-foreground">{formatWindowLabel(label)}</span>
@@ -942,13 +953,21 @@ export const Header: React.FC = () => {
{formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)} {formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)}
</span> </span>
</span> </span>
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} className="h-1.5 mb-1.5" /> <UsageProgressBar
</> percent={displayPercent}
); tonePercent={window.usedPercent}
})()} className="h-1.5"
expectedMarkerPercent={expectedMarker}
/>
{paceInfo && (
<div className="mb-1">
<PaceIndicator paceInfo={paceInfo} compact />
</div>
)}
</span> </span>
</DropdownMenuItem> </DropdownMenuItem>
))} );
})}
{group.modelFamilies && group.modelFamilies.length > 0 && ( {group.modelFamilies && group.modelFamilies.length > 0 && (
<div className="px-2 py-1"> <div className="px-2 py-1">
@@ -973,36 +992,42 @@ export const Header: React.FC = () => {
</CollapsibleTrigger> </CollapsibleTrigger>
<CollapsibleContent> <CollapsibleContent>
<div className="space-y-1 pl-2"> <div className="space-y-1 pl-2">
{family.models.map(([modelName, window]) => ( {family.models.map(([modelName, window]) => {
const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent
: window.usedPercent;
// For model-level quotas, use '5h' as typical window label for Google models
const paceInfo = calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, '5h');
const expectedMarker = paceInfo?.dailyAllocationPercent != null
? calculateExpectedUsagePercent(paceInfo.elapsedRatio)
: null;
return (
<div <div
key={`${group.providerId}-${modelName}`} key={`${group.providerId}-${modelName}`}
className="py-1.5" className="py-1.5"
> >
<div className="flex min-w-0 flex-col gap-1.5"> <div className="flex min-w-0 flex-col gap-1.5">
<span className="flex min-w-0 items-center justify-between gap-3"> <span className="flex min-w-0 items-center justify-between gap-3">
<span className="truncate typography-micro text-muted-foreground">{modelName}</span> <span className="truncate typography-micro text-muted-foreground">{getDisplayModelName(modelName)}</span>
{(() => { <span className="typography-ui-label text-foreground tabular-nums">
const displayPercent = quotaDisplayMode === 'remaining' {formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)}
? window.remainingPercent </span>
: window.usedPercent;
return (
<span className="typography-ui-label text-foreground tabular-nums">
{formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)}
</span>
);
})()}
</span> </span>
{(() => { <UsageProgressBar
const displayPercent = quotaDisplayMode === 'remaining' percent={displayPercent}
? window.remainingPercent tonePercent={window.usedPercent}
: window.usedPercent; className="h-1.5"
return ( expectedMarkerPercent={expectedMarker}
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} className="h-1.5 mb-1.5" /> />
); {paceInfo && (
})()} <div className="mb-1">
<PaceIndicator paceInfo={paceInfo} compact />
</div>
)}
</div> </div>
</div> </div>
))} );
})}
</div> </div>
</CollapsibleContent> </CollapsibleContent>
</Collapsible> </Collapsible>
@@ -1360,14 +1385,23 @@ export const Header: React.FC = () => {
)} )}
{rateLimitGroups.map((group) => ( {rateLimitGroups.map((group) => (
<React.Fragment key={group.providerId}> <React.Fragment key={group.providerId}>
<div className="sticky top-0 z-10 flex items-center gap-2 bg-[var(--surface-elevated)] px-3 py-2"> <div className="flex items-center gap-2 bg-[var(--surface-elevated)] px-3 py-2">
<ProviderLogo providerId={group.providerId} className="h-4 w-4" /> <ProviderLogo providerId={group.providerId} className="h-4 w-4" />
<span className="typography-ui-label text-foreground">{group.providerName}</span> <span className="typography-ui-label text-foreground">{group.providerName}</span>
</div> </div>
{group.entries.length === 0 && (!group.modelFamilies || group.modelFamilies.length === 0) && (
<div className="px-3 py-2 typography-ui-label text-muted-foreground">
{group.error ?? 'No rate limits reported.'}
</div>
)}
{group.entries.map(([label, window]) => { {group.entries.map(([label, window]) => {
const displayPercent = quotaDisplayMode === 'remaining' const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent ? window.remainingPercent
: window.usedPercent; : window.usedPercent;
const paceInfo = calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, label);
const expectedMarker = paceInfo?.dailyAllocationPercent != null
? calculateExpectedUsagePercent(paceInfo.elapsedRatio)
: null;
return ( return (
<div key={`${group.providerId}-${label}`} className="px-3 py-2"> <div key={`${group.providerId}-${label}`} className="px-3 py-2">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
@@ -1378,7 +1412,17 @@ export const Header: React.FC = () => {
{formatPercent(displayPercent)} {formatPercent(displayPercent)}
</span> </span>
</div> </div>
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} className="mt-2 h-1" /> <UsageProgressBar
percent={displayPercent}
tonePercent={window.usedPercent}
className="mt-2 h-1"
expectedMarkerPercent={expectedMarker}
/>
{paceInfo && (
<div className="mt-1.5">
<PaceIndicator paceInfo={paceInfo} compact />
</div>
)}
<div className="mt-1 typography-micro text-muted-foreground text-[10px]"> <div className="mt-1 typography-micro text-muted-foreground text-[10px]">
{window.resetAfterFormatted ?? window.resetAtFormatted ?? ''} {window.resetAfterFormatted ?? window.resetAtFormatted ?? ''}
</div> </div>
@@ -1414,17 +1458,32 @@ export const Header: React.FC = () => {
const displayPercent = quotaDisplayMode === 'remaining' const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent ? window.remainingPercent
: window.usedPercent; : window.usedPercent;
// For model-level quotas, use '5h' as typical window label for Google models
const paceInfo = calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, '5h');
const expectedMarker = paceInfo?.dailyAllocationPercent != null
? calculateExpectedUsagePercent(paceInfo.elapsedRatio)
: null;
return ( return (
<div key={`${group.providerId}-${modelName}`} className="py-1.5"> <div key={`${group.providerId}-${modelName}`} className="py-1.5">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<span className="truncate typography-micro text-muted-foreground"> <span className="truncate typography-micro text-muted-foreground">
{modelName} {getDisplayModelName(modelName)}
</span> </span>
<span className="typography-ui-label text-foreground tabular-nums"> <span className="typography-ui-label text-foreground tabular-nums">
{formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)} {formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)}
</span> </span>
</div> </div>
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} className="mt-1.5 h-1" /> <UsageProgressBar
percent={displayPercent}
tonePercent={window.usedPercent}
className="mt-1.5 h-1"
expectedMarkerPercent={expectedMarker}
/>
{paceInfo && (
<div className="mt-1">
<PaceIndicator paceInfo={paceInfo} compact />
</div>
)}
</div> </div>
); );
})} })}
@@ -17,7 +17,8 @@ import {
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { ProviderLogo } from '@/components/ui/ProviderLogo'; import { ProviderLogo } from '@/components/ui/ProviderLogo';
import { UsageProgressBar } from '@/components/sections/usage/UsageProgressBar'; import { UsageProgressBar } from '@/components/sections/usage/UsageProgressBar';
import { formatPercent, formatWindowLabel, QUOTA_PROVIDERS } from '@/lib/quota'; import { PaceIndicator } from '@/components/sections/usage/PaceIndicator';
import { formatPercent, formatWindowLabel, QUOTA_PROVIDERS, calculatePace, calculateExpectedUsagePercent } from '@/lib/quota';
import { useQuotaAutoRefresh, useQuotaStore } from '@/stores/useQuotaStore'; import { useQuotaAutoRefresh, useQuotaStore } from '@/stores/useQuotaStore';
import { updateDesktopSettings } from '@/lib/persistence'; import { updateDesktopSettings } from '@/lib/persistence';
import type { UsageWindow } from '@/types'; import type { UsageWindow } from '@/types';
@@ -447,6 +448,7 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
providerId: string; providerId: string;
providerName: string; providerName: string;
entries: Array<[string, UsageWindow]>; entries: Array<[string, UsageWindow]>;
error?: string;
}> = []; }> = [];
for (const provider of QUOTA_PROVIDERS) { for (const provider of QUOTA_PROVIDERS) {
@@ -456,8 +458,9 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
const result = quotaResults.find((entry) => entry.providerId === provider.id); const result = quotaResults.find((entry) => entry.providerId === provider.id);
const windows = (result?.usage?.windows ?? {}) as Record<string, UsageWindow>; const windows = (result?.usage?.windows ?? {}) as Record<string, UsageWindow>;
const entries = Object.entries(windows); const entries = Object.entries(windows);
if (entries.length > 0) { const error = (result && !result.ok && result.configured) ? result.error : undefined;
groups.push({ providerId: provider.id, providerName: provider.name, entries }); if (entries.length > 0 || error) {
groups.push({ providerId: provider.id, providerName: provider.name, entries, error });
} }
} }
@@ -527,8 +530,11 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
<RiTimerLine className="h-5 w-5" /> <RiTimerLine className="h-5 w-5" />
</button> </button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 max-h-[70vh] overflow-y-auto overflow-x-hidden p-0"> <DropdownMenuContent
<div className="sticky top-0 z-20 bg-[var(--surface-elevated)] border-b border-[var(--interactive-border)]"> align="end"
className="w-80 max-h-[70vh] overflow-y-auto overflow-x-hidden bg-[var(--surface-elevated)] p-0"
>
<div className="sticky top-0 z-20 bg-[var(--surface-elevated)]">
<DropdownMenuLabel className="flex items-center justify-between gap-3 typography-ui-header font-semibold text-foreground"> <DropdownMenuLabel className="flex items-center justify-between gap-3 typography-ui-header font-semibold text-foreground">
<span>Rate limits</span> <span>Rate limits</span>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
@@ -573,9 +579,9 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
</button> </button>
</div> </div>
</DropdownMenuLabel> </DropdownMenuLabel>
<div className="px-2 pb-2 typography-micro text-muted-foreground text-[10px]"> </div>
Last updated {formatTime(quotaLastUpdated)} <div className="border-b border-[var(--interactive-border)] px-2 pb-2 typography-micro text-muted-foreground text-[10px]">
</div> Last updated {formatTime(quotaLastUpdated)}
</div> </div>
{!hasRateLimits && ( {!hasRateLimits && (
<DropdownMenuItem className="cursor-default" onSelect={(event) => event.preventDefault()}> <DropdownMenuItem className="cursor-default" onSelect={(event) => event.preventDefault()}>
@@ -584,7 +590,7 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
)} )}
{rateLimitGroups.map((group, index) => ( {rateLimitGroups.map((group, index) => (
<React.Fragment key={group.providerId}> <React.Fragment key={group.providerId}>
<DropdownMenuLabel className="sticky top-[60px] z-10 flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground"> <DropdownMenuLabel className="flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground">
<ProviderLogo providerId={group.providerId} className="h-4 w-4" /> <ProviderLogo providerId={group.providerId} className="h-4 w-4" />
{group.providerName} {group.providerName}
</DropdownMenuLabel> </DropdownMenuLabel>
@@ -594,38 +600,50 @@ const VSCodeHeader: React.FC<VSCodeHeaderProps> = ({ title, showBack, onBack, on
className="cursor-default" className="cursor-default"
onSelect={(event) => event.preventDefault()} onSelect={(event) => event.preventDefault()}
> >
<span className="typography-ui-label text-muted-foreground">No rate limits reported.</span> <span className="typography-ui-label text-muted-foreground">
{group.error ?? 'No rate limits reported.'}
</span>
</DropdownMenuItem> </DropdownMenuItem>
) : ( ) : (
group.entries.map(([label, window]) => ( group.entries.map(([label, window]) => {
const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent
: window.usedPercent;
const paceInfo = calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, label);
const expectedMarker = paceInfo?.dailyAllocationPercent != null
? calculateExpectedUsagePercent(paceInfo.elapsedRatio)
: null;
return (
<DropdownMenuItem <DropdownMenuItem
key={`${group.providerId}-${label}`} key={`${group.providerId}-${label}`}
className="cursor-default items-start" className="cursor-default items-start"
onSelect={(event) => event.preventDefault()} onSelect={(event) => event.preventDefault()}
> >
<span className="flex min-w-0 flex-1 flex-col gap-2"> <span className="flex min-w-0 flex-1 flex-col gap-2">
{(() => {
const displayPercent = quotaDisplayMode === 'remaining'
? window.remainingPercent
: window.usedPercent;
return (
<>
<span className="flex min-w-0 items-center justify-between gap-3"> <span className="flex min-w-0 items-center justify-between gap-3">
<span className="truncate typography-micro text-muted-foreground">{formatWindowLabel(label)}</span> <span className="truncate typography-micro text-muted-foreground">{formatWindowLabel(label)}</span>
<span className="typography-ui-label text-foreground tabular-nums"> <span className="typography-ui-label text-foreground tabular-nums">
{formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)} {formatPercent(displayPercent) === '-' ? '' : formatPercent(displayPercent)}
</span> </span>
</span> </span>
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} className="h-1" /> <UsageProgressBar
percent={displayPercent}
tonePercent={window.usedPercent}
className="h-1"
expectedMarkerPercent={expectedMarker}
/>
{paceInfo && (
<div className="mt-0.5">
<PaceIndicator paceInfo={paceInfo} compact />
</div>
)}
<span className="flex items-center justify-between typography-micro text-muted-foreground text-[10px]"> <span className="flex items-center justify-between typography-micro text-muted-foreground text-[10px]">
<span>{window.resetAfterFormatted ?? window.resetAtFormatted ?? ''}</span> <span>{window.resetAfterFormatted ?? window.resetAtFormatted ?? ''}</span>
</span> </span>
</>
);
})()}
</span> </span>
</DropdownMenuItem> </DropdownMenuItem>
)) );
})
)} )}
{index < rateLimitGroups.length - 1 && <DropdownMenuSeparator />} {index < rateLimitGroups.length - 1 && <DropdownMenuSeparator />}
</React.Fragment> </React.Fragment>
@@ -0,0 +1,97 @@
import React from 'react';
import { cn } from '@/lib/utils';
import type { PaceInfo } from '@/lib/quota';
import { getPaceStatusColor, formatRemainingTime } from '@/lib/quota';
interface PaceIndicatorProps {
paceInfo: PaceInfo;
className?: string;
/** Compact mode shows just the status dot and prediction */
compact?: boolean;
}
/**
* Visual indicator showing whether usage is on track, slightly fast, or too fast.
* Inspired by opencode-bar's pace visualization.
*/
export const PaceIndicator: React.FC<PaceIndicatorProps> = ({
paceInfo,
className,
compact = false,
}) => {
const statusColor = getPaceStatusColor(paceInfo.status);
const statusLabel = React.useMemo(() => {
switch (paceInfo.status) {
case 'on-track':
return 'On track';
case 'slightly-fast':
return 'Slightly fast';
case 'too-fast':
return 'Too fast';
case 'exhausted':
return 'Used up';
}
}, [paceInfo.status]);
const predictionTooltip = `Predicted usage at window end based on current pace: ${paceInfo.predictText}`;
if (compact) {
return (
<div className={cn('flex items-center gap-1.5', className)}>
<div
className="h-2 w-2 rounded-full flex-shrink-0"
style={{ backgroundColor: statusColor }}
title={statusLabel}
/>
<span
className="typography-micro tabular-nums"
style={{ color: statusColor }}
title={paceInfo.isExhausted ? undefined : predictionTooltip}
>
{paceInfo.isExhausted ? (
<>Wait {formatRemainingTime(paceInfo.remainingSeconds)}</>
) : (
<>Pred: {paceInfo.predictText}</>
)}
</span>
</div>
);
}
return (
<div className={cn('flex items-center justify-between gap-2', className)}>
<div className="flex items-center gap-1.5">
{!paceInfo.isExhausted && (
<span className="typography-micro text-muted-foreground">
Pace: {paceInfo.paceRateText}
</span>
)}
</div>
<div className="flex items-center gap-1.5">
<span
className="typography-micro tabular-nums"
style={{ color: statusColor }}
>
{paceInfo.isExhausted ? (
<>
<span className="font-medium">{statusLabel}</span>
<span className="text-muted-foreground"> · Wait </span>
<span className="font-medium">{formatRemainingTime(paceInfo.remainingSeconds)}</span>
</>
) : (
<span title={predictionTooltip}>
<span className="text-muted-foreground">Pred: </span>
<span className="font-medium">{paceInfo.predictText}</span>
</span>
)}
</span>
<div
className="h-2 w-2 rounded-full flex-shrink-0"
style={{ backgroundColor: statusColor }}
title={statusLabel}
/>
</div>
</div>
);
};
@@ -1,7 +1,8 @@
import React from 'react'; import React from 'react';
import type { UsageWindow } from '@/types'; import type { UsageWindow } from '@/types';
import { formatPercent, formatWindowLabel } from '@/lib/quota'; import { formatPercent, formatWindowLabel, calculatePace, calculateExpectedUsagePercent } from '@/lib/quota';
import { UsageProgressBar } from './UsageProgressBar'; import { UsageProgressBar } from './UsageProgressBar';
import { PaceIndicator } from './PaceIndicator';
import { useQuotaStore } from '@/stores/useQuotaStore'; import { useQuotaStore } from '@/stores/useQuotaStore';
import { Switch } from '@/components/ui/switch'; import { Switch } from '@/components/ui/switch';
@@ -29,6 +30,21 @@ export const UsageCard: React.FC<UsageCardProps> = ({
const resetLabel = window.resetAfterFormatted ?? window.resetAtFormatted ?? ''; const resetLabel = window.resetAfterFormatted ?? window.resetAtFormatted ?? '';
const windowLabel = formatWindowLabel(title); const windowLabel = formatWindowLabel(title);
// Calculate pace info for the usage window
// Pass the title (window label) to infer windowSeconds when not provided by the API
const paceInfo = React.useMemo(() => {
return calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, title);
}, [window.usedPercent, window.resetAt, window.windowSeconds, title]);
// Calculate expected marker position for weekly/monthly quotas
const expectedMarkerPercent = React.useMemo(() => {
if (!paceInfo || paceInfo.dailyAllocationPercent === null) {
return null;
}
// Show marker based on elapsed time ratio
return calculateExpectedUsagePercent(paceInfo.elapsedRatio);
}, [paceInfo]);
return ( return (
<div className="rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 shadow-sm"> <div className="rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 shadow-sm">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
@@ -52,12 +68,23 @@ export const UsageCard: React.FC<UsageCardProps> = ({
</div> </div>
<div className="mt-3"> <div className="mt-3">
<UsageProgressBar percent={displayPercent} tonePercent={window.usedPercent} /> <UsageProgressBar
percent={displayPercent}
tonePercent={window.usedPercent}
expectedMarkerPercent={expectedMarkerPercent}
/>
<div className="mt-1 text-right typography-micro text-muted-foreground text-[10px]"> <div className="mt-1 text-right typography-micro text-muted-foreground text-[10px]">
{barLabel} {barLabel}
</div> </div>
</div> </div>
{/* Pace indicator - only shown when we have pace info */}
{paceInfo && (
<div className="mt-2">
<PaceIndicator paceInfo={paceInfo} />
</div>
)}
<div className="mt-3 flex items-center justify-between text-muted-foreground"> <div className="mt-3 flex items-center justify-between text-muted-foreground">
<span className="typography-micro">Resets</span> <span className="typography-micro">Resets</span>
<span className="typography-micro tabular-nums">{resetLabel}</span> <span className="typography-micro tabular-nums">{resetLabel}</span>
@@ -13,7 +13,7 @@ import {
} from '@/components/ui/collapsible'; } from '@/components/ui/collapsible';
import { RiArrowDownSLine, RiArrowRightSLine } from '@remixicon/react'; import { RiArrowDownSLine, RiArrowRightSLine } from '@remixicon/react';
import type { UsageWindows, QuotaProviderId } from '@/types'; import type { UsageWindows, QuotaProviderId } from '@/types';
import { getAllModelFamilies, sortModelFamilies, groupModelsByFamilyWithGetter } from '@/lib/quota/model-families'; import { getAllModelFamilies, getDisplayModelName, sortModelFamilies, groupModelsByFamilyWithGetter } from '@/lib/quota/model-families';
const formatTime = (timestamp: number | null) => { const formatTime = (timestamp: number | null) => {
if (!timestamp) return '-'; if (!timestamp) return '-';
@@ -257,7 +257,7 @@ export const UsagePage: React.FC = () => {
<UsageCard <UsageCard
key={model.name} key={model.name}
title={label} title={label}
subtitle={model.name} subtitle={getDisplayModelName(model.name)}
window={window} window={window}
showToggle showToggle
toggleEnabled={isSelected} toggleEnabled={isSelected}
@@ -306,7 +306,7 @@ export const UsagePage: React.FC = () => {
<UsageCard <UsageCard
key={model.name} key={model.name}
title={label} title={label}
subtitle={model.name} subtitle={getDisplayModelName(model.name)}
window={window} window={window}
showToggle showToggle
toggleEnabled={isSelected} toggleEnabled={isSelected}
@@ -6,11 +6,24 @@ interface UsageProgressBarProps {
percent: number | null; percent: number | null;
tonePercent?: number | null; tonePercent?: number | null;
className?: string; className?: string;
/**
* Position (0-100) to show a marker indicating expected usage based on time elapsed.
* Used for weekly/monthly quotas to show where usage "should" be if evenly distributed.
*/
expectedMarkerPercent?: number | null;
} }
export const UsageProgressBar: React.FC<UsageProgressBarProps> = ({ percent, tonePercent, className }) => { export const UsageProgressBar: React.FC<UsageProgressBarProps> = ({
percent,
tonePercent,
className,
expectedMarkerPercent,
}) => {
const clamped = clampPercent(percent) ?? 0; const clamped = clampPercent(percent) ?? 0;
const tone = resolveUsageTone(tonePercent ?? percent); const tone = resolveUsageTone(tonePercent ?? percent);
const markerClamped = expectedMarkerPercent != null
? Math.max(0, Math.min(100, expectedMarkerPercent))
: null;
const fillStyle = tone === 'critical' const fillStyle = tone === 'critical'
? { backgroundColor: 'var(--status-error)' } ? { backgroundColor: 'var(--status-error)' }
@@ -19,7 +32,7 @@ export const UsageProgressBar: React.FC<UsageProgressBarProps> = ({ percent, ton
: { backgroundColor: 'var(--status-success)' }; : { backgroundColor: 'var(--status-success)' };
return ( return (
<div className={cn('h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden', className)}> <div className={cn('relative h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden', className)}>
<div <div
className="h-full transition-all duration-300" className="h-full transition-all duration-300"
style={{ ...fillStyle, width: `${clamped}%` }} style={{ ...fillStyle, width: `${clamped}%` }}
@@ -28,6 +41,14 @@ export const UsageProgressBar: React.FC<UsageProgressBarProps> = ({ percent, ton
aria-valuemin={0} aria-valuemin={0}
aria-valuemax={100} aria-valuemax={100}
/> />
{markerClamped != null && markerClamped > 0 && markerClamped < 100 && (
<div
className="absolute top-0 h-full w-0.5 bg-foreground"
style={{ left: `${markerClamped}%` }}
title={`Expected usage if spread evenly: ${Math.round(markerClamped)}% of quota`}
aria-hidden="true"
/>
)}
</div> </div>
); );
}; };
+12 -1
View File
@@ -1,3 +1,14 @@
export { QUOTA_PROVIDERS, QUOTA_PROVIDER_MAP } from './providers'; export { QUOTA_PROVIDERS, QUOTA_PROVIDER_MAP } from './providers';
export type { QuotaProviderMeta } from './providers'; export type { QuotaProviderMeta } from './providers';
export { clampPercent, formatPercent, resolveUsageTone, formatWindowLabel } from './utils'; export {
clampPercent,
formatPercent,
resolveUsageTone,
formatWindowLabel,
calculatePace,
inferWindowSeconds,
getPaceStatusColor,
formatRemainingTime,
calculateExpectedUsagePercent,
} from './utils';
export type { PaceStatus, PaceInfo } from './utils';
+44 -8
View File
@@ -7,17 +7,50 @@ export interface ModelFamily {
order: number; order: number;
} }
/**
* Strip auth source prefix from model name for display.
* e.g., "gemini/gemini-2.5-flash" -> "gemini-2.5-flash"
* "antigravity/claude-sonnet" -> "claude-sonnet"
*/
export function getDisplayModelName(modelName: string): string {
// Handle prefixes like "gemini/", "antigravity/"
const slashIndex = modelName.indexOf('/');
if (slashIndex !== -1) {
const prefix = modelName.substring(0, slashIndex);
// Check if it's an auth source prefix
if (prefix === 'gemini' || prefix === 'antigravity') {
return modelName.substring(slashIndex + 1);
}
}
return modelName;
}
/**
* Get the auth source label from a model name prefix.
* e.g., "gemini/..." -> "Gemini"
* "antigravity/..." -> "Antigravity"
*/
export function getAuthSourceLabel(modelName: string): string | null {
const slashIndex = modelName.indexOf('/');
if (slashIndex === -1) return null;
const prefix = modelName.substring(0, slashIndex);
if (prefix === 'gemini') return 'Gemini';
if (prefix === 'antigravity') return 'Antigravity';
return null;
}
const GOOGLE_MODEL_FAMILIES: ModelFamily[] = [ const GOOGLE_MODEL_FAMILIES: ModelFamily[] = [
{ {
id: 'gemini', id: 'gemini-auth',
label: 'Gemini', label: 'Gemini',
matcher: (modelName) => modelName.toLowerCase().startsWith('gemini-'), matcher: (modelName) => modelName.startsWith('gemini/'),
order: 1, order: 1,
}, },
{ {
id: 'claude', id: 'antigravity-auth',
label: 'Claude', label: 'Antigravity',
matcher: (modelName) => modelName.toLowerCase().startsWith('claude-'), matcher: (modelName) => modelName.startsWith('antigravity/'),
order: 2, order: 2,
}, },
]; ];
@@ -92,7 +125,8 @@ export function groupModelsByFamilyWithGetter<T>(
/** /**
* Get default models for a provider based on simple patterns. * Get default models for a provider based on simple patterns.
* - Gemini 3.x models (starting with gemini-3-) * For Google provider with gemini/ and antigravity/ prefixes:
* - Gemini 3.x models
* - All Claude models * - All Claude models
*/ */
export function getDefaultModels( export function getDefaultModels(
@@ -101,10 +135,12 @@ export function getDefaultModels(
): string[] { ): string[] {
return availableModels.filter((model) => { return availableModels.filter((model) => {
const lower = model.toLowerCase(); const lower = model.toLowerCase();
// Handle gemini/ and antigravity/ prefixes
const modelName = lower.includes('/') ? lower.split('/')[1] : lower;
// Gemini 3.x // Gemini 3.x
if (lower.startsWith('gemini-3-')) return true; if (modelName.startsWith('gemini-3-')) return true;
// All Claude models // All Claude models
if (lower.startsWith('claude-')) return true; if (modelName.startsWith('claude-')) return true;
return false; return false;
}); });
} }
+200
View File
@@ -40,3 +40,203 @@ export const formatWindowLabel = (label: string): string => {
if (label === 'premium_interactions') return 'Premium interactions'; if (label === 'premium_interactions') return 'Premium interactions';
return label; return label;
}; };
/**
* Pace status indicating whether usage is on track, slightly fast, or too fast
*/
export type PaceStatus = 'on-track' | 'slightly-fast' | 'too-fast' | 'exhausted';
/**
* Information about the current pace of usage
*/
export interface PaceInfo {
/** Ratio of time elapsed in the window (0-1) */
elapsedRatio: number;
/** Ratio of quota used (0-1) */
usageRatio: number;
/** Predicted final usage percentage at end of window */
predictedFinalPercent: number;
/** Seconds remaining until reset */
remainingSeconds: number;
/** Whether usage is exhausted (100% used with time remaining) */
isExhausted: boolean;
/** Elapsed seconds in the window */
elapsedSeconds: number;
/** Total window duration in seconds */
totalSeconds: number;
/** Current pace status */
status: PaceStatus;
/** Per-unit pace rate (e.g., "2.5%/h" or "15%/d") */
paceRateText: string;
/** Prediction text (e.g., "85%" or "+120%") */
predictText: string;
/** For weekly quotas: the per-day allocation percentage */
dailyAllocationPercent: number | null;
}
/**
* Infer window duration in seconds from a window label.
* Used when the API doesn't provide windowSeconds directly.
*/
export const inferWindowSeconds = (label: string): number | null => {
const normalized = label.toLowerCase().trim();
// Exact matches
if (normalized === '5h') return 5 * 3600;
if (normalized === '7d' || normalized === 'weekly' || normalized === '7d-sonnet' || normalized === '7d-opus') return 7 * 86400;
if (normalized === 'monthly') return 30 * 86400;
if (normalized === '24h' || normalized === 'daily') return 86400;
if (normalized === '1h') return 3600;
// Pattern matches
const hourMatch = normalized.match(/^(\d+)h$/);
if (hourMatch) return parseInt(hourMatch[1], 10) * 3600;
const dayMatch = normalized.match(/^(\d+)d$/);
if (dayMatch) return parseInt(dayMatch[1], 10) * 86400;
return null;
};
/**
* Calculate pace information for a usage window.
*
* @param usedPercent - Current usage percentage (0-100)
* @param resetAt - Timestamp (ms) when the window resets
* @param windowSeconds - Total window duration in seconds (can be null, will be inferred from label if possible)
* @param windowLabel - Optional label to infer window duration from
* @returns PaceInfo object with pace calculations
*/
export const calculatePace = (
usedPercent: number | null,
resetAt: number | null,
windowSeconds: number | null,
windowLabel?: string
): PaceInfo | null => {
// Try to infer windowSeconds from label if not provided
let effectiveWindowSeconds = windowSeconds;
if (effectiveWindowSeconds === null && windowLabel) {
effectiveWindowSeconds = inferWindowSeconds(windowLabel);
}
if (usedPercent === null || resetAt === null || effectiveWindowSeconds === null || effectiveWindowSeconds <= 0) {
return null;
}
const now = Date.now();
const remainingSeconds = Math.max(0, (resetAt - now) / 1000);
const elapsedSeconds = Math.max(0, Math.min(effectiveWindowSeconds, effectiveWindowSeconds - remainingSeconds));
const elapsedRatio = Math.max(0, Math.min(1, elapsedSeconds / effectiveWindowSeconds));
const usageRatio = usedPercent / 100;
const isExhausted = usedPercent >= 100 && remainingSeconds > 0;
// Calculate predicted final usage
let predictedFinalPercent: number;
if (elapsedRatio > 0.01) {
predictedFinalPercent = Math.min(999, (usageRatio / elapsedRatio) * 100);
} else {
predictedFinalPercent = usedPercent;
}
// Determine pace status
let status: PaceStatus;
if (isExhausted) {
status = 'exhausted';
} else if (usageRatio <= elapsedRatio) {
status = 'on-track';
} else if (predictedFinalPercent <= 130) {
status = 'slightly-fast';
} else {
status = 'too-fast';
}
// Calculate pace rate text (per hour for < 5 days, per day otherwise)
const usePerDay = effectiveWindowSeconds >= 5 * 24 * 3600;
const unitSeconds = usePerDay ? 86400 : 3600;
const unitSuffix = usePerDay ? 'd' : 'h';
const totalUnits = effectiveWindowSeconds / unitSeconds;
const elapsedUnits = Math.max(elapsedSeconds / unitSeconds, totalUnits * 0.01);
const pacePercentPerUnit = (usedPercent / elapsedUnits);
const paceRateText = Number.isFinite(pacePercentPerUnit)
? `${Math.min(999.9, Math.max(0, pacePercentPerUnit)).toFixed(1)}%/${unitSuffix}`
: '-';
// Calculate predict text
const predictText = predictedFinalPercent > 100
? `+${Math.round(predictedFinalPercent)}%`
: `${Math.round(predictedFinalPercent)}%`;
// Calculate daily allocation for weekly quotas (7 days = 604800 seconds)
// Also include monthly quotas (roughly 30 days)
let dailyAllocationPercent: number | null = null;
const windowDays = effectiveWindowSeconds / 86400;
if (windowDays >= 7) {
// For a 7-day window, each day should use ~14.3% (100/7)
// For monthly, each day should use ~3.3% (100/30)
dailyAllocationPercent = 100 / windowDays;
}
return {
elapsedRatio,
usageRatio,
predictedFinalPercent,
remainingSeconds,
isExhausted,
elapsedSeconds,
totalSeconds: effectiveWindowSeconds,
status,
paceRateText,
predictText,
dailyAllocationPercent,
};
};
/**
* Get the color for a pace status (returns CSS variable names)
*/
export const getPaceStatusColor = (status: PaceStatus): string => {
switch (status) {
case 'exhausted':
case 'too-fast':
return 'var(--status-error)';
case 'slightly-fast':
return 'var(--status-warning)';
case 'on-track':
return 'var(--status-success)';
}
};
/**
* Format remaining time as a human-readable string
*/
export const formatRemainingTime = (seconds: number): string => {
const totalSeconds = Math.max(0, Math.floor(seconds));
const totalMinutes = Math.floor(totalSeconds / 60);
const totalHours = Math.floor(totalMinutes / 60);
const days = Math.floor(totalHours / 24);
const hours = totalHours % 24;
const minutes = totalMinutes % 60;
if (days > 0) {
return `${days}d ${hours}h`;
}
if (totalHours > 0) {
return `${totalHours}h`;
}
if (totalMinutes === 0) {
return '<1m';
}
return `${minutes}m`;
};
/**
* Calculate the marker position for daily allocation on weekly quotas.
* Returns a percentage (0-100) representing where the "expected" usage should be
* based on how much time has elapsed.
*
* @param elapsedRatio - Ratio of time elapsed (0-1)
* @returns Expected usage percentage based on time elapsed
*/
export const calculateExpectedUsagePercent = (elapsedRatio: number): number => {
return Math.min(100, Math.max(0, elapsedRatio * 100));
};