mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge branch 'main' of gitlab.com:soapbox-pub/act2 into esmProxy
This commit is contained in:
commit
5bcf7d7b79
11 files changed
+532
-103
No files matched your search
@@ -6,6 +6,7 @@ import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
@@ -299,8 +300,12 @@ export const AIMessageItem = memo(({
|
||||
);
|
||||
}
|
||||
|
||||
// If there's no reasoning content and the main content is empty, render nothing
|
||||
if (!hasReasoningContent(message) && !getContent().trim()) {
|
||||
if (message.role !== 'assistant') {
|
||||
return null; // Only render assistant and user messages
|
||||
}
|
||||
|
||||
// If the message is empty (no content or reasoning), render nothing
|
||||
if (isEmptyMessage({ ...message, tool_calls: [] })) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
// import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
// import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
@@ -16,42 +14,12 @@ interface Act1DialogProps {
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
// const { setProvider, updateSettings } = useAISettings();
|
||||
|
||||
// // Get the selectedNSPAddr from localStorage
|
||||
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
|
||||
// Get user's credits
|
||||
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
|
||||
const { data: creditsData } = useAICredits(getShakespeareProvider());
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
try {
|
||||
// // Add Shakespeare provider to their config
|
||||
// setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// // Configure recently used models based on credits or NSP
|
||||
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
|
||||
// if (hasCredits || hasMKStackNSP) {
|
||||
// // User has credits or MKStack NSP - set to shakespeare model
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
// } else {
|
||||
// // No credits - set to tybalt model (free)
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
// }
|
||||
|
||||
// Move to migration step
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
@@ -269,36 +237,21 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent className="pt-6">
|
||||
{creditsData?.amount && creditsData.amount > 0 ? (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${creditsData.amount.toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${(creditsData?.amount ?? 0).toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-2xl">🆓</div>
|
||||
<p className="font-medium">Free Access</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
You can continue using Shakespeare for free with the Tybalt model.
|
||||
It's perfect for learning and building amazing projects!
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -429,7 +429,7 @@ describe('ModelSelector', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
|
||||
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
|
||||
expect(cautionButton).toBeInTheDocument();
|
||||
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
|
||||
|
||||
@@ -472,8 +472,163 @@ describe('ModelSelector', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
|
||||
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
|
||||
expect(cautionButton).toBeInTheDocument();
|
||||
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
|
||||
});
|
||||
|
||||
it('shows warning icon when selected model is not in provider models list', () => {
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning icon for model not in list
|
||||
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon when selected model is in provider models list', () => {
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/model1" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon when model is in list
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon while models are loading', () => {
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [],
|
||||
isLoading: true,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon while loading
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon when no models are loaded', () => {
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/some-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon when no models loaded
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows correct tooltip message for model not in list', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const warningIcon = screen.getByTestId('triangle-alert');
|
||||
expect(warningIcon).toBeInTheDocument();
|
||||
|
||||
// Hover over the warning icon
|
||||
await user.hover(warningIcon);
|
||||
|
||||
// Wait for tooltip to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('prioritizes "not in list" warning over "free model" warning in tooltip', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const warningIcon = screen.getByTestId('triangle-alert');
|
||||
expect(warningIcon).toBeInTheDocument();
|
||||
|
||||
// Hover over the warning icon
|
||||
await user.hover(warningIcon);
|
||||
|
||||
// Wait for tooltip to appear - should show "not in list" message, not "free model" message
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// Should not show the free model message
|
||||
expect(screen.queryByText('You are using a free model. For better results, switch to a paid model.')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -104,6 +104,30 @@ export function ModelSelector({
|
||||
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
|
||||
}, [value, models]);
|
||||
|
||||
// Check if the current model is not in the provider's model list
|
||||
const isCurrentModelNotInList = useMemo(() => {
|
||||
if (!value) return false;
|
||||
if (isLoading) return false; // Don't show warning while loading
|
||||
if (models.length === 0) return false; // Don't show warning if no models loaded
|
||||
|
||||
const currentModel = models.find(model => model.fullId === value);
|
||||
return !currentModel;
|
||||
}, [value, models, isLoading]);
|
||||
|
||||
// Determine if we should show the warning icon
|
||||
const shouldShowWarning = isCurrentModelFree || isCurrentModelNotInList;
|
||||
|
||||
// Get the warning message
|
||||
const warningMessage = useMemo(() => {
|
||||
if (isCurrentModelNotInList) {
|
||||
return "This model is not available in your provider's model list. It may not work or may have been deprecated.";
|
||||
}
|
||||
if (isCurrentModelFree) {
|
||||
return "You are using a free model. For better results, switch to a paid model.";
|
||||
}
|
||||
return "";
|
||||
}, [isCurrentModelNotInList, isCurrentModelFree]);
|
||||
|
||||
// Don't auto-initialize with recently used models
|
||||
// Let the parent component handle initialization
|
||||
|
||||
@@ -198,7 +222,7 @@ export function ModelSelector({
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={cn("flex justify-end gap-0.5", className)}>
|
||||
{isCurrentModelFree && (
|
||||
{shouldShowWarning && (
|
||||
<Tooltip
|
||||
open={isMobile ? isTooltipOpen : undefined}
|
||||
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
|
||||
@@ -209,7 +233,7 @@ export function ModelSelector({
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none"
|
||||
aria-label="Free model warning"
|
||||
aria-label="Model warning"
|
||||
tabIndex={isMobile ? 0 : -1}
|
||||
onClick={isMobile ? (e) => {
|
||||
e.preventDefault();
|
||||
@@ -242,7 +266,7 @@ export function ModelSelector({
|
||||
avoidCollisions={true}
|
||||
collisionPadding={8}
|
||||
>
|
||||
<p>You are using a free model. For better results, switch to a paid model.</p>
|
||||
<p>{warningMessage}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
+100
-35
@@ -1,4 +1,4 @@
|
||||
import OpenAI from 'openai';
|
||||
import { APIError } from 'openai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -10,25 +10,27 @@ import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onTryAgain?: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
message: string;
|
||||
action?: {
|
||||
actions?: Array<{
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
@@ -44,96 +46,151 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||
action: {
|
||||
actions: [{
|
||||
label: 'Help fix errors',
|
||||
onClick: () => {
|
||||
onRequestConsoleErrorHelp?.(error);
|
||||
onDismiss();
|
||||
},
|
||||
},
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof MalformedToolCallError) {
|
||||
return {
|
||||
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
|
||||
action: {
|
||||
actions: [{
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
},
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof EmptyMessageError) {
|
||||
return {
|
||||
message: 'The AI generated an empty response. This may be due to a provider issue or model configuration problem. Try generating again, or switch to a different model.',
|
||||
actions: onTryAgain ? [{
|
||||
label: 'Try again',
|
||||
onClick: () => {
|
||||
onTryAgain();
|
||||
onDismiss();
|
||||
},
|
||||
}] : [{
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
case 'invalid_api_key':
|
||||
case 'invalid_request_error':
|
||||
if (error instanceof APIError) {
|
||||
switch (true) {
|
||||
case error.code ==='invalid_api_key':
|
||||
case error.code === 'invalid_request_error':
|
||||
return {
|
||||
message: 'Authentication error: Please check your API key in AI settings.',
|
||||
action: {
|
||||
actions: [{
|
||||
label: 'Check API key',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
}],
|
||||
};
|
||||
|
||||
case 'insufficient_quota': {
|
||||
case error.code === 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
action: {
|
||||
actions: [{
|
||||
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: {
|
||||
actions: [{
|
||||
label: 'Check AI settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
}],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
case 'rate_limit_exceeded':
|
||||
case error.code === 'rate_limit_exceeded':
|
||||
return {
|
||||
message: 'Rate limit exceeded. Please wait a moment before trying again.',
|
||||
actions: [],
|
||||
};
|
||||
|
||||
case 'model_not_found':
|
||||
case error.code === 'model_not_found':
|
||||
return {
|
||||
message: 'The selected AI model is not available. Please choose a different model.',
|
||||
action: {
|
||||
actions: [{
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
case 'context_length_exceeded':
|
||||
case error.code === '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: {
|
||||
actions: [{
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
},
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case 'server_error':
|
||||
case 'service_unavailable':
|
||||
case error.status === 403:
|
||||
return {
|
||||
message: `It seems your API key has been used up. Check your API provider's settings, or try a different API key or different provider/model combo:`,
|
||||
actions: [{
|
||||
label: 'Check API settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.status === 400:
|
||||
return {
|
||||
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
|
||||
actions: [{
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.status === 422:
|
||||
return {
|
||||
message: 'Request rejected by AI provider. Try a different model.',
|
||||
actions: [{
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.code === 'server_error':
|
||||
case error.code === 'service_unavailable':
|
||||
return {
|
||||
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
|
||||
actions: [],
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
message: `AI service error: ${error.message}`,
|
||||
actions: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -143,10 +200,11 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
|
||||
message: error.message
|
||||
? `AI service error: ${error.message}`
|
||||
: 'Sorry, I encountered an unexpected error. Please try again.',
|
||||
actions: [],
|
||||
};
|
||||
};
|
||||
|
||||
const { message, action } = renderBody(error);
|
||||
const { message, actions = [] } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
@@ -159,11 +217,18 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
{actions.length > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
{actions.map((action, i) => (
|
||||
<span key={action.label}>
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
{i < actions.length - 1 && <> or </>}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -649,6 +649,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onDismiss={handleErrorDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onTryAgain={() => startGeneration(providerModel)}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join } from "path-browserify";
|
||||
import type OpenAI from "openai";
|
||||
import type { JSRuntimeFS } from "./JSRuntime";
|
||||
import { isEmptyMessage } from "./isEmptyMessage";
|
||||
|
||||
/** AI message history manager and .git/ai directory utilities */
|
||||
export class DotAI {
|
||||
@@ -46,6 +47,9 @@ export class DotAI {
|
||||
sessionName: string,
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
|
||||
): Promise<void> {
|
||||
// Filter out empty assistant messages
|
||||
messages = messages.filter((msg) => !isEmptyMessage(msg));
|
||||
|
||||
// Validate messages before saving
|
||||
this.validateMessages(messages);
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { makeSystemPrompt } from './system';
|
||||
import { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { MalformedToolCallError } from './errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from './errors/EmptyMessageError';
|
||||
import { isEmptyMessage } from './isEmptyMessage';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -362,6 +364,20 @@ export class SessionManager {
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||
if (isEmptyMessage(assistantMessage)) {
|
||||
console.error('Empty assistant message detected', {
|
||||
projectId,
|
||||
providerModel,
|
||||
finishReason,
|
||||
});
|
||||
|
||||
throw new EmptyMessageError(
|
||||
'The AI generated an empty response. This may be due to a provider issue or model configuration problem.',
|
||||
providerModel,
|
||||
);
|
||||
}
|
||||
|
||||
// Add final message but keep streaming message until finally block
|
||||
await this.addMessage(projectId, assistantMessage);
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Error thrown when the AI generates an empty message with no content, reasoning, or tool calls.
|
||||
* This typically indicates an issue with the AI provider or model configuration.
|
||||
*/
|
||||
export class EmptyMessageError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly providerModel: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'EmptyMessageError';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isEmptyMessage } from './isEmptyMessage';
|
||||
import type { AIMessage } from './SessionManager';
|
||||
|
||||
describe('isEmptyMessage', () => {
|
||||
it('returns false for user messages', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'user',
|
||||
content: 'Hello',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for tool messages', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'tool',
|
||||
content: 'Tool result',
|
||||
tool_call_id: 'call_123',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for assistant message with no content, reasoning, or tool calls', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for assistant message with only whitespace content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: ' \n\t ',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for assistant message with content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: 'Hello, how can I help?',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for assistant message with reasoning content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
reasoning_content: 'Let me think about this...',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for assistant message with tool calls', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_123',
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'text_editor_view',
|
||||
arguments: '{"path": "test.txt"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for assistant message with array content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Hello',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for assistant message with empty array content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: [],
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for assistant message with array content containing only whitespace', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: ' ',
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
text: '\n\t',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for assistant message with content and reasoning', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: 'Here is the answer',
|
||||
reasoning_content: 'I thought about this carefully',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for assistant message with empty reasoning and no content', () => {
|
||||
const message: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
reasoning_content: ' ',
|
||||
};
|
||||
|
||||
expect(isEmptyMessage(message)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { AIMessage } from './SessionManager';
|
||||
|
||||
/**
|
||||
* Type guard to check if message has reasoning content
|
||||
*/
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
return (
|
||||
message.role === 'assistant' &&
|
||||
'reasoning_content' in message &&
|
||||
typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the text content from a message, handling both string and array formats
|
||||
*/
|
||||
function getMessageContent(message: AIMessage): string {
|
||||
if (typeof message.content === 'string') {
|
||||
return message.content;
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content
|
||||
.map(item => {
|
||||
if (typeof item === 'string') return item;
|
||||
if (item.type === 'text') return item.text;
|
||||
return '';
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an assistant message is considered "empty"
|
||||
* A message is empty if:
|
||||
* - Its trimmed text content is empty
|
||||
* - Its reasoning content (if present) is empty
|
||||
* - It has no tool calls
|
||||
*/
|
||||
export function isEmptyMessage(message: AIMessage): boolean {
|
||||
// Only check assistant messages
|
||||
if (message.role !== 'assistant') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const content = getMessageContent(message).trim();
|
||||
const reasoningContent = hasReasoningContent(message) ? message.reasoning_content.trim() : '';
|
||||
const hasToolCalls = message.tool_calls && message.tool_calls.length > 0;
|
||||
|
||||
// Message is empty if there's no content, no reasoning, and no tool calls
|
||||
return !content && !reasoningContent && !hasToolCalls;
|
||||
}
|
||||
Reference in new issue
Block a user