diff --git a/src/components/CreditsBadge.test.tsx b/src/components/CreditsBadge.test.tsx new file mode 100644 index 00000000..e1662bfc --- /dev/null +++ b/src/components/CreditsBadge.test.tsx @@ -0,0 +1,128 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { CreditsBadge } from './CreditsBadge'; +import { TestApp } from '@/test/TestApp'; +import type { AIConnection } from '@/contexts/AISettingsContext'; + +// Mock the useAICredits hook +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: vi.fn(), +})); + +import { useAICredits } from '@/hooks/useAICredits'; +const mockUseAICredits = vi.mocked(useAICredits); + +describe('CreditsBadge', () => { + const mockConnection: AIConnection = { + baseURL: 'https://api.example.com/v1', + apiKey: 'test-key', + }; + + it('should render credits badge with formatted amount', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 25.50 }, + isLoading: false, + error: null, + isSuccess: true, + isError: false, + } as any); + + render( + + + + ); + + expect(screen.getByText('$25.50')).toBeInTheDocument(); + }); + + it('should not render anything when loading', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: true, + error: null, + isSuccess: false, + isError: false, + } as any); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('should not render anything when there is an error', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: new Error('Failed to fetch'), + isSuccess: false, + isError: true, + } as any); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('should not render anything when no credits data is available', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: null, + isSuccess: true, + isError: false, + } as any); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('should format large amounts correctly', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 1234.56 }, + isLoading: false, + error: null, + isSuccess: true, + isError: false, + } as any); + + render( + + + + ); + + expect(screen.getByText('$1,234.56')).toBeInTheDocument(); + }); + + it('should format zero amounts correctly', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 0 }, + isLoading: false, + error: null, + isSuccess: true, + isError: false, + } as any); + + render( + + + + ); + + expect(screen.getByText('$0.00')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/CreditsBadge.tsx b/src/components/CreditsBadge.tsx new file mode 100644 index 00000000..850c955a --- /dev/null +++ b/src/components/CreditsBadge.tsx @@ -0,0 +1,40 @@ +import { Badge } from '@/components/ui/badge'; +import { useAICredits } from '@/hooks/useAICredits'; +import type { AIConnection } from '@/contexts/AISettingsContext'; + +interface CreditsBadgeProps { + providerId: string; + connection: AIConnection; + className?: string; +} + +/** + * Displays a credits badge showing the remaining credits for an AI provider + */ +export function CreditsBadge({ providerId, connection, className }: CreditsBadgeProps) { + const { data: credits, isLoading, error } = useAICredits(providerId, connection); + + // Don't render anything if there's an error (provider doesn't support credits endpoint) + if (error || isLoading) { + return null; + } + + // Don't render if no credits data is available + if (!credits) { + return null; + } + + // Format the amount as currency + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(credits.amount); + + return ( + + {formattedAmount} + + ); +} \ No newline at end of file diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts new file mode 100644 index 00000000..b0be9785 --- /dev/null +++ b/src/hooks/useAICredits.ts @@ -0,0 +1,67 @@ +import { useQuery } from '@tanstack/react-query'; +import { z } from 'zod'; +import { createAIClient } from '@/lib/ai-client'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import type { AIConnection } from '@/contexts/AISettingsContext'; + +// Zod schemas for the two possible response formats +const creditsResponseV1Schema = z.object({ + object: z.literal('credits'), + amount: z.number(), +}); + +const creditsResponseV2Schema = z.object({ + data: z.object({ + total_credits: z.number(), + total_usage: z.number(), + }), +}); + +// Union schema to handle both response formats +const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]); + +// Normalized response type (always in V1 format) +export interface CreditsResponse { + object: 'credits'; + amount: number; +} + +/** + * Custom hook to fetch AI provider credits + * @param providerId - The ID of the AI provider + * @param connection - The AI connection configuration + * @returns Query result with credits information + */ +export function useAICredits(providerId: string, connection: AIConnection) { + const { user } = useCurrentUser(); + + return useQuery({ + queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryFn: async (): Promise => { + try { + const ai = createAIClient(connection, user); + const data = await ai.get('/credits'); + + // Validate and normalize the response + const parsed = creditsResponseSchema.parse(data); + + // Convert V2 format to V1 format if needed + if ('data' in parsed) { + return { + object: 'credits', + amount: parsed.data.total_credits - parsed.data.total_usage, + }; + } + + // Already in V1 format + return parsed; + } catch (error) { + console.error('Error fetching AI credits:', error); + throw error; + } + }, + retry: false, // Don't retry as not all providers support this endpoint + refetchOnWindowFocus: false, + staleTime: 5 * 60 * 1000, // 5 minutes + }); +} \ No newline at end of file diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index 3e59ce38..36b2ee9c 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -6,8 +6,8 @@ import { Input } from '@/components/ui/input'; import { PasswordInput } from '@/components/ui/password-input'; import { Label } from '@/components/ui/label'; import { Separator } from '@/components/ui/separator'; -import { Badge } from '@/components/ui/badge'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; +import { CreditsBadge } from '@/components/CreditsBadge'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { useAISettings } from '@/hooks/useAISettings'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -193,7 +193,6 @@ export function AISettings() { {configuredProviderIds.map((providerId) => { const preset = PRESET_PROVIDERS.find(p => p.id === providerId); const provider = settings.providers[providerId]; - const isCustom = !preset; return ( @@ -203,19 +202,21 @@ export function AISettings() { {preset?.name || providerId} - {isCustom && {t('custom')}} - { - e.stopPropagation(); - handleRemoveProvider(providerId); - }} - className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent" - > - - + + + { + e.stopPropagation(); + handleRemoveProvider(providerId); + }} + className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent" + > + + +