From 399e9a0262f141d49a5166839170dce5de0f369e Mon Sep 17 00:00:00 2001
From: Mary Kate Fain
Date: Wed, 24 Sep 2025 11:05:17 -0500
Subject: [PATCH 01/15] Add email signup page to Settings
- Add new Email Updates page under Settings menu
- Simple form for Shakespeare newsletter subscription
- Uses same Mailchimp setup as soapbox2 with tag ID 8982396
- Automatically includes user's npub if signed in to Nostr
- Added to both mobile and desktop settings layouts
- Includes translations for all supported languages
- Clean success/error handling with opt-out messaging
---
src/AppRouter.tsx | 2 +
src/components/SettingsLayout.tsx | 9 +-
src/lib/i18n.ts | 18 +++
src/pages/EmailSettings.tsx | 256 ++++++++++++++++++++++++++++++
src/pages/Settings.tsx | 9 +-
5 files changed, 292 insertions(+), 2 deletions(-)
create mode 100644 src/pages/EmailSettings.tsx
diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx
index a80c5fea..c0d70908 100644
--- a/src/AppRouter.tsx
+++ b/src/AppRouter.tsx
@@ -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() {
} />
} />
} />
+ } />
} />
} />
diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx
index 6cf9ea0c..200fff49 100644
--- a/src/components/SettingsLayout.tsx
+++ b/src/components/SettingsLayout.tsx
@@ -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'),
diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts
index 8e1b1296..65febe78 100644
--- a/src/lib/i18n.ts
+++ b/src/lib/i18n.ts
@@ -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',
diff --git a/src/pages/EmailSettings.tsx b/src/pages/EmailSettings.tsx
new file mode 100644
index 00000000..c8a0e176
--- /dev/null
+++ b/src/pages/EmailSettings.tsx
@@ -0,0 +1,256 @@
+import { useState } 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);
+
+ 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);
+
+ 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 (
+
+ {isMobile && (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+ Thanks for subscribing!
+
+
+ You can opt out at any time using the unsubscribe link in our emails.
+
+
+
+
+
+
+
+
+ );
+ }
+
+ return (
+
+ {isMobile && (
+
+
+
+
+
+ {t('emailUpdates')}
+
+
+ {t('emailUpdatesDescriptionLong')}
+
+
+
+ )}
+
+ {!isMobile && (
+
+
+
+ {t('emailUpdates')}
+
+
+ {t('emailUpdatesDescriptionLong')}
+
+
+ )}
+
+
+
+
+
+ Stay Updated with Shakespeare
+
+
+
+
+
+
+
+
+ );
+}
+
+export default EmailSettings;
\ No newline at end of file
diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx
index cf978600..ecb29350 100644
--- a/src/pages/Settings.tsx
+++ b/src/pages/Settings.tsx
@@ -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'),
From 3751cb23fcadc5cdcda0c9de3b32c9ff26b7317e Mon Sep 17 00:00:00 2001
From: Mary Kate Fain
Date: Wed, 24 Sep 2025 11:08:47 -0500
Subject: [PATCH 02/15] Add localStorage to remember email subscription status
- Check localStorage on component mount to show thank you screen if already subscribed
- Save subscription status after successful signup
- Add 'Subscribe with different email' button to reset localStorage
- Prevents duplicate subscription attempts and improves UX
---
src/pages/EmailSettings.tsx | 38 ++++++++++++++++++++++++++++++-------
1 file changed, 31 insertions(+), 7 deletions(-)
diff --git a/src/pages/EmailSettings.tsx b/src/pages/EmailSettings.tsx
index c8a0e176..fc929f36 100644
--- a/src/pages/EmailSettings.tsx
+++ b/src/pages/EmailSettings.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, useEffect } from 'react';
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
@@ -22,6 +22,14 @@ export function EmailSettings() {
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();
@@ -108,6 +116,9 @@ export function EmailSettings() {
document.body.removeChild(form);
}, 1000);
+ // Save subscription status to localStorage
+ localStorage.setItem('shakespeare-email-subscribed', 'true');
+
setIsSubmitted(true);
toast({
title: "Successfully subscribed!",
@@ -155,12 +166,25 @@ export function EmailSettings() {
You can opt out at any time using the unsubscribe link in our emails.
-
+
+
+
+
From f40ef03b58bcbecd96450758d44130c28cfa3a86 Mon Sep 17 00:00:00 2001
From: Mary Kate Fain
Date: Wed, 24 Sep 2025 11:11:28 -0500
Subject: [PATCH 03/15] Fix email signup page styling
- Add 'Email Updates' header to thank you page for consistency
- Remove mx-auto centering from forms to make them left-aligned
- Maintain responsive layout for both mobile and desktop
---
src/pages/EmailSettings.tsx | 25 +++++++++++++++++++++++--
1 file changed, 23 insertions(+), 2 deletions(-)
diff --git a/src/pages/EmailSettings.tsx b/src/pages/EmailSettings.tsx
index fc929f36..2ce12e91 100644
--- a/src/pages/EmailSettings.tsx
+++ b/src/pages/EmailSettings.tsx
@@ -150,10 +150,31 @@ export function EmailSettings() {
{t('backToSettings')}
+
+
+
+ {t('emailUpdates')}
+
+
+ {t('emailUpdatesDescriptionLong')}
+
+
)}
-
+ {!isMobile && (
+
+
+
+ {t('emailUpdates')}
+
+
+ {t('emailUpdatesDescriptionLong')}
+
+
+ )}
+
+
@@ -230,7 +251,7 @@ export function EmailSettings() {
)}
-
+
From 9bd7e3659725ca0b958f3408e76c5dcd8cef9ab7 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 14:04:20 -0500
Subject: [PATCH 04/15] Display loading skeleton when generation is stuck (not
streaming tool calls, eg GLM)
---
src/components/Shakespeare/ChatPane.tsx | 36 +++++++++++++++++++++----
1 file changed, 31 insertions(+), 5 deletions(-)
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index 0fd5dc39..4409078b 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -117,6 +117,7 @@ export const ChatPane = forwardRef(({
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set());
const [showOnboarding, setShowOnboarding] = useState(false);
+ const [isStuck, setIsStuck] = useState(false);
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -240,6 +241,19 @@ export const ChatPane = forwardRef(({
}
}, [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) {
@@ -581,11 +595,23 @@ export const ChatPane = forwardRef(({
})}
{streamingMessage && (
streamingMessage.content || streamingMessage.reasoning_content ? (
-
+ <>
+
+ {/* Show loading skeleton if AI appears stuck generating tools */}
+ {isStuck && (
+
+ )}
+ >
) : (
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
From 568ea5dc0440701f5d2bdae35ebe4f17f406096b Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 14:22:55 -0500
Subject: [PATCH 05/15] Fix missing linebreaks in system prompt
---
src/lib/system.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/lib/system.ts b/src/lib/system.ts
index 78976c9e..926276af 100644
--- a/src/lib/system.ts
+++ b/src/lib/system.ts
@@ -46,7 +46,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise
Date: Wed, 24 Sep 2025 15:10:09 -0500
Subject: [PATCH 06/15] Prevent duplicate sessions when starting a new project
---
src/components/Shakespeare/ChatPane.tsx | 4 ++++
src/lib/SessionManager.ts | 1 +
2 files changed, 5 insertions(+)
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index 4409078b..f9c987af 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -129,6 +129,7 @@ export const ChatPane = forwardRef(({
});
// State to control model selector dropdown
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
+ const autostartedRef = useRef(false);
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
@@ -282,6 +283,8 @@ export const ChatPane = forwardRef(({
// Check for autostart parameter and trigger AI generation
useEffect(() => {
+ if (autostartedRef.current) return;
+
const autostart = searchParams.get('autostart');
const urlModel = searchParams.get('model');
@@ -304,6 +307,7 @@ export const ChatPane = forwardRef(({
// Start AI generation
addRecentlyUsedModel(modelToUse);
startGeneration(modelToUse);
+ autostartedRef.current = true;
}
}
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts
index e90f285a..9cf996b9 100644
--- a/src/lib/SessionManager.ts
+++ b/src/lib/SessionManager.ts
@@ -178,6 +178,7 @@ export class SessionManager {
* Start AI generation for a session
*/
async startGeneration(projectId: string, providerModel: string): Promise {
+ console.log('Starting AI generation for project:', projectId, 'with model:', providerModel);
let session = this.sessions.get(projectId);
if (!session) {
From 688b35fa412e8aee2fff6be2f619f09925357efe Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 15:21:04 -0500
Subject: [PATCH 07/15] Start adding special rendering to tool results
---
src/components/AIMessageItem.tsx | 77 +++++++++++++++++++++++++++++---
1 file changed, 70 insertions(+), 7 deletions(-)
diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx
index ecc64720..f850d900 100644
--- a/src/components/AIMessageItem.tsx
+++ b/src/components/AIMessageItem.tsx
@@ -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 = {};
+ 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 (
+
+
+ {toolArgs.file_text as string}
+
+
+ );
+ }
+
+ 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 (
+
+
+ {/* Old content (removed) */}
+
+ {oldLines.map((line, index) => (
+
+ -
+
+ {line}
+
+
+ ))}
+
+
+ {/* New content (added) */}
+
+ {newLines.map((line, index) => (
+
+ +
+
+ {line}
+
+
+ ))}
+
+
+
+ );
+ }
+
+ // Default rendering for other tools
+ return (
+
+ );
+ };
+
// Regular tool message rendering
return (
{/* -mt-2 to make it snug with the previous assistant message */}
@@ -200,13 +269,7 @@ export const AIMessageItem = memo(({
- {isToolExpanded && (
-
- )}
+ {isToolExpanded && renderSpecialContent()}
);
}
From 0bdc9fa6a3570c66d9b600d86aab4794e4dd7217 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 15:34:15 -0500
Subject: [PATCH 08/15] Don't display an error in the chat when the user
cancels their own generation
---
src/lib/SessionManager.ts | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts
index 9cf996b9..c7b6b689 100644
--- a/src/lib/SessionManager.ts
+++ b/src/lib/SessionManager.ts
@@ -405,7 +405,9 @@ export class SessionManager {
console.error('AI generation error:', error);
// Handle different error types
- if (error?.name === 'AbortError') return; // User cancelled
+ if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
+ return; // User cancelled
+ }
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
const errorMsg = error?.message || '';
From e9f8e99ac5ea14291f2068b2046b6672927b8ec5 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 20:00:02 -0500
Subject: [PATCH 09/15] Surface AI Errors to ChatPane
---
src/components/Shakespeare/ChatPane.tsx | 88 ++++++++++++++++++++++---
src/hooks/useAIChat.ts | 32 +++++++--
src/lib/SessionManager.test.ts | 22 +++++++
src/lib/SessionManager.ts | 18 +----
4 files changed, 128 insertions(+), 32 deletions(-)
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index f9c987af..366630db 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -118,6 +118,7 @@ export const ChatPane = forwardRef(({
const [scrolledProjects] = useState(() => new Set());
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
+ const [aiError, setAIError] = useState(null);
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -204,6 +205,11 @@ export const ChatPane = forwardRef(({
updateMetadata(title, description);
}, [updateMetadata]);
+ // Handle AI errors from the SessionManager
+ const onAIError = useCallback((error: Error) => {
+ setAIError(error);
+ }, []);
+
const {
messages,
streamingMessage,
@@ -219,6 +225,7 @@ export const ChatPane = forwardRef(({
tools,
customTools,
onUpdateMetadata,
+ onAIError,
});
// Use external loading state if provided, otherwise use internal state
@@ -272,14 +279,71 @@ export const ChatPane = forwardRef(({
const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
+ // Create AI error alert object
+ const aiErrorAlert = useMemo(() => {
+ if (!aiError) {
+ return { hasError: false, errorMessage: '', dismiss: () => {}, action: undefined };
+ }
+
+ let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
+ let action: { label: string; onClick: () => void } | undefined;
+
+ const errorMsg = aiError.message || '';
+
+ if (aiError.name === 'TypeError' && errorMsg.includes('fetch')) {
+ errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
+ action = {
+ label: 'Check AI settings',
+ onClick: () => {
+ // Navigate to AI settings
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('API key')) {
+ errorMessage = 'Authentication error: Please check your API key in AI settings.';
+ action = {
+ label: 'Check API key',
+ onClick: () => {
+ // Navigate to AI settings
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('rate limit')) {
+ errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
+ } else if (errorMsg.includes('insufficient_quota')) {
+ errorMessage = 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.';
+ action = {
+ label: 'Check AI settings',
+ onClick: () => {
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
+ errorMessage = 'Model not found: The selected AI model is not available. Please choose a different model.';
+ action = {
+ label: 'Choose model',
+ onClick: openModelSelector
+ };
+ } else if (errorMsg) {
+ errorMessage = `AI service error: ${errorMsg}`;
+ }
+
+ return {
+ hasError: true,
+ errorMessage,
+ dismiss: () => setAIError(null),
+ action
+ };
+ }, [aiError, openModelSelector]);
+
// Scroll to bottom when alerts appear
useEffect(() => {
- if (aiModelAlert.hasError || consoleAlert.hasError) {
+ if (aiModelAlert.hasError || consoleAlert.hasError || aiErrorAlert.hasError) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
- }, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]);
+ }, [aiModelAlert.hasError, consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
@@ -467,14 +531,9 @@ export const ChatPane = forwardRef(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
- try {
- // Send as text parts if we have multiple parts, otherwise send as string for simplicity
- const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
- await sendMessage(messageContent, modelToUse);
- } catch (error) {
- console.error('AI chat error:', error);
- // Error handling is done in the useAIChat hook and SessionManager
- }
+ // Send as text parts if we have multiple parts, otherwise send as string for simplicity
+ const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
+ await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
@@ -660,6 +719,15 @@ export const ChatPane = forwardRef(({
/>
)}
+ {/* AI Error Alert */}
+ {aiErrorAlert.hasError && (
+
+ )}
+
diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts
index ad28255f..a6c1418f 100644
--- a/src/hooks/useAIChat.ts
+++ b/src/hooks/useAIChat.ts
@@ -12,6 +12,7 @@ interface UseAIChatSessionOptions {
customTools?: Record
>;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
+ onAIError?: (error: Error) => void;
}
interface StreamingMessage {
@@ -30,7 +31,8 @@ export function useAIChat({
tools = {},
customTools = {},
maxSteps = 50,
- onUpdateMetadata
+ onUpdateMetadata,
+ onAIError
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
@@ -113,14 +115,30 @@ export function useAIChat({
// Actions
const sendMessage = useCallback(async (content: string | Array, providerModel: string) => {
- await initSession();
- await sessionManager.sendMessage(projectId, content, providerModel);
- }, [projectId, sessionManager, initSession]);
+ try {
+ await initSession();
+ await sessionManager.sendMessage(projectId, content, providerModel);
+ } catch (error) {
+ if (onAIError && error instanceof Error) {
+ onAIError(error);
+ } else {
+ console.error('AI chat error:', error);
+ }
+ }
+ }, [projectId, sessionManager, initSession, onAIError]);
const startGeneration = useCallback(async (providerModel: string) => {
- await initSession();
- await sessionManager.startGeneration(projectId, providerModel);
- }, [projectId, sessionManager, initSession]);
+ try {
+ await initSession();
+ await sessionManager.startGeneration(projectId, providerModel);
+ } catch (error) {
+ if (onAIError && error instanceof Error) {
+ onAIError(error);
+ } else {
+ console.error('AI chat error:', error);
+ }
+ }
+ }, [projectId, sessionManager, initSession, onAIError]);
const stopGeneration = useCallback(() => {
sessionManager.stopGeneration(projectId);
diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts
index 25de75ef..911b2a63 100644
--- a/src/lib/SessionManager.test.ts
+++ b/src/lib/SessionManager.test.ts
@@ -95,4 +95,26 @@ describe('SessionManager', () => {
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
}
});
+
+ it('should throw service errors instead of adding them to message history', async () => {
+ const projectId = 'test-project';
+ const tools = {};
+ const customTools = {};
+
+ // Load a session
+ await sessionManager.loadSession(projectId, tools, customTools);
+
+ // Add a user message to enable generation
+ await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' });
+
+ // Attempt to start generation with invalid provider - should throw error instead of adding to messages
+ await expect(
+ sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model')
+ ).rejects.toThrow('Provider "invalid-provider" not found');
+
+ // Verify that no error message was added to the conversation
+ const updatedSession = sessionManager.getSession(projectId);
+ expect(updatedSession?.messages).toHaveLength(1); // Only the user message
+ expect(updatedSession?.messages[0].role).toBe('user');
+ });
});
\ No newline at end of file
diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts
index c7b6b689..19978226 100644
--- a/src/lib/SessionManager.ts
+++ b/src/lib/SessionManager.ts
@@ -404,25 +404,13 @@ export class SessionManager {
} catch (error) {
console.error('AI generation error:', error);
- // Handle different error types
+ // Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
return; // User cancelled
}
- let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
- const errorMsg = error?.message || '';
-
- if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
- errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
- } else if (errorMsg.includes('API key')) {
- errorMessage = 'Authentication error: Please check your API key in AI settings.';
- } else if (errorMsg.includes('rate limit')) {
- errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
- } else if (errorMsg) {
- errorMessage = `AI service error: ${errorMsg}`;
- }
-
- await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
+ // Re-throw service errors to be handled at the UI level
+ throw error;
} finally {
if (session) {
session.isLoading = false;
From d932f05d04feab268cac5da3899c4d8ef9b569aa Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 20:18:43 -0500
Subject: [PATCH 10/15] Make Quilly intercept actual Error objects
---
src/components/Quilly.test.tsx | 116 ++++++++++++++++++++++++
src/components/Quilly.tsx | 72 +++++++++++++++
src/components/Shakespeare/ChatPane.tsx | 100 ++++++--------------
src/hooks/useErrorDetection.ts | 81 -----------------
4 files changed, 214 insertions(+), 155 deletions(-)
create mode 100644 src/components/Quilly.test.tsx
create mode 100644 src/components/Quilly.tsx
diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx
new file mode 100644
index 00000000..6e50e06c
--- /dev/null
+++ b/src/components/Quilly.test.tsx
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import { Quilly } from './Quilly';
+
+describe('Quilly', () => {
+ it('renders with error message', () => {
+ const error = new Error('Test error message');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ expect(screen.getByText('Pardon the interruption')).toBeInTheDocument();
+ expect(screen.getByText(/AI service error: Test error message/)).toBeInTheDocument();
+ });
+
+ it('calls onDismiss when dismiss button is clicked', () => {
+ const error = new Error('Test error');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ const dismissButton = screen.getByRole('button');
+ fireEvent.click(dismissButton);
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders action button when provided', () => {
+ const error = new Error('Test error');
+ const onDismiss = vi.fn();
+ const actionOnClick = vi.fn();
+
+ render(
+
+ );
+
+ const actionButton = screen.getByRole('button', { name: 'Fix it' });
+ expect(actionButton).toBeInTheDocument();
+
+ fireEvent.click(actionButton);
+ expect(actionOnClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('formats network error messages correctly', () => {
+ const error = new TypeError('fetch failed');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ expect(screen.getByText(/Network error: Unable to connect to AI service/)).toBeInTheDocument();
+ });
+
+ it('formats API key error messages correctly', () => {
+ const error = new Error('Invalid API key provided');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ expect(screen.getByText(/Authentication error: Please check your API key/)).toBeInTheDocument();
+ });
+
+ it('formats rate limit error messages correctly', () => {
+ const error = new Error('Rate limit exceeded');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ expect(screen.getByText(/Rate limit exceeded/)).toBeInTheDocument();
+ });
+
+ it('formats context length error messages correctly', () => {
+ const error = new Error('maximum context length is 4096 tokens');
+ const onDismiss = vi.fn();
+
+ render(
+
+ );
+
+ expect(screen.getByText(/Your conversation is too long for this model/)).toBeInTheDocument();
+ });
+});
\ No newline at end of file
diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx
new file mode 100644
index 00000000..d8a08d44
--- /dev/null
+++ b/src/components/Quilly.tsx
@@ -0,0 +1,72 @@
+import { Button } from '@/components/ui/button';
+import { QuillySVG } from '@/components/ui/QuillySVG';
+import { X } from 'lucide-react';
+
+export interface QuillyProps {
+ error: Error;
+ onDismiss: () => void;
+ action?: { label: string; onClick: () => void };
+}
+
+export function Quilly({ error, onDismiss, action }: QuillyProps) {
+ // Generate user-friendly message from error
+ const getMessage = (error: Error): string => {
+ const errorMsg = error.message || '';
+
+ if (error.name === 'TypeError' && errorMsg.includes('fetch')) {
+ return 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
+ } else if (errorMsg.includes('API key')) {
+ return 'Authentication error: Please check your API key in AI settings.';
+ } else if (errorMsg.includes('rate limit')) {
+ return 'Rate limit exceeded. Please wait a moment before trying again.';
+ } else if (errorMsg.includes('insufficient_quota')) {
+ return 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.';
+ } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
+ return 'Model not found: The selected AI model is not available. Please choose a different model.';
+ } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
+ return 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.';
+ } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
+ return 'The AI model encountered an issue. Try switching to a different model or starting a new chat.';
+ } else if (errorMsg.includes('too many requests')) {
+ return 'You\'re sending requests too quickly. Please wait a moment before trying again.';
+ } else if (errorMsg) {
+ return `AI service error: ${errorMsg}`;
+ } else {
+ return 'Sorry, I encountered an unexpected error. Please try again.';
+ }
+ };
+
+ const message = getMessage(error);
+
+ return (
+
+
+
+
+
+
+ Pardon the interruption
+
+
+ {message}
+ {' '}
+ {action && (
+
+ )}
+
+
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index 366630db..38ef71ba 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -8,7 +8,7 @@ import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { OnboardingDialog } from '@/components/OnboardingDialog';
-import { Square, Loader2, ChevronDown, ArrowUp, X } from 'lucide-react';
+import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -39,51 +39,8 @@ import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
-import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection';
-import { QuillySVG } from '@/components/ui/QuillySVG';
-
-
-function ChatIntervention({
- message,
- onDismiss,
- action,
-}: {
- message: string;
- onDismiss: () => void;
- action?: { label: string; onClick: () => void };
-}) {
- return (
-
-
-
-
-
-
- Pardon the interruption
-
-
- {message}
- {' '}
- {action && (
-
- )}
-
-
-
-
-
-
- );
-}
+import { useConsoleErrorAlert } from '@/hooks/useErrorDetection';
+import { Quilly } from '@/components/Quilly';
// Clean interfaces now handled by proper hooks
@@ -138,6 +95,11 @@ export const ChatPane = forwardRef(({
}
}, [providerModel, settings.recentlyUsedModels]);
+ // Reset state when navigating between projects
+ useEffect(() => {
+ setAIError(null);
+ }, [projectId]);
+
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
@@ -276,22 +238,19 @@ export const ChatPane = forwardRef(({
// Function to suggest error fix
// Clean alert hooks with proper interfaces
- const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
// Create AI error alert object
const aiErrorAlert = useMemo(() => {
if (!aiError) {
- return { hasError: false, errorMessage: '', dismiss: () => {}, action: undefined };
+ return { hasError: false, dismiss: () => {}, action: undefined };
}
- let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
let action: { label: string; onClick: () => void } | undefined;
const errorMsg = aiError.message || '';
if (aiError.name === 'TypeError' && errorMsg.includes('fetch')) {
- errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
action = {
label: 'Check AI settings',
onClick: () => {
@@ -300,7 +259,6 @@ export const ChatPane = forwardRef(({
}
};
} else if (errorMsg.includes('API key')) {
- errorMessage = 'Authentication error: Please check your API key in AI settings.';
action = {
label: 'Check API key',
onClick: () => {
@@ -308,10 +266,7 @@ export const ChatPane = forwardRef(({
window.location.href = '/settings/ai';
}
};
- } else if (errorMsg.includes('rate limit')) {
- errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
} else if (errorMsg.includes('insufficient_quota')) {
- errorMessage = 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.';
action = {
label: 'Check AI settings',
onClick: () => {
@@ -319,31 +274,37 @@ export const ChatPane = forwardRef(({
}
};
} else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
- errorMessage = 'Model not found: The selected AI model is not available. Please choose a different model.';
action = {
label: 'Choose model',
onClick: openModelSelector
};
- } else if (errorMsg) {
- errorMessage = `AI service error: ${errorMsg}`;
+ } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
+ action = _onNewChat ? {
+ label: 'New chat',
+ onClick: _onNewChat
+ } : undefined;
+ } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
+ action = openModelSelector ? {
+ label: 'Change model',
+ onClick: openModelSelector
+ } : undefined;
}
return {
hasError: true,
- errorMessage,
dismiss: () => setAIError(null),
action
};
- }, [aiError, openModelSelector]);
+ }, [aiError, openModelSelector, _onNewChat]);
// Scroll to bottom when alerts appear
useEffect(() => {
- if (aiModelAlert.hasError || consoleAlert.hasError || aiErrorAlert.hasError) {
+ if (consoleAlert.hasError || aiErrorAlert.hasError) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
- }, [aiModelAlert.hasError, consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]);
+ }, [consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
@@ -698,19 +659,10 @@ export const ChatPane = forwardRef(({
)}
- {/* AI Model Alert */}
- {aiModelAlert.hasError && (
-
- )}
-
{/* Console Error Alert */}
{consoleAlert.hasError && (
- (({
{/* AI Error Alert */}
{aiErrorAlert.hasError && (
-
diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts
index 9a100f85..c530f646 100644
--- a/src/hooks/useErrorDetection.ts
+++ b/src/hooks/useErrorDetection.ts
@@ -69,85 +69,4 @@ export const useConsoleErrorAlert = (
};
};
-export interface AIModelErrorAlert {
- hasError: boolean;
- errorMessage: string | null;
- errorType: 'warn' | 'error' | null;
- action?: { label: string; onClick: () => void };
- dismiss: () => void;
-}
-export const useAIModelErrorAlert = (
- messages: AIMessage[],
- onNewChat?: () => void,
- onChangeModel?: () => void
-): AIModelErrorAlert => {
- const [dismissedAlertKey, setDismissedAlertKey] = useState('');
-
- const { hasError, errorMessage, errorType, action } = useMemo(() => {
- const lastMessage = messages[messages.length - 1];
-
- // Only show AI model alerts if the last message is from the assistant
- // This ensures we don't show stale alerts when user continues the conversation
- if (!lastMessage || lastMessage.role !== 'assistant') {
- return { hasError: false, errorMessage: null, errorType: null, action: undefined };
- }
-
- const content = typeof lastMessage.content === 'string' ? lastMessage.content : '';
-
- // Define error patterns with actions
- const errorPatterns = [
- {
- test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content),
- type: 'error' as const,
- message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.',
- action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined
- },
- {
- test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content),
- type: 'warn' as const,
- message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
- action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined
- },
- {
- test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content),
- type: 'warn' as const,
- message: 'You\'re sending requests too quickly. Please wait a moment before trying again.'
- }
- ];
-
- for (const pattern of errorPatterns) {
- if (pattern.test(content)) {
- const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
- const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`;
-
- return {
- hasError: dismissedAlertKey !== alertKey,
- errorMessage: pattern.message,
- errorType: pattern.type,
- action: pattern.action,
- alertKey
- };
- }
- }
-
- return { hasError: false, errorMessage: null, errorType: null, action: undefined };
- }, [messages, dismissedAlertKey, onNewChat, onChangeModel]);
-
- const dismiss = useCallback(() => {
- const lastMessage = messages[messages.length - 1];
- if (errorMessage && lastMessage) {
- const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
- const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`;
- setDismissedAlertKey(alertKey);
- }
- }, [errorMessage, messages]);
-
- return {
- hasError,
- errorMessage,
- errorType,
- action,
- dismiss
- };
-};
From 7057c34f01d7746e44db23d180b5989845a5fc04 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 20:53:24 -0500
Subject: [PATCH 11/15] Consolidate action logic into Quilly
---
src/components/Quilly.test.tsx | 35 ++++++++---
src/components/Quilly.tsx | 61 ++++++++++++++++++-
src/components/Shakespeare/ChatPane.tsx | 79 +++----------------------
src/pages/ProjectView.tsx | 31 ----------
4 files changed, 94 insertions(+), 112 deletions(-)
diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx
index 6e50e06c..e3657f19 100644
--- a/src/components/Quilly.test.tsx
+++ b/src/components/Quilly.test.tsx
@@ -35,27 +35,44 @@ describe('Quilly', () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
});
- it('renders action button when provided', () => {
- const error = new Error('Test error');
+ it('renders action button for console errors', () => {
+ const error = new Error('Console errors detected in your app. Would you like me to help fix them?');
const onDismiss = vi.fn();
- const actionOnClick = vi.fn();
+ const onFixConsoleErrors = vi.fn();
render(
);
- const actionButton = screen.getByRole('button', { name: 'Fix it' });
+ const actionButton = screen.getByRole('button', { name: 'Fix errors' });
expect(actionButton).toBeInTheDocument();
fireEvent.click(actionButton);
- expect(actionOnClick).toHaveBeenCalledTimes(1);
+ expect(onFixConsoleErrors).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders action button for model not found errors', () => {
+ const error = new Error('model_not_found: The specified model does not exist');
+ const onDismiss = vi.fn();
+ const onOpenModelSelector = vi.fn();
+
+ render(
+
+ );
+
+ const actionButton = screen.getByRole('button', { name: 'Choose model' });
+ expect(actionButton).toBeInTheDocument();
+
+ fireEvent.click(actionButton);
+ expect(onOpenModelSelector).toHaveBeenCalledTimes(1);
});
it('formats network error messages correctly', () => {
diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx
index d8a08d44..b335d00c 100644
--- a/src/components/Quilly.tsx
+++ b/src/components/Quilly.tsx
@@ -5,10 +5,12 @@ import { X } from 'lucide-react';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
- action?: { label: string; onClick: () => void };
+ onNewChat?: () => void;
+ onOpenModelSelector?: () => void;
+ onFixConsoleErrors?: () => void;
}
-export function Quilly({ error, onDismiss, action }: QuillyProps) {
+export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) {
// Generate user-friendly message from error
const getMessage = (error: Error): string => {
const errorMsg = error.message || '';
@@ -36,7 +38,62 @@ export function Quilly({ error, onDismiss, action }: QuillyProps) {
}
};
+ // Determine action based on error
+ const getAction = (error: Error): { label: string; onClick: () => void } | undefined => {
+ const errorMsg = error.message || '';
+
+ // Check for console error messages first
+ if (errorMsg.includes('Console') && errorMsg.includes('detected in your app') && onFixConsoleErrors) {
+ const isPlural = errorMsg.includes('errors detected');
+ return {
+ label: `Fix ${isPlural ? 'errors' : 'error'}`,
+ onClick: onFixConsoleErrors
+ };
+ }
+
+ if (error.name === 'TypeError' && errorMsg.includes('fetch')) {
+ return {
+ label: 'Check AI settings',
+ onClick: () => {
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('API key')) {
+ return {
+ label: 'Check API key',
+ onClick: () => {
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('insufficient_quota')) {
+ return {
+ label: 'Check AI settings',
+ onClick: () => {
+ window.location.href = '/settings/ai';
+ }
+ };
+ } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
+ return onOpenModelSelector ? {
+ label: 'Choose model',
+ onClick: onOpenModelSelector
+ } : undefined;
+ } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
+ return onNewChat ? {
+ label: 'New chat',
+ onClick: onNewChat
+ } : undefined;
+ } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
+ return onOpenModelSelector ? {
+ label: 'Change model',
+ onClick: onOpenModelSelector
+ } : undefined;
+ }
+
+ return undefined;
+ };
+
const message = getMessage(error);
+ const action = getAction(error);
return (
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index 38ef71ba..ee22914e 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -47,7 +47,6 @@ import { Quilly } from '@/components/Quilly';
interface ChatPaneProps {
projectId: string;
onNewChat?: () => void;
- onBuild?: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
@@ -60,8 +59,7 @@ export interface ChatPaneRef {
export const ChatPane = forwardRef
(({
projectId,
- onNewChat: _onNewChat,
- onBuild: _onBuild,
+ onNewChat,
onFirstInteraction,
onLoadingChange,
isLoading: externalIsLoading,
@@ -240,71 +238,14 @@ export const ChatPane = forwardRef(({
// Clean alert hooks with proper interfaces
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
- // Create AI error alert object
- const aiErrorAlert = useMemo(() => {
- if (!aiError) {
- return { hasError: false, dismiss: () => {}, action: undefined };
- }
-
- let action: { label: string; onClick: () => void } | undefined;
-
- const errorMsg = aiError.message || '';
-
- if (aiError.name === 'TypeError' && errorMsg.includes('fetch')) {
- action = {
- label: 'Check AI settings',
- onClick: () => {
- // Navigate to AI settings
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('API key')) {
- action = {
- label: 'Check API key',
- onClick: () => {
- // Navigate to AI settings
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('insufficient_quota')) {
- action = {
- label: 'Check AI settings',
- onClick: () => {
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
- action = {
- label: 'Choose model',
- onClick: openModelSelector
- };
- } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
- action = _onNewChat ? {
- label: 'New chat',
- onClick: _onNewChat
- } : undefined;
- } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
- action = openModelSelector ? {
- label: 'Change model',
- onClick: openModelSelector
- } : undefined;
- }
-
- return {
- hasError: true,
- dismiss: () => setAIError(null),
- action
- };
- }, [aiError, openModelSelector, _onNewChat]);
-
// Scroll to bottom when alerts appear
useEffect(() => {
- if (consoleAlert.hasError || aiErrorAlert.hasError) {
+ if (consoleAlert.hasError || aiError) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
- }, [consoleAlert.hasError, aiErrorAlert.hasError, scrollToBottom]);
+ }, [consoleAlert.hasError, aiError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
@@ -664,19 +605,17 @@ export const ChatPane = forwardRef(({
suggestErrorFix(consoleAlert.errorSummary || '')
- }}
+ onFixConsoleErrors={() => suggestErrorFix(consoleAlert.errorSummary || '')}
/>
)}
{/* AI Error Alert */}
- {aiErrorAlert.hasError && (
+ {aiError && (
setAIError(null)}
+ onNewChat={onNewChat}
+ onOpenModelSelector={openModelSelector}
/>
)}
diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx
index c4cdef53..5fe49405 100644
--- a/src/pages/ProjectView.tsx
+++ b/src/pages/ProjectView.tsx
@@ -14,7 +14,6 @@ import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { ActionsMenu } from '@/components/ActionsMenu';
import { useIsMobile } from '@/hooks/useIsMobile';
-import { useKeepAlive } from '@/hooks/useKeepAlive';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { StarButton } from '@/components/StarButton';
@@ -40,20 +39,6 @@ export function ProjectView() {
const build = useBuildProject(projectId!);
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
- // Keep-alive functionality to prevent tab throttling during AI processing
- const { updateMetadata } = useKeepAlive({
- enabled: isAILoading || build.isPending,
- title: 'Shakespeare',
- artist: project ? `Working on ${project.name}...` : 'Working...',
- artwork: [
- {
- src: '/favicon.png',
- sizes: '512x512',
- type: 'image/png'
- }
- ]
- });
-
const loadProject = useCallback(async () => {
if (!projectId) return;
@@ -91,20 +76,6 @@ export function ProjectView() {
}
}, [isPreviewable, mobileView, activeTab]);
- const runBuild = async () => {
- if (build.isPending || !project) return;
- updateMetadata('Shakespeare', `Building ${project.name}...`);
-
- await build.mutateAsync(undefined, {
- onSuccess(result) {
- console.log('Project built:', result);
- },
- onError(error) {
- console.error('Build failed:', error);
- },
- });
- };
-
const handleNewChat = () => {
// Reset to chat view on mobile when starting new chat
if (isMobile) {
@@ -234,7 +205,6 @@ export function ProjectView() {
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
- onBuild={runBuild}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
@@ -414,7 +384,6 @@ export function ProjectView() {
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
- onBuild={runBuild}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
From 25f14ee2b39bf4d0b7677b55e8ac34f3874a8d70 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 21:06:52 -0500
Subject: [PATCH 12/15] Clean up Quilly
---
src/components/Quilly.tsx | 173 ++++++++++++++++++++------------------
1 file changed, 91 insertions(+), 82 deletions(-)
diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx
index b335d00c..71d0ad22 100644
--- a/src/components/Quilly.tsx
+++ b/src/components/Quilly.tsx
@@ -1,99 +1,108 @@
import { Button } from '@/components/ui/button';
import { QuillySVG } from '@/components/ui/QuillySVG';
+import OpenAI from 'openai';
import { X } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
- onNewChat?: () => void;
- onOpenModelSelector?: () => void;
- onFixConsoleErrors?: () => void;
+ onNewChat: () => void;
+ onOpenModelSelector: () => void;
+ onFixConsoleErrors: () => void;
+}
+
+interface ErrorBody {
+ message: string;
+ action?: {
+ label: string;
+ onClick: () => void;
+ };
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) {
- // Generate user-friendly message from error
- const getMessage = (error: Error): string => {
- const errorMsg = error.message || '';
+ const navigate = useNavigate();
- if (error.name === 'TypeError' && errorMsg.includes('fetch')) {
- return 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
- } else if (errorMsg.includes('API key')) {
- return 'Authentication error: Please check your API key in AI settings.';
- } else if (errorMsg.includes('rate limit')) {
- return 'Rate limit exceeded. Please wait a moment before trying again.';
- } else if (errorMsg.includes('insufficient_quota')) {
- return 'Quota exceeded: Your API key has reached its usage limit. Please check your billing or try a different provider.';
- } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
- return 'Model not found: The selected AI model is not available. Please choose a different model.';
- } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
- return 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.';
- } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
- return 'The AI model encountered an issue. Try switching to a different model or starting a new chat.';
- } else if (errorMsg.includes('too many requests')) {
- return 'You\'re sending requests too quickly. Please wait a moment before trying again.';
- } else if (errorMsg) {
- return `AI service error: ${errorMsg}`;
- } else {
- return 'Sorry, I encountered an unexpected error. Please try again.';
+ const renderBody = (error: Error): ErrorBody => {
+ // Handle OpenAI API errors with specific error codes
+ if (error instanceof OpenAI.APIError) {
+ switch (error.code) {
+ case 'invalid_api_key':
+ case 'invalid_request_error':
+ return {
+ message: 'Authentication error: Please check your API key in AI settings.',
+ action: {
+ label: 'Check API key',
+ onClick: () => navigate('/settings/ai'),
+ }
+ };
+
+ case 'insufficient_quota':
+ return {
+ message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
+ action: {
+ label: 'Check AI settings',
+ onClick: () => navigate('/settings/ai'),
+ }
+ };
+
+ case 'rate_limit_exceeded':
+ return {
+ message: 'Rate limit exceeded. Please wait a moment before trying again.',
+ };
+
+ case 'model_not_found':
+ return {
+ message: 'The selected AI model is not available. Please choose a different model.',
+ action: {
+ label: 'Choose model',
+ onClick: onOpenModelSelector,
+ },
+ };
+
+ case 'context_length_exceeded':
+ return {
+ message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
+ action: {
+ label: 'New chat',
+ onClick: onNewChat,
+ },
+ };
+
+ case 'server_error':
+ case 'service_unavailable':
+ return {
+ message: 'The AI service is temporarily unavailable. Please try again in a moment.',
+ };
+
+ default:
+ return {
+ message: `AI service error: ${error.message}`,
+ };
+ }
}
+
+ // Handle console error messages
+ if (error.message.includes('Console') && error.message.includes('detected in your app') && onFixConsoleErrors) {
+ const isPlural = error.message.includes('errors detected');
+ return {
+ message: error.message,
+ action: {
+ label: `Fix ${isPlural ? 'errors' : 'error'}`,
+ onClick: onFixConsoleErrors,
+ }
+ };
+ }
+
+ // Default fallback
+ return {
+ message: error.message
+ ? `AI service error: ${error.message}`
+ : 'Sorry, I encountered an unexpected error. Please try again.',
+ };
};
- // Determine action based on error
- const getAction = (error: Error): { label: string; onClick: () => void } | undefined => {
- const errorMsg = error.message || '';
-
- // Check for console error messages first
- if (errorMsg.includes('Console') && errorMsg.includes('detected in your app') && onFixConsoleErrors) {
- const isPlural = errorMsg.includes('errors detected');
- return {
- label: `Fix ${isPlural ? 'errors' : 'error'}`,
- onClick: onFixConsoleErrors
- };
- }
-
- if (error.name === 'TypeError' && errorMsg.includes('fetch')) {
- return {
- label: 'Check AI settings',
- onClick: () => {
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('API key')) {
- return {
- label: 'Check API key',
- onClick: () => {
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('insufficient_quota')) {
- return {
- label: 'Check AI settings',
- onClick: () => {
- window.location.href = '/settings/ai';
- }
- };
- } else if (errorMsg.includes('model_not_found') || errorMsg.includes('does not exist')) {
- return onOpenModelSelector ? {
- label: 'Choose model',
- onClick: onOpenModelSelector
- } : undefined;
- } else if (errorMsg.includes('maximum context length') || errorMsg.includes('context length')) {
- return onNewChat ? {
- label: 'New chat',
- onClick: onNewChat
- } : undefined;
- } else if (errorMsg.includes('422') || errorMsg.includes('Provider returned error')) {
- return onOpenModelSelector ? {
- label: 'Change model',
- onClick: onOpenModelSelector
- } : undefined;
- }
-
- return undefined;
- };
-
- const message = getMessage(error);
- const action = getAction(error);
+ const { message, action } = renderBody(error);
return (
From 0b949d55b9b7e89bdb76bfac20362f244c768597 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 21:14:41 -0500
Subject: [PATCH 13/15] Remove Quilly tests (for now)
---
src/components/Quilly.test.tsx | 133 ---------------------------------
1 file changed, 133 deletions(-)
delete mode 100644 src/components/Quilly.test.tsx
diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx
deleted file mode 100644
index e3657f19..00000000
--- a/src/components/Quilly.test.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-import { Quilly } from './Quilly';
-
-describe('Quilly', () => {
- it('renders with error message', () => {
- const error = new Error('Test error message');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- expect(screen.getByText('Pardon the interruption')).toBeInTheDocument();
- expect(screen.getByText(/AI service error: Test error message/)).toBeInTheDocument();
- });
-
- it('calls onDismiss when dismiss button is clicked', () => {
- const error = new Error('Test error');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- const dismissButton = screen.getByRole('button');
- fireEvent.click(dismissButton);
-
- expect(onDismiss).toHaveBeenCalledTimes(1);
- });
-
- it('renders action button for console errors', () => {
- const error = new Error('Console errors detected in your app. Would you like me to help fix them?');
- const onDismiss = vi.fn();
- const onFixConsoleErrors = vi.fn();
-
- render(
-
- );
-
- const actionButton = screen.getByRole('button', { name: 'Fix errors' });
- expect(actionButton).toBeInTheDocument();
-
- fireEvent.click(actionButton);
- expect(onFixConsoleErrors).toHaveBeenCalledTimes(1);
- });
-
- it('renders action button for model not found errors', () => {
- const error = new Error('model_not_found: The specified model does not exist');
- const onDismiss = vi.fn();
- const onOpenModelSelector = vi.fn();
-
- render(
-
- );
-
- const actionButton = screen.getByRole('button', { name: 'Choose model' });
- expect(actionButton).toBeInTheDocument();
-
- fireEvent.click(actionButton);
- expect(onOpenModelSelector).toHaveBeenCalledTimes(1);
- });
-
- it('formats network error messages correctly', () => {
- const error = new TypeError('fetch failed');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- expect(screen.getByText(/Network error: Unable to connect to AI service/)).toBeInTheDocument();
- });
-
- it('formats API key error messages correctly', () => {
- const error = new Error('Invalid API key provided');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- expect(screen.getByText(/Authentication error: Please check your API key/)).toBeInTheDocument();
- });
-
- it('formats rate limit error messages correctly', () => {
- const error = new Error('Rate limit exceeded');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- expect(screen.getByText(/Rate limit exceeded/)).toBeInTheDocument();
- });
-
- it('formats context length error messages correctly', () => {
- const error = new Error('maximum context length is 4096 tokens');
- const onDismiss = vi.fn();
-
- render(
-
- );
-
- expect(screen.getByText(/Your conversation is too long for this model/)).toBeInTheDocument();
- });
-});
\ No newline at end of file
From ec5d84d3f71382b783b87d298c4235d9c5dc4674 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 21:23:31 -0500
Subject: [PATCH 14/15] Disconnect Quilly from console errors temporarily
---
src/components/Quilly.tsx | 15 +-
src/components/Shakespeare/ChatPane.test.tsx | 313 -------------------
src/components/Shakespeare/ChatPane.tsx | 30 +-
src/hooks/useErrorDetection.ts | 72 -----
4 files changed, 2 insertions(+), 428 deletions(-)
delete mode 100644 src/components/Shakespeare/ChatPane.test.tsx
delete mode 100644 src/hooks/useErrorDetection.ts
diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx
index 71d0ad22..5ca08602 100644
--- a/src/components/Quilly.tsx
+++ b/src/components/Quilly.tsx
@@ -9,7 +9,6 @@ export interface QuillyProps {
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
- onFixConsoleErrors: () => void;
}
interface ErrorBody {
@@ -20,7 +19,7 @@ interface ErrorBody {
};
}
-export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFixConsoleErrors }: QuillyProps) {
+export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: QuillyProps) {
const navigate = useNavigate();
const renderBody = (error: Error): ErrorBody => {
@@ -82,18 +81,6 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onFix
}
}
- // Handle console error messages
- if (error.message.includes('Console') && error.message.includes('detected in your app') && onFixConsoleErrors) {
- const isPlural = error.message.includes('errors detected');
- return {
- message: error.message,
- action: {
- label: `Fix ${isPlural ? 'errors' : 'error'}`,
- onClick: onFixConsoleErrors,
- }
- };
- }
-
// Default fallback
return {
message: error.message
diff --git a/src/components/Shakespeare/ChatPane.test.tsx b/src/components/Shakespeare/ChatPane.test.tsx
deleted file mode 100644
index 2345596b..00000000
--- a/src/components/Shakespeare/ChatPane.test.tsx
+++ /dev/null
@@ -1,313 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent, act } from '@testing-library/react';
-import { TestApp } from '@/test/TestApp';
-import { ChatPane } from './ChatPane';
-
-// Mock the AI settings hook to return configured state
-vi.mock('@/hooks/useAISettings', () => ({
- useAISettings: () => ({
- isConfigured: true,
- settings: {
- providers: [],
- recentlyUsedModels: ['gpt-4'],
- },
- setProvider: vi.fn(),
- removeProvider: vi.fn(),
- setProviders: vi.fn(),
-
- addRecentlyUsedModel: vi.fn(),
- updateSettings: vi.fn(),
- }),
-}));
-
-// Mock other hooks
-vi.mock('@/hooks/useFS', () => ({
- useFS: () => ({
- fs: {},
- }),
-}));
-
-vi.mock('@/hooks/useCurrentUser', () => ({
- useCurrentUser: () => ({
- user: null,
- metadata: null,
- }),
-}));
-
-vi.mock('@/hooks/useKeepAlive', () => ({
- useKeepAlive: () => ({
- updateMetadata: vi.fn(),
- }),
-}));
-
-vi.mock('@/hooks/useAIChat', () => ({
- useAIChat: () => ({
- messages: [],
- streamingMessage: null,
- isLoading: false,
- totalCost: 0,
- lastInputTokens: 0,
- sendMessage: vi.fn(),
- startGeneration: vi.fn(),
- stopGeneration: vi.fn(),
- startNewSession: vi.fn(),
- }),
-}));
-
-vi.mock('@/hooks/useProviderModels', () => ({
- useProviderModels: () => ({
- models: [
- {
- fullId: 'gpt-4',
- contextLength: 8192,
- },
- ],
- }),
-}));
-
-vi.mock('@/hooks/useToast', () => ({
- useToast: () => ({
- toast: vi.fn(),
- }),
-}));
-
-describe('ChatPane', () => {
- describe('Placeholder switching', () => {
- it('shows "Please select a model" placeholder when providerModel is empty', () => {
- // Create a test that doesn't require modifying mocks
- // Instead, we'll test the existing behavior which shows the placeholder when configured
- render(
-
-
-
- );
-
- const textarea = screen.getByPlaceholderText(/Ask me to add features/);
- expect(textarea).toBeInTheDocument();
- });
-
- it('shows "Ask me to add features" placeholder when providerModel is set', () => {
- render(
-
-
-
- );
-
- const textarea = screen.getByPlaceholderText(/Ask me to add features/);
- expect(textarea).toBeInTheDocument();
- });
- });
-
- describe('Drag and drop functionality', () => {
- it('handles dropping a single valid file', () => {
- render(
-
-
-
- );
-
- const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
- expect(chatContainer).toBeInTheDocument();
-
- const validFile = new File(['test content'], 'test.txt', { type: 'text/plain' });
-
- // Simulate drag and drop events
- act(() => {
- if (chatContainer) {
- fireEvent.dragEnter(chatContainer, {
- dataTransfer: { files: [] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.dragOver(chatContainer, {
- dataTransfer: { files: [validFile] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.drop(chatContainer, {
- dataTransfer: { files: [validFile] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
- }
- });
-
- // Verify the drop was handled (no errors thrown)
- expect(chatContainer).toBeInTheDocument();
- });
-
- it('handles dropping multiple valid files', () => {
- render(
-
-
-
- );
-
- const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
- expect(chatContainer).toBeInTheDocument();
-
- const files = [
- new File(['content1'], 'file1.txt', { type: 'text/plain' }),
- new File(['content2'], 'file2.txt', { type: 'text/plain' }),
- ];
-
- // Simulate drag and drop events
- act(() => {
- if (chatContainer) {
- fireEvent.dragEnter(chatContainer, {
- dataTransfer: { files: [] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.dragOver(chatContainer, {
- dataTransfer: { files },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.drop(chatContainer, {
- dataTransfer: { files },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
- }
- });
-
- // Verify the drop was handled (no errors thrown)
- expect(chatContainer).toBeInTheDocument();
- });
-
- it('handles dropping an unsupported file type', () => {
- // Test that the drop handler exists and doesn't throw errors
- render(
-
-
-
- );
-
- const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
- expect(chatContainer).toBeInTheDocument();
-
- const unsupportedFile = new File(['malicious content'], 'virus.exe', { type: 'application/x-executable' });
-
- // Simulate drag and drop events - should not throw errors
- act(() => {
- if (chatContainer) {
- fireEvent.dragEnter(chatContainer, {
- dataTransfer: { files: [] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.dragOver(chatContainer, {
- dataTransfer: { files: [unsupportedFile] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
-
- fireEvent.drop(chatContainer, {
- dataTransfer: { files: [unsupportedFile] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
- }
- });
-
- // Test passes if no errors are thrown during drop
- expect(chatContainer).toBeInTheDocument();
- });
-
- it('adds visual drag-over state during drag operations', () => {
- render(
-
-
-
- );
-
- const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
- expect(chatContainer).toBeInTheDocument();
-
- const _file = new File(['test content'], 'test.txt', { type: 'text/plain' });
-
- // Simulate drag enter - should not throw errors
- act(() => {
- if (chatContainer) {
- fireEvent.dragEnter(chatContainer, {
- dataTransfer: { files: [] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- });
- }
- });
-
- // Test passes if no errors are thrown during drag operations
- expect(chatContainer).toBeInTheDocument();
-
- // Simulate drag leave
- act(() => {
- if (chatContainer) {
- fireEvent.dragLeave(chatContainer, {
- dataTransfer: { files: [] },
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- relatedTarget: null, // Simulate leaving the container
- });
- }
- });
-
- // Test passes if no errors are thrown during drag operations
- expect(chatContainer).toBeInTheDocument();
- });
- });
-
- it('handles image paste from clipboard', async () => {
- render(
-
-
-
- );
-
- const textarea = screen.getByPlaceholderText(/Ask me to add features/);
- expect(textarea).toBeInTheDocument();
-
- // Create a mock image file
- const imageFile = new File(['fake-image-data'], 'test.png', {
- type: 'image/png',
- });
-
- // Create mock clipboard data
- const mockClipboardItem = {
- type: 'image/png',
- getAsFile: () => imageFile,
- } as DataTransferItem;
-
- const mockClipboardData = {
- items: [mockClipboardItem],
- length: 1,
- } as unknown as DataTransfer;
-
- // Fire the paste event on the textarea using fireEvent
- fireEvent.paste(textarea, {
- clipboardData: mockClipboardData,
- });
-
- // The file should be added to the attached files
- // We can't easily test the internal state, but we can verify the event was handled
- // without throwing an error
- expect(textarea).toBeInTheDocument();
- });
-
- it('renders welcome message when no messages exist', () => {
- render(
-
-
-
- );
-
- expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
- expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
- });
-});
\ No newline at end of file
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index ee22914e..52ec50bf 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -39,14 +39,13 @@ import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
-import { useConsoleErrorAlert } from '@/hooks/useErrorDetection';
import { Quilly } from '@/components/Quilly';
// Clean interfaces now handled by proper hooks
interface ChatPaneProps {
projectId: string;
- onNewChat?: () => void;
+ onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
@@ -234,19 +233,6 @@ export const ChatPane = forwardRef(({
setIsModelSelectorOpen(true);
}, []);
- // Function to suggest error fix
- // Clean alert hooks with proper interfaces
- const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
-
- // Scroll to bottom when alerts appear
- useEffect(() => {
- if (consoleAlert.hasError || aiError) {
- setTimeout(() => {
- scrollToBottom();
- }, 50);
- }
- }, [consoleAlert.hasError, aiError, scrollToBottom]);
-
// Check for autostart parameter and trigger AI generation
useEffect(() => {
if (autostartedRef.current) return;
@@ -504,10 +490,6 @@ export const ChatPane = forwardRef(({
}
}), [internalStartNewSession]);
- const suggestErrorFix = useCallback(async (errorMessage: string) => {
- await send(errorMessage, attachedFiles);
- }, [send, attachedFiles]);
-
return (
@@ -600,15 +582,6 @@ export const ChatPane = forwardRef(({
)}
- {/* Console Error Alert */}
- {consoleAlert.hasError && (
- suggestErrorFix(consoleAlert.errorSummary || '')}
- />
- )}
-
{/* AI Error Alert */}
{aiError && (
(({
onOpenModelSelector={openModelSelector}
/>
)}
-
diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts
deleted file mode 100644
index c530f646..00000000
--- a/src/hooks/useErrorDetection.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useState, useCallback, useMemo } from 'react';
-import type { AIMessage } from '@/lib/SessionManager';
-import { useConsoleMessages } from './useConsoleMessages';
-
-export interface ConsoleErrorAlert {
- hasError: boolean;
- errorSummary: string | null;
- errorCount: number;
- dismiss: () => void;
-}
-
-export const useConsoleErrorAlert = (
- aiMessages: AIMessage[],
- isBuilding?: boolean,
- isLoading?: boolean
-): ConsoleErrorAlert => {
- const { messages } = useConsoleMessages();
- const [dismissedErrorSummary, setDismissedErrorSummary] = useState('');
-
- const { hasError, errorSummary, errorCount } = useMemo(() => {
- // Don't show alerts while building or AI is working
- if (isBuilding || isLoading) {
- return { hasError: false, errorSummary: null, errorCount: 0 };
- }
-
- // Find the timestamp of the last AI assistant message
- // Since AIMessage doesn't have timestamps, we'll use a different approach:
- // Only show errors if there are any errors at all and no recent user activity
- const lastMessage = aiMessages[aiMessages.length - 1];
- const isLastMessageFromAssistant = lastMessage?.role === 'assistant';
-
- // Only show console errors if the last message was from assistant (AI just responded)
- if (!isLastMessageFromAssistant) {
- return { hasError: false, errorSummary: null, errorCount: 0 };
- }
-
- // Get recent errors (last 10 seconds worth to catch errors from recent AI actions)
- const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago
- const recentErrors = messages.filter(msg =>
- msg.level === 'error' &&
- msg.timestamp > recentTimeThreshold
- );
-
- if (recentErrors.length === 0) {
- return { hasError: false, errorSummary: null, errorCount: 0 };
- }
-
- // Just return the raw error messages, no formatting
- const summary = recentErrors.slice(-3).map(e => e.message).join('\n');
-
- return {
- hasError: dismissedErrorSummary !== summary,
- errorSummary: summary,
- errorCount: recentErrors.length
- };
- }, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]);
-
- const dismiss = useCallback(() => {
- if (errorSummary) {
- setDismissedErrorSummary(errorSummary);
- }
- }, [errorSummary]);
-
- return {
- hasError,
- errorSummary,
- errorCount,
- dismiss
- };
-};
-
-
From db57619bcaa24f62ad85feac40a91004911f4c43 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Wed, 24 Sep 2025 21:42:12 -0500
Subject: [PATCH 15/15] Allow refilling Shakespeare credits from Quilly
---
src/components/Quilly.tsx | 51 +++++++++++++++++++------
src/components/Shakespeare/ChatPane.tsx | 12 +++++-
2 files changed, 49 insertions(+), 14 deletions(-)
diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx
index 5ca08602..1eacabb0 100644
--- a/src/components/Quilly.tsx
+++ b/src/components/Quilly.tsx
@@ -1,14 +1,20 @@
+import OpenAI from 'openai';
+import { useNavigate } from 'react-router-dom';
+import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { QuillySVG } from '@/components/ui/QuillySVG';
-import OpenAI from 'openai';
-import { X } from 'lucide-react';
-import { useNavigate } from 'react-router-dom';
+import { useAISettings } from '@/hooks/useAISettings';
+import { parseProviderModel } from '@/lib/parseProviderModel';
+import { useAICredits } from '@/hooks/useAICredits';
+import { CreditsDialog } from './CreditsDialog';
+import { useState } from 'react';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
+ providerModel: string;
}
interface ErrorBody {
@@ -19,8 +25,12 @@ interface ErrorBody {
};
}
-export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: QuillyProps) {
+export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) {
const navigate = useNavigate();
+ const { settings } = useAISettings();
+ const { provider } = parseProviderModel(providerModel, settings.providers);
+ const credits = useAICredits(provider);
+ const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error): ErrorBody => {
// Handle OpenAI API errors with specific error codes
@@ -36,14 +46,25 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: Qui
}
};
- case 'insufficient_quota':
- return {
- message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
- action: {
- label: 'Check AI settings',
- onClick: () => navigate('/settings/ai'),
- }
- };
+ case 'insufficient_quota': {
+ if (credits.data) {
+ return {
+ message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
+ action: {
+ label: 'Add credits',
+ onClick: () => setShowCreditsDialog(true),
+ }
+ };
+ } else {
+ return {
+ message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
+ action: {
+ label: 'Check AI settings',
+ onClick: () => navigate('/settings/ai'),
+ }
+ };
+ }
+ }
case 'rate_limit_exceeded':
return {
@@ -120,6 +141,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector }: Qui
+
+
);
}
\ No newline at end of file
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx
index 52ec50bf..0d7d5ee1 100644
--- a/src/components/Shakespeare/ChatPane.tsx
+++ b/src/components/Shakespeare/ChatPane.tsx
@@ -92,10 +92,10 @@ export const ChatPane = forwardRef(({
}
}, [providerModel, settings.recentlyUsedModels]);
- // Reset state when navigating between projects
+ // Reset error state when navigating between projects and switching models
useEffect(() => {
setAIError(null);
- }, [projectId]);
+ }, [projectId, providerModel]);
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
@@ -233,6 +233,11 @@ export const ChatPane = forwardRef(({
setIsModelSelectorOpen(true);
}, []);
+ // Scroll to bottom when AI error occurs
+ useEffect(() => {
+ scrollToBottom();
+ }, [aiError, scrollToBottom]);
+
// Check for autostart parameter and trigger AI generation
useEffect(() => {
if (autostartedRef.current) return;
@@ -377,6 +382,8 @@ export const ChatPane = forwardRef(({
// If configured but no model selected, don't proceed
if (!providerModel.trim()) return;
+ setAIError(null);
+
const modelToUse = providerModel.trim();
// Build message content as text parts
@@ -589,6 +596,7 @@ export const ChatPane = forwardRef(({
onDismiss={() => setAIError(null)}
onNewChat={onNewChat}
onOpenModelSelector={openModelSelector}
+ providerModel={providerModel}
/>
)}