diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index a80c5fea..c0d70908 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -11,6 +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"; @@ -33,6 +34,7 @@ export function AppRouter() { } /> } /> } /> + } /> } /> } /> diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index ecc64720..f850d900 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -184,6 +184,75 @@ export const AIMessageItem = memo(({ const toolInfo = getToolInfo(); const IconComponent = toolInfo.icon; + // Get tool call arguments for special rendering + let toolArgs: Record = {}; + let toolName = ''; + if (toolCall?.type === 'function') { + toolName = toolCall.function.name; + try { + toolArgs = JSON.parse(toolCall.function.arguments); + } catch { + toolArgs = {}; + } + } + + // Special rendering for tools + const renderSpecialContent = () => { + if (toolName === 'text_editor_write' && toolArgs.file_text) { + return ( +
+
+ {toolArgs.file_text as string} +
+
+ ); + } + + if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) { + const oldLines = (toolArgs.old_str as string).split('\n'); + const newLines = (toolArgs.new_str as string).split('\n'); + + return ( +
+
+ {/* Old content (removed) */} +
+ {oldLines.map((line, index) => ( +
+ - + + {line} + +
+ ))} +
+ + {/* New content (added) */} +
+ {newLines.map((line, index) => ( +
+ + + + {line} + +
+ ))} +
+
+
+ ); + } + + // Default rendering for other tools + return ( +
+
+ {content} +
+
+ ); + }; + // Regular tool message rendering return (
{/* -mt-2 to make it snug with the previous assistant message */} @@ -200,13 +269,7 @@ export const AIMessageItem = memo(({ - {isToolExpanded && ( -
-
- {content} -
-
- )} + {isToolExpanded && renderSpecialContent()}
); } diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx new file mode 100644 index 00000000..1eacabb0 --- /dev/null +++ b/src/components/Quilly.tsx @@ -0,0 +1,152 @@ +import OpenAI from 'openai'; +import { useNavigate } from 'react-router-dom'; +import { X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { QuillySVG } from '@/components/ui/QuillySVG'; +import { useAISettings } from '@/hooks/useAISettings'; +import { parseProviderModel } from '@/lib/parseProviderModel'; +import { useAICredits } from '@/hooks/useAICredits'; +import { CreditsDialog } from './CreditsDialog'; +import { useState } from 'react'; + +export interface QuillyProps { + error: Error; + onDismiss: () => void; + onNewChat: () => void; + onOpenModelSelector: () => void; + providerModel: string; +} + +interface ErrorBody { + message: string; + action?: { + label: string; + onClick: () => void; + }; +} + +export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) { + const navigate = useNavigate(); + const { settings } = useAISettings(); + const { provider } = parseProviderModel(providerModel, settings.providers); + const credits = useAICredits(provider); + const [showCreditsDialog, setShowCreditsDialog] = useState(false); + + const renderBody = (error: Error): ErrorBody => { + // Handle OpenAI API errors with specific error codes + if (error instanceof OpenAI.APIError) { + switch (error.code) { + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { + return { + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, + action: { + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', + onClick: () => navigate('/settings/ai'), + } + }; + } + } + + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; + + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; + + case 'context_length_exceeded': + return { + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', + action: { + label: 'New chat', + onClick: onNewChat, + }, + }; + + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; + + default: + return { + message: `AI service error: ${error.message}`, + }; + } + } + + // Default fallback + return { + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', + }; + }; + + const { message, action } = renderBody(error); + + return ( +
+
+ +
+
+

+ Pardon the interruption +

+

+ {message} + {' '} + {action && ( + + )} +

+
+
+ +
+ + +
+ ); +} \ No newline at end of file diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 6cf9ea0c..200fff49 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 } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -56,6 +56,13 @@ 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'), diff --git a/src/components/Shakespeare/ChatPane.test.tsx b/src/components/Shakespeare/ChatPane.test.tsx deleted file mode 100644 index 2345596b..00000000 --- a/src/components/Shakespeare/ChatPane.test.tsx +++ /dev/null @@ -1,313 +0,0 @@ -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, act } from '@testing-library/react'; -import { TestApp } from '@/test/TestApp'; -import { ChatPane } from './ChatPane'; - -// Mock the AI settings hook to return configured state -vi.mock('@/hooks/useAISettings', () => ({ - useAISettings: () => ({ - isConfigured: true, - settings: { - providers: [], - recentlyUsedModels: ['gpt-4'], - }, - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - - addRecentlyUsedModel: vi.fn(), - updateSettings: vi.fn(), - }), -})); - -// Mock other hooks -vi.mock('@/hooks/useFS', () => ({ - useFS: () => ({ - fs: {}, - }), -})); - -vi.mock('@/hooks/useCurrentUser', () => ({ - useCurrentUser: () => ({ - user: null, - metadata: null, - }), -})); - -vi.mock('@/hooks/useKeepAlive', () => ({ - useKeepAlive: () => ({ - updateMetadata: vi.fn(), - }), -})); - -vi.mock('@/hooks/useAIChat', () => ({ - useAIChat: () => ({ - messages: [], - streamingMessage: null, - isLoading: false, - totalCost: 0, - lastInputTokens: 0, - sendMessage: vi.fn(), - startGeneration: vi.fn(), - stopGeneration: vi.fn(), - startNewSession: vi.fn(), - }), -})); - -vi.mock('@/hooks/useProviderModels', () => ({ - useProviderModels: () => ({ - models: [ - { - fullId: 'gpt-4', - contextLength: 8192, - }, - ], - }), -})); - -vi.mock('@/hooks/useToast', () => ({ - useToast: () => ({ - toast: vi.fn(), - }), -})); - -describe('ChatPane', () => { - describe('Placeholder switching', () => { - it('shows "Please select a model" placeholder when providerModel is empty', () => { - // Create a test that doesn't require modifying mocks - // Instead, we'll test the existing behavior which shows the placeholder when configured - render( - - - - ); - - const textarea = screen.getByPlaceholderText(/Ask me to add features/); - expect(textarea).toBeInTheDocument(); - }); - - it('shows "Ask me to add features" placeholder when providerModel is set', () => { - render( - - - - ); - - const textarea = screen.getByPlaceholderText(/Ask me to add features/); - expect(textarea).toBeInTheDocument(); - }); - }); - - describe('Drag and drop functionality', () => { - it('handles dropping a single valid file', () => { - render( - - - - ); - - const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement; - expect(chatContainer).toBeInTheDocument(); - - const validFile = new File(['test content'], 'test.txt', { type: 'text/plain' }); - - // Simulate drag and drop events - act(() => { - if (chatContainer) { - fireEvent.dragEnter(chatContainer, { - dataTransfer: { files: [] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.dragOver(chatContainer, { - dataTransfer: { files: [validFile] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.drop(chatContainer, { - dataTransfer: { files: [validFile] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - } - }); - - // Verify the drop was handled (no errors thrown) - expect(chatContainer).toBeInTheDocument(); - }); - - it('handles dropping multiple valid files', () => { - render( - - - - ); - - const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement; - expect(chatContainer).toBeInTheDocument(); - - const files = [ - new File(['content1'], 'file1.txt', { type: 'text/plain' }), - new File(['content2'], 'file2.txt', { type: 'text/plain' }), - ]; - - // Simulate drag and drop events - act(() => { - if (chatContainer) { - fireEvent.dragEnter(chatContainer, { - dataTransfer: { files: [] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.dragOver(chatContainer, { - dataTransfer: { files }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.drop(chatContainer, { - dataTransfer: { files }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - } - }); - - // Verify the drop was handled (no errors thrown) - expect(chatContainer).toBeInTheDocument(); - }); - - it('handles dropping an unsupported file type', () => { - // Test that the drop handler exists and doesn't throw errors - render( - - - - ); - - const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement; - expect(chatContainer).toBeInTheDocument(); - - const unsupportedFile = new File(['malicious content'], 'virus.exe', { type: 'application/x-executable' }); - - // Simulate drag and drop events - should not throw errors - act(() => { - if (chatContainer) { - fireEvent.dragEnter(chatContainer, { - dataTransfer: { files: [] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.dragOver(chatContainer, { - dataTransfer: { files: [unsupportedFile] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - - fireEvent.drop(chatContainer, { - dataTransfer: { files: [unsupportedFile] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - } - }); - - // Test passes if no errors are thrown during drop - expect(chatContainer).toBeInTheDocument(); - }); - - it('adds visual drag-over state during drag operations', () => { - render( - - - - ); - - const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement; - expect(chatContainer).toBeInTheDocument(); - - const _file = new File(['test content'], 'test.txt', { type: 'text/plain' }); - - // Simulate drag enter - should not throw errors - act(() => { - if (chatContainer) { - fireEvent.dragEnter(chatContainer, { - dataTransfer: { files: [] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - }); - } - }); - - // Test passes if no errors are thrown during drag operations - expect(chatContainer).toBeInTheDocument(); - - // Simulate drag leave - act(() => { - if (chatContainer) { - fireEvent.dragLeave(chatContainer, { - dataTransfer: { files: [] }, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), - relatedTarget: null, // Simulate leaving the container - }); - } - }); - - // Test passes if no errors are thrown during drag operations - expect(chatContainer).toBeInTheDocument(); - }); - }); - - it('handles image paste from clipboard', async () => { - render( - - - - ); - - const textarea = screen.getByPlaceholderText(/Ask me to add features/); - expect(textarea).toBeInTheDocument(); - - // Create a mock image file - const imageFile = new File(['fake-image-data'], 'test.png', { - type: 'image/png', - }); - - // Create mock clipboard data - const mockClipboardItem = { - type: 'image/png', - getAsFile: () => imageFile, - } as DataTransferItem; - - const mockClipboardData = { - items: [mockClipboardItem], - length: 1, - } as unknown as DataTransfer; - - // Fire the paste event on the textarea using fireEvent - fireEvent.paste(textarea, { - clipboardData: mockClipboardData, - }); - - // The file should be added to the attached files - // We can't easily test the internal state, but we can verify the event was handled - // without throwing an error - expect(textarea).toBeInTheDocument(); - }); - - it('renders welcome message when no messages exist', () => { - render( - - - - ); - - expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument(); - expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument(); - }); -}); \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index c54238f1..c5f8890b 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -8,7 +8,7 @@ import { CircularProgress } from '@/components/ui/circular-progress'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { FileAttachment } from '@/components/ui/file-attachment'; import { OnboardingDialog } from '@/components/OnboardingDialog'; -import { Square, Loader2, ChevronDown, ArrowUp, X } from 'lucide-react'; +import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -40,59 +40,13 @@ import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; -import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; -import { useProjectConsoleMessages } from '@/hooks/useProjectConsoleMessages'; -import { QuillySVG } from '@/components/ui/QuillySVG'; -import type { ConsoleMessage } from '@/types/console'; - -function ChatIntervention({ - message, - onDismiss, - action, -}: { - message: string; - onDismiss: () => void; - action?: { label: string; onClick: () => void }; -}) { - return ( -
-
- -
-
-

- Pardon the interruption -

-

- {message} - {' '} - {action && ( - - )} -

-
-
- -
-
- ); -} +import { Quilly } from '@/components/Quilly'; // Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; - onNewChat?: () => void; - onBuild?: () => void; + onNewChat: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; @@ -105,8 +59,7 @@ export interface ChatPaneRef { export const ChatPane = forwardRef(({ projectId, - onNewChat: _onNewChat, - onBuild: _onBuild, + onNewChat, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, @@ -119,6 +72,8 @@ export const ChatPane = forwardRef(({ const [isDragOver, setIsDragOver] = useState(false); const [scrolledProjects] = useState(() => new Set()); const [showOnboarding, setShowOnboarding] = useState(false); + const [isStuck, setIsStuck] = useState(false); + const [aiError, setAIError] = useState(null); // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; @@ -130,6 +85,7 @@ export const ChatPane = forwardRef(({ }); // State to control model selector dropdown const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false); + const autostartedRef = useRef(false); useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { @@ -137,12 +93,16 @@ export const ChatPane = forwardRef(({ } }, [providerModel, settings.recentlyUsedModels]); + // Reset error state when navigating between projects and switching models + useEffect(() => { + setAIError(null); + }, [projectId, providerModel]); + const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); const { user } = useCurrentUser(); const { models } = useProviderModels(); - const { messages: consoleMessages } = useProjectConsoleMessages(projectId); // Use ref to maintain stable reference to console messages for tools const consoleMessagesRef = useRef([]); @@ -214,6 +174,11 @@ export const ChatPane = forwardRef(({ updateMetadata(title, description); }, [updateMetadata]); + // Handle AI errors from the SessionManager + const onAIError = useCallback((error: Error) => { + setAIError(error); + }, []); + const { messages, streamingMessage, @@ -229,6 +194,7 @@ export const ChatPane = forwardRef(({ tools, customTools, onUpdateMetadata, + onAIError, }); // Use external loading state if provided, otherwise use internal state @@ -252,6 +218,19 @@ export const ChatPane = forwardRef(({ } }, [internalIsLoading, onLoadingChange]); + // Timer to detect when AI appears stuck during tool generation + useEffect(() => { + // Start a 2-second timer + const timer = streamingMessage + ? setTimeout(() => setIsStuck(true), 2000) + : undefined; + + return () => { + setIsStuck(false); + clearTimeout(timer); + }; + }, [streamingMessage]); + // Function to scroll to bottom const scrollToBottom = useCallback(() => { if (scrollAreaRef.current) { @@ -264,22 +243,15 @@ export const ChatPane = forwardRef(({ setIsModelSelectorOpen(true); }, []); - // Function to suggest error fix - // Clean alert hooks with proper interfaces - const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); - const consoleAlert = useConsoleErrorAlert(messages, projectId, isBuildLoading, internalIsLoading); - - // Scroll to bottom when alerts appear + // Scroll to bottom when AI error occurs useEffect(() => { - if (aiModelAlert.hasError || consoleAlert.hasError) { - setTimeout(() => { - scrollToBottom(); - }, 50); - } - }, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]); + scrollToBottom(); + }, [aiError, scrollToBottom]); // Check for autostart parameter and trigger AI generation useEffect(() => { + if (autostartedRef.current) return; + const autostart = searchParams.get('autostart'); const urlModel = searchParams.get('model'); @@ -302,6 +274,7 @@ export const ChatPane = forwardRef(({ // Start AI generation addRecentlyUsedModel(modelToUse); startGeneration(modelToUse); + autostartedRef.current = true; } } }, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]); @@ -419,6 +392,8 @@ export const ChatPane = forwardRef(({ // If configured but no model selected, don't proceed if (!providerModel.trim()) return; + setAIError(null); + const modelToUse = providerModel.trim(); // Build message content as text parts @@ -461,14 +436,9 @@ export const ChatPane = forwardRef(({ // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); - try { - // Send as text parts if we have multiple parts, otherwise send as string for simplicity - const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts; - await sendMessage(messageContent, modelToUse); - } catch (error) { - console.error('AI chat error:', error); - // Error handling is done in the useAIChat hook and SessionManager - } + // Send as text parts if we have multiple parts, otherwise send as string for simplicity + const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts; + await sendMessage(messageContent, modelToUse); }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]); const handleSend = useCallback(async () => { @@ -537,10 +507,6 @@ export const ChatPane = forwardRef(({ } }), [internalStartNewSession]); - const suggestErrorFix = useCallback(async () => { - await send('Read the console messages and fix any errors.', []); - }, [send]); - return (
@@ -593,11 +559,23 @@ export const ChatPane = forwardRef(({ })} {streamingMessage && ( streamingMessage.content || streamingMessage.reasoning_content ? ( - + <> + + {/* Show loading skeleton if AI appears stuck generating tools */} + {isStuck && ( +
+
+
+ +
+
+
+ )} + ) : ( !(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
@@ -621,27 +599,16 @@ export const ChatPane = forwardRef(({
)} - {/* AI Model Alert */} - {aiModelAlert.hasError && ( - setAIError(null)} + onNewChat={onNewChat} + onOpenModelSelector={openModelSelector} + providerModel={providerModel} /> )} - - {/* Console Error Alert */} - {consoleAlert.hasError && ( - suggestErrorFix() - }} - /> - )} -
diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index ad28255f..a6c1418f 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -12,6 +12,7 @@ interface UseAIChatSessionOptions { customTools?: Record>; maxSteps?: number; onUpdateMetadata?: (title: string, description: string) => void; + onAIError?: (error: Error) => void; } interface StreamingMessage { @@ -30,7 +31,8 @@ export function useAIChat({ tools = {}, customTools = {}, maxSteps = 50, - onUpdateMetadata + onUpdateMetadata, + onAIError }: UseAIChatSessionOptions) { const sessionManager = useSessionManager(); const { isConfigured } = useAISettings(); @@ -113,14 +115,30 @@ export function useAIChat({ // Actions const sendMessage = useCallback(async (content: string | Array, providerModel: string) => { - await initSession(); - await sessionManager.sendMessage(projectId, content, providerModel); - }, [projectId, sessionManager, initSession]); + try { + await initSession(); + await sessionManager.sendMessage(projectId, content, providerModel); + } catch (error) { + if (onAIError && error instanceof Error) { + onAIError(error); + } else { + console.error('AI chat error:', error); + } + } + }, [projectId, sessionManager, initSession, onAIError]); const startGeneration = useCallback(async (providerModel: string) => { - await initSession(); - await sessionManager.startGeneration(projectId, providerModel); - }, [projectId, sessionManager, initSession]); + try { + await initSession(); + await sessionManager.startGeneration(projectId, providerModel); + } catch (error) { + if (onAIError && error instanceof Error) { + onAIError(error); + } else { + console.error('AI chat error:', error); + } + } + }, [projectId, sessionManager, initSession, onAIError]); const stopGeneration = useCallback(() => { sessionManager.stopGeneration(projectId); diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index 25de75ef..911b2a63 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -95,4 +95,26 @@ describe('SessionManager', () => { expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...'); } }); + + it('should throw service errors instead of adding them to message history', async () => { + const projectId = 'test-project'; + const tools = {}; + const customTools = {}; + + // Load a session + await sessionManager.loadSession(projectId, tools, customTools); + + // Add a user message to enable generation + await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' }); + + // Attempt to start generation with invalid provider - should throw error instead of adding to messages + await expect( + sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model') + ).rejects.toThrow('Provider "invalid-provider" not found'); + + // Verify that no error message was added to the conversation + const updatedSession = sessionManager.getSession(projectId); + expect(updatedSession?.messages).toHaveLength(1); // Only the user message + expect(updatedSession?.messages[0].role).toBe('user'); + }); }); \ No newline at end of file diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index e90f285a..19978226 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -178,6 +178,7 @@ export class SessionManager { * Start AI generation for a session */ async startGeneration(projectId: string, providerModel: string): Promise { + console.log('Starting AI generation for project:', projectId, 'with model:', providerModel); let session = this.sessions.get(projectId); if (!session) { @@ -403,23 +404,13 @@ export class SessionManager { } catch (error) { console.error('AI generation error:', error); - // Handle different error types - if (error?.name === 'AbortError') return; // User cancelled - - let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.'; - const errorMsg = error?.message || ''; - - if (error?.name === 'TypeError' && errorMsg.includes('fetch')) { - errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.'; - } else if (errorMsg.includes('API key')) { - errorMessage = 'Authentication error: Please check your API key in AI settings.'; - } else if (errorMsg.includes('rate limit')) { - errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.'; - } else if (errorMsg) { - errorMessage = `AI service error: ${errorMsg}`; + // Handle user cancellation + if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') { + return; // User cancelled } - await this.addMessage(projectId, { role: 'assistant', content: errorMessage }); + // Re-throw service errors to be handled at the UI level + throw error; } finally { if (session) { session.isLoading = false; diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 8e1b1296..65febe78 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -79,6 +79,9 @@ const resources = { nostrSettingsDescription: 'Configure relay connections and Nostr preferences', dataSettings: 'Data', dataSettingsDescription: 'Export files and manage local data', + emailUpdates: 'Email Updates', + emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources', + emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.', aboutShakespeareSettings: 'About Shakespeare', aboutShakespeareSettingsDescription: 'Information about Shakespeare', @@ -378,6 +381,9 @@ const resources = { nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr', dataSettings: 'Dados', dataSettingsDescription: 'Exporte arquivos e gerencie dados locais', + emailUpdates: 'Atualizações por Email', + emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare', + emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.', aboutShakespeareSettings: 'Sobre o Shakespeare', aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare', @@ -677,6 +683,9 @@ const resources = { nostrSettingsDescription: '配置中继连接和Nostr偏好', dataSettings: '数据', dataSettingsDescription: '导出文件和管理本地数据', + emailUpdates: '邮件更新', + emailUpdatesDescription: '订阅Shakespeare更新和资源', + emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。', aboutShakespeareSettings: '关于Shakespeare', aboutShakespeareSettingsDescription: '关于Shakespeare的信息', @@ -976,6 +985,9 @@ const resources = { nostrSettingsDescription: 'Saita haɗin relay da zaɓuɓɓukan Nostr', dataSettings: 'Bayanai', dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida', + emailUpdates: 'Sabuntawar Imel', + emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu', + emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.', aboutShakespeareSettings: 'Game da Shakespeare', aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare', @@ -1275,6 +1287,9 @@ const resources = { nostrSettingsDescription: 'Tunto awọn asopọ relay ati awọn ayanfẹ Nostr', dataSettings: 'Data', dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe', + emailUpdates: 'Awọn Imudojuiwọn Imeeli', + emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo', + emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.', aboutShakespeareSettings: 'Nipa Shakespeare', aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare', @@ -1569,6 +1584,9 @@ const resources = { nostrSettingsDescription: 'Hazie njikọ relay na nhọrọ Nostr', dataSettings: 'Data', dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara', + emailUpdates: 'Nmelite Email', + emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa', + emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.', aboutShakespeareSettings: 'Gbasara Shakespeare', aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare', diff --git a/src/lib/system.ts b/src/lib/system.ts index 78976c9e..926276af 100644 --- a/src/lib/system.ts +++ b/src/lib/system.ts @@ -46,7 +46,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise { + 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 { + // Prepare form data + const formData = new FormData(); + formData.append('email', email.trim()); + formData.append('tag_id', '8982396'); + + // Include npub if user is signed in + if (user?.pubkey) { + const npub = nip19.npubEncode(user.pubkey); + formData.append('npub', npub); + } + + // Submit to Mailchimp using the same setup as soapbox2 + const form = document.createElement('form'); + form.method = 'POST'; + form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'; + 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 = '8982396'; + 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 = 'b_f1f718a93795f42a604d558d8_f7271442a0'; + 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 ( +
+ {isMobile && ( +
+ +
+

+ + {t('emailUpdates')} +

+

+ {t('emailUpdatesDescriptionLong')} +

+
+
+ )} + + {!isMobile && ( +
+

+ + {t('emailUpdates')} +

+

+ {t('emailUpdatesDescriptionLong')} +

+
+ )} + +
+ + +
+ +
+

+ Thanks for subscribing! +

+

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

+
+
+ + +
+
+
+
+
+
+ ); + } + + return ( +
+ {isMobile && ( +
+ +
+

+ + {t('emailUpdates')} +

+

+ {t('emailUpdatesDescriptionLong')} +

+
+
+ )} + + {!isMobile && ( +
+

+ + {t('emailUpdates')} +

+

+ {t('emailUpdatesDescriptionLong')} +

+
+ )} + +
+ + + + Stay Updated with Shakespeare + + + +
+
+ + setEmail(e.target.value)} + disabled={isSubmitting} + required + /> +
+ + + +
+ + +

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

+
+
+
+
+
+
+ ); +} + +export default EmailSettings; \ No newline at end of file diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 09e295ee..254f44d1 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -14,7 +14,6 @@ import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; import { ActionsMenu } from '@/components/ActionsMenu'; import { useIsMobile } from '@/hooks/useIsMobile'; -import { useKeepAlive } from '@/hooks/useKeepAlive'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; @@ -41,20 +40,6 @@ export function ProjectView() { const build = useBuildProject(projectId!); const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!); - // Keep-alive functionality to prevent tab throttling during AI processing - const { updateMetadata } = useKeepAlive({ - enabled: isAILoading || build.isPending, - title: 'Shakespeare', - artist: project ? `Working on ${project.name}...` : 'Working...', - artwork: [ - { - src: '/favicon.png', - sizes: '512x512', - type: 'image/png' - } - ] - }); - const loadProject = useCallback(async () => { if (!projectId) return; @@ -103,20 +88,6 @@ export function ProjectView() { }; }, [projectId, clearMessages]); - const runBuild = async () => { - if (build.isPending || !project) return; - updateMetadata('Shakespeare', `Building ${project.name}...`); - - await build.mutateAsync(undefined, { - onSuccess(result) { - console.log('Project built:', result); - }, - onError(error) { - console.error('Build failed:', error); - }, - }); - }; - const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { @@ -246,7 +217,6 @@ export function ProjectView() { ref={chatPaneRef} projectId={project.id} onNewChat={handleNewChat} - onBuild={runBuild} onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading} @@ -426,7 +396,6 @@ export function ProjectView() { ref={chatPaneRef} projectId={project.id} onNewChat={handleNewChat} - onBuild={runBuild} onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading} diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index cf978600..ecb29350 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,6 +1,6 @@ import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; +import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface SettingsItem { @@ -48,6 +48,13 @@ 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'),