mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Merge in from upstream and resolve conflicts
This commit is contained in:
commit
c46077af67
14 files changed
+680
-476
No files matched your search
@@ -11,6 +11,7 @@ import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
import EmailSettings from "./pages/EmailSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
@@ -33,6 +34,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="email" element={<EmailSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -184,6 +184,75 @@ export const AIMessageItem = memo(({
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Get tool call arguments for special rendering
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
let toolName = '';
|
||||
if (toolCall?.type === 'function') {
|
||||
toolName = toolCall.function.name;
|
||||
try {
|
||||
toolArgs = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
toolArgs = {};
|
||||
}
|
||||
}
|
||||
|
||||
// Special rendering for tools
|
||||
const renderSpecialContent = () => {
|
||||
if (toolName === 'text_editor_write' && toolArgs.file_text) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{toolArgs.file_text as string}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
|
||||
const oldLines = (toolArgs.old_str as string).split('\n');
|
||||
const newLines = (toolArgs.new_str as string).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
<div className="space-y-1">
|
||||
{/* Old content (removed) */}
|
||||
<div className="space-y-0">
|
||||
{oldLines.map((line, index) => (
|
||||
<div key={`old-${index}`} className="flex">
|
||||
<span className="text-red-500 select-none mr-2">-</span>
|
||||
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New content (added) */}
|
||||
<div className="space-y-0">
|
||||
{newLines.map((line, index) => (
|
||||
<div key={`new-${index}`} className="flex">
|
||||
<span className="text-green-500 select-none mr-2">+</span>
|
||||
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
@@ -200,13 +269,7 @@ export const AIMessageItem = memo(({
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isToolExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isToolExpanded && renderSpecialContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import OpenAI from 'openai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { QuillySVG } from '@/components/ui/QuillySVG';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
message: string;
|
||||
action?: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
const credits = useAICredits(provider);
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
case 'invalid_api_key':
|
||||
case 'invalid_request_error':
|
||||
return {
|
||||
message: 'Authentication error: Please check your API key in AI settings.',
|
||||
action: {
|
||||
label: 'Check API key',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
};
|
||||
|
||||
case 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
action: {
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
|
||||
action: {
|
||||
label: 'Check AI settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
case 'rate_limit_exceeded':
|
||||
return {
|
||||
message: 'Rate limit exceeded. Please wait a moment before trying again.',
|
||||
};
|
||||
|
||||
case 'model_not_found':
|
||||
return {
|
||||
message: 'The selected AI model is not available. Please choose a different model.',
|
||||
action: {
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
},
|
||||
};
|
||||
|
||||
case 'context_length_exceeded':
|
||||
return {
|
||||
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
|
||||
action: {
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
},
|
||||
};
|
||||
|
||||
case 'server_error':
|
||||
case 'service_unavailable':
|
||||
return {
|
||||
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
message: `AI service error: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return {
|
||||
message: error.message
|
||||
? `AI service error: ${error.message}`
|
||||
: 'Sorry, I encountered an unexpected error. Please try again.',
|
||||
};
|
||||
};
|
||||
|
||||
const { message, action } = renderBody(error);
|
||||
|
||||
return (
|
||||
<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>
|
||||
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -56,6 +56,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
@@ -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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
@@ -40,59 +40,13 @@ import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection';
|
||||
import { useProjectConsoleMessages } from '@/hooks/useProjectConsoleMessages';
|
||||
import { QuillySVG } from '@/components/ui/QuillySVG';
|
||||
import type { ConsoleMessage } from '@/types/console';
|
||||
|
||||
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 { Quilly } from '@/components/Quilly';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
interface ChatPaneProps {
|
||||
projectId: string;
|
||||
onNewChat?: () => void;
|
||||
onBuild?: () => void;
|
||||
onNewChat: () => void;
|
||||
onFirstInteraction?: () => void;
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
isLoading?: boolean;
|
||||
@@ -105,8 +59,7 @@ export interface ChatPaneRef {
|
||||
|
||||
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
onNewChat: _onNewChat,
|
||||
onBuild: _onBuild,
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
@@ -119,6 +72,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
@@ -130,6 +85,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
});
|
||||
// State to control model selector dropdown
|
||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||
const autostartedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
@@ -137,12 +93,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels]);
|
||||
|
||||
// Reset error state when navigating between projects and switching models
|
||||
useEffect(() => {
|
||||
setAIError(null);
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
const { messages: consoleMessages } = useProjectConsoleMessages(projectId);
|
||||
|
||||
// Use ref to maintain stable reference to console messages for tools
|
||||
const consoleMessagesRef = useRef<ConsoleMessage[]>([]);
|
||||
@@ -214,6 +174,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
updateMetadata(title, description);
|
||||
}, [updateMetadata]);
|
||||
|
||||
// Handle AI errors from the SessionManager
|
||||
const onAIError = useCallback((error: Error) => {
|
||||
setAIError(error);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
messages,
|
||||
streamingMessage,
|
||||
@@ -229,6 +194,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
tools,
|
||||
customTools,
|
||||
onUpdateMetadata,
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
@@ -252,6 +218,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [internalIsLoading, onLoadingChange]);
|
||||
|
||||
// Timer to detect when AI appears stuck during tool generation
|
||||
useEffect(() => {
|
||||
// Start a 2-second timer
|
||||
const timer = streamingMessage
|
||||
? setTimeout(() => setIsStuck(true), 2000)
|
||||
: undefined;
|
||||
|
||||
return () => {
|
||||
setIsStuck(false);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [streamingMessage]);
|
||||
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = useCallback(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
@@ -264,22 +243,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
setIsModelSelectorOpen(true);
|
||||
}, []);
|
||||
|
||||
// Function to suggest error fix
|
||||
// Clean alert hooks with proper interfaces
|
||||
const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
|
||||
const consoleAlert = useConsoleErrorAlert(messages, projectId, isBuildLoading, internalIsLoading);
|
||||
|
||||
// Scroll to bottom when alerts appear
|
||||
// Scroll to bottom when AI error occurs
|
||||
useEffect(() => {
|
||||
if (aiModelAlert.hasError || consoleAlert.hasError) {
|
||||
setTimeout(() => {
|
||||
scrollToBottom();
|
||||
}, 50);
|
||||
}
|
||||
}, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]);
|
||||
scrollToBottom();
|
||||
}, [aiError, scrollToBottom]);
|
||||
|
||||
// Check for autostart parameter and trigger AI generation
|
||||
useEffect(() => {
|
||||
if (autostartedRef.current) return;
|
||||
|
||||
const autostart = searchParams.get('autostart');
|
||||
const urlModel = searchParams.get('model');
|
||||
|
||||
@@ -302,6 +274,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
autostartedRef.current = true;
|
||||
}
|
||||
}
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
|
||||
@@ -419,6 +392,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// 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
|
||||
@@ -461,14 +436,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// 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 () => {
|
||||
@@ -537,10 +507,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}), [internalStartNewSession]);
|
||||
|
||||
const suggestErrorFix = useCallback(async () => {
|
||||
await send('Read the console messages and fix any errors.', []);
|
||||
}, [send]);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col relative">
|
||||
|
||||
@@ -593,11 +559,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
})}
|
||||
{streamingMessage && (
|
||||
streamingMessage.content || streamingMessage.reasoning_content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
<>
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
{/* Show loading skeleton if AI appears stuck generating tools */}
|
||||
{isStuck && (
|
||||
<div key="stuck-loading-skeleton" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
|
||||
<div key="streaming-loading" className="flex">
|
||||
@@ -621,27 +599,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Model Alert */}
|
||||
{aiModelAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={aiModelAlert.errorMessage || ''}
|
||||
onDismiss={aiModelAlert.dismiss}
|
||||
action={aiModelAlert.action}
|
||||
{/* AI Error Alert */}
|
||||
{aiError && (
|
||||
<Quilly
|
||||
error={aiError}
|
||||
onDismiss={() => setAIError(null)}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 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'}?`}
|
||||
onDismiss={consoleAlert.dismiss}
|
||||
action={{
|
||||
label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`,
|
||||
onClick: () => suggestErrorFix()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+25
-7
@@ -12,6 +12,7 @@ interface UseAIChatSessionOptions {
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
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<OpenAI.Chat.Completions.ChatCompletionContentPartText>, 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);
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -178,6 +178,7 @@ export class SessionManager {
|
||||
* Start AI generation for a session
|
||||
*/
|
||||
async startGeneration(projectId: string, providerModel: string): Promise<void> {
|
||||
console.log('Starting AI generation for project:', projectId, 'with model:', providerModel);
|
||||
let session = this.sessions.get(projectId);
|
||||
|
||||
if (!session) {
|
||||
@@ -403,23 +404,13 @@ export class SessionManager {
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle different error types
|
||||
if (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}`;
|
||||
// Handle user cancellation
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -79,6 +79,9 @@ const resources = {
|
||||
nostrSettingsDescription: 'Configure relay connections and Nostr preferences',
|
||||
dataSettings: 'Data',
|
||||
dataSettingsDescription: 'Export files and manage local data',
|
||||
emailUpdates: 'Email Updates',
|
||||
emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources',
|
||||
emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.',
|
||||
aboutShakespeareSettings: 'About Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Information about Shakespeare',
|
||||
|
||||
@@ -378,6 +381,9 @@ const resources = {
|
||||
nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr',
|
||||
dataSettings: 'Dados',
|
||||
dataSettingsDescription: 'Exporte arquivos e gerencie dados locais',
|
||||
emailUpdates: 'Atualizações por Email',
|
||||
emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare',
|
||||
emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.',
|
||||
aboutShakespeareSettings: 'Sobre o Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare',
|
||||
|
||||
@@ -677,6 +683,9 @@ const resources = {
|
||||
nostrSettingsDescription: '配置中继连接和Nostr偏好',
|
||||
dataSettings: '数据',
|
||||
dataSettingsDescription: '导出文件和管理本地数据',
|
||||
emailUpdates: '邮件更新',
|
||||
emailUpdatesDescription: '订阅Shakespeare更新和资源',
|
||||
emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。',
|
||||
aboutShakespeareSettings: '关于Shakespeare',
|
||||
aboutShakespeareSettingsDescription: '关于Shakespeare的信息',
|
||||
|
||||
@@ -976,6 +985,9 @@ const resources = {
|
||||
nostrSettingsDescription: 'Saita haɗin relay da zaɓuɓɓukan Nostr',
|
||||
dataSettings: 'Bayanai',
|
||||
dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida',
|
||||
emailUpdates: 'Sabuntawar Imel',
|
||||
emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu',
|
||||
emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.',
|
||||
aboutShakespeareSettings: 'Game da Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare',
|
||||
|
||||
@@ -1275,6 +1287,9 @@ const resources = {
|
||||
nostrSettingsDescription: 'Tunto awọn asopọ relay ati awọn ayanfẹ Nostr',
|
||||
dataSettings: 'Data',
|
||||
dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe',
|
||||
emailUpdates: 'Awọn Imudojuiwọn Imeeli',
|
||||
emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo',
|
||||
emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.',
|
||||
aboutShakespeareSettings: 'Nipa Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare',
|
||||
|
||||
@@ -1569,6 +1584,9 @@ const resources = {
|
||||
nostrSettingsDescription: 'Hazie njikọ relay na nhọrọ Nostr',
|
||||
dataSettings: 'Data',
|
||||
dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara',
|
||||
emailUpdates: 'Nmelite Email',
|
||||
emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa',
|
||||
emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.',
|
||||
aboutShakespeareSettings: 'Gbasara Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare',
|
||||
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
|
||||
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
|
||||
|
||||
userText += `Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
} else {
|
||||
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Prepare form data
|
||||
const formData = new FormData();
|
||||
formData.append('email', email.trim());
|
||||
formData.append('tag_id', '8982396');
|
||||
|
||||
// Include npub if user is signed in
|
||||
if (user?.pubkey) {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
formData.append('npub', npub);
|
||||
}
|
||||
|
||||
// Submit to Mailchimp using the same setup as soapbox2
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0';
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = '8982396';
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = 'b_f1f718a93795f42a604d558d8_f7271442a0';
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => navigate('/settings')}
|
||||
className="w-full"
|
||||
>
|
||||
Back to Settings
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
Stay Updated with Shakespeare
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmailSettings;
|
||||
@@ -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';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
@@ -41,20 +40,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;
|
||||
|
||||
@@ -103,20 +88,6 @@ export function ProjectView() {
|
||||
};
|
||||
}, [projectId, clearMessages]);
|
||||
|
||||
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) {
|
||||
@@ -246,7 +217,6 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
@@ -426,7 +396,6 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface SettingsItem {
|
||||
@@ -48,6 +48,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
Reference in new issue
Block a user