fix(usage): refresh work status quotas automatically

This commit is contained in:
Bohdan Triapitsyn
2026-08-11 12:58:36 +03:00
parent 99e254acf3
commit b55152db6f
31 changed files with 130 additions and 625 deletions
@@ -1,99 +0,0 @@
import React from 'react';
import { cn } from '@/lib/utils';
import type { PaceInfo } from '@/lib/quota';
import { getPaceStatusColor, formatRemainingTime } from '@/lib/quota';
import { useI18n } from '@/lib/i18n';
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 { t } = useI18n();
const statusColor = getPaceStatusColor(paceInfo.status);
const statusLabel = React.useMemo(() => {
switch (paceInfo.status) {
case 'on-track':
return t('settings.usage.pace.status.onTrack');
case 'slightly-fast':
return t('settings.usage.pace.status.slightlyFast');
case 'too-fast':
return t('settings.usage.pace.status.tooFast');
case 'exhausted':
return t('settings.usage.pace.status.usedUp');
}
}, [paceInfo.status, t]);
const predictionTooltip = t('settings.usage.pace.predictionTooltip', { prediction: 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 ? (
<>{t('settings.usage.pace.wait', { duration: formatRemainingTime(paceInfo.remainingSeconds) })}</>
) : (
<>{t('settings.usage.pace.prediction', { prediction: 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">
{t('settings.usage.pace.rate', { rate: 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">{t('settings.usage.pace.waitSeparator')}</span>
<span className="font-medium">{formatRemainingTime(paceInfo.remainingSeconds)}</span>
</>
) : (
<span title={predictionTooltip}>
<span className="text-muted-foreground">{t('settings.usage.pace.predictionLabel')}</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,8 +1,6 @@
import React from 'react';
import type { UsageWindow } from '@/types';
import { formatQuotaValueLabel, formatQuotaResetLabel, formatWindowLabel, calculatePace, calculateExpectedUsagePercent } from '@/lib/quota';
import { formatQuotaValueLabel, formatQuotaResetLabel, formatWindowLabel } from '@/lib/quota';
import { UsageProgressBar } from './UsageProgressBar';
import { PaceIndicator } from './PaceIndicator';
import { useQuotaStore } from '@/stores/useQuotaStore';
import { Checkbox } from '@/components/ui/checkbox';
import { useUIStore } from '@/stores/useUIStore';
@@ -25,7 +23,6 @@ export const UsageCard: React.FC<UsageCardProps> = ({
onToggle,
}) => {
const displayMode = useQuotaStore((state) => state.displayMode);
const showPredValues = useQuotaStore((state) => state.showPredValues);
const timeFormatPreference = useUIStore((state) => state.timeFormatPreference);
const displayPercent = displayMode === 'remaining' ? window.remainingPercent : window.usedPercent;
const barLabel = displayMode === 'remaining' ? 'remaining' : 'used';
@@ -33,18 +30,6 @@ export const UsageCard: React.FC<UsageCardProps> = ({
const resetLabel = formatQuotaResetLabel(window.resetAt, window.resetAfterFormatted ?? window.resetAtFormatted, timeFormatPreference);
const windowLabel = formatWindowLabel(title);
const paceInfo = React.useMemo(() => {
return calculatePace(window.usedPercent, window.resetAt, window.windowSeconds, title);
}, [window.usedPercent, window.resetAt, window.windowSeconds, title]);
const expectedMarkerPercent = React.useMemo(() => {
if (!paceInfo || paceInfo.dailyAllocationPercent === null) {
return null;
}
const expectedUsed = calculateExpectedUsagePercent(paceInfo.elapsedRatio);
return displayMode === 'remaining' ? 100 - expectedUsed : expectedUsed;
}, [paceInfo, displayMode]);
return (
<div className="py-3">
<div className="flex items-center justify-between gap-3">
@@ -72,7 +57,6 @@ export const UsageCard: React.FC<UsageCardProps> = ({
<UsageProgressBar
percent={displayPercent}
tonePercent={window.usedPercent}
expectedMarkerPercent={expectedMarkerPercent}
className="h-1.5"
/>
<div className="mt-1 flex items-center justify-between">
@@ -85,11 +69,6 @@ export const UsageCard: React.FC<UsageCardProps> = ({
</div>
</div>
{paceInfo && showPredValues && (
<div className="mt-1.5">
<PaceIndicator paceInfo={paceInfo} />
</div>
)}
</div>
);
};
@@ -168,13 +168,13 @@ export const UsagePage: React.FC = () => {
}
showSaveStatus
>
<SettingsSection divider={false} settingsItem="usage.header-menu">
<SettingsSection divider={false} settingsItem="usage.work-status-panel">
<SettingsCheckboxRow
checked={showInDropdown}
onChange={handleDropdownToggle}
label={t('settings.usage.page.options.showInHeader')}
ariaLabel={t('settings.usage.page.options.showInHeaderAria')}
info={t('settings.usage.page.options.showInHeaderTooltip')}
label={t('settings.usage.page.options.showInWorkStatus')}
ariaLabel={t('settings.usage.page.options.showInWorkStatusAria')}
info={t('settings.usage.page.options.showInWorkStatusTooltip')}
/>
</SettingsSection>
@@ -6,24 +6,15 @@ interface UsageProgressBarProps {
percent: number | null;
tonePercent?: number | null;
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,
expectedMarkerPercent,
}) => {
const clamped = clampPercent(percent) ?? 0;
const tone = resolveUsageTone(tonePercent ?? percent);
const markerClamped = expectedMarkerPercent != null
? Math.max(0, Math.min(100, expectedMarkerPercent))
: null;
const fillStyle = tone === 'critical'
? { backgroundColor: 'var(--status-error)' }
@@ -41,14 +32,6 @@ export const UsageProgressBar: React.FC<UsageProgressBarProps> = ({
aria-valuemin={0}
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>
);
};
@@ -2,8 +2,6 @@ import React from 'react';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { ProviderLogo } from '@/components/ui/ProviderLogo';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Icon } from "@/components/icon/Icon";
import { cn } from '@/lib/utils';
@@ -35,21 +33,15 @@ export const UsageSidebar: React.FC<UsageSidebarProps> = ({ onItemSelect }) => {
const setSelectedProvider = useQuotaStore((state) => state.setSelectedProvider);
const fetchAllQuotas = useQuotaStore((state) => state.fetchAllQuotas);
const isLoading = useQuotaStore((state) => state.isLoading);
const usageAutoRefresh = useQuotaStore((state) => state.autoRefresh);
const usageRefreshIntervalMs = useQuotaStore((state) => state.refreshIntervalMs);
const usageDisplayMode = useQuotaStore((state) => state.displayMode);
const setUsageAutoRefresh = useQuotaStore((state) => state.setAutoRefresh);
const setUsageRefreshInterval = useQuotaStore((state) => state.setRefreshInterval);
const setUsageDisplayMode = useQuotaStore((state) => state.setDisplayMode);
const showPredValues = useQuotaStore((state) => state.showPredValues);
const setShowPredValues = useQuotaStore((state) => state.setShowPredValues);
const loadUsageSettings = useQuotaStore((state) => state.loadSettings);
React.useEffect(() => {
void loadUsageSettings();
}, [loadUsageSettings]);
const persistUsageSettings = React.useCallback(async (changes: { usageAutoRefresh?: boolean; usageRefreshIntervalMs?: number; usageDisplayMode?: 'usage' | 'remaining'; usageDropdownProviders?: string[]; usageShowPredValues?: boolean }) => {
const persistUsageSettings = React.useCallback(async (changes: { usageDisplayMode?: 'usage' | 'remaining'; usageDropdownProviders?: string[] }) => {
try {
await updateDesktopSettings(changes);
} catch (error) {
@@ -57,20 +49,6 @@ export const UsageSidebar: React.FC<UsageSidebarProps> = ({ onItemSelect }) => {
}
}, []);
const handleUsageAutoRefreshChange = React.useCallback((enabled: boolean) => {
setUsageAutoRefresh(enabled);
void persistUsageSettings({ usageAutoRefresh: enabled });
}, [persistUsageSettings, setUsageAutoRefresh]);
const handleUsageRefreshIntervalChange = React.useCallback((value: string) => {
const next = Number(value);
if (!Number.isFinite(next)) {
return;
}
setUsageRefreshInterval(next);
void persistUsageSettings({ usageRefreshIntervalMs: next });
}, [persistUsageSettings, setUsageRefreshInterval]);
const handleUsageDisplayModeChange = React.useCallback((value: string) => {
if (value !== 'usage' && value !== 'remaining') {
return;
@@ -79,11 +57,6 @@ export const UsageSidebar: React.FC<UsageSidebarProps> = ({ onItemSelect }) => {
void persistUsageSettings({ usageDisplayMode: value });
}, [persistUsageSettings, setUsageDisplayMode]);
const handleShowPredValuesChange = React.useCallback((enabled: boolean) => {
setShowPredValues(enabled);
void persistUsageSettings({ usageShowPredValues: enabled });
}, [persistUsageSettings, setShowPredValues]);
const bgClass = 'bg-background';
return (
@@ -93,34 +66,6 @@ export const UsageSidebar: React.FC<UsageSidebarProps> = ({ onItemSelect }) => {
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">{t('settings.usage.sidebar.total', { count: QUOTA_PROVIDERS.length })}</span>
<div className="flex items-center gap-2">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex">
<Checkbox
checked={usageAutoRefresh}
onChange={handleUsageAutoRefreshChange}
ariaLabel={t('settings.usage.sidebar.actions.toggleAutoRefreshAria')}
/>
</span>
</TooltipTrigger>
<TooltipContent side="bottom">
{t('settings.usage.sidebar.tooltip.autoRefresh')}
</TooltipContent>
</Tooltip>
<Select
value={String(usageRefreshIntervalMs)}
onValueChange={handleUsageRefreshIntervalChange}
disabled={!usageAutoRefresh}
>
<SelectTrigger className="w-fit">
<SelectValue placeholder={t('settings.usage.sidebar.field.intervalPlaceholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="30000">30s</SelectItem>
<SelectItem value="60000">1m</SelectItem>
<SelectItem value="300000">5m</SelectItem>
</SelectContent>
</Select>
<Button size="sm"
variant="ghost"
className="h-7 w-7 px-0 text-muted-foreground"
@@ -145,16 +90,6 @@ export const UsageSidebar: React.FC<UsageSidebarProps> = ({ onItemSelect }) => {
</SelectContent>
</Select>
</div>
<div className="mt-2 flex items-center justify-between gap-2">
<span className="typography-micro text-muted-foreground">
{t('settings.usage.sidebar.field.showPredictions')}
</span>
<Checkbox
checked={showPredValues}
onChange={handleShowPredValuesChange}
ariaLabel={t('settings.usage.sidebar.field.showPredictions')}
/>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2 overflow-x-hidden">