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/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 f9c987af..0d7d5ee1 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'; @@ -39,58 +39,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 { QuillySVG } from '@/components/ui/QuillySVG'; - - -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; @@ -103,8 +58,7 @@ export interface ChatPaneRef { export const ChatPane = forwardRef(({ projectId, - onNewChat: _onNewChat, - onBuild: _onBuild, + onNewChat, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, @@ -118,6 +72,7 @@ export const ChatPane = forwardRef(({ 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; @@ -137,6 +92,11 @@ 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(); @@ -204,6 +164,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, @@ -219,6 +184,7 @@ export const ChatPane = forwardRef(({ tools, customTools, onUpdateMetadata, + onAIError, }); // Use external loading state if provided, otherwise use internal state @@ -267,19 +233,10 @@ 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, 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(() => { @@ -425,6 +382,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 @@ -467,14 +426,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 () => { @@ -543,10 +497,6 @@ export const ChatPane = forwardRef(({ } }), [internalStartNewSession]); - const suggestErrorFix = useCallback(async (errorMessage: string) => { - await send(errorMessage, attachedFiles); - }, [send, attachedFiles]); - return (
@@ -639,27 +589,16 @@ export const ChatPane = forwardRef(({
)} - {/* AI Model Alert */} - {aiModelAlert.hasError && ( - setAIError(null)} + onNewChat={onNewChat} + onOpenModelSelector={openModelSelector} + providerModel={providerModel} /> )} - - {/* Console Error Alert */} - {consoleAlert.hasError && ( - suggestErrorFix(consoleAlert.errorSummary || '') - }} - /> - )} - 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/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts deleted file mode 100644 index 9a100f85..00000000 --- a/src/hooks/useErrorDetection.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { useState, useCallback, useMemo } from 'react'; -import type { AIMessage } from '@/lib/SessionManager'; -import { useConsoleMessages } from './useConsoleMessages'; - -export interface ConsoleErrorAlert { - hasError: boolean; - errorSummary: string | null; - errorCount: number; - dismiss: () => void; -} - -export const useConsoleErrorAlert = ( - aiMessages: AIMessage[], - isBuilding?: boolean, - isLoading?: boolean -): ConsoleErrorAlert => { - const { messages } = useConsoleMessages(); - const [dismissedErrorSummary, setDismissedErrorSummary] = useState(''); - - const { hasError, errorSummary, errorCount } = useMemo(() => { - // Don't show alerts while building or AI is working - if (isBuilding || isLoading) { - return { hasError: false, errorSummary: null, errorCount: 0 }; - } - - // Find the timestamp of the last AI assistant message - // Since AIMessage doesn't have timestamps, we'll use a different approach: - // Only show errors if there are any errors at all and no recent user activity - const lastMessage = aiMessages[aiMessages.length - 1]; - const isLastMessageFromAssistant = lastMessage?.role === 'assistant'; - - // Only show console errors if the last message was from assistant (AI just responded) - if (!isLastMessageFromAssistant) { - return { hasError: false, errorSummary: null, errorCount: 0 }; - } - - // Get recent errors (last 10 seconds worth to catch errors from recent AI actions) - const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago - const recentErrors = messages.filter(msg => - msg.level === 'error' && - msg.timestamp > recentTimeThreshold - ); - - if (recentErrors.length === 0) { - return { hasError: false, errorSummary: null, errorCount: 0 }; - } - - // Just return the raw error messages, no formatting - const summary = recentErrors.slice(-3).map(e => e.message).join('\n'); - - return { - hasError: dismissedErrorSummary !== summary, - errorSummary: summary, - errorCount: recentErrors.length - }; - }, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]); - - const dismiss = useCallback(() => { - if (errorSummary) { - setDismissedErrorSummary(errorSummary); - } - }, [errorSummary]); - - return { - hasError, - errorSummary, - errorCount, - dismiss - }; -}; - -export interface AIModelErrorAlert { - hasError: boolean; - errorMessage: string | null; - errorType: 'warn' | 'error' | null; - action?: { label: string; onClick: () => void }; - dismiss: () => void; -} - -export const useAIModelErrorAlert = ( - messages: AIMessage[], - onNewChat?: () => void, - onChangeModel?: () => void -): AIModelErrorAlert => { - const [dismissedAlertKey, setDismissedAlertKey] = useState(''); - - const { hasError, errorMessage, errorType, action } = useMemo(() => { - const lastMessage = messages[messages.length - 1]; - - // Only show AI model alerts if the last message is from the assistant - // This ensures we don't show stale alerts when user continues the conversation - if (!lastMessage || lastMessage.role !== 'assistant') { - return { hasError: false, errorMessage: null, errorType: null, action: undefined }; - } - - const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; - - // Define error patterns with actions - const errorPatterns = [ - { - test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), - type: 'error' as const, - message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.', - action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined - }, - { - test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), - type: 'warn' as const, - 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: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined - }, - { - test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content), - type: 'warn' as const, - message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' - } - ]; - - for (const pattern of errorPatterns) { - if (pattern.test(content)) { - const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content); - const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`; - - return { - hasError: dismissedAlertKey !== alertKey, - errorMessage: pattern.message, - errorType: pattern.type, - action: pattern.action, - alertKey - }; - } - } - - return { hasError: false, errorMessage: null, errorType: null, action: undefined }; - }, [messages, dismissedAlertKey, onNewChat, onChangeModel]); - - const dismiss = useCallback(() => { - const lastMessage = messages[messages.length - 1]; - if (errorMessage && lastMessage) { - const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content); - const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`; - setDismissedAlertKey(alertKey); - } - }, [errorMessage, messages]); - - return { - hasError, - errorMessage, - errorType, - action, - dismiss - }; -}; 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 c7b6b689..19978226 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -404,25 +404,13 @@ export class SessionManager { } catch (error) { console.error('AI generation error:', error); - // Handle different error types + // Handle user cancellation if (error instanceof OpenAI.APIUserAbortError || 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}`; - } - - 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/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index c4cdef53..5fe49405 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'; @@ -40,20 +39,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; @@ -91,20 +76,6 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); - 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) { @@ -234,7 +205,6 @@ export function ProjectView() { ref={chatPaneRef} projectId={project.id} onNewChat={handleNewChat} - onBuild={runBuild} onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading} @@ -414,7 +384,6 @@ export function ProjectView() { ref={chatPaneRef} projectId={project.id} onNewChat={handleNewChat} - onBuild={runBuild} onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading}