import { useState, useEffect, useMemo } from 'react'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Button } from '@/components/ui/button'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { RefreshCw, AlertTriangle, CheckCircle, XCircle, Clock, ExternalLink } from 'lucide-react'; import { Spinner } from '@/components/ui/spinner'; import { cn } from '@/lib/utils'; import { useSetupStore } from '@/store/setup-store'; import { AnthropicIcon, OpenAIIcon } from '@/components/ui/provider-icon'; import { useClaudeUsage, useCodexUsage } from '@/hooks/queries'; // Error codes for distinguishing failure modes const ERROR_CODES = { API_BRIDGE_UNAVAILABLE: 'API_BRIDGE_UNAVAILABLE', AUTH_ERROR: 'AUTH_ERROR', NOT_AVAILABLE: 'NOT_AVAILABLE', TRUST_PROMPT: 'TRUST_PROMPT', UNKNOWN: 'UNKNOWN', } as const; type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]; type UsageError = { code: ErrorCode; message: string; }; const CLAUDE_SESSION_WINDOW_HOURS = 5; // Helper to format reset time for Codex function formatCodexResetTime(unixTimestamp: number): string { const date = new Date(unixTimestamp * 1000); const now = new Date(); const diff = date.getTime() - now.getTime(); if (diff < 3600000) { const mins = Math.ceil(diff / 60000); return `Resets in ${mins}m`; } 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` : ''}`; } return `Resets ${date.toLocaleDateString()} at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`; } // Helper to format window duration for Codex function getCodexWindowLabel(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 UsagePopover() { const claudeAuthStatus = useSetupStore((state) => state.claudeAuthStatus); const codexAuthStatus = useSetupStore((state) => state.codexAuthStatus); const [open, setOpen] = useState(false); const [activeTab, setActiveTab] = useState<'claude' | 'codex'>('claude'); // Check authentication status const isClaudeAuthenticated = !!claudeAuthStatus?.authenticated; const isCodexAuthenticated = codexAuthStatus?.authenticated; // Use React Query hooks for usage data // Only enable polling when popover is open AND the tab is active const { data: claudeUsage, isLoading: claudeLoading, error: claudeQueryError, dataUpdatedAt: claudeUsageLastUpdated, refetch: refetchClaude, } = useClaudeUsage(open && activeTab === 'claude' && isClaudeAuthenticated); const { data: codexUsage, isLoading: codexLoading, error: codexQueryError, dataUpdatedAt: codexUsageLastUpdated, refetch: refetchCodex, } = useCodexUsage(open && activeTab === 'codex' && isCodexAuthenticated); // Parse errors into structured format const claudeError = useMemo((): UsageError | null => { if (!claudeQueryError) return null; const message = claudeQueryError instanceof Error ? claudeQueryError.message : String(claudeQueryError); // Detect trust prompt error const isTrustPrompt = message.includes('Trust prompt') || message.includes('folder permission'); if (isTrustPrompt) { return { code: ERROR_CODES.TRUST_PROMPT, message }; } if (message.includes('API bridge')) { return { code: ERROR_CODES.API_BRIDGE_UNAVAILABLE, message }; } return { code: ERROR_CODES.AUTH_ERROR, message }; }, [claudeQueryError]); const codexError = useMemo((): UsageError | null => { if (!codexQueryError) return null; const message = codexQueryError instanceof Error ? codexQueryError.message : String(codexQueryError); if (message.includes('not available') || message.includes('does not provide')) { return { code: ERROR_CODES.NOT_AVAILABLE, message }; } if (message.includes('API bridge')) { return { code: ERROR_CODES.API_BRIDGE_UNAVAILABLE, message }; } return { code: ERROR_CODES.AUTH_ERROR, message }; }, [codexQueryError]); // Determine which tab to show by default useEffect(() => { if (isClaudeAuthenticated) { setActiveTab('claude'); } else if (isCodexAuthenticated) { setActiveTab('codex'); } }, [isClaudeAuthenticated, isCodexAuthenticated]); // Check if data is stale (older than 2 minutes) const isClaudeStale = useMemo(() => { return !claudeUsageLastUpdated || Date.now() - claudeUsageLastUpdated > 2 * 60 * 1000; }, [claudeUsageLastUpdated]); const isCodexStale = useMemo(() => { return !codexUsageLastUpdated || Date.now() - codexUsageLastUpdated > 2 * 60 * 1000; }, [codexUsageLastUpdated]); // Refetch functions for manual refresh const fetchClaudeUsage = () => refetchClaude(); const fetchCodexUsage = () => refetchCodex(); // 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}

)}
); }; // Calculate max percentage for header button const claudeSessionPercentage = claudeUsage?.sessionPercentage || 0; const getProgressBarColor = (percentage: number) => { if (percentage >= 80) return 'bg-red-500'; if (percentage >= 50) return 'bg-yellow-500'; return 'bg-green-500'; }; const codexPrimaryWindowMinutes = codexUsage?.rateLimits?.primary?.windowDurationMins ?? null; const codexSecondaryWindowMinutes = codexUsage?.rateLimits?.secondary?.windowDurationMins ?? null; const codexWindowMinutes = codexSecondaryWindowMinutes && codexPrimaryWindowMinutes ? Math.min(codexPrimaryWindowMinutes, codexSecondaryWindowMinutes) : (codexSecondaryWindowMinutes ?? codexPrimaryWindowMinutes); const codexWindowLabel = codexWindowMinutes ? getCodexWindowLabel(codexWindowMinutes).title : 'Window'; const codexWindowUsage = codexWindowMinutes === codexSecondaryWindowMinutes ? codexUsage?.rateLimits?.secondary?.usedPercent : codexUsage?.rateLimits?.primary?.usedPercent; // Determine which provider icon and percentage to show based on active tab const indicatorInfo = activeTab === 'claude' ? { icon: AnthropicIcon, percentage: claudeSessionPercentage, isStale: isClaudeStale, title: `Session usage (${CLAUDE_SESSION_WINDOW_HOURS}h window)`, } : { icon: OpenAIIcon, percentage: codexWindowUsage ?? 0, isStale: isCodexStale, title: `Usage (${codexWindowLabel})`, }; const statusColor = getStatusInfo(indicatorInfo.percentage).color; const ProviderIcon = indicatorInfo.icon; const trigger = ( ); // Determine which tabs to show const showClaudeTab = isClaudeAuthenticated; const showCodexTab = isCodexAuthenticated; return ( {trigger} setActiveTab(v as 'claude' | 'codex')}> {/* Tabs Header */} {showClaudeTab && showCodexTab && ( Claude Codex )} {/* Claude Tab Content */} {/* Header */}
Claude Usage
{claudeError && ( )}
{/* Content */}
{claudeError ? (

{claudeError.message}

{claudeError.code === ERROR_CODES.API_BRIDGE_UNAVAILABLE ? ( 'Ensure the Electron bridge is running or restart the app' ) : claudeError.code === ERROR_CODES.TRUST_PROMPT ? ( <> Run claude in your terminal and approve access to continue ) : ( <> Make sure Claude CLI is installed and authenticated via{' '} claude login )}

) : !claudeUsage ? (

Loading usage data...

) : ( <>
{claudeUsage.costLimit && claudeUsage.costLimit > 0 && ( 0 ? ((claudeUsage.costUsed ?? 0) / claudeUsage.costLimit) * 100 : 0 } stale={isClaudeStale} /> )} )}
{/* Footer */}
Claude Status Updates every minute
{/* Codex Tab Content */} {/* Header */}
Codex Usage
{codexError && codexError.code !== ERROR_CODES.NOT_AVAILABLE && ( )}
{/* Content */}
{codexError ? (

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

{codexError.code === ERROR_CODES.API_BRIDGE_UNAVAILABLE ? ( 'Ensure the Electron bridge is running or restart the app' ) : codexError.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 usage data...

) : codexUsage.rateLimits ? ( <> {codexUsage.rateLimits.primary && ( )} {codexUsage.rateLimits.secondary && ( )} {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
); }