import { useState, useEffect, useMemo, useCallback } from 'react'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Button } from '@/components/ui/button'; import { RefreshCw, AlertTriangle, CheckCircle, XCircle, Clock, ExternalLink } from 'lucide-react'; import { cn } from '@/lib/utils'; import { getElectronAPI } from '@/lib/electron'; import { useAppStore } from '@/store/app-store'; import { useSetupStore } from '@/store/setup-store'; // Error codes for distinguishing failure modes const ERROR_CODES = { API_BRIDGE_UNAVAILABLE: 'API_BRIDGE_UNAVAILABLE', AUTH_ERROR: 'AUTH_ERROR', NOT_AVAILABLE: 'NOT_AVAILABLE', UNKNOWN: 'UNKNOWN', } as const; type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]; type UsageError = { code: ErrorCode; message: string; }; // Fixed refresh interval (45 seconds) const REFRESH_INTERVAL_SECONDS = 45; // Helper to format reset time function formatResetTime(unixTimestamp: number): string { const date = new Date(unixTimestamp * 1000); const now = new Date(); const diff = date.getTime() - now.getTime(); // If less than 1 hour, show minutes if (diff < 3600000) { const mins = Math.ceil(diff / 60000); return `Resets in ${mins}m`; } // If less than 24 hours, show hours and minutes if (diff < 86400000) { const hours = Math.floor(diff / 3600000); const mins = Math.ceil((diff % 3600000) / 60000); return `Resets in ${hours}h ${mins > 0 ? `${mins}m` : ''}`; } // Otherwise show date return `Resets ${date.toLocaleDateString()} at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`; } // Helper to format window duration function getWindowLabel(durationMins: number): { title: string; subtitle: string } { if (durationMins < 60) { return { title: `${durationMins}min Window`, subtitle: 'Rate limit' }; } if (durationMins < 1440) { const hours = Math.round(durationMins / 60); return { title: `${hours}h Window`, subtitle: 'Rate limit' }; } const days = Math.round(durationMins / 1440); return { title: `${days}d Window`, subtitle: 'Rate limit' }; } export function CodexUsagePopover() { const { codexUsage, codexUsageLastUpdated, setCodexUsage } = useAppStore(); const codexAuthStatus = useSetupStore((state) => state.codexAuthStatus); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // Check if Codex is authenticated const isCodexAuthenticated = codexAuthStatus?.authenticated; // Check if data is stale (older than 2 minutes) const isStale = useMemo(() => { return !codexUsageLastUpdated || Date.now() - codexUsageLastUpdated > 2 * 60 * 1000; }, [codexUsageLastUpdated]); const fetchUsage = useCallback( async (isAutoRefresh = false) => { if (!isAutoRefresh) setLoading(true); setError(null); try { const api = getElectronAPI(); if (!api.codex) { setError({ code: ERROR_CODES.API_BRIDGE_UNAVAILABLE, message: 'Codex API bridge not available', }); return; } const data = await api.codex.getUsage(); if ('error' in data) { // Check if it's the "not available" error if ( data.message?.includes('not available') || data.message?.includes('does not provide') ) { setError({ code: ERROR_CODES.NOT_AVAILABLE, message: data.message || data.error, }); } else { setError({ code: ERROR_CODES.AUTH_ERROR, message: data.message || data.error, }); } return; } setCodexUsage(data); } catch (err) { setError({ code: ERROR_CODES.UNKNOWN, message: err instanceof Error ? err.message : 'Failed to fetch usage', }); } finally { if (!isAutoRefresh) setLoading(false); } }, [setCodexUsage] ); // Auto-fetch on mount if data is stale (only if authenticated) useEffect(() => { if (isStale && isCodexAuthenticated) { fetchUsage(true); } }, [isStale, isCodexAuthenticated, fetchUsage]); useEffect(() => { // Skip if not authenticated if (!isCodexAuthenticated) return; // Initial fetch when opened if (open) { if (!codexUsage || isStale) { fetchUsage(); } } // Auto-refresh interval (only when open) let intervalId: NodeJS.Timeout | null = null; if (open) { intervalId = setInterval(() => { fetchUsage(true); }, REFRESH_INTERVAL_SECONDS * 1000); } return () => { if (intervalId) clearInterval(intervalId); }; }, [open, codexUsage, isStale, isCodexAuthenticated, fetchUsage]); // Derived status color/icon helper const getStatusInfo = (percentage: number) => { if (percentage >= 75) return { color: 'text-red-500', icon: XCircle, bg: 'bg-red-500' }; if (percentage >= 50) return { color: 'text-orange-500', icon: AlertTriangle, bg: 'bg-orange-500' }; return { color: 'text-green-500', icon: CheckCircle, bg: 'bg-green-500' }; }; // Helper component for the progress bar const ProgressBar = ({ percentage, colorClass }: { percentage: number; colorClass: string }) => (
); const UsageCard = ({ title, subtitle, percentage, resetText, isPrimary = false, stale = false, }: { title: string; subtitle: string; percentage: number; resetText?: string; isPrimary?: boolean; stale?: boolean; }) => { const isValidPercentage = typeof percentage === 'number' && !isNaN(percentage) && isFinite(percentage); const safePercentage = isValidPercentage ? percentage : 0; const status = getStatusInfo(safePercentage); const StatusIcon = status.icon; return (

{title}

{subtitle}

{isValidPercentage ? (
{Math.round(safePercentage)}%
) : ( N/A )}
{resetText && (

{resetText}

)}
); }; // Header Button const maxPercentage = codexUsage?.rateLimits ? Math.max( codexUsage.rateLimits.primary?.usedPercent || 0, codexUsage.rateLimits.secondary?.usedPercent || 0 ) : 0; const getProgressBarColor = (percentage: number) => { if (percentage >= 80) return 'bg-red-500'; if (percentage >= 50) return 'bg-yellow-500'; return 'bg-green-500'; }; const trigger = ( ); return ( {trigger} {/* Header */}
Codex Usage
{error && error.code !== ERROR_CODES.NOT_AVAILABLE && ( )}
{/* Content */}
{error ? (

{error.code === ERROR_CODES.NOT_AVAILABLE ? 'Usage not available' : error.message}

{error.code === ERROR_CODES.API_BRIDGE_UNAVAILABLE ? ( 'Ensure the Electron bridge is running or restart the app' ) : error.code === ERROR_CODES.NOT_AVAILABLE ? ( <> Codex CLI doesn't provide usage statistics. Check{' '} OpenAI dashboard {' '} for usage details. ) : ( <> Make sure Codex CLI is installed and authenticated via{' '} codex login )}

) : !codexUsage ? ( // Loading state

Loading usage data...

) : codexUsage.rateLimits ? ( <> {/* Primary Window Card */} {codexUsage.rateLimits.primary && ( )} {/* Secondary Window Card */} {codexUsage.rateLimits.secondary && ( )} {/* Plan Type */} {codexUsage.rateLimits.planType && (

Plan:{' '} {codexUsage.rateLimits.planType.charAt(0).toUpperCase() + codexUsage.rateLimits.planType.slice(1)}

)} ) : (

No usage data available

)}
{/* Footer */}
OpenAI Dashboard Updates every minute
); }