diff --git a/.gitignore b/.gitignore index 086cb28e..ad625af1 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ dist dist-ssr *.local .ai-history/ +*.apk +*.aab # Editor directories and files .idea @@ -30,3 +32,4 @@ dist-ssr .env.* !.env.example .ai/ +*.keystore diff --git a/.vscode/settings.json b/.vscode/settings.json index 0a770118..e0eaa2f0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "editor.tabSize": 2 -} \ No newline at end of file + "editor.tabSize": 2, + "editor.insertSpaces": true +} diff --git a/README.md b/README.md index 5cb1e23b..cd584ebb 100644 --- a/README.md +++ b/README.md @@ -1,85 +1,38 @@ -# Shakespeare - AI-Powered Nostr Website Builder +# Shakespeare 🎭 -Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it. +[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git) + +AI-powered Nostr website builder. Describe what you want to build, and AI helps you create it. + +https://shakespeare.diy ## Features -- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website -- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting -- **Project Management**: Create and manage multiple projects with sidebar navigation -- **Real-time Editing**: Edit files directly in the browser with syntax highlighting -- **File Explorer**: Browse and manage your project files -- **Project Preview**: Preview your website as you build it -- **Template Cloning**: Start from a pre-configured Nostr template +- **AI Chat**: Build websites through natural conversation +- **File Attachments**: Drag & drop files or paste images +- **Live Preview**: See changes in real-time +- **Code Editor**: Edit files with syntax highlighting +- **Git Integration**: Full version control with credential management +- **Nostr Ready**: Built-in Nostr protocol support + +## Quick Start + +1. **Describe** your project in the textarea +2. **Chat** with AI to build features +3. **Preview** your website instantly +4. **Deploy** with one click + +## Tech Stack + +- React 18 + TypeScript +- Vite + TailwindCSS +- shadcn/ui + Nostrify +- LightningFS + isomorphic-git ## Getting Started -1. **Create a Project**: Enter a description of what you want to build in the prompt textarea -2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website -3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename" -4. **Edit Code**: Switch to the code view to manually edit files if needed -5. **Preview**: View your website in the preview pane +Visit the homepage, enter your project idea, and start building with AI assistance. -## Project Structure +## License -Each project includes: -- React 18 with TypeScript -- Vite for building -- TailwindCSS for styling -- Nostrify for Nostr integration -- shadcn/ui components - -## AI Capabilities - -The AI assistant can: -- Read and write project files -- Add new components and pages -- Configure Nostr functionality -- Build the project -- Search through files -- Provide project structure overview -- Add and remove npm packages -- Install dependencies and dev dependencies - -## Usage - -1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar -2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right -3. **File Explorer**: Navigate your project files in the code view -4. **File Editor**: Edit files with syntax highlighting and save changes - -## Git Integration - -Shakespeare includes full Git functionality with credential management: - -### Features -- **Version Control**: Full Git repository support with commit history and branch management -- **Global Credentials**: Configure Git credentials once and use them across all projects -- **Automatic Matching**: Credentials are automatically matched to repository origins -- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers -- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB - -### Setting Up Git Credentials - -1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option -2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider -3. **Enter Token**: Use your username and personal access token for authentication -4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories - -### Repository Operations - -- **Push/Pull**: Sync changes with remote repositories using configured credentials -- **Status Monitoring**: Real-time Git status with file changes and sync information -- **Commit History**: View commit history and repository information -- **Branch Management**: Work with different branches and track remote changes - -## Development - -Built with: -- React 18 -- TypeScript -- Vite -- TailwindCSS -- shadcn/ui -- LightningFS for filesystem -- isomorphic-git for template cloning \ No newline at end of file +AGPLv3 \ No newline at end of file diff --git a/eslint.config.js b/eslint.config.js index 1e1fc7fd..53b7e435 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -40,11 +40,18 @@ export default tseslint.config( "ignoreRestSiblings": true, }, ], + "indent": [ + "warn", + 2, + { SwitchCase: 1 }, + ], + "no-tabs": "warn", "custom/no-placeholder-comments": "error", "no-warning-comments": [ "error", { terms: ["fixme"] }, ], + "no-control-regex": "off", // Allow ANSI escape sequences in regex }, }, { diff --git a/index.html b/index.html index 752478ff..2db63cd7 100644 --- a/index.html +++ b/index.html @@ -3,13 +3,15 @@ + + Shakespeare - AI-Powered Nostr Development - + diff --git a/package-lock.json b/package-lock.json index 2d331915..8aea64c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -79,6 +79,7 @@ "streamdown": "~1.0.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "tailwindcss-safe-area": "^0.8.0", "turndown": "^7.2.1", "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", @@ -4668,9 +4669,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001716", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz", - "integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==", + "version": "1.0.30001746", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz", + "integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==", "dev": true, "funding": [ { @@ -10092,6 +10093,21 @@ "tailwindcss": ">=3.0.0 || insiders" } }, + "node_modules/tailwindcss-safe-area": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/tailwindcss-safe-area/-/tailwindcss-safe-area-0.8.0.tgz", + "integrity": "sha512-OIKZfSvinI9kZ3hduoSxqP8EfW2rXoKvHnNyTDY2zwem06IIRtLcKdMe0nF98o+Xluk5Fy7mmesr1rSXg/wkhA==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/mvllow" + }, + "peerDependencies": { + "tailwindcss": "^2.0.0 || >=3.0.0" + } + }, "node_modules/tailwindcss/node_modules/postcss-selector-parser": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", diff --git a/package.json b/package.json index 8761be75..cfb24d13 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,7 @@ "streamdown": "~1.0.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "tailwindcss-safe-area": "^0.8.0", "turndown": "^7.2.1", "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index f30b2c96..ed0d3952 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -8,12 +8,12 @@ "theme_color": "#000000", "icons": [ { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "192x192", "type": "image/png" }, { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "512x512", "type": "image/png" } diff --git a/public/favicon.png b/public/shakespeare.png similarity index 100% rename from public/favicon.png rename to public/shakespeare.png diff --git a/public/shakespeare.svg b/public/shakespeare.svg new file mode 100644 index 00000000..7eba08b6 --- /dev/null +++ b/public/shakespeare.svg @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/App.tsx b/src/App.tsx index b3944f7d..bd3cd3eb 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,8 +16,10 @@ import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { SessionManagerProvider } from '@/components/SessionManagerProvider'; import { FSProvider } from '@/components/FSProvider'; +import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; +import { DynamicFavicon } from '@/components/DynamicFavicon'; import AppRouter from './AppRouter'; @@ -38,7 +40,7 @@ const queryClient = new QueryClient({ }); const defaultConfig: AppConfig = { - theme: "light", + theme: "system", relayUrl: "wss://relay.primal.net", deployServer: "shakespeare.wtf", }; @@ -73,22 +75,25 @@ export function App() { - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index c0d70908..5558d2db 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -11,7 +11,7 @@ import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; import DataSettings from "./pages/DataSettings"; import AboutSettings from "./pages/AboutSettings"; -import EmailSettings from "./pages/EmailSettings"; + import GitHubOAuth from "./pages/GitHubOAuth"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; @@ -34,7 +34,6 @@ export function AppRouter() { } /> } /> } /> - } /> } /> } /> diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index f850d900..952addbb 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,6 +1,6 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; -import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react'; +import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; @@ -69,8 +69,8 @@ export const AIMessageItem = memo(({ case 'text_editor_view': { const title = args.path ? (args.start_line || args.end_line - ? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})` - : `Viewed ${args.path}`) + ? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})` + : `Viewed ${args.path}`) : 'Viewed File'; return { icon: Eye, title }; } @@ -150,6 +150,11 @@ export const AIMessageItem = memo(({ icon: CheckCircle, title: 'TypeScript' }; + case 'read_console_messages': + return { + icon: Logs, + title: 'Read Console' + }; default: return { icon: Wrench, diff --git a/src/components/Act1Dialog.tsx b/src/components/Act1Dialog.tsx index 5cdeade2..e31611b7 100644 --- a/src/components/Act1Dialog.tsx +++ b/src/components/Act1Dialog.tsx @@ -5,9 +5,9 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; -import { useAISettings } from '@/hooks/useAISettings'; +// import { useAISettings } from '@/hooks/useAISettings'; import { useAICredits } from '@/hooks/useAICredits'; -import { useLocalStorage } from '@/hooks/useLocalStorage'; +// import { useLocalStorage } from '@/hooks/useLocalStorage'; interface Act1DialogProps { open: boolean; @@ -22,44 +22,39 @@ const SHAKESPEARE_PROVIDER = { nostr: true, }; -const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; +// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { const [step, setStep] = useState('welcome'); - const [isSettingUp, setIsSettingUp] = useState(false); - const { setProvider, updateSettings } = useAISettings(); + // const { setProvider, updateSettings } = useAISettings(); - // Get the selectedNSPAddr from localStorage - const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); + // // Get the selectedNSPAddr from localStorage + // const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); // Get user's credits const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER); const handleGetStarted = async () => { - setIsSettingUp(true); - try { - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // // Add Shakespeare provider to their config + // setProvider(SHAKESPEARE_PROVIDER); - // Configure recently used models based on credits or NSP - const hasCredits = creditsData?.amount && creditsData.amount > 0; - const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; + // // Configure recently used models based on credits or NSP + // const hasCredits = creditsData?.amount && creditsData.amount > 0; + // const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; - if (hasCredits || hasMKStackNSP) { - // User has credits or MKStack NSP - set to shakespeare model - updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); - } else { - // No credits - set to tybalt model (free) - updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); - } + // if (hasCredits || hasMKStackNSP) { + // // User has credits or MKStack NSP - set to shakespeare model + // updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); + // } else { + // // No credits - set to tybalt model (free) + // updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); + // } // Move to migration step setStep('migration'); } catch (error) { console.error('Failed to configure Shakespeare provider:', error); - } finally { - setIsSettingUp(false); } }; @@ -87,7 +82,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { useEffect(() => { if (open) { setStep('welcome'); - setIsSettingUp(false); } }, [open]); @@ -126,12 +120,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { )} - - {step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'} - {step === 'migration' && 'Migrating Your Projects'} - {step === 'credits' && 'Your Credits'} - {step === 'conclusion' && "You're All Set!"} - @@ -197,21 +185,10 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { )} @@ -343,14 +320,7 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {

Welcome to the Future!

- You're all set up with Act 2! Your AI assistant is configured - and ready to help you build amazing Nostr applications. -

-
- -
-

- "Create a decentralized social media app with custom feeds and real-time messaging..." + You're all up to speed with Act 2! Get ready to build amazing Nostr applications.

diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx index f58455e0..69311d9a 100644 --- a/src/components/AppLayout.tsx +++ b/src/components/AppLayout.tsx @@ -18,7 +18,6 @@ interface AppLayoutProps { export function AppLayout({ children, selectedProject = null, - title = "Shakespeare", showSidebar = true, headerContent }: AppLayoutProps) { @@ -73,23 +72,22 @@ export function AppLayout({ return (
{/* Mobile Header */} -
-
- {showSidebar && ( - - )} -

- {title} -

+
+
+
+ {showSidebar && ( + + )} +
+ {headerContent}
- {headerContent}
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */} diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx new file mode 100644 index 00000000..3ef2b767 --- /dev/null +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -0,0 +1,152 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { ReactNode } from 'react'; +import { ConsoleErrorProvider } from './ConsoleErrorProvider'; +import { useConsoleError } from '@/hooks/useConsoleError'; +import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages'; + +// Wrapper component for testing +function TestWrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +describe('ConsoleErrorProvider', () => { + beforeEach(() => { + clearConsoleMessages(); + }); + + it('should provide initial state with no errors', () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + expect(result.current.hasErrors).toBe(false); + expect(result.current.consoleError).toBeNull(); + }); + + it('should update hasErrors when console error is added', async () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + expect(result.current.hasErrors).toBe(false); + + // Add an error message + act(() => { + addConsoleMessage('error', 'Test error message'); + }); + + expect(result.current.hasErrors).toBe(true); + expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError); + expect(result.current.consoleError?.message).toBe('Console error detected: Test error message'); + }); + + it('should not update hasErrors for non-error messages', async () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add non-error messages + act(() => { + addConsoleMessage('log', 'Test log message'); + addConsoleMessage('warn', 'Test warning message'); + addConsoleMessage('info', 'Test info message'); + }); + + expect(result.current.hasErrors).toBe(false); + expect(result.current.consoleError).toBeNull(); + }); + + it('should update consoleError with latest error message', () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add first error + act(() => { + addConsoleMessage('error', 'First error'); + }); + + expect(result.current.consoleError?.message).toBe('Console error detected: First error'); + + // Add second error - should update to show latest error + act(() => { + addConsoleMessage('error', 'Second error'); + }); + + expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); + expect(result.current.consoleError?.logs).toHaveLength(2); + }); + + it('should clear errors when clearErrors is called', async () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add error to set state + act(() => { + addConsoleMessage('error', 'Test error message'); + }); + + expect(result.current.hasErrors).toBe(true); + expect(result.current.consoleError).not.toBeNull(); + + // Clear errors + act(() => { + result.current.clearErrors(); + }); + + expect(result.current.hasErrors).toBe(false); + expect(result.current.consoleError).toBeNull(); + }); + + it('should dismiss console error when dismissConsoleError is called', async () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add error to create console error + act(() => { + addConsoleMessage('error', 'Test error message'); + }); + + expect(result.current.consoleError).not.toBeNull(); + + // Dismiss console error (this only clears the Quilly error, not the global state) + act(() => { + result.current.dismissConsoleError(); + }); + + expect(result.current.consoleError).toBeNull(); + // hasErrors should still be true since we only dismissed the Quilly display + expect(result.current.hasErrors).toBe(true); + }); + + it('should include all error messages in console error logs', () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add multiple errors and non-errors + act(() => { + addConsoleMessage('log', 'Log message'); + addConsoleMessage('error', 'First error'); + addConsoleMessage('warn', 'Warning message'); + addConsoleMessage('error', 'Second error'); + addConsoleMessage('info', 'Info message'); + addConsoleMessage('error', 'Third error'); + }); + + expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); + expect(result.current.consoleError?.logs).toHaveLength(3); + expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([ + 'First error', + 'Second error', + 'Third error' + ]); + }); +}); \ No newline at end of file diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx new file mode 100644 index 00000000..b033ed64 --- /dev/null +++ b/src/components/ConsoleErrorProvider.tsx @@ -0,0 +1,63 @@ +import { useState, useEffect, useCallback, ReactNode } from 'react'; +import { + addConsoleMessageListener, + removeConsoleMessageListener, + getHasConsoleErrors, + getConsoleMessages, + clearConsoleMessages, + ProjectPreviewConsoleError +} from '@/lib/consoleMessages'; +import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; + +interface ConsoleErrorProviderProps { + children: ReactNode; +} + +export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { + const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors()); + const [consoleError, setConsoleError] = useState(null); + + const updateState = useCallback(() => { + const hasConsoleErrors = getHasConsoleErrors(); + setHasErrors(hasConsoleErrors); + + if (hasConsoleErrors) { + const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error'); + const latestError = errorMessages[errorMessages.length - 1]; + setConsoleError(new ProjectPreviewConsoleError( + `Console error detected: ${latestError.message}`, + errorMessages + )); + } else { + setConsoleError(null); + } + }, []); + + useEffect(() => { + addConsoleMessageListener(updateState); + updateState(); // Initial sync + + return () => removeConsoleMessageListener(updateState); + }, [updateState]); + + const clearErrors = useCallback(() => { + clearConsoleMessages(); + }, []); + + const dismissConsoleError = useCallback(() => { + setConsoleError(null); + }, []); + + const value = { + hasErrors, + consoleError, + clearErrors, + dismissConsoleError, + }; + + return ( + + {children} + + ); +} \ No newline at end of file diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 64dd1f30..15823432 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label'; import { Badge } from '@/components/ui/badge'; import { Separator } from '@/components/ui/separator'; import { Skeleton } from '@/components/ui/skeleton'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro return ( - + e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> {lightningInvoice ? ( @@ -434,68 +434,61 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Add Credits Form - Fixed size section */}
-
-
- setAmount(Number(e.target.value))} - placeholder="Enter amount" - className="text-center text-lg font-medium" - /> -
- {PRESET_AMOUNTS.map((preset) => ( - - ))} + + ))} +
+
-
-
-
- - -
+ Lightning + + + +
- +
@@ -528,65 +521,65 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro ) : (
{payments.map((payment) => ( -
-
-
- {getStatusIcon(payment.status)} - - {payment.method === 'stripe' ? 'Credit Card' : 'Lightning'} - - - {payment.status} - -
-
-

{formatCurrency(payment.amount)}

- {payment.fee > 0 && ( -

+

+
+
+ {getStatusIcon(payment.status)} + + {payment.method === 'stripe' ? 'Credit Card' : 'Lightning'} + + + {payment.status} + +
+
+

{formatCurrency(payment.amount)}

+ {payment.fee > 0 && ( +

+{formatCurrency(payment.fee)} -

- )} -
-
+

+ )} +
+
-
- {formatDate(payment.created_at)} - {payment.status === 'pending' && ( -
- - {payment.url && ( - +
+ {formatDate(payment.created_at)} + {payment.status === 'pending' && ( +
+ + {payment.url && ( + + )} +
)}
- )} -
-
+
))}
)} diff --git a/src/components/DynamicFavicon.tsx b/src/components/DynamicFavicon.tsx new file mode 100644 index 00000000..9e02c0f5 --- /dev/null +++ b/src/components/DynamicFavicon.tsx @@ -0,0 +1,151 @@ +import { useEffect, useRef } from 'react'; +import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy'; + +/** + * Component that dynamically updates the favicon when any project is busy with AI + * Rotates the favicon counter-clockwise when busy + */ +export function DynamicFavicon() { + const isBusy = useAnyProjectBusy(); + const canvasRef = useRef(null); + const animationRef = useRef(null); + const rotationRef = useRef(0); + const originalFaviconRef = useRef(null); + const originalImageRef = useRef(null); + + // Initialize canvas and save original favicon + useEffect(() => { + // Create canvas element for drawing the favicon + if (!canvasRef.current) { + canvasRef.current = document.createElement('canvas'); + canvasRef.current.width = 32; + canvasRef.current.height = 32; + } + + // Store the original favicon URL + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement && !originalFaviconRef.current) { + originalFaviconRef.current = faviconElement.getAttribute('href'); + } + + // Preload the favicon image + if (!originalImageRef.current) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.src = originalFaviconRef.current || '/shakespeare.png'; + img.onload = () => { + originalImageRef.current = img; + }; + } + + return () => { + // Restore original favicon on unmount + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + + // Cancel any ongoing animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + } + }; + }, []); + + // Handle busy state changes + useEffect(() => { + if (!canvasRef.current) return; + + // If busy, start rotation animation + if (isBusy) { + const startRotationAnimation = () => { + if (!canvasRef.current || !originalImageRef.current) { + // If image isn't loaded yet, try again in a moment + setTimeout(startRotationAnimation, 100); + return; + } + + const canvas = canvasRef.current; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + const img = originalImageRef.current; + + const animate = () => { + if (!ctx || !canvas) return; + + // Clear canvas + ctx.clearRect(0, 0, canvas.width, canvas.height); + + // Save context state + ctx.save(); + + // Translate to center for rotation + ctx.translate(canvas.width / 2, canvas.height / 2); + + // Rotate counter-clockwise + ctx.rotate(-rotationRef.current); + + // Draw the image centered + ctx.drawImage( + img, + -canvas.width / 2, + -canvas.height / 2, + canvas.width, + canvas.height + ); + + // Restore context state + ctx.restore(); + + // Update rotation for next frame (slower rotation) + rotationRef.current += 0.05; + + // Update favicon + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', canvas.toDataURL('image/png')); + } + + // Continue animation + animationRef.current = requestAnimationFrame(animate); + }; + + // Start animation loop + animate(); + }; + + startRotationAnimation(); + } else { + // If not busy, restore original favicon and stop animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + + // Reset rotation + rotationRef.current = 0; + + // Restore original favicon + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + } + + return () => { + // Cancel animation on effect cleanup + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + }; + }, [isBusy]); + + // This component doesn't render anything visible + return null; +} diff --git a/src/components/EmailSubscription.tsx b/src/components/EmailSubscription.tsx new file mode 100644 index 00000000..3337864a --- /dev/null +++ b/src/components/EmailSubscription.tsx @@ -0,0 +1,204 @@ +import { useState, useEffect } from 'react'; +import { Mail, CheckCircle } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useToast } from '@/hooks/useToast'; +import { nip19 } from 'nostr-tools'; + +export function EmailSubscription() { + const { t } = useTranslation(); + const { user } = useCurrentUser(); + const { toast } = useToast(); + + const [email, setEmail] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'); + const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`; + const tag = '8982396'; + + // Check localStorage on component mount + useEffect(() => { + const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed'); + if (hasSubscribed === 'true') { + setIsSubmitted(true); + } + }, []); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!email.trim()) { + toast({ + title: "Email required", + description: "Please enter your email address", + variant: "destructive", + }); + return; + } + + // Basic email validation + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + toast({ + title: "Invalid email", + description: "Please enter a valid email address", + variant: "destructive", + }); + return; + } + + setIsSubmitting(true); + + try { + // Submit to Mailchimp + const form = document.createElement('form'); + form.method = 'POST'; + form.action = url.href; + form.target = '_blank'; // Open in new tab + form.style.display = 'none'; + + // Add email field + const emailInput = document.createElement('input'); + emailInput.type = 'email'; + emailInput.name = 'EMAIL'; + emailInput.value = email.trim(); + form.appendChild(emailInput); + + // Add tag field with the new Shakespeare tag ID + const tagInput = document.createElement('input'); + tagInput.type = 'hidden'; + tagInput.name = 'tags'; + tagInput.value = tag; + form.appendChild(tagInput); + + // Add npub if available + if (user?.pubkey) { + const npubInput = document.createElement('input'); + npubInput.type = 'text'; + npubInput.name = 'NPUB'; + npubInput.value = nip19.npubEncode(user.pubkey); + npubInput.style.display = 'none'; + form.appendChild(npubInput); + } + + // Add honeypot field + const honeypotInput = document.createElement('input'); + honeypotInput.type = 'text'; + honeypotInput.name = honeypot; + honeypotInput.tabIndex = -1; + honeypotInput.style.position = 'absolute'; + honeypotInput.style.left = '-5000px'; + form.appendChild(honeypotInput); + + // Add form to document and submit + document.body.appendChild(form); + form.submit(); + + // Clean up after a short delay + setTimeout(() => { + document.body.removeChild(form); + }, 1000); + + // Save subscription status to localStorage + localStorage.setItem('shakespeare-email-subscribed', 'true'); + + setIsSubmitted(true); + toast({ + title: "Successfully subscribed!", + description: "You'll receive Shakespeare updates and resources occasionally.", + }); + } catch (error) { + console.error('Email signup error:', error); + toast({ + title: "Subscription failed", + description: "There was an error subscribing you to updates. Please try again.", + variant: "destructive", + }); + } finally { + setIsSubmitting(false); + } + }; + + if (isSubmitted) { + return ( + + +
+ +
+

+ Thanks for subscribing! +

+

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+ +
+
+
+ ); + } + + return ( + + + + + {t('emailUpdates')} + + + {t('emailUpdatesDescription')} + + + +
+
+ + setEmail(e.target.value)} + disabled={isSubmitting} + required + /> +
+ +
+ + +

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index b2c4d6b5..08f76ce4 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -47,7 +47,7 @@ import { cn } from '@/lib/utils'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; -const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"]; interface GitDialogProps { projectId: string; @@ -335,6 +335,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push to Nostr failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushingToNostr(false); @@ -396,6 +397,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushing(false); @@ -474,6 +476,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Pull failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPulling(false); diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index b5c7102b..43e97dbd 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -1,5 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { Decimal } from 'decimal.js'; import { TestApp } from '@/test/TestApp'; import { ModelSelector } from './ModelSelector'; @@ -12,6 +14,10 @@ vi.mock('@/hooks/useProviderModels', () => ({ useProviderModels: vi.fn(), })); +vi.mock('@/hooks/useIsMobile', () => ({ + useIsMobile: vi.fn(), +})); + vi.mock('react-router-dom', async (importOriginal) => { const actual = await importOriginal() as Record; return { @@ -22,9 +28,11 @@ vi.mock('react-router-dom', async (importOriginal) => { import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; +import { useIsMobile } from '@/hooks/useIsMobile'; const mockUseAISettings = vi.mocked(useAISettings); const mockUseProviderModels = vi.mocked(useProviderModels); +const mockUseIsMobile = vi.mocked(useIsMobile); describe('ModelSelector', () => { const mockOnChange = vi.fn(); @@ -41,7 +49,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); mockUseProviderModels.mockReturnValue({ @@ -50,6 +58,8 @@ describe('ModelSelector', () => { error: null, refetch: vi.fn(), }); + + mockUseIsMobile.mockReturnValue(false); }); it('hides recently used section when less than 5 models and all recently used are available', async () => { @@ -77,7 +87,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -92,11 +102,17 @@ describe('ModelSelector', () => { // Wait for the dropdown to open await waitFor(() => { - expect(screen.getByText('provider1')).toBeInTheDocument(); + expect(screen.getByText('provider2')).toBeInTheDocument(); }); // Recently used section should NOT be visible expect(screen.queryByText('Recently Used')).not.toBeInTheDocument(); + + // provider1 should be hidden since all its models are in recently used + expect(screen.queryByText('provider1')).not.toBeInTheDocument(); + + // provider2 should still show with model3 + expect(screen.getByText('provider2/model3')).toBeInTheDocument(); }); it('shows recently used section when less than 5 models but some recently used are not available', async () => { @@ -124,7 +140,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -173,7 +189,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -188,11 +204,19 @@ describe('ModelSelector', () => { // Wait for the dropdown to open await waitFor(() => { - expect(screen.getByText('provider1')).toBeInTheDocument(); + expect(screen.getByText('provider2')).toBeInTheDocument(); }); // Recently used section SHOULD be visible expect(screen.getByText('Recently Used')).toBeInTheDocument(); + + // provider1 should be hidden since all its models are in recently used + expect(screen.queryByText('provider1')).not.toBeInTheDocument(); + + // provider2 and provider3 should still show + expect(screen.getByText('provider2/model3')).toBeInTheDocument(); + expect(screen.getByText('provider2/model4')).toBeInTheDocument(); + expect(screen.getByText('provider3/model5')).toBeInTheDocument(); }); it('hides recently used section when no recently used models exist', async () => { @@ -216,7 +240,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -237,4 +261,219 @@ describe('ModelSelector', () => { // Recently used section should NOT be visible expect(screen.queryByText('Recently Used')).not.toBeInTheDocument(); }); + + it('shows caution icon for free models', async () => { + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + const paidModel = { + fullId: 'provider1/paid-model', + provider: 'provider1', + id: 'paid-model', + pricing: { + prompt: new Decimal('0.01'), + completion: new Decimal('0.02'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel, paidModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + // Test with free model selected + const { rerender } = render( + + + + ); + + // Should show caution icon for free model + expect(screen.getByTestId('triangle-alert')).toBeInTheDocument(); + + // Test with paid model selected + rerender( + + + + ); + + // Should not show caution icon for paid model + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('does not show caution icon when no model is selected', () => { + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + // Should not show caution icon when no model is selected + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('does not show caution icon for models without pricing information', () => { + const modelWithoutPricing = { + fullId: 'provider1/unknown-pricing', + provider: 'provider1', + id: 'unknown-pricing', + // No pricing property + }; + + mockUseProviderModels.mockReturnValue({ + models: [modelWithoutPricing], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + // Should not show caution icon for models without pricing info + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('shows tooltip when hovering over caution icon', async () => { + const user = userEvent.setup(); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionIcon = screen.getByTestId('triangle-alert'); + expect(cautionIcon).toBeInTheDocument(); + + // Hover over the caution icon + await user.hover(cautionIcon); + + // Wait for tooltip to appear + await waitFor(() => { + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); + }); + }); + + it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => { + const user = userEvent.setup(); + mockUseIsMobile.mockReturnValue(true); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionButton = screen.getByRole('button', { name: 'Free model warning' }); + expect(cautionButton).toBeInTheDocument(); + expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile + + // Click to open tooltip - just verify the click works without errors + await user.click(cautionButton); + + // Tooltip should appear + await waitFor(() => { + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); + }); + + // The button should still be clickable (no errors) + await user.click(cautionButton); + expect(cautionButton).toBeInTheDocument(); + }); + + it('makes caution icon not focusable on desktop', () => { + mockUseIsMobile.mockReturnValue(false); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionButton = screen.getByRole('button', { name: 'Free model warning' }); + expect(cautionButton).toBeInTheDocument(); + expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop + }); }); \ No newline at end of file diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 767f510c..ad2eb95d 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -1,14 +1,16 @@ -import { useState, useMemo } from 'react'; +import { useState, useMemo, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; +import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'; import { Skeleton } from '@/components/ui/skeleton'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; +import { useIsMobile } from '@/hooks/useIsMobile'; import { cn } from '@/lib/utils'; interface ModelSelectorProps { @@ -32,6 +34,7 @@ export function ModelSelector({ }: ModelSelectorProps) { const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); + const [isTooltipOpen, setIsTooltipOpen] = useState(false); // Use controlled state if provided, otherwise use local state const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; @@ -42,22 +45,31 @@ export function ModelSelector({ const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); const { models, isLoading, error, refetch } = useProviderModels(); const navigate = useNavigate(); + const isMobile = useIsMobile(); const defaultPlaceholder = t('selectOrEnterModel'); const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]); - // Group models by provider + // Create a Set of recently used model IDs for efficient lookup + const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]); + + // Group models by provider, excluding models that are in the recently used section const modelsByProvider = useMemo(() => { const groups: Record = {}; for (const model of models) { + // Skip models that are already shown in recently used + if (recentlyUsedSet.has(model.fullId)) { + continue; + } + if (!groups[model.provider]) { groups[model.provider] = []; } groups[model.provider].push(model); } return groups; - }, [models]); + }, [models, recentlyUsedSet]); // Determine if we should show the "Recently Used" section const shouldShowRecentlyUsed = useMemo(() => { @@ -82,9 +94,43 @@ export function ModelSelector({ return !allRecentlyUsedAreAvailable; }, [recentlyUsedModels, models]); + // Check if the current model is free + const isCurrentModelFree = useMemo(() => { + if (!value) return false; + + const currentModel = models.find(model => model.fullId === value); + if (!currentModel?.pricing) return false; + + return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0); + }, [value, models]); + // Don't auto-initialize with recently used models // Let the parent component handle initialization + // Close tooltip when clicking outside on mobile + useEffect(() => { + if (!isMobile || !isTooltipOpen) return; + + const handleClickOutside = (event: MouseEvent | TouchEvent) => { + const target = event.target as Element; + // Check if the click is outside the tooltip and trigger + if (!target.closest('[data-radix-tooltip-content]') && + !target.closest('[data-radix-tooltip-trigger]') && + !target.closest('[data-testid="triangle-alert"]')) { + setIsTooltipOpen(false); + } + }; + + // Add both click and touch event listeners + document.addEventListener('click', handleClickOutside, true); + document.addEventListener('touchstart', handleClickOutside, true); + + return () => { + document.removeEventListener('click', handleClickOutside, true); + document.removeEventListener('touchstart', handleClickOutside, true); + }; + }, [isMobile, isTooltipOpen]); + const handleSelect = (selectedValue: string) => { if (selectedValue === '__custom__') { setIsCustomInput(true); @@ -125,169 +171,222 @@ export function ModelSelector({ if (isCustomInput) { return ( -
- setCustomValue(e.target.value)} - onKeyDown={handleCustomKeyDown} - onBlur={handleCustomSubmit} - placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" - className="h-8 text-xs" - autoFocus - /> - -
+ +
+ setCustomValue(e.target.value)} + onKeyDown={handleCustomKeyDown} + onBlur={handleCustomSubmit} + placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" + className="h-8 text-xs" + autoFocus + /> + +
+
); } return ( - - - - - - - {(isConfigured && models.length >= 5) && ( - - )} - - -
-

{t('noModelsFound')}

-

{t('tryCustomModel')}

-
-
- - {shouldShowRecentlyUsed && ( - - {recentlyUsedModels.map((model) => ( - handleSelect(model)} - className="cursor-pointer" - > - - {model} - - ))} - - )} - - {shouldShowRecentlyUsed && } - - {/* Loading state */} - {isLoading && ( - -
-
- - - + +
+ {isCurrentModelFree && ( + + + + + +

You are using a free model. For better results, switch to a paid model.

+
+
+ )} + + + + + + + {(isConfigured && models.length >= 5) && ( + + )} + + +
+

{t('noModelsFound')}

+

{t('tryCustomModel')}

-
- - )} + - {/* Error state */} - {error && !isLoading && ( - -
-
- -
-

{error}

- -
-
-
-
- )} + + {model} + + ))} + + )} - {/* Provider models */} - {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( -
+ {shouldShowRecentlyUsed && } + + {/* Loading state */} + {isLoading && ( + +
+
+ + + +
+
+
+ )} + + {/* Error state */} + {error && !isLoading && ( + +
+
+ +
+

{error}

+ +
+
+
+
+ )} + + {/* Provider models */} + {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( +
+ + + {providerModels.map((model) => ( + handleSelect(model.fullId)} + className="cursor-pointer" + > + + {model.fullId} + + ))} + +
+ ))} + + {/* Custom model option and manage providers - moved to bottom */} - - {providerModels.map((model) => ( + + {isConfigured && ( handleSelect(model.fullId)} + value="__custom_model_option__" + onSelect={() => handleSelect('__custom__')} className="cursor-pointer" > - - {model.fullId} + + {t('enterCustomModel')} - ))} + )} + handleSelect('__manage_providers__')} + className="cursor-pointer" + > + + {t('manageProviders')} + -
- ))} - - {/* Custom model option and manage providers - moved to bottom */} - - - {isConfigured && ( - handleSelect('__custom__')} - className="cursor-pointer" - > - - {t('enterCustomModel')} - - )} - handleSelect('__manage_providers__')} - className="cursor-pointer" - > - - {t('manageProviders')} - - - - - - + + + + +
+ ); } \ No newline at end of file diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 7b89ae81..b902f297 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -18,7 +18,6 @@ const GIT_KINDS = [ const GIT_RELAYS = [ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', ]; const NostrProvider: React.FC = (props) => { diff --git a/src/components/OnboardingCreditsBadge.test.tsx b/src/components/OnboardingCreditsBadge.test.tsx new file mode 100644 index 00000000..9fcff5a8 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.test.tsx @@ -0,0 +1,103 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import { OnboardingCreditsBadge } from './OnboardingCreditsBadge'; +import type { UseQueryResult } from '@tanstack/react-query'; +import type { CreditsResponse } from '@/hooks/useAICredits'; + +// Mock the useAICredits hook +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: vi.fn(), +})); + +import { useAICredits } from '@/hooks/useAICredits'; + +const mockUseAICredits = vi.mocked(useAICredits); + +describe('OnboardingCreditsBadge', () => { + const mockProvider = { + id: 'shakespeare', + baseURL: 'https://ai.shakespeare.diy/v1', + nostr: true, + }; + + it('renders credits badge when data is available', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 25.50 }, + isLoading: false, + error: null, + } as UseQueryResult); + + render( + + + + ); + + expect(screen.getByText('$25.50')).toBeInTheDocument(); + }); + + it('does not render when loading', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: true, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when there is an error', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: new Error('Provider does not support credits'), + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when no credits data is available', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when credits amount is 0', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 0 }, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); +}); \ No newline at end of file diff --git a/src/components/OnboardingCreditsBadge.tsx b/src/components/OnboardingCreditsBadge.tsx new file mode 100644 index 00000000..f2eaae42 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.tsx @@ -0,0 +1,42 @@ +import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; +import { useAICredits } from '@/hooks/useAICredits'; + +interface OnboardingCreditsBadgeProps { + provider: AIProvider; + className?: string; +} + +/** + * Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider + */ +export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) { + const { data: credits, isLoading, error } = useAICredits(provider); + + // 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 or if amount is 0 + if (!credits || credits.amount === 0) { + 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/components/OnboardingDialog.test.tsx b/src/components/OnboardingDialog.test.tsx index cbf028e4..79bd7d2c 100644 --- a/src/components/OnboardingDialog.test.tsx +++ b/src/components/OnboardingDialog.test.tsx @@ -42,7 +42,7 @@ describe('OnboardingDialog', () => { ); - expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading + expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument(); }); diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 4fa385a1..1ab8e51e 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -1,59 +1,100 @@ import { Decimal } from 'decimal.js'; -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { generateSecretKey } from 'nostr-tools'; import { nip19 } from 'nostr-tools'; -import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react'; +import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; -import { ScrollArea } from '@/components/ui/scroll-area'; +import { Checkbox } from '@/components/ui/checkbox'; +import { PasswordInput } from '@/components/ui/password-input'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; +import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; +import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; +import { cn } from '@/lib/utils'; + interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; } -type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion'; - -const SHAKESPEARE_PROVIDER = { - id: "shakespeare", - baseURL: "https://ai.shakespeare.diy/v1", - nostr: true, -}; +type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion'; export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) { const [step, setStep] = useState('welcome'); + const [selectedProvider, setSelectedProvider] = useState(null); + const [providerApiKey, setProviderApiKey] = useState(''); const [selectedModel, setSelectedModel] = useState(''); const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); + const [agreedToTerms, setAgreedToTerms] = useState(false); + const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false); + + // Ref for the scrollable content area + const scrollableContentRef = useRef(null); const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); const login = useLoginActions(); const { models, isLoading: isLoadingModels } = useProviderModels(); - // Filter models to only show Shakespeare provider models - const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); + // Filter models to only show selected provider models + const providerModels = selectedProvider + ? models.filter(model => model.provider === selectedProvider.id) + : []; + + const handleGetStarted = () => { + setStep('open-source'); + }; + + const handleContinueFromOpenSource = () => { + if (!agreedToTerms) return; + setStep('provider-selection'); + }; + + const handleProviderSelect = (provider: PresetProvider) => { + setSelectedProvider(provider); + // Clear API key when switching providers + setProviderApiKey(''); + // Reset provider terms agreement when switching providers + setAgreedToProviderTerms(false); + }; + + const handleContinueFromProviderSelection = async () => { + if (!selectedProvider) return; + + // Check if user agreed to provider terms + if (!agreedToProviderTerms) return; + + // Check if provider requires API key and if it's provided + const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr; + if (requiresApiKey && !providerApiKey.trim()) return; - const handleGetStarted = async () => { setIsSettingUp(true); try { - // If user is not logged in, generate and login with secret key - if (!user) { + // If user is not logged in and provider uses Nostr auth, generate and login with secret key + if (!user && selectedProvider.nostr) { const secretKey = generateSecretKey(); const nsec = nip19.nsecEncode(secretKey); login.nsec(nsec); } - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // Add selected provider to their config + const providerConfig = { + id: selectedProvider.id, + baseURL: selectedProvider.baseURL, + nostr: selectedProvider.nostr || undefined, + apiKey: requiresApiKey ? providerApiKey.trim() : undefined, + }; + setProvider(providerConfig); // Move to model selection setStep('model-selection'); @@ -75,7 +116,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) addRecentlyUsedModel(selectedModel); // Find the selected model to check if it's free - const model = shakespeareModels.find(m => m.fullId === selectedModel); + const model = providerModels.find(m => m.fullId === selectedModel); const isFreeModel = !model?.pricing || ( model.pricing.prompt.equals(0) && model.pricing.completion.equals(0) ); @@ -110,19 +151,30 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) useEffect(() => { if (open) { setStep('welcome'); + setSelectedProvider(null); + setProviderApiKey(''); setSelectedModel(''); setIsSettingUp(false); setShowCreditsDialog(false); + setAgreedToTerms(false); + setAgreedToProviderTerms(false); } }, [open]); + // Scroll to top when step changes + useEffect(() => { + if (scrollableContentRef.current) { + scrollableContentRef.current.scrollTop = 0; + } + }, [step]); + return ( <> - - + + - {step === 'model-selection' && ( + {step === 'open-source' && ( )} + {step === 'provider-selection' && ( + + )} + {step === 'model-selection' && ( + + )} + {step === 'conclusion' && ( + + )} - {step === 'welcome' && 'Welcome to Shakespeare!'} {step === 'model-selection' && 'Choose Your AI Model'} - {step === 'conclusion' && "You're All Set!"} -
+
{step === 'welcome' && (
-
🎭
+
+ +

Welcome to Shakespeare! @@ -190,16 +272,215 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)

)} - {step === 'model-selection' && ( -
-
-

- Choose an AI model to power your development experience. - Different models offer various capabilities and pricing. + {step === 'open-source' && ( +

+
+

+ Shakespeare is Open Source software that runs entirely in your web browser +

+
+ +
+
+
+

Your device connects directly to third-party AI providers of your choice

+
+
+
+

Your files are stored on your device in your browser

+
+
+
+

Be careful not to delete your browser data or you may lose project files

+
+
+
+

You are responsible for taking backups or syncing to git

+
+
+
+

Quality of output depends on quality of input and models used, and is not guaranteed

+
+
+ +
+

+ Shakespeare is not a cloud service. It's Open Source software that runs on your device. + You agree to the Terms of Service of AI providers you interact with. + Shakespeare is provided "as is" without warranty of any kind. +

+ +
+ setAgreedToTerms(checked === true)} + /> + +
+
+ +
+ +
+
+ )} + + {step === 'provider-selection' && ( +
+
+

Choose your AI provider

+

+ Select an AI provider to power your development assistant. You can add more providers later in settings.

- +
+ {AI_PROVIDER_PRESETS.map((provider) => { + const isSelected = selectedProvider?.id === provider.id; + const isShakespeare = provider.id === 'shakespeare'; + + return ( + handleProviderSelect(provider)} + > +
+
+ + {provider.name} + +
+
+ + {isSelected && ( +
+ +
+ )} +
+
+
+ ); + })} +
+ + {/* API Key Input Section */} + {selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && ( +
+
+

+ {selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'} +

+

+ {selectedProvider.id === 'routstr' ? ( + <>{selectedProvider.name} requires a Cashu token + ) : ( + <> + {selectedProvider.name} requires an {selectedProvider.apiKeysURL ? ( + + API key + + + ) : ( + <>API key + )} + + )} +

+
+ setProviderApiKey(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && providerApiKey.trim()) { + handleContinueFromProviderSelection(); + } + }} + /> +
+ )} + + {/* Terms of Service Agreement */} + {selectedProvider && ( +
+
+ setAgreedToProviderTerms(checked === true)} + /> + +
+
+ )} + +
+ +
+
+ )} + + {step === 'model-selection' && ( +
+
{isLoadingModels ? ( <> @@ -219,7 +500,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) ))} - ) : shakespeareModels.length === 0 ? ( + ) : providerModels.length === 0 ? (
@@ -229,9 +510,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
) : ( - shakespeareModels.map((model) => { + providerModels.map((model) => { const isSelected = selectedModel === model.fullId; const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0); + const isPremium = !!model.pricing && !isFree; + const modelName = model.name || model.id; return ( handleModelSelect(model.fullId)} > - +
- - {model.description || model.name || model.id} + + {modelName} {model.description && (

- {model.name || model.id} + {model.description.length > 70 + ? model.description.slice(0, 70) + '...' + : model.description}

)}
@@ -259,6 +546,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) Free )} + {isPremium && ( + + Premium + + )} {isSelected && (
@@ -267,27 +559,29 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
- -
- {model.pricing && ( - <> - Input: {formatPrice(model.pricing.prompt)} - Output: {formatPrice(model.pricing.completion)} - - )} - {model.contextLength && ( - Context: {model.contextLength.toLocaleString()} tokens - )} -
-
+ {(model.pricing || model.contextLength) && ( + +
+ {model.pricing && ( +
+
Input: {formatPrice(model.pricing.prompt)}
+
Output: {formatPrice(model.pricing.completion)}
+
+ )} + {model.contextLength && ( + Context: {model.contextLength.toLocaleString()} tokens + )} +
+
+ )}
); }) )}
- +
-
+
-
-

- "Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..." -

-
{/* Credits Dialog */} - {showCreditsDialog && selectedModel && ( + {showCreditsDialog && selectedModel && selectedProvider && ( { @@ -334,7 +623,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) handleCreditsDialogClose(); } }} - provider={SHAKESPEARE_PROVIDER} + provider={{ + id: selectedProvider.id, + baseURL: selectedProvider.baseURL, + nostr: selectedProvider.nostr || undefined, + }} /> )} diff --git a/src/components/ProjectSidebar.test.tsx b/src/components/ProjectSidebar.test.tsx index a94ca9e6..c78e4ccb 100644 --- a/src/components/ProjectSidebar.test.tsx +++ b/src/components/ProjectSidebar.test.tsx @@ -60,7 +60,7 @@ describe('ProjectSidebar', () => { ); - expect(screen.getByText('🎭')).toBeInTheDocument(); + expect(screen.getByAltText('Shakespeare')).toBeInTheDocument(); expect(screen.getByText('Shakespeare')).toBeInTheDocument(); }); diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 3d6782a0..03022f82 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -9,12 +9,10 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; -import { ZipImportDialog } from '@/components/ZipImportDialog'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useToast } from '@/hooks/useToast'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; interface ProjectItemProps { project: Project; @@ -95,9 +93,6 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); - const projectsManager = useProjectsManager(); - const { toast } = useToast(); - const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -123,24 +118,7 @@ export function ProjectSidebar({ } }; - const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { - try { - // Import project from zip file - const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); - // Show success toast - toast({ - title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", - description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, - }); - - // Navigate to the imported project - navigate(`/project/${project.id}`); - } catch (error) { - console.error('Failed to import project:', error); - throw error; // Re-throw to let the dialog handle the error display - } - }; useEffect(() => { queryClient.invalidateQueries({ queryKey: ['projects'] }); @@ -153,34 +131,36 @@ export function ProjectSidebar({ return (
{/* Header with Logo */} -
-
- - {(onToggleSidebar || (onClose && isMobile)) && ( -
- -
- )} +
+
+
+ + {(onToggleSidebar || (onClose && isMobile)) && ( +
+ +
+ )} +
@@ -211,13 +191,6 @@ export function ProjectSidebar({ {t('importRepository')} - setIsZipDialogOpen(true)} - className="flex items-center gap-2 w-full" - > - - Import ZIP File -
@@ -258,8 +231,8 @@ export function ProjectSidebar({
{/* Settings and Help at Bottom */} -
-
+
+
- - {/* ZIP Import Dialog */} -
); } \ No newline at end of file diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx new file mode 100644 index 00000000..59d388e1 --- /dev/null +++ b/src/components/Quilly.test.tsx @@ -0,0 +1,80 @@ +import { render, screen } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { Quilly } from './Quilly'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; + +// Mock all required hooks and components +vi.mock('@/hooks/useAISettings', () => ({ + useAISettings: () => ({ + settings: { + providers: [] + } + }) +})); + +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: () => ({ + data: null + }) +})); + +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); + +// Mock CreditsDialog to avoid NostrProvider dependency +vi.mock('./CreditsDialog', () => ({ + CreditsDialog: () => null +})); + +describe('Quilly', () => { + const defaultProps = { + error: new Error('Generic error'), + onDismiss: vi.fn(), + onNewChat: vi.fn(), + onOpenModelSelector: vi.fn(), + providerModel: 'test/model' + }; + + it('renders generic error message', () => { + render(); + + expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); + }); + + it('renders correctly for malformed tool call errors', () => { + const error = new MalformedToolCallError( + 'The AI provider sent an incomplete response.', + 'call_abc123', + 'test/model' + ); + + render( + + ); + + expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); + expect(screen.getByText(/Change model/)).toBeInTheDocument(); + }); + + it('renders correctly for console errors', () => { + const error = new ProjectPreviewConsoleError( + 'Console error', + [] + ); + + render( + + ); + + expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); + expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); + }); +}); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index 445bc87a..d5598e23 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -7,8 +7,9 @@ import { useAISettings } from '@/hooks/useAISettings'; import { parseProviderModel } from '@/lib/parseProviderModel'; import { useAICredits } from '@/hooks/useAICredits'; import { CreditsDialog } from './CreditsDialog'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; export interface QuillyProps { error: Error; @@ -58,6 +59,16 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq }; } + if (error instanceof MalformedToolCallError) { + return { + message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', + action: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; + } + // Handle OpenAI API errors with specific error codes if (error instanceof OpenAI.APIError) { switch (error.code) { diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 200fff49..ba1fe434 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -56,13 +56,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ icon: Database, href: '/settings/data', }, - { - id: 'email', - title: t('emailUpdates'), - description: t('emailUpdatesDescription'), - icon: Mail, - href: '/settings/email', - }, { id: 'about', title: t('aboutShakespeare'), @@ -127,10 +120,10 @@ export function SettingsLayout() { if (isMobile) { return ( -
+
{/* Mobile Header */} -
-
+
+
@@ -549,7 +566,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - consoleMessages.map((msg, index) => ( + messages.map((msg, index) => (
{msg.message}
@@ -647,94 +664,94 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o {isPreviewable && ( -
- {/* Always show browser address bar */} -
- 0} - canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1} - extraContent={( -
- {(!isMobile && onToggleView && isPreviewable) && ( +
+ {/* Always show browser address bar */} +
+ 0} + canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1} + extraContent={( +
+ {(!isMobile && onToggleView && isPreviewable) && ( + + )} + + +
+ )} + /> +
+ + {/* Content area */} +
+ {hasBuiltProject ? ( +