diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx new file mode 100644 index 00000000..6e50e06c --- /dev/null +++ b/src/components/Quilly.test.tsx @@ -0,0 +1,116 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, fireEvent } from '@testing-library/react'; +import { Quilly } from './Quilly'; + +describe('Quilly', () => { + it('renders with error message', () => { + const error = new Error('Test error message'); + const onDismiss = vi.fn(); + + render( + + ); + + expect(screen.getByText('Pardon the interruption')).toBeInTheDocument(); + expect(screen.getByText(/AI service error: Test error message/)).toBeInTheDocument(); + }); + + it('calls onDismiss when dismiss button is clicked', () => { + const error = new Error('Test error'); + const onDismiss = vi.fn(); + + render( + + ); + + const dismissButton = screen.getByRole('button'); + fireEvent.click(dismissButton); + + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('renders action button when provided', () => { + const error = new Error('Test error'); + const onDismiss = vi.fn(); + const actionOnClick = vi.fn(); + + render( + + ); + + const actionButton = screen.getByRole('button', { name: 'Fix it' }); + expect(actionButton).toBeInTheDocument(); + + fireEvent.click(actionButton); + expect(actionOnClick).toHaveBeenCalledTimes(1); + }); + + it('formats network error messages correctly', () => { + const error = new TypeError('fetch failed'); + const onDismiss = vi.fn(); + + render( + + ); + + expect(screen.getByText(/Network error: Unable to connect to AI service/)).toBeInTheDocument(); + }); + + it('formats API key error messages correctly', () => { + const error = new Error('Invalid API key provided'); + const onDismiss = vi.fn(); + + render( + + ); + + expect(screen.getByText(/Authentication error: Please check your API key/)).toBeInTheDocument(); + }); + + it('formats rate limit error messages correctly', () => { + const error = new Error('Rate limit exceeded'); + const onDismiss = vi.fn(); + + render( + + ); + + expect(screen.getByText(/Rate limit exceeded/)).toBeInTheDocument(); + }); + + it('formats context length error messages correctly', () => { + const error = new Error('maximum context length is 4096 tokens'); + const onDismiss = vi.fn(); + + render( + + ); + + expect(screen.getByText(/Your conversation is too long for this model/)).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx new file mode 100644 index 00000000..d8a08d44 --- /dev/null +++ b/src/components/Quilly.tsx @@ -0,0 +1,72 @@ +import { Button } from '@/components/ui/button'; +import { QuillySVG } from '@/components/ui/QuillySVG'; +import { X } from 'lucide-react'; + +export interface QuillyProps { + error: Error; + onDismiss: () => void; + action?: { label: string; onClick: () => void }; +} + +export function Quilly({ error, onDismiss, action }: QuillyProps) { + // Generate user-friendly message from error + const getMessage = (error: Error): string => { + const errorMsg = error.message || ''; + + if (error.name === 'TypeError' && errorMsg.includes('fetch')) { + return 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.'; + } else if (errorMsg.includes('API key')) { + return 'Authentication error: Please check your API key in AI settings.'; + } else if (errorMsg.includes('rate limit')) { + return 'Rate limit exceeded. Please wait a moment before trying again.'; + } else if (errorMsg.includes('insufficient_quota')) { + return 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.'; + } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) { + return 'Model not found: The selected AI model is not available. Please choose a different model.'; + } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) { + return 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.'; + } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) { + return 'The AI model encountered an issue. Try switching to a different model or starting a new chat.'; + } else if (errorMsg.includes('too many requests')) { + return 'You\'re sending requests too quickly. Please wait a moment before trying again.'; + } else if (errorMsg) { + return `AI service error: ${errorMsg}`; + } else { + return 'Sorry, I encountered an unexpected error. Please try again.'; + } + }; + + const message = getMessage(error); + + return ( +
+
+ +
+
+

+ Pardon the interruption +

+

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

+
+
+ +
+
+ ); +} \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 366630db..38ef71ba 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,51 +39,8 @@ 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 { useConsoleErrorAlert } from '@/hooks/useErrorDetection'; +import { Quilly } from '@/components/Quilly'; // Clean interfaces now handled by proper hooks @@ -138,6 +95,11 @@ export const ChatPane = forwardRef(({ } }, [providerModel, settings.recentlyUsedModels]); + // Reset state when navigating between projects + useEffect(() => { + setAIError(null); + }, [projectId]); + const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); @@ -276,22 +238,19 @@ export const ChatPane = forwardRef(({ // Function to suggest error fix // Clean alert hooks with proper interfaces - const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); // Create AI error alert object const aiErrorAlert = useMemo(() => { if (!aiError) { - return { hasError: false, errorMessage: '', dismiss: () => {}, action: undefined }; + return { hasError: false, dismiss: () => {}, action: undefined }; } - let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.'; let action: { label: string; onClick: () => void } | undefined; const errorMsg = aiError.message || ''; if (aiError.name === 'TypeError' && errorMsg.includes('fetch')) { - errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.'; action = { label: 'Check AI settings', onClick: () => { @@ -300,7 +259,6 @@ export const ChatPane = forwardRef(({ } }; } else if (errorMsg.includes('API key')) { - errorMessage = 'Authentication error: Please check your API key in AI settings.'; action = { label: 'Check API key', onClick: () => { @@ -308,10 +266,7 @@ export const ChatPane = forwardRef(({ window.location.href = '/settings/ai'; } }; - } else if (errorMsg.includes('rate limit')) { - errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.'; } else if (errorMsg.includes('insufficient_quota')) { - errorMessage = 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.'; action = { label: 'Check AI settings', onClick: () => { @@ -319,31 +274,37 @@ export const ChatPane = forwardRef(({ } }; } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) { - errorMessage = 'Model not found: The selected AI model is not available. Please choose a different model.'; action = { label: 'Choose model', onClick: openModelSelector }; - } else if (errorMsg) { - errorMessage = `AI service error: ${errorMsg}`; + } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) { + action = _onNewChat ? { + label: 'New chat', + onClick: _onNewChat + } : undefined; + } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) { + action = openModelSelector ? { + label: 'Change model', + onClick: openModelSelector + } : undefined; } return { hasError: true, - errorMessage, dismiss: () => setAIError(null), action }; - }, [aiError, openModelSelector]); + }, [aiError, openModelSelector, _onNewChat]); // Scroll to bottom when alerts appear useEffect(() => { - if (aiModelAlert.hasError || consoleAlert.hasError || aiErrorAlert.hasError) { + if (consoleAlert.hasError || aiErrorAlert.hasError) { setTimeout(() => { scrollToBottom(); }, 50); } - }, [aiModelAlert.hasError, consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]); + }, [consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -698,19 +659,10 @@ export const ChatPane = forwardRef(({ )} - {/* AI Model Alert */} - {aiModelAlert.hasError && ( - - )} - {/* Console Error Alert */} {consoleAlert.hasError && ( - (({ {/* AI Error Alert */} {aiErrorAlert.hasError && ( - diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index 9a100f85..c530f646 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -69,85 +69,4 @@ export const useConsoleErrorAlert = ( }; }; -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 - }; -};