From e9f8e99ac5ea14291f2068b2046b6672927b8ec5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 20:00:02 -0500 Subject: [PATCH 1/7] Surface AI Errors to ChatPane --- src/components/Shakespeare/ChatPane.tsx | 88 ++++++++++++++++++++++--- src/hooks/useAIChat.ts | 32 +++++++-- src/lib/SessionManager.test.ts | 22 +++++++ src/lib/SessionManager.ts | 18 +---- 4 files changed, 128 insertions(+), 32 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f9c987af..366630db 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -118,6 +118,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; @@ -204,6 +205,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 +225,7 @@ export const ChatPane = forwardRef(({ tools, customTools, onUpdateMetadata, + onAIError, }); // Use external loading state if provided, otherwise use internal state @@ -272,14 +279,71 @@ export const ChatPane = forwardRef(({ 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 }; + } + + 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: () => { + // Navigate to AI settings + window.location.href = '/settings/ai'; + } + }; + } else if (errorMsg.includes('API key')) { + errorMessage = 'Authentication error: Please check your API key in AI settings.'; + action = { + label: 'Check API key', + onClick: () => { + // Navigate to AI settings + 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: () => { + window.location.href = '/settings/ai'; + } + }; + } 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}`; + } + + return { + hasError: true, + errorMessage, + dismiss: () => setAIError(null), + action + }; + }, [aiError, openModelSelector]); + // Scroll to bottom when alerts appear useEffect(() => { - if (aiModelAlert.hasError || consoleAlert.hasError) { + if (aiModelAlert.hasError || consoleAlert.hasError || aiErrorAlert.hasError) { setTimeout(() => { scrollToBottom(); }, 50); } - }, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]); + }, [aiModelAlert.hasError, consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -467,14 +531,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 () => { @@ -660,6 +719,15 @@ export const ChatPane = forwardRef(({ /> )} + {/* AI Error Alert */} + {aiErrorAlert.hasError && ( + + )} + 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 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; From d932f05d04feab268cac5da3899c4d8ef9b569aa Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 20:18:43 -0500 Subject: [PATCH 2/7] Make Quilly intercept actual Error objects --- src/components/Quilly.test.tsx | 116 ++++++++++++++++++++++++ src/components/Quilly.tsx | 72 +++++++++++++++ src/components/Shakespeare/ChatPane.tsx | 100 ++++++-------------- src/hooks/useErrorDetection.ts | 81 ----------------- 4 files changed, 214 insertions(+), 155 deletions(-) create mode 100644 src/components/Quilly.test.tsx create mode 100644 src/components/Quilly.tsx 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 - }; -}; From 7057c34f01d7746e44db23d180b5989845a5fc04 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 20:53:24 -0500 Subject: [PATCH 3/7] Consolidate action logic into Quilly --- src/components/Quilly.test.tsx | 35 ++++++++--- src/components/Quilly.tsx | 61 ++++++++++++++++++- src/components/Shakespeare/ChatPane.tsx | 79 +++---------------------- src/pages/ProjectView.tsx | 31 ---------- 4 files changed, 94 insertions(+), 112 deletions(-) diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index 6e50e06c..e3657f19 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -35,27 +35,44 @@ describe('Quilly', () => { expect(onDismiss).toHaveBeenCalledTimes(1); }); - it('renders action button when provided', () => { - const error = new Error('Test error'); + it('renders action button for console errors', () => { + const error = new Error('Console errors detected in your app. Would you like me to help fix them?'); const onDismiss = vi.fn(); - const actionOnClick = vi.fn(); + const onFixConsoleErrors = vi.fn(); render( ); - const actionButton = screen.getByRole('button', { name: 'Fix it' }); + const actionButton = screen.getByRole('button', { name: 'Fix errors' }); expect(actionButton).toBeInTheDocument(); fireEvent.click(actionButton); - expect(actionOnClick).toHaveBeenCalledTimes(1); + expect(onFixConsoleErrors).toHaveBeenCalledTimes(1); + }); + + it('renders action button for model not found errors', () => { + const error = new Error('model_not_found: The specified model does not exist'); + const onDismiss = vi.fn(); + const onOpenModelSelector = vi.fn(); + + render( + + ); + + const actionButton = screen.getByRole('button', { name: 'Choose model' }); + expect(actionButton).toBeInTheDocument(); + + fireEvent.click(actionButton); + expect(onOpenModelSelector).toHaveBeenCalledTimes(1); }); it('formats network error messages correctly', () => { diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index d8a08d44..b335d00c 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -5,10 +5,12 @@ import { X } from 'lucide-react'; export interface QuillyProps { error: Error; onDismiss: () => void; - action?: { label: string; onClick: () => void }; + onNewChat?: () => void; + onOpenModelSelector?: () => void; + onFixConsoleErrors?: () => void; } -export function Quilly({ error, onDismiss, action }: QuillyProps) { +export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) { // Generate user-friendly message from error const getMessage = (error: Error): string => { const errorMsg = error.message || ''; @@ -36,7 +38,62 @@ export function Quilly({ error, onDismiss, action }: QuillyProps) { } }; + // Determine action based on error + const getAction = (error: Error): { label: string; onClick: () => void } | undefined => { + const errorMsg = error.message || ''; + + // Check for console error messages first + if (errorMsg.includes('Console') && errorMsg.includes('detected in your app') && onFixConsoleErrors) { + const isPlural = errorMsg.includes('errors detected'); + return { + label: `Fix ${isPlural ? 'errors' : 'error'}`, + onClick: onFixConsoleErrors + }; + } + + if (error.name === 'TypeError' && errorMsg.includes('fetch')) { + return { + label: 'Check AI settings', + onClick: () => { + window.location.href = '/settings/ai'; + } + }; + } else if (errorMsg.includes('API key')) { + return { + label: 'Check API key', + onClick: () => { + window.location.href = '/settings/ai'; + } + }; + } else if (errorMsg.includes('insufficient_quota')) { + return { + label: 'Check AI settings', + onClick: () => { + window.location.href = '/settings/ai'; + } + }; + } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) { + return onOpenModelSelector ? { + label: 'Choose model', + onClick: onOpenModelSelector + } : undefined; + } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) { + return onNewChat ? { + label: 'New chat', + onClick: onNewChat + } : undefined; + } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) { + return onOpenModelSelector ? { + label: 'Change model', + onClick: onOpenModelSelector + } : undefined; + } + + return undefined; + }; + const message = getMessage(error); + const action = getAction(error); return (
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 38ef71ba..ee22914e 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -47,7 +47,6 @@ import { Quilly } from '@/components/Quilly'; interface ChatPaneProps { projectId: string; onNewChat?: () => void; - onBuild?: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; @@ -60,8 +59,7 @@ export interface ChatPaneRef { export const ChatPane = forwardRef(({ projectId, - onNewChat: _onNewChat, - onBuild: _onBuild, + onNewChat, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, @@ -240,71 +238,14 @@ export const ChatPane = forwardRef(({ // Clean alert hooks with proper interfaces const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); - // Create AI error alert object - const aiErrorAlert = useMemo(() => { - if (!aiError) { - return { hasError: false, dismiss: () => {}, action: undefined }; - } - - let action: { label: string; onClick: () => void } | undefined; - - const errorMsg = aiError.message || ''; - - if (aiError.name === 'TypeError' && errorMsg.includes('fetch')) { - action = { - label: 'Check AI settings', - onClick: () => { - // Navigate to AI settings - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('API key')) { - action = { - label: 'Check API key', - onClick: () => { - // Navigate to AI settings - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('insufficient_quota')) { - action = { - label: 'Check AI settings', - onClick: () => { - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) { - action = { - label: 'Choose model', - onClick: openModelSelector - }; - } 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, - dismiss: () => setAIError(null), - action - }; - }, [aiError, openModelSelector, _onNewChat]); - // Scroll to bottom when alerts appear useEffect(() => { - if (consoleAlert.hasError || aiErrorAlert.hasError) { + if (consoleAlert.hasError || aiError) { setTimeout(() => { scrollToBottom(); }, 50); } - }, [consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]); + }, [consoleAlert.hasError, aiError, scrollToBottom]); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -664,19 +605,17 @@ export const ChatPane = forwardRef(({ suggestErrorFix(consoleAlert.errorSummary || '') - }} + onFixConsoleErrors={() => suggestErrorFix(consoleAlert.errorSummary || '')} /> )} {/* AI Error Alert */} - {aiErrorAlert.hasError && ( + {aiError && ( setAIError(null)} + onNewChat={onNewChat} + onOpenModelSelector={openModelSelector} /> )} 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} From 25f14ee2b39bf4d0b7677b55e8ac34f3874a8d70 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 21:06:52 -0500 Subject: [PATCH 4/7] Clean up Quilly --- src/components/Quilly.tsx | 173 ++++++++++++++++++++------------------ 1 file changed, 91 insertions(+), 82 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index b335d00c..71d0ad22 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,99 +1,108 @@ import { Button } from '@/components/ui/button'; import { QuillySVG } from '@/components/ui/QuillySVG'; +import OpenAI from 'openai'; import { X } from 'lucide-react'; +import { useNavigate } from 'react-router-dom'; export interface QuillyProps { error: Error; onDismiss: () => void; - onNewChat?: () => void; - onOpenModelSelector?: () => void; - onFixConsoleErrors?: () => void; + onNewChat: () => void; + onOpenModelSelector: () => void; + onFixConsoleErrors: () => void; +} + +interface ErrorBody { + message: string; + action?: { + label: string; + onClick: () => void; + }; } export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) { - // Generate user-friendly message from error - const getMessage = (error: Error): string => { - const errorMsg = error.message || ''; + const navigate = useNavigate(); - 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 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': + 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}`, + }; + } } + + // Handle console error messages + if (error.message.includes('Console') && error.message.includes('detected in your app') && onFixConsoleErrors) { + const isPlural = error.message.includes('errors detected'); + return { + message: error.message, + action: { + label: `Fix ${isPlural ? 'errors' : 'error'}`, + onClick: onFixConsoleErrors, + } + }; + } + + // Default fallback + return { + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', + }; }; - // Determine action based on error - const getAction = (error: Error): { label: string; onClick: () => void } | undefined => { - const errorMsg = error.message || ''; - - // Check for console error messages first - if (errorMsg.includes('Console') && errorMsg.includes('detected in your app') && onFixConsoleErrors) { - const isPlural = errorMsg.includes('errors detected'); - return { - label: `Fix ${isPlural ? 'errors' : 'error'}`, - onClick: onFixConsoleErrors - }; - } - - if (error.name === 'TypeError' && errorMsg.includes('fetch')) { - return { - label: 'Check AI settings', - onClick: () => { - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('API key')) { - return { - label: 'Check API key', - onClick: () => { - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('insufficient_quota')) { - return { - label: 'Check AI settings', - onClick: () => { - window.location.href = '/settings/ai'; - } - }; - } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) { - return onOpenModelSelector ? { - label: 'Choose model', - onClick: onOpenModelSelector - } : undefined; - } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) { - return onNewChat ? { - label: 'New chat', - onClick: onNewChat - } : undefined; - } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) { - return onOpenModelSelector ? { - label: 'Change model', - onClick: onOpenModelSelector - } : undefined; - } - - return undefined; - }; - - const message = getMessage(error); - const action = getAction(error); + const { message, action } = renderBody(error); return (
From 0b949d55b9b7e89bdb76bfac20362f244c768597 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 21:14:41 -0500 Subject: [PATCH 5/7] Remove Quilly tests (for now) --- src/components/Quilly.test.tsx | 133 --------------------------------- 1 file changed, 133 deletions(-) delete mode 100644 src/components/Quilly.test.tsx diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx deleted file mode 100644 index e3657f19..00000000 --- a/src/components/Quilly.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -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 for console errors', () => { - const error = new Error('Console errors detected in your app. Would you like me to help fix them?'); - const onDismiss = vi.fn(); - const onFixConsoleErrors = vi.fn(); - - render( - - ); - - const actionButton = screen.getByRole('button', { name: 'Fix errors' }); - expect(actionButton).toBeInTheDocument(); - - fireEvent.click(actionButton); - expect(onFixConsoleErrors).toHaveBeenCalledTimes(1); - }); - - it('renders action button for model not found errors', () => { - const error = new Error('model_not_found: The specified model does not exist'); - const onDismiss = vi.fn(); - const onOpenModelSelector = vi.fn(); - - render( - - ); - - const actionButton = screen.getByRole('button', { name: 'Choose model' }); - expect(actionButton).toBeInTheDocument(); - - fireEvent.click(actionButton); - expect(onOpenModelSelector).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 From ec5d84d3f71382b783b87d298c4235d9c5dc4674 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 21:23:31 -0500 Subject: [PATCH 6/7] Disconnect Quilly from console errors temporarily --- src/components/Quilly.tsx | 15 +- src/components/Shakespeare/ChatPane.test.tsx | 313 ------------------- src/components/Shakespeare/ChatPane.tsx | 30 +- src/hooks/useErrorDetection.ts | 72 ----- 4 files changed, 2 insertions(+), 428 deletions(-) delete mode 100644 src/components/Shakespeare/ChatPane.test.tsx delete mode 100644 src/hooks/useErrorDetection.ts diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index 71d0ad22..5ca08602 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -9,7 +9,6 @@ export interface QuillyProps { onDismiss: () => void; onNewChat: () => void; onOpenModelSelector: () => void; - onFixConsoleErrors: () => void; } interface ErrorBody { @@ -20,7 +19,7 @@ interface ErrorBody { }; } -export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) { +export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: QuillyProps) { const navigate = useNavigate(); const renderBody = (error: Error): ErrorBody => { @@ -82,18 +81,6 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFix } } - // Handle console error messages - if (error.message.includes('Console') && error.message.includes('detected in your app') && onFixConsoleErrors) { - const isPlural = error.message.includes('errors detected'); - return { - message: error.message, - action: { - label: `Fix ${isPlural ? 'errors' : 'error'}`, - onClick: onFixConsoleErrors, - } - }; - } - // Default fallback return { message: error.message 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 ee22914e..52ec50bf 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -39,14 +39,13 @@ import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; -import { useConsoleErrorAlert } from '@/hooks/useErrorDetection'; import { Quilly } from '@/components/Quilly'; // Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; - onNewChat?: () => void; + onNewChat: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; @@ -234,19 +233,6 @@ export const ChatPane = forwardRef(({ setIsModelSelectorOpen(true); }, []); - // Function to suggest error fix - // Clean alert hooks with proper interfaces - const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); - - // Scroll to bottom when alerts appear - useEffect(() => { - if (consoleAlert.hasError || aiError) { - setTimeout(() => { - scrollToBottom(); - }, 50); - } - }, [consoleAlert.hasError, aiError, scrollToBottom]); - // Check for autostart parameter and trigger AI generation useEffect(() => { if (autostartedRef.current) return; @@ -504,10 +490,6 @@ export const ChatPane = forwardRef(({ } }), [internalStartNewSession]); - const suggestErrorFix = useCallback(async (errorMessage: string) => { - await send(errorMessage, attachedFiles); - }, [send, attachedFiles]); - return (
@@ -600,15 +582,6 @@ export const ChatPane = forwardRef(({
)} - {/* Console Error Alert */} - {consoleAlert.hasError && ( - suggestErrorFix(consoleAlert.errorSummary || '')} - /> - )} - {/* AI Error Alert */} {aiError && ( (({ onOpenModelSelector={openModelSelector} /> )} -
diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts deleted file mode 100644 index c530f646..00000000 --- a/src/hooks/useErrorDetection.ts +++ /dev/null @@ -1,72 +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 - }; -}; - - From db57619bcaa24f62ad85feac40a91004911f4c43 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Sep 2025 21:42:12 -0500 Subject: [PATCH 7/7] Allow refilling Shakespeare credits from Quilly --- src/components/Quilly.tsx | 51 +++++++++++++++++++------ src/components/Shakespeare/ChatPane.tsx | 12 +++++- 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index 5ca08602..1eacabb0 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,14 +1,20 @@ +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 OpenAI from 'openai'; -import { X } from 'lucide-react'; -import { useNavigate } from 'react-router-dom'; +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 { @@ -19,8 +25,12 @@ interface ErrorBody { }; } -export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: QuillyProps) { +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 @@ -36,14 +46,25 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: Qui } }; - case 'insufficient_quota': - 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 '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 { @@ -120,6 +141,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: Qui + + ); } \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 52ec50bf..0d7d5ee1 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -92,10 +92,10 @@ export const ChatPane = forwardRef(({ } }, [providerModel, settings.recentlyUsedModels]); - // Reset state when navigating between projects + // Reset error state when navigating between projects and switching models useEffect(() => { setAIError(null); - }, [projectId]); + }, [projectId, providerModel]); const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); @@ -233,6 +233,11 @@ export const ChatPane = forwardRef(({ setIsModelSelectorOpen(true); }, []); + // Scroll to bottom when AI error occurs + useEffect(() => { + scrollToBottom(); + }, [aiError, scrollToBottom]); + // Check for autostart parameter and trigger AI generation useEffect(() => { if (autostartedRef.current) return; @@ -377,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 @@ -589,6 +596,7 @@ export const ChatPane = forwardRef(({ onDismiss={() => setAIError(null)} onNewChat={onNewChat} onOpenModelSelector={openModelSelector} + providerModel={providerModel} /> )}