mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Make Quilly intercept actual Error objects
This commit is contained in:
4 files changed
+214
-155
No files matched your search
@@ -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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
action={{
|
||||
label: 'Fix it',
|
||||
onClick: actionOnClick
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
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(
|
||||
<Quilly
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Your conversation is too long for this model/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-1">
|
||||
<h4 className="font-semibold text-primary">
|
||||
Pardon the interruption
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onDismiss}
|
||||
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-1">
|
||||
<h4 className="font-semibold text-primary">
|
||||
Pardon the interruption
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onDismiss}
|
||||
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [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<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
// 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<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
};
|
||||
} 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<ChatPaneRef, ChatPaneProps>(({
|
||||
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<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
};
|
||||
} 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<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Model Alert */}
|
||||
{aiModelAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={aiModelAlert.errorMessage || ''}
|
||||
onDismiss={aiModelAlert.dismiss}
|
||||
action={aiModelAlert.action}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Console Error Alert */}
|
||||
{consoleAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={`Console ${consoleAlert.errorCount === 1 ? 'error' : 'errors'} detected in your app. Would you like me to help fix ${consoleAlert.errorCount === 1 ? 'it' : 'them'}?`}
|
||||
<Quilly
|
||||
error={new Error(`Console ${consoleAlert.errorCount === 1 ? 'error' : 'errors'} detected in your app. Would you like me to help fix ${consoleAlert.errorCount === 1 ? 'it' : 'them'}?`)}
|
||||
onDismiss={consoleAlert.dismiss}
|
||||
action={{
|
||||
label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`,
|
||||
@@ -721,8 +673,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
{/* AI Error Alert */}
|
||||
{aiErrorAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={aiErrorAlert.errorMessage}
|
||||
<Quilly
|
||||
error={aiError!}
|
||||
onDismiss={aiErrorAlert.dismiss}
|
||||
action={aiErrorAlert.action}
|
||||
/>
|
||||
|
||||
@@ -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<string>('');
|
||||
|
||||
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
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user