diff --git a/AGENTS.md b/AGENTS.md
index 3aa30b40..a87c1361 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -108,6 +108,30 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
+### Gift Card Redemption
+
+Shakespeare supports automatic gift card redemption via URL parameters. Users can click shareable gift card links to instantly redeem AI credits.
+
+**URL Format:**
+```
+/giftcard#baseURL=&code=
+```
+
+**Flow:**
+1. User clicks gift card link (e.g., from email or social media)
+2. Shakespeare displays a dialog showing the credit amount
+3. URL is rewritten to `/` for privacy (removes gift card code from history)
+4. If user is not logged in or provider is not configured, a multi-step wizard guides them through setup
+5. User can switch between Nostr accounts before redeeming
+6. Credits are added to the user's account via NIP-98 authenticated API call
+
+**Components:**
+- `GiftCardRedeemDialog`: Main dialog handling the entire redemption flow
+- Integrates with existing login/signup dialogs and provider configuration
+- Automatically matches provider baseURL against configured providers and presets
+
+See `GIFTCARD_REDEMPTION.md` for detailed documentation.
+
## AI Message Format
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
diff --git a/README.md b/README.md
index 556c1eac..5eaa2d15 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,7 @@ https://shakespeare.diy
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
- **Buy credits anonymously** with Nostr and Lightning ⚡
+- **Redeem gift cards** with shareable links for instant credits
- **Runs entirely in the browser** No backend required
## How it Works
diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx
index 82e52b44..3ca949d2 100644
--- a/src/AppRouter.tsx
+++ b/src/AppRouter.tsx
@@ -31,6 +31,7 @@ export function AppRouter() {
} />
+ } />
} />
} />
} />
diff --git a/src/components/AddProviderDialog.tsx b/src/components/AddProviderDialog.tsx
index 3b9dfcb3..bc38bbcd 100644
--- a/src/components/AddProviderDialog.tsx
+++ b/src/components/AddProviderDialog.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useRef } from 'react';
-import { Check, Sparkles, ArrowRight, AlertCircle } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
import { useAISettings } from '@/hooks/useAISettings';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { AIProvider } from '@/contexts/AISettingsContext';
@@ -14,6 +15,7 @@ interface AddProviderDialogProps {
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
const scrollableContentRef = useRef(null);
+ const [agreedToTerms, setAgreedToTerms] = useState(false);
const { settings, setProvider } = useAISettings();
@@ -25,27 +27,26 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
existingProvider.nostr === provider.nostr &&
existingProvider.proxy === provider.proxy;
- // Get provider name from presets or fallback to id
- const getProviderName = () => {
- const preset = AI_PROVIDER_PRESETS.find(
- p => p.id === provider.id && p.baseURL === provider.baseURL
- );
- return preset?.name || provider.id;
- };
-
- const providerName = getProviderName();
+ // Get provider preset if available
+ const preset = AI_PROVIDER_PRESETS.find(
+ p => p.id === provider.id && p.baseURL === provider.baseURL
+ );
+ const providerName = preset?.name || provider.id;
const handleAddProvider = () => {
setProvider(provider);
onOpenChange(false);
};
- // Scroll to top when dialog opens
+ // Reset agreed to terms when dialog opens or provider changes
useEffect(() => {
- if (open && scrollableContentRef.current) {
- scrollableContentRef.current.scrollTop = 0;
+ if (open) {
+ setAgreedToTerms(false);
+ if (scrollableContentRef.current) {
+ scrollableContentRef.current.scrollTop = 0;
+ }
}
- }, [open]);
+ }, [open, provider.id]);
return (
+ {/* Terms of Service Agreement */}
+ {preset?.tosURL && (
+
+
+ setAgreedToTerms(checked === true)}
+ />
+
+
+
+ )}
+
-
diff --git a/src/components/GiftCardRedeemDialog.test.tsx b/src/components/GiftCardRedeemDialog.test.tsx
new file mode 100644
index 00000000..343aa479
--- /dev/null
+++ b/src/components/GiftCardRedeemDialog.test.tsx
@@ -0,0 +1,155 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { TestApp } from '@/test/TestApp';
+import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
+
+// Mock fetch
+global.fetch = vi.fn();
+
+describe('GiftCardRedeemDialog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('renders loading state initially', async () => {
+ // Mock the gift card check endpoint
+ (global.fetch as ReturnType).mockImplementation(() =>
+ new Promise(() => {}) // Never resolves to keep it loading
+ );
+
+ render(
+
+ {}}
+ baseURL="https://ai.shakespeare.diy/v1"
+ code="TEST-CODE-1234-5678"
+ />
+
+ );
+
+ // Should show loading skeleton
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ });
+
+ it('shows error for invalid gift card', async () => {
+ // Mock the gift card check endpoint to return an error
+ (global.fetch as ReturnType).mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({
+ error: {
+ message: 'No giftcard found with code "INVALID-CODE"',
+ },
+ }),
+ });
+
+ render(
+
+ {}}
+ baseURL="https://ai.shakespeare.diy/v1"
+ code="INVALID-CODE"
+ />
+
+ );
+
+ // Wait for error message to appear
+ await waitFor(() => {
+ expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
+ });
+ });
+
+ it('shows already redeemed message for redeemed gift card', async () => {
+ // Mock the gift card check endpoint to return a redeemed gift card
+ (global.fetch as ReturnType).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ object: 'giftcard',
+ id: 'gc_123',
+ code: 'TEST-CODE-1234-5678',
+ amount: 25.0,
+ redeemed: true,
+ created_at: 1640995200,
+ }),
+ });
+
+ render(
+
+ {}}
+ baseURL="https://ai.shakespeare.diy/v1"
+ code="TEST-CODE-1234-5678"
+ />
+
+ );
+
+ // Wait for redeemed message to appear
+ await waitFor(() => {
+ expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
+ });
+ });
+
+ it('shows gift card amount for valid unredeemed gift card', async () => {
+ // Mock the gift card check endpoint to return a valid gift card
+ (global.fetch as ReturnType).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ object: 'giftcard',
+ id: 'gc_123',
+ code: 'TEST-CODE-1234-5678',
+ amount: 25.0,
+ redeemed: false,
+ created_at: 1640995200,
+ }),
+ });
+
+ render(
+
+ {}}
+ baseURL="https://ai.shakespeare.diy/v1"
+ code="TEST-CODE-1234-5678"
+ />
+
+ );
+
+ // Wait for gift card amount to appear
+ await waitFor(() => {
+ expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
+ });
+ });
+
+ it('shows provider name when matching preset is found', async () => {
+ // Mock the gift card check endpoint
+ (global.fetch as ReturnType).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ object: 'giftcard',
+ id: 'gc_123',
+ code: 'TEST-CODE-1234-5678',
+ amount: 10.0,
+ redeemed: false,
+ created_at: 1640995200,
+ }),
+ });
+
+ render(
+
+ {}}
+ baseURL="https://ai.shakespeare.diy/v1"
+ code="TEST-CODE-1234-5678"
+ />
+
+ );
+
+ // Wait for provider name to appear
+ await waitFor(() => {
+ expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/src/components/GiftCardRedeemDialog.tsx b/src/components/GiftCardRedeemDialog.tsx
new file mode 100644
index 00000000..f9c5236f
--- /dev/null
+++ b/src/components/GiftCardRedeemDialog.tsx
@@ -0,0 +1,410 @@
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { useMutation, useQuery } from '@tanstack/react-query';
+import { Gift, Check, LogIn, Settings as SettingsIcon } from 'lucide-react';
+import { Dialog, DialogContent } from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useToast } from '@/hooks/useToast';
+import { useCurrentUser } from '@/hooks/useCurrentUser';
+import { useAISettings } from '@/hooks/useAISettings';
+import { createAIClient } from '@/lib/ai-client';
+import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
+import { AccountSwitcher } from '@/components/auth/AccountSwitcher';
+import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog';
+import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog';
+import { AddProviderDialog } from '@/components/AddProviderDialog';
+import { useAppContext } from '@/hooks/useAppContext';
+
+interface GiftCardRedeemDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ baseURL: string;
+ code: string;
+}
+
+interface Giftcard {
+ object: 'giftcard';
+ id: string;
+ code: string;
+ amount: number;
+ redeemed: boolean;
+ created_at?: number;
+}
+
+interface GiftcardRedemption {
+ object: 'giftcard_redemption';
+ amount: number;
+}
+
+type Step = 'preview' | 'login' | 'provider';
+
+/**
+ * Gift Card Redemption Dialog
+ *
+ * This component handles the complete gift card redemption flow, including:
+ * - Fetching gift card details from the provider API
+ * - Multi-step wizard for login and provider setup
+ * - Account switching before redemption
+ * - Automatic provider matching against presets
+ *
+ * Flow:
+ * 1. Check if gift card is valid (unauthenticated API call)
+ * 2. Determine required steps based on user state:
+ * - Not logged in? → Show login step
+ * - Provider not configured? → Show provider setup step
+ * - Ready to redeem? → Show preview with account switcher
+ * 3. Redeem gift card and add credits to user's account
+ * 4. Navigate to AI Settings to show new balance
+ *
+ * @param open - Whether the dialog is open
+ * @param onOpenChange - Callback when dialog open state changes
+ * @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
+ * @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
+ */
+export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
+ const { user } = useCurrentUser();
+ const { settings } = useAISettings();
+ const { config } = useAppContext();
+ const { toast } = useToast();
+ const navigate = useNavigate();
+
+ const [currentStep, setCurrentStep] = useState('preview');
+ const [showLoginDialog, setShowLoginDialog] = useState(false);
+ const [showSignupDialog, setShowSignupDialog] = useState(false);
+ const [showAddProviderDialog, setShowAddProviderDialog] = useState(false);
+
+ // Find matching provider by baseURL
+ const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
+ const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
+
+ // Query gift card details without authentication
+ const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
+ queryKey: ['giftcard-check', baseURL, code],
+ queryFn: async (): Promise => {
+ const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error?.message || 'Failed to fetch gift card details');
+ }
+ return response.json();
+ },
+ enabled: open && !!baseURL && !!code,
+ retry: false,
+ });
+
+ // Mutation for redeeming gift card
+ const redeemMutation = useMutation({
+ mutationFn: async (): Promise => {
+ if (!matchingProvider) {
+ throw new Error('Provider not configured');
+ }
+ const ai = createAIClient(matchingProvider, user, config.corsProxy);
+ return await ai.post('/credits/giftcards/redeem', {
+ body: { code },
+ }) as GiftcardRedemption;
+ },
+ onSuccess: (redemption) => {
+ toast({
+ title: '🎉 Gift card redeemed!',
+ description: `${formatCurrency(redemption.amount)} has been added to your account.`,
+ });
+ onOpenChange(false);
+ // Navigate to AI settings to show the new credits
+ navigate('/settings/ai');
+ },
+ onError: (error: Error) => {
+ toast({
+ title: 'Redemption failed',
+ description: error.message || 'Failed to redeem gift card',
+ variant: 'destructive',
+ });
+ },
+ });
+
+ // Determine current step based on conditions
+ useEffect(() => {
+ if (!open) return;
+
+ // Check if user is logged in and provider is configured
+ const hasUser = !!user;
+ const hasProvider = !!matchingProvider;
+
+ if (hasUser && hasProvider) {
+ setCurrentStep('preview');
+ } else if (!hasUser) {
+ setCurrentStep('login');
+ } else if (!hasProvider) {
+ setCurrentStep('provider');
+ }
+ }, [open, user, matchingProvider]);
+
+ const formatCurrency = (amount: number) => {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }).format(amount);
+ };
+
+ const handleRedeem = () => {
+ // Check prerequisites
+ if (!user) {
+ setCurrentStep('login');
+ return;
+ }
+
+ if (!matchingProvider) {
+ setCurrentStep('provider');
+ return;
+ }
+
+ // All good, redeem the gift card
+ redeemMutation.mutate();
+ };
+
+ const handleLoginSuccess = () => {
+ setShowLoginDialog(false);
+ setShowSignupDialog(false);
+
+ // After login, check if provider is configured
+ if (matchingProvider) {
+ setCurrentStep('preview');
+ } else {
+ setCurrentStep('provider');
+ }
+ };
+
+ const handleProviderAdded = () => {
+ setShowAddProviderDialog(false);
+ setCurrentStep('preview');
+ };
+
+ const handleNext = () => {
+ if (currentStep === 'login') {
+ // User needs to log in
+ setShowSignupDialog(true);
+ } else if (currentStep === 'provider') {
+ // User needs to add provider
+ setShowAddProviderDialog(true);
+ }
+ };
+
+ const handleAddAccountClick = () => {
+ setShowLoginDialog(true);
+ };
+
+ // Error state
+ if (giftcardError) {
+ return (
+
+ );
+ }
+
+ // Loading state
+ if (isLoadingGiftcard) {
+ return (
+
+ );
+ }
+
+ // Already redeemed
+ if (giftcard?.redeemed) {
+ return (
+
+ );
+ }
+
+ return (
+ <>
+
+
+ {/* Login/Signup Dialogs */}
+ setShowLoginDialog(false)}
+ onLogin={handleLoginSuccess}
+ onSignup={() => {
+ setShowLoginDialog(false);
+ setShowSignupDialog(true);
+ }}
+ />
+
+ setShowSignupDialog(false)}
+ onComplete={handleLoginSuccess}
+ onLogin={() => {
+ setShowSignupDialog(false);
+ setShowLoginDialog(true);
+ }}
+ />
+
+ {/* Add Provider Dialog */}
+ {matchingPreset && (
+ {
+ setShowAddProviderDialog(open);
+ if (!open) {
+ // Check if provider was added when dialog closes
+ const wasAdded = settings.providers.some(p => p.baseURL === baseURL);
+ if (wasAdded) {
+ handleProviderAdded();
+ }
+ }
+ }}
+ provider={{
+ id: matchingPreset.id,
+ baseURL: matchingPreset.baseURL,
+ nostr: matchingPreset.nostr,
+ proxy: matchingPreset.proxy,
+ }}
+ />
+ )}
+ >
+ );
+}
diff --git a/src/components/auth/AccountSwitcher.tsx b/src/components/auth/AccountSwitcher.tsx
index 92dce660..6d822181 100644
--- a/src/components/auth/AccountSwitcher.tsx
+++ b/src/components/auth/AccountSwitcher.tsx
@@ -31,7 +31,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
return (
-
+ {getDisplayName(currentUser).charAt(0)}
diff --git a/src/pages/Index.giftcard.test.tsx b/src/pages/Index.giftcard.test.tsx
new file mode 100644
index 00000000..1d12351a
--- /dev/null
+++ b/src/pages/Index.giftcard.test.tsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { TestApp } from '@/test/TestApp';
+import Index from './Index';
+
+// Mock fetch
+global.fetch = vi.fn();
+
+// Mock useLocation and useNavigate
+const mockNavigate = vi.fn();
+const mockLocation = { pathname: '/', hash: '', search: '', state: null, key: 'default' };
+
+vi.mock('react-router-dom', async () => {
+ const actual = await vi.importActual('react-router-dom');
+ return {
+ ...actual,
+ useNavigate: () => mockNavigate,
+ useLocation: () => mockLocation,
+ };
+});
+
+describe('Index - Gift Card URL Handling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockNavigate.mockClear();
+ mockLocation.pathname = '/';
+ mockLocation.hash = '';
+ });
+
+ it('opens gift card dialog when navigating to /giftcard with hash parameters', async () => {
+ // Mock the gift card check endpoint
+ (global.fetch as ReturnType).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ object: 'giftcard',
+ id: 'gc_123',
+ code: 'TEST-CODE-1234-5678',
+ amount: 25.0,
+ redeemed: false,
+ created_at: 1640995200,
+ }),
+ });
+
+ // Set location to /giftcard with hash
+ mockLocation.pathname = '/giftcard';
+ mockLocation.hash = '#baseURL=https://ai.shakespeare.diy/v1&code=TEST-CODE-1234-5678';
+
+ render(
+
+
+
+ );
+
+ // Wait for gift card dialog to appear
+ await waitFor(() => {
+ expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
+ }, { timeout: 3000 });
+
+ // Verify URL was rewritten to '/'
+ expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
+ });
+
+ it('redirects to home when /giftcard has no hash parameters', async () => {
+ // Set location to /giftcard without hash
+ mockLocation.pathname = '/giftcard';
+ mockLocation.hash = '';
+
+ render(
+
+
+
+ );
+
+ // Should redirect to home page
+ await waitFor(() => {
+ expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
+ });
+ });
+
+ it('redirects to home when /giftcard has incomplete hash parameters', async () => {
+ // Set location to /giftcard with incomplete hash
+ mockLocation.pathname = '/giftcard';
+ mockLocation.hash = '#baseURL=https://ai.shakespeare.diy/v1';
+
+ render(
+
+
+
+ );
+
+ // Should redirect to home page
+ await waitFor(() => {
+ expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
+ });
+ });
+});
diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx
index 2ef64c6a..befeed5d 100644
--- a/src/pages/Index.tsx
+++ b/src/pages/Index.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useAIProjectId } from '@/hooks/useAIProjectId';
@@ -11,6 +11,7 @@ import { useAppContext } from '@/hooks/useAppContext';
import { AppLayout } from '@/components/AppLayout';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Act1Dialog } from '@/components/Act1Dialog';
+import { GiftCardRedeemDialog } from '@/components/GiftCardRedeemDialog';
import { Quilly } from '@/components/Quilly';
import { DotAI } from '@/lib/DotAI';
import type { AIMessage } from '@/lib/SessionManager';
@@ -32,7 +33,11 @@ export default function Index() {
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
const [showOnboarding, setShowOnboarding] = useState(false);
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
+ const [showGiftCardDialog, setShowGiftCardDialog] = useState(false);
+ const [giftCardBaseURL, setGiftCardBaseURL] = useState('');
+ const [giftCardCode, setGiftCardCode] = useState('');
const navigate = useNavigate();
+ const location = useLocation();
const projectsManager = useProjectsManager();
const { fs } = useFS();
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
@@ -75,6 +80,31 @@ export default function Index() {
}
}, []);
+ // Handle gift card redemption from URL
+ useEffect(() => {
+ // Check if we're on the /giftcard route
+ if (location.pathname === '/giftcard') {
+ // Parse hash parameters
+ const hash = location.hash.slice(1); // Remove the '#'
+ const params = new URLSearchParams(hash);
+ const baseURL = params.get('baseURL');
+ const code = params.get('code');
+
+ if (baseURL && code) {
+ // Store the gift card details
+ setGiftCardBaseURL(baseURL);
+ setGiftCardCode(code);
+ setShowGiftCardDialog(true);
+
+ // Rewrite URL to '/' for privacy
+ navigate('/', { replace: true });
+ } else {
+ // Invalid gift card URL, just navigate to home
+ navigate('/', { replace: true });
+ }
+ }
+ }, [location, navigate]);
+
// Sync prompt with local storage
const handlePromptChange = (e: React.ChangeEvent) => {
const newPrompt = e.target.value;
@@ -399,6 +429,16 @@ export default function Index() {
open={showAct1Dialog}
onOpenChange={setShowAct1Dialog}
/>
+
+ {/* Gift Card Redeem Dialog */}
+ {giftCardBaseURL && giftCardCode && (
+
+ )}
>
);
}
\ No newline at end of file