mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Display provider credits in the UI
This commit is contained in:
4 files changed
+250
-14
No files matched your search
@@ -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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<CreditsBadge providerId="test-provider" connection={mockConnection} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$0.00')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<Badge variant="secondary" className={className}>
|
||||
{formattedAmount}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -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<CreditsResponse> => {
|
||||
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
|
||||
});
|
||||
}
|
||||
+15
-14
@@ -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 (
|
||||
<AccordionItem key={providerId} value={providerId} className="border rounded-lg">
|
||||
@@ -203,19 +202,21 @@ export function AISettings() {
|
||||
<span className="font-medium">
|
||||
{preset?.name || providerId}
|
||||
</span>
|
||||
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveProvider(providerId);
|
||||
}}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditsBadge providerId={providerId} connection={provider} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveProvider(providerId);
|
||||
}}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
|
||||
Reference in new issue
Block a user