From ba0ec1f4204b995a8f4ca1fb964362c1de747381 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 13:33:04 -0500 Subject: [PATCH 01/52] Add Open Source section to OnboardingDialog --- src/components/OnboardingDialog.tsx | 100 ++++++++++++++++++++++++++-- 1 file changed, 96 insertions(+), 4 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index e1d2ae0c..9a754a76 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; +import { Checkbox } from '@/components/ui/checkbox'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; @@ -20,7 +21,7 @@ interface OnboardingDialogProps { onOpenChange: (open: boolean) => void; } -type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion'; +type OnboardingStep = 'welcome' | 'open-source' | 'model-selection' | 'conclusion'; const SHAKESPEARE_PROVIDER = { id: "shakespeare", @@ -33,6 +34,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [selectedModel, setSelectedModel] = useState(''); const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); + const [agreedToTerms, setAgreedToTerms] = useState(false); const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); @@ -42,7 +44,13 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) // Filter models to only show Shakespeare provider models const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); - const handleGetStarted = async () => { + const handleGetStarted = () => { + setStep('open-source'); + }; + + const handleContinueFromOpenSource = async () => { + if (!agreedToTerms) return; + setIsSettingUp(true); try { @@ -114,16 +122,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) setSelectedModel(''); setIsSettingUp(false); setShowCreditsDialog(false); + setAgreedToTerms(false); } }, [open]); return ( <> - + - {step === 'model-selection' && ( + {step === 'open-source' && ( )} + {step === 'model-selection' && ( + + )} {step === 'conclusion' && ( + + + )} + {step === 'model-selection' && (
From 92483728d0d0a8925a17719b5f53bfee6dd583a2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 13:37:45 -0500 Subject: [PATCH 02/52] Scroll OnboardingDialog to top when navigating between steps --- src/components/OnboardingDialog.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 9a754a76..14c6834c 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -1,5 +1,5 @@ import { Decimal } from 'decimal.js'; -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { generateSecretKey } from 'nostr-tools'; import { nip19 } from 'nostr-tools'; import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react'; @@ -36,6 +36,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [showCreditsDialog, setShowCreditsDialog] = useState(false); const [agreedToTerms, setAgreedToTerms] = useState(false); + // Ref for the scrollable content area + const scrollableContentRef = useRef(null); + const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); const login = useLoginActions(); @@ -126,10 +129,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) } }, [open]); + // Scroll to top when step changes + useEffect(() => { + if (scrollableContentRef.current) { + scrollableContentRef.current.scrollTop = 0; + } + }, [step]); + return ( <> - + {step === 'open-source' && ( @@ -168,7 +178,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) -
+
{step === 'welcome' && (
From 2477b5417cd4c55ba10023b0bd0939b6780dc4ee Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 14:48:44 -0500 Subject: [PATCH 03/52] Add provider step to onboarding --- src/components/OnboardingDialog.tsx | 211 +++++++++++++++++++++++----- src/lib/aiProviderPresets.test.ts | 62 ++++++++ src/lib/aiProviderPresets.ts | 72 ++++++++++ src/pages/AISettings.tsx | 64 +-------- 4 files changed, 310 insertions(+), 99 deletions(-) create mode 100644 src/lib/aiProviderPresets.test.ts create mode 100644 src/lib/aiProviderPresets.ts diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 14c6834c..cc8db615 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -2,35 +2,34 @@ import { Decimal } from 'decimal.js'; import { useState, useEffect, useRef } from 'react'; import { generateSecretKey } from 'nostr-tools'; import { nip19 } from 'nostr-tools'; -import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react'; +import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; import { Checkbox } from '@/components/ui/checkbox'; +import { PasswordInput } from '@/components/ui/password-input'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; +import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; +import { cn } from '@/lib/utils'; interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; } -type OnboardingStep = 'welcome' | 'open-source' | 'model-selection' | 'conclusion'; - -const SHAKESPEARE_PROVIDER = { - id: "shakespeare", - baseURL: "https://ai.shakespeare.diy/v1", - nostr: true, -}; +type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion'; export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) { const [step, setStep] = useState('welcome'); + const [selectedProvider, setSelectedProvider] = useState(null); + const [providerApiKey, setProviderApiKey] = useState(''); const [selectedModel, setSelectedModel] = useState(''); const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); @@ -44,28 +43,51 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const login = useLoginActions(); const { models, isLoading: isLoadingModels } = useProviderModels(); - // Filter models to only show Shakespeare provider models - const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); + // Filter models to only show selected provider models + const providerModels = selectedProvider + ? models.filter(model => model.provider === selectedProvider.id) + : []; const handleGetStarted = () => { setStep('open-source'); }; - const handleContinueFromOpenSource = async () => { + const handleContinueFromOpenSource = () => { if (!agreedToTerms) return; + setStep('provider-selection'); + }; + + const handleProviderSelect = (provider: PresetProvider) => { + setSelectedProvider(provider); + // Clear API key when switching providers + setProviderApiKey(''); + }; + + const handleContinueFromProviderSelection = async () => { + if (!selectedProvider) return; + + // Check if provider requires API key and if it's provided + const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr; + if (requiresApiKey && !providerApiKey.trim()) return; setIsSettingUp(true); try { - // If user is not logged in, generate and login with secret key - if (!user) { + // If user is not logged in and provider uses Nostr auth, generate and login with secret key + if (!user && selectedProvider.nostr) { const secretKey = generateSecretKey(); const nsec = nip19.nsecEncode(secretKey); login.nsec(nsec); } - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // Add selected provider to their config + const providerConfig = { + id: selectedProvider.id, + baseURL: selectedProvider.baseURL, + nostr: selectedProvider.nostr || undefined, + apiKey: requiresApiKey ? providerApiKey.trim() : undefined, + }; + setProvider(providerConfig); // Move to model selection setStep('model-selection'); @@ -87,7 +109,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) addRecentlyUsedModel(selectedModel); // Find the selected model to check if it's free - const model = shakespeareModels.find(m => m.fullId === selectedModel); + const model = providerModels.find(m => m.fullId === selectedModel); const isFreeModel = !model?.pricing || ( model.pricing.prompt.equals(0) && model.pricing.completion.equals(0) ); @@ -122,6 +144,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) useEffect(() => { if (open) { setStep('welcome'); + setSelectedProvider(null); + setProviderApiKey(''); setSelectedModel(''); setIsSettingUp(false); setShowCreditsDialog(false); @@ -152,7 +176,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) )} - {step === 'model-selection' && ( + {step === 'provider-selection' && ( )} + {step === 'model-selection' && ( + + )} {step === 'conclusion' && ( +
+
+ )} + + {step === 'provider-selection' && ( +
+
+

Choose your AI provider

+

+ Select an AI provider to power your development assistant. You can add more providers later in settings. +

+
+ +
+ {AI_PROVIDER_PRESETS.map((provider) => { + const isSelected = selectedProvider?.id === provider.id; + const isShakespeare = provider.id === 'shakespeare'; + + return ( + handleProviderSelect(provider)} + > +
+
+ + {provider.name} + +
+
+ {isSelected && ( +
+ +
+ )} +
+
+
+ ); + })} +
+ + {/* API Key Input Section */} + {selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && ( +
+
+

+ {selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'} +

+

+ {selectedProvider.id === 'routstr' ? ( + <>{selectedProvider.name} requires a Cashu token + ) : ( + <> + {selectedProvider.name} requires an {selectedProvider.apiKeysURL ? ( + + API key + + + ) : ( + <>API key + )} + + )} +

+
+ setProviderApiKey(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && providerApiKey.trim()) { + handleContinueFromProviderSelection(); + } + }} + /> +
+ )} + +
+
-
+
) : ( -
- {!preset.nostr && ( - setPresetApiKeys(prev => ({ +
+
+ {!preset.nostr && ( + setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && + presetApiKeys[preset.id]?.trim() && + presetTermsAgreements[preset.id]) { + handleAddPresetProvider(preset); + } + }} + /> + )} + +
+ + {/* Terms of Service Agreement */} +
+ setPresetTermsAgreements(prev => ({ ...prev, - [preset.id]: e.target.value, + [preset.id]: checked === true, }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} + className="h-3 w-3" /> - )} - + +
)}
From cb4cc16760348f242723f133e431e4dd5a2af376 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 15:41:57 -0500 Subject: [PATCH 07/52] Don't configure users through the Act1Dialog, still force them to go through the normal onboarding flow --- src/components/Act1Dialog.tsx | 70 ++++++++++------------------------- 1 file changed, 20 insertions(+), 50 deletions(-) diff --git a/src/components/Act1Dialog.tsx b/src/components/Act1Dialog.tsx index 5cdeade2..e31611b7 100644 --- a/src/components/Act1Dialog.tsx +++ b/src/components/Act1Dialog.tsx @@ -5,9 +5,9 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; -import { useAISettings } from '@/hooks/useAISettings'; +// import { useAISettings } from '@/hooks/useAISettings'; import { useAICredits } from '@/hooks/useAICredits'; -import { useLocalStorage } from '@/hooks/useLocalStorage'; +// import { useLocalStorage } from '@/hooks/useLocalStorage'; interface Act1DialogProps { open: boolean; @@ -22,44 +22,39 @@ const SHAKESPEARE_PROVIDER = { nostr: true, }; -const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; +// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { const [step, setStep] = useState('welcome'); - const [isSettingUp, setIsSettingUp] = useState(false); - const { setProvider, updateSettings } = useAISettings(); + // const { setProvider, updateSettings } = useAISettings(); - // Get the selectedNSPAddr from localStorage - const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); + // // Get the selectedNSPAddr from localStorage + // const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); // Get user's credits const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER); const handleGetStarted = async () => { - setIsSettingUp(true); - try { - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // // Add Shakespeare provider to their config + // setProvider(SHAKESPEARE_PROVIDER); - // Configure recently used models based on credits or NSP - const hasCredits = creditsData?.amount && creditsData.amount > 0; - const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; + // // Configure recently used models based on credits or NSP + // const hasCredits = creditsData?.amount && creditsData.amount > 0; + // const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; - if (hasCredits || hasMKStackNSP) { - // User has credits or MKStack NSP - set to shakespeare model - updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); - } else { - // No credits - set to tybalt model (free) - updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); - } + // if (hasCredits || hasMKStackNSP) { + // // User has credits or MKStack NSP - set to shakespeare model + // updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); + // } else { + // // No credits - set to tybalt model (free) + // updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); + // } // Move to migration step setStep('migration'); } catch (error) { console.error('Failed to configure Shakespeare provider:', error); - } finally { - setIsSettingUp(false); } }; @@ -87,7 +82,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { useEffect(() => { if (open) { setStep('welcome'); - setIsSettingUp(false); } }, [open]); @@ -126,12 +120,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { )} - - {step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'} - {step === 'migration' && 'Migrating Your Projects'} - {step === 'credits' && 'Your Credits'} - {step === 'conclusion' && "You're All Set!"} - @@ -197,21 +185,10 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
)} @@ -343,14 +320,7 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {

Welcome to the Future!

- You're all set up with Act 2! Your AI assistant is configured - and ready to help you build amazing Nostr applications. -

-
- -
-

- "Create a decentralized social media app with custom feeds and real-time messaging..." + You're all up to speed with Act 2! Get ready to build amazing Nostr applications.

From 7b438bae347f49b56878761df4827e5377ef0527 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:00:43 -0500 Subject: [PATCH 08/52] Display credits badge in Onboarding if the user is coming from Act1 --- .../OnboardingCreditsBadge.test.tsx | 103 ++++++++++++++++++ src/components/OnboardingCreditsBadge.tsx | 42 +++++++ src/components/OnboardingDialog.tsx | 6 +- src/hooks/useAICredits.ts | 2 +- 4 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 src/components/OnboardingCreditsBadge.test.tsx create mode 100644 src/components/OnboardingCreditsBadge.tsx diff --git a/src/components/OnboardingCreditsBadge.test.tsx b/src/components/OnboardingCreditsBadge.test.tsx new file mode 100644 index 00000000..9fcff5a8 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.test.tsx @@ -0,0 +1,103 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import { OnboardingCreditsBadge } from './OnboardingCreditsBadge'; +import type { UseQueryResult } from '@tanstack/react-query'; +import type { CreditsResponse } from '@/hooks/useAICredits'; + +// Mock the useAICredits hook +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: vi.fn(), +})); + +import { useAICredits } from '@/hooks/useAICredits'; + +const mockUseAICredits = vi.mocked(useAICredits); + +describe('OnboardingCreditsBadge', () => { + const mockProvider = { + id: 'shakespeare', + baseURL: 'https://ai.shakespeare.diy/v1', + nostr: true, + }; + + it('renders credits badge when data is available', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 25.50 }, + isLoading: false, + error: null, + } as UseQueryResult); + + render( + + + + ); + + expect(screen.getByText('$25.50')).toBeInTheDocument(); + }); + + it('does not render when loading', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: true, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when there is an error', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: new Error('Provider does not support credits'), + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when no credits data is available', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when credits amount is 0', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 0 }, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); +}); \ No newline at end of file diff --git a/src/components/OnboardingCreditsBadge.tsx b/src/components/OnboardingCreditsBadge.tsx new file mode 100644 index 00000000..f2eaae42 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.tsx @@ -0,0 +1,42 @@ +import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; +import { useAICredits } from '@/hooks/useAICredits'; + +interface OnboardingCreditsBadgeProps { + provider: AIProvider; + className?: string; +} + +/** + * Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider + */ +export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) { + const { data: credits, isLoading, error } = useAICredits(provider); + + // Don't render anything if there's an error (provider doesn't support credits endpoint) + if (error || isLoading) { + return null; + } + + // Don't render if no credits data is available or if amount is 0 + if (!credits || credits.amount === 0) { + return null; + } + + // Format the amount as currency + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(credits.amount); + + return ( + + {formattedAmount} + + ); +} \ No newline at end of file diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index fb693003..f7f72df4 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -15,6 +15,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; +import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; import { cn } from '@/lib/utils'; @@ -359,11 +360,14 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) >
- + {provider.name}
+ {isSelected && (
diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index 8652e772..6091283f 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -36,6 +36,6 @@ export function useAICredits(provider: AIProvider) { retry: false, // Don't retry as not all providers support this endpoint refetchOnWindowFocus: false, staleTime: 5 * 60 * 1000, // 5 minutes - enabled: provider.id === 'shakespeare' && !!user, + enabled: !!provider.nostr && !!user, }); } \ No newline at end of file From 3e8d5fb87c8882626d3a48e18eb3026d77715ee8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:06:12 -0500 Subject: [PATCH 09/52] Fix tiny checkboxes on AI Settings page --- src/pages/AISettings.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index d4cc53ec..7519fabf 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -412,7 +412,7 @@ export function AISettings() { ...prev, [preset.id]: checked === true, }))} - className="h-3 w-3" + className="size-3 [&_svg]:size-3" />
-

Quality of output depends on models used and is not guaranteed

+

Quality of output depends on quality of input and models used and is not guaranteed

From 24c8525360b9f8ae589421c3c979ab4f911e6033 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:20:36 -0500 Subject: [PATCH 11/52] Fix OnboardingDialog height, remove scrollbar customizations, add comma --- src/components/OnboardingDialog.tsx | 4 ++-- src/index.css | 19 ------------------- 2 files changed, 2 insertions(+), 21 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 38a0f09d..3a62b183 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -171,7 +171,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) return ( <> - + {step === 'open-source' && ( @@ -297,7 +297,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
-

Quality of output depends on quality of input and models used and is not guaranteed

+

Quality of output depends on quality of input and models used, and is not guaranteed

diff --git a/src/index.css b/src/index.css index b09c5aa2..b98d00b9 100644 --- a/src/index.css +++ b/src/index.css @@ -120,25 +120,6 @@ font-feature-settings: "rlig" 1, "calt" 1; } - /* GitHub-style scrollbars */ - ::-webkit-scrollbar { - width: 8px; - height: 8px; - } - - ::-webkit-scrollbar-track { - background: transparent; - } - - ::-webkit-scrollbar-thumb { - background: hsl(var(--border)); - border-radius: 4px; - } - - ::-webkit-scrollbar-thumb:hover { - background: hsl(var(--muted-foreground) / 0.5); - } - /* GitHub-style focus rings */ .focus-ring:focus-visible { outline: none; From 1abc37f38867a02e5acda1798ec883d0a5ebdd23 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:29:58 -0500 Subject: [PATCH 12/52] Actually, bring back the custom scrollbars --- src/index.css | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/index.css b/src/index.css index b98d00b9..b09c5aa2 100644 --- a/src/index.css +++ b/src/index.css @@ -120,6 +120,25 @@ font-feature-settings: "rlig" 1, "calt" 1; } + /* GitHub-style scrollbars */ + ::-webkit-scrollbar { + width: 8px; + height: 8px; + } + + ::-webkit-scrollbar-track { + background: transparent; + } + + ::-webkit-scrollbar-thumb { + background: hsl(var(--border)); + border-radius: 4px; + } + + ::-webkit-scrollbar-thumb:hover { + background: hsl(var(--muted-foreground) / 0.5); + } + /* GitHub-style focus rings */ .focus-ring:focus-visible { outline: none; From 75cab68281c3a2944162fb047d6f17e46a646e48 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:48:35 -0500 Subject: [PATCH 13/52] Clean up directory if cloning fails --- src/lib/ProjectsManager.test.ts | 62 +++++++++++++++++++++++++++++++++ src/lib/ProjectsManager.ts | 62 ++++++++++++++++++++------------- 2 files changed, 99 insertions(+), 25 deletions(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index f823c200..b7239ad5 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -440,6 +440,68 @@ describe('ProjectsManager', () => { }); }); + describe('cloneProject', () => { + it('should clean up project directory when clone fails', async () => { + await projectsManager.init(); + + // Mock git.clone to fail + const mockGit = { + clone: vi.fn().mockRejectedValue(new Error('Clone failed')), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Attempt to clone a project + await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git')) + .rejects.toThrow('Clone failed'); + + // Verify that the project directory was cleaned up + const project = await projectsManager.getProject('test-project'); + expect(project).toBeNull(); + + // Verify directory doesn't exist in filesystem + await expect(fs.stat('/projects/test-project')).rejects.toThrow('ENOENT'); + }); + + it('should handle cleanup errors gracefully', async () => { + await projectsManager.init(); + + // Mock git.clone to fail + const mockGit = { + clone: vi.fn().mockRejectedValue(new Error('Clone failed')), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Spy on console.warn to check for cleanup warnings + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + // Mock deleteDirectory to also fail (simulate cleanup error) + type ProjectsManagerWithPrivate = ProjectsManager & { deleteDirectory: (path: string) => Promise }; + const originalDeleteDirectory = (projectsManager as ProjectsManagerWithPrivate).deleteDirectory; + (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = vi.fn().mockRejectedValue(new Error('Cleanup failed')); + + try { + // Attempt to clone a project + await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git')) + .rejects.toThrow('Clone failed'); + + // Should have logged a cleanup warning + expect(consoleSpy).toHaveBeenCalledWith( + 'Failed to clean up directory after clone failure:', + expect.any(Error) + ); + + } finally { + // Restore mocks + consoleSpy.mockRestore(); + (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = originalDeleteDirectory; + } + }); + }); + describe('renameProject', () => { it('should rename a project directory', async () => { await projectsManager.init(); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 486d4207..11b57787 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -290,33 +290,45 @@ export class ProjectsManager { await this.fs.mkdir(projectPath); - // Clone the repository (Git class now handles Nostr URIs automatically) - await this.git.clone({ - dir: projectPath, - url: repoUrl, - singleBranch: true, - depth: options?.depth, // Use depth if provided, otherwise clone full history - }); - - // Get filesystem stats for timestamps - const stats = await this.fs.stat(projectPath); - const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); - - // Automatically request persistent storage after project cloning try { - await ensurePersistentStorage(); - } catch (error) { - // Don't fail project cloning if persistent storage request fails - console.warn('Failed to request persistent storage after project cloning:', error); - } + // Clone the repository (Git class now handles Nostr URIs automatically) + await this.git.clone({ + dir: projectPath, + url: repoUrl, + singleBranch: true, + depth: options?.depth, // Use depth if provided, otherwise clone full history + }); - // Return the full project object with dynamically generated properties - return { - id, - name: this.formatProjectName(id), // Use formatted directory name - path: projectPath, - lastModified: timestamp, - }; + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Automatically request persistent storage after project cloning + try { + await ensurePersistentStorage(); + } catch (error) { + // Don't fail project cloning if persistent storage request fails + console.warn('Failed to request persistent storage after project cloning:', error); + } + + // Return the full project object with dynamically generated properties + return { + id, + name: this.formatProjectName(id), // Use formatted directory name + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up the directory that was created if cloning fails + try { + await this.deleteDirectory(projectPath); + } catch (cleanupError) { + // Log cleanup error but don't mask the original clone error + console.warn('Failed to clean up directory after clone failure:', cleanupError); + } + // Re-throw the original clone error + throw error; + } } async getProjects(): Promise { From a87063f6e9867e34e1945463af33a2ecb6cf8179 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:55:28 -0500 Subject: [PATCH 14/52] Fix types in test --- src/lib/ProjectsManager.test.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index b7239ad5..5e43cf2a 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -478,10 +478,9 @@ describe('ProjectsManager', () => { // Spy on console.warn to check for cleanup warnings const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - // Mock deleteDirectory to also fail (simulate cleanup error) - type ProjectsManagerWithPrivate = ProjectsManager & { deleteDirectory: (path: string) => Promise }; - const originalDeleteDirectory = (projectsManager as ProjectsManagerWithPrivate).deleteDirectory; - (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = vi.fn().mockRejectedValue(new Error('Cleanup failed')); + // Mock fs.rmdir to fail (simulate cleanup error) + const originalRmdir = fs.rmdir; + fs.rmdir = vi.fn().mockRejectedValue(new Error('Cleanup failed')); try { // Attempt to clone a project @@ -497,7 +496,7 @@ describe('ProjectsManager', () => { } finally { // Restore mocks consoleSpy.mockRestore(); - (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = originalDeleteDirectory; + fs.rmdir = originalRmdir; } }); }); From 3da2075539cb4e6e1ccb9045432e7d4330171959 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:01:30 -0500 Subject: [PATCH 15/52] Ensure console errors get passed to Quilly on desktop --- src/pages/ProjectView.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index f73f3a3b..4b5d926b 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -409,6 +409,8 @@ export function ProjectView() { onLoadingChange={handleAILoadingChange} isLoading={isAILoading} isBuildLoading={build.isPending} + consoleError={consoleError} + onDismissConsoleError={handleDismissConsoleError} /> ) : (
From 795eaa50c2cdb3026c4865e8ddd4511422a55440 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:19:02 -0500 Subject: [PATCH 16/52] Make Quilly's "fix error" add assistant messages --- src/components/AIMessageItem.tsx | 7 +++++- src/components/Shakespeare/ChatPane.tsx | 31 ++++++++++++++++++++++--- src/lib/SessionManager.ts | 4 ---- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index f850d900..2287ac82 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,6 +1,6 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; -import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react'; +import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; @@ -150,6 +150,11 @@ export const AIMessageItem = memo(({ icon: CheckCircle, title: 'TypeScript' }; + case 'read_console_messages': + return { + icon: Logs, + title: 'Read Console' + }; default: return { icon: Wrench, diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 02721a19..913011ad 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -203,6 +203,7 @@ export const ChatPane = forwardRef(({ isLoading: internalIsLoading, totalCost, lastInputTokens, + addMessage, sendMessage, startGeneration, stopGeneration, @@ -216,9 +217,33 @@ export const ChatPane = forwardRef(({ }); // Handle console error help requests - const handleConsoleErrorHelp = useCallback(() => { - sendMessage('Read the console messages and fix any errors present.', providerModel); - }, [sendMessage, providerModel]); + const handleConsoleErrorHelp = useCallback(async () => { + const tool = new ReadConsoleMessagesTool(); + const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`; + + await addMessage({ + role: 'assistant', + content: 'Let me take a look at the console messages to help diagnose the issue.', + tool_calls: [ + { + id: toolCallId, + type: 'function', + function: { + name: 'read_console_messages', + arguments: '{}', + } + } + ] + }); + + await addMessage({ + role: 'tool', + content: await tool.execute({ filter: 'error' }), + tool_call_id: toolCallId, + }); + + await startGeneration(providerModel); + }, [addMessage, providerModel, startGeneration]); // Handle error dismissal const handleErrorDismiss = useCallback(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index fde41dd3..22f416c1 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -188,10 +188,6 @@ export class SessionManager { throw new Error('No messages in session'); } - // Check if last message is from user - const lastMessage = session.messages[session.messages.length - 1]; - if (lastMessage.role !== 'user') return; - session.isLoading = true; session.abortController = new AbortController(); session.lastActivity = new Date(); From 5fa16115fd4a6bcfc1e84136873976ab02f9ffd2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:51:25 -0500 Subject: [PATCH 17/52] Rebuild project after saving file Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/53 --- src/components/Shakespeare/PreviewPane.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 03783f08..751e87e9 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -497,6 +497,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o try { await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content); setFileContent(content); + + // Automatically trigger a rebuild after saving a file + if (isPreviewable) { + console.log('File saved, triggering rebuild...'); + handleBuildProject(); + } } catch (error) { console.error('Failed to save file:', error); } From b04c1440b5a12081cd6325efe0d940a62c3b6d3c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 18:01:49 -0500 Subject: [PATCH 18/52] Improve display of buttons --- src/components/Shakespeare/PreviewPane.tsx | 2 +- src/components/ui/button-variants.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 751e87e9..959c9eaa 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -532,7 +532,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o -
+ +
+ setCustomValue(e.target.value)} + onKeyDown={handleCustomKeyDown} + onBlur={handleCustomSubmit} + placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" + className="h-8 text-xs" + autoFocus + /> + +
+
); } return ( - - - - + +
+ {isCurrentModelFree && ( + + + + + +

You are using a free model. For better results, switch to a premium model.

+
+
+ )} + + + + {(isConfigured && models.length >= 5) && ( @@ -289,5 +378,7 @@ export function ModelSelector({ +
+
); } \ No newline at end of file From cb794b5719fbc98839731a2dbc4a2b2936dbd6e4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 1 Oct 2025 17:08:31 -0500 Subject: [PATCH 36/52] We do a little discord coding --- src/components/ModelSelector.tsx | 236 ++++++++++++------------ src/components/Shakespeare/ChatPane.tsx | 1 - 2 files changed, 118 insertions(+), 119 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 76257bba..2e674c00 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -189,7 +189,7 @@ export function ModelSelector({ return ( -
+
{isCurrentModelFree && ( - - - {(isConfigured && models.length >= 5) && ( - - )} - - -
-

{t('noModelsFound')}

-

{t('tryCustomModel')}

-
-
- - {shouldShowRecentlyUsed && ( - - {recentlyUsedModels.map((model) => ( - handleSelect(model)} - className="cursor-pointer" - > - - {model} - - ))} - - )} - - {shouldShowRecentlyUsed && } - - {/* Loading state */} - {isLoading && ( - -
-
- - - + + + {(isConfigured && models.length >= 5) && ( + + )} + + +
+

{t('noModelsFound')}

+

{t('tryCustomModel')}

-
- - )} + - {/* Error state */} - {error && !isLoading && ( - -
-
- -
-

{error}

- -
-
-
-
- )} + + {model} + + ))} + + )} - {/* Provider models */} - {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( -
+ {shouldShowRecentlyUsed && } + + {/* Loading state */} + {isLoading && ( + +
+
+ + + +
+
+
+ )} + + {/* Error state */} + {error && !isLoading && ( + +
+
+ +
+

{error}

+ +
+
+
+
+ )} + + {/* Provider models */} + {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( +
+ + + {providerModels.map((model) => ( + handleSelect(model.fullId)} + className="cursor-pointer" + > + + {model.fullId} + + ))} + +
+ ))} + + {/* Custom model option and manage providers - moved to bottom */} - - {providerModels.map((model) => ( + + {isConfigured && ( handleSelect(model.fullId)} + value="__custom_model_option__" + onSelect={() => handleSelect('__custom__')} className="cursor-pointer" > - - {model.fullId} + + {t('enterCustomModel')} - ))} + )} + handleSelect('__manage_providers__')} + className="cursor-pointer" + > + + {t('manageProviders')} + -
- ))} - - {/* Custom model option and manage providers - moved to bottom */} - - - {isConfigured && ( - handleSelect('__custom__')} - className="cursor-pointer" - > - - {t('enterCustomModel')} - - )} - handleSelect('__manage_providers__')} - className="cursor-pointer" - > - - {t('manageProviders')} - - - - - - + + + +
); diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index d6d740f4..e8626112 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -763,7 +763,6 @@ export const ChatPane = forwardRef(({ Date: Wed, 1 Oct 2025 17:13:23 -0500 Subject: [PATCH 37/52] Fix ModelSelector test --- src/components/ModelSelector.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index 56d15fb9..ca350262 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -384,7 +384,7 @@ describe('ModelSelector', () => { // Wait for tooltip to appear await waitFor(() => { - expect(screen.getAllByText('You are using a free model. For better results, switch to a premium model.').length).toBeGreaterThan(0); + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); }); }); @@ -424,7 +424,7 @@ describe('ModelSelector', () => { // Tooltip should appear await waitFor(() => { - expect(screen.getAllByText('You are using a free model. For better results, switch to a premium model.').length).toBeGreaterThan(0); + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); }); // The button should still be clickable (no errors) From 3fba26ddb7e5ddff3c8f2d6a4cc761651b858fa6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 1 Oct 2025 17:24:22 -0500 Subject: [PATCH 38/52] Switch payment method to a tabbed UI instead of dropdown --- src/components/CreditsDialog.tsx | 35 +++++++++++++------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 4b33517c..8b4de085 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label'; import { Badge } from '@/components/ui/badge'; import { Separator } from '@/components/ui/separator'; import { Skeleton } from '@/components/ui/skeleton'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -464,26 +464,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
- - + + setPaymentMethod(value)} className="w-full"> + + + + Credit Card + + + + Lightning + + +
@@ -555,7 +574,21 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - consoleMessages.map((msg, index) => ( + <> + {/* Clear button when messages exist */} + {messageCount > 0 && ( +
+ +
+ )} + {messages.map((msg, index) => (
- )) + ))} + )}
diff --git a/src/contexts/ConsoleErrorContext.ts b/src/contexts/ConsoleErrorContext.ts new file mode 100644 index 00000000..ed576ce4 --- /dev/null +++ b/src/contexts/ConsoleErrorContext.ts @@ -0,0 +1,11 @@ +import { createContext } from 'react'; +import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; + +export interface ConsoleErrorContextValue { + hasErrors: boolean; + consoleError: ProjectPreviewConsoleError | null; + clearErrors: () => void; + dismissConsoleError: () => void; +} + +export const ConsoleErrorContext = createContext(undefined); \ No newline at end of file diff --git a/src/hooks/useConsoleError.test.ts b/src/hooks/useConsoleError.test.ts new file mode 100644 index 00000000..d1560f5e --- /dev/null +++ b/src/hooks/useConsoleError.test.ts @@ -0,0 +1,12 @@ +import { describe, it, expect } from 'vitest'; +import { renderHook } from '@testing-library/react'; +import { useConsoleError } from './useConsoleError'; + +describe('useConsoleError', () => { + it('should throw error when used outside ConsoleErrorProvider', () => { + // Expect the hook to throw when not wrapped in provider + expect(() => { + renderHook(() => useConsoleError()); + }).toThrow('useConsoleError must be used within a ConsoleErrorProvider'); + }); +}); \ No newline at end of file diff --git a/src/hooks/useConsoleError.ts b/src/hooks/useConsoleError.ts new file mode 100644 index 00000000..12141dbc --- /dev/null +++ b/src/hooks/useConsoleError.ts @@ -0,0 +1,16 @@ +import { useContext } from 'react'; +import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; + +/** + * Hook to access console error state from the ConsoleErrorProvider. + * Provides boolean error state and console error information for Quilly. + */ +export function useConsoleError() { + const context = useContext(ConsoleErrorContext); + + if (context === undefined) { + throw new Error('useConsoleError must be used within a ConsoleErrorProvider'); + } + + return context; +} \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 1b2647ef..d31c11f0 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -4,8 +4,9 @@ import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError, - addErrorListener, - removeErrorListener + addErrorStateListener, + removeErrorStateListener, + getHasConsoleErrors } from './ReadConsoleMessagesTool'; describe('ReadConsoleMessagesTool', () => { @@ -80,58 +81,83 @@ describe('ProjectPreviewConsoleError', () => { }); }); -describe('Console Error Listeners', () => { +describe('Console Error State Management', () => { beforeEach(() => { clearConsoleMessages(); }); - it('should trigger error listener when console error is added', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); + it('should track error state with boolean', () => { + expect(getHasConsoleErrors()).toBe(false); - // Add an error message + // Add non-error messages - should not change state + addConsoleMessage('log', 'Test log message'); + addConsoleMessage('warn', 'Test warning message'); + expect(getHasConsoleErrors()).toBe(false); + + // Add error message - should change state addConsoleMessage('error', 'Test error message'); - - // Wait a bit for the listener to be called - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(errorListener).toHaveBeenCalledTimes(1); - expect(errorListener).toHaveBeenCalledWith( - expect.objectContaining({ - message: 'Console error detected: Test error message', - logs: expect.arrayContaining([ - expect.objectContaining({ - level: 'error', - message: 'Test error message' - }) - ]) - }) - ); + expect(getHasConsoleErrors()).toBe(true); - removeErrorListener(errorListener); + // Add another error - should remain true + addConsoleMessage('error', 'Another error'); + expect(getHasConsoleErrors()).toBe(true); }); - it('should not trigger error listener for non-error messages', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); + it('should trigger error state listener when error state changes', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); - // Add non-error messages + // Add non-error messages - should not trigger addConsoleMessage('log', 'Test log message'); addConsoleMessage('warn', 'Test warning message'); - addConsoleMessage('info', 'Test info message'); // Wait a bit await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).not.toHaveBeenCalled(); - expect(errorListener).not.toHaveBeenCalled(); + // Add error message - should trigger with true + addConsoleMessage('error', 'Test error message'); - removeErrorListener(errorListener); + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(1); + expect(errorStateListener).toHaveBeenCalledWith(true); + + // Add another error - should not trigger again (already true) + addConsoleMessage('error', 'Another error'); + + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(1); // Still only called once + + removeErrorStateListener(errorStateListener); }); - it('should remove error listener correctly', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); - removeErrorListener(errorListener); + it('should reset error state when clearing messages', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); + + // Add error to set state to true + addConsoleMessage('error', 'Test error message'); + expect(getHasConsoleErrors()).toBe(true); + + // Clear messages - should reset state and notify + clearConsoleMessages(); + expect(getHasConsoleErrors()).toBe(false); + + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(2); + expect(errorStateListener).toHaveBeenNthCalledWith(1, true); // First call when error added + expect(errorStateListener).toHaveBeenNthCalledWith(2, false); // Second call when cleared + + removeErrorStateListener(errorStateListener); + }); + + it('should remove error state listener correctly', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); + removeErrorStateListener(errorStateListener); // Add an error message addConsoleMessage('error', 'Test error message'); @@ -139,7 +165,7 @@ describe('Console Error Listeners', () => { // Wait a bit await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorListener).not.toHaveBeenCalled(); + expect(errorStateListener).not.toHaveBeenCalled(); }); it('should handle listener errors gracefully', async () => { @@ -148,8 +174,8 @@ describe('Console Error Listeners', () => { }); const workingListener = vi.fn(); - addErrorListener(faultyListener); - addErrorListener(workingListener); + addErrorStateListener(faultyListener); + addErrorStateListener(workingListener); // Should not throw despite faulty listener expect(() => { @@ -162,7 +188,7 @@ describe('Console Error Listeners', () => { expect(faultyListener).toHaveBeenCalled(); expect(workingListener).toHaveBeenCalled(); - removeErrorListener(faultyListener); - removeErrorListener(workingListener); + removeErrorStateListener(faultyListener); + removeErrorStateListener(workingListener); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index f2396b40..a7cbb26c 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -25,7 +25,10 @@ export class ProjectPreviewConsoleError extends Error { // Simple global console messages storage const consoleMessages: ConsoleMessage[] = []; -const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; + +// Boolean-based error detection system +let hasConsoleErrors = false; +const errorStateListeners: Array<(hasErrors: boolean) => void> = []; export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { const consoleMessage: ConsoleMessage = { @@ -35,18 +38,16 @@ export const addConsoleMessage = (level: ConsoleMessage['level'], message: strin consoleMessages.push(consoleMessage); - // If this is an error, notify listeners - if (level === 'error') { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${message}`, - consoleMessages.filter(msg => msg.level === 'error') - ); + // If this is an error, update boolean state + if (level === 'error' && !hasConsoleErrors) { + hasConsoleErrors = true; - errorListeners.forEach(listener => { + // Notify boolean state listeners + errorStateListeners.forEach(listener => { try { - listener(error); + listener(true); } catch (err) { - console.warn('Error listener failed:', err); + console.warn('Error state listener failed:', err); } }); } @@ -56,19 +57,38 @@ export const getConsoleMessages = (): ConsoleMessage[] => { return [...consoleMessages]; }; -export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - errorListeners.push(listener); +export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { + errorStateListeners.push(listener); }; -export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - const index = errorListeners.indexOf(listener); +export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { + const index = errorStateListeners.indexOf(listener); if (index > -1) { - errorListeners.splice(index, 1); + errorStateListeners.splice(index, 1); } }; +export const getHasConsoleErrors = (): boolean => { + return hasConsoleErrors; +}; + export const clearConsoleMessages = () => { consoleMessages.length = 0; + + // Reset error state + const hadErrors = hasConsoleErrors; + hasConsoleErrors = false; + + // Notify listeners if state changed + if (hadErrors) { + errorStateListeners.forEach(listener => { + try { + listener(false); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } }; export class ReadConsoleMessagesTool implements Tool { diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 4b5d926b..a2b23c9e 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; -import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; +import { useConsoleError } from '@/hooks/useConsoleError'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -29,7 +29,9 @@ export function ProjectView() { const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); - const [consoleError, setConsoleError] = useState(null); + + // Use console error state from provider + const { consoleError, dismissConsoleError, clearErrors } = useConsoleError(); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); @@ -48,14 +50,13 @@ export function ProjectView() { const projectData = await projectsManager.getProject(projectId); setProject(projectData); // Clear console messages and error state when switching projects - clearConsoleMessages(); - setConsoleError(null); + clearErrors(); } catch (error) { console.error('Failed to load project:', error); } finally { setIsLoading(false); } - }, [projectId, projectsManager]); + }, [projectId, projectsManager, clearErrors]); useEffect(() => { loadProject(); @@ -81,15 +82,7 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); - // Global console error listener (always active regardless of current tab) - useEffect(() => { - const handleConsoleError = (error: ProjectPreviewConsoleError) => { - setConsoleError(error); - }; - - addErrorListener(handleConsoleError); - return () => removeErrorListener(handleConsoleError); - }, []); + // Console error handling is now managed by useQuillyConsoleErrors hook const handleNewChat = () => { // Reset to chat view on mobile when starting new chat @@ -113,7 +106,7 @@ export function ProjectView() { }; const handleDismissConsoleError = () => { - setConsoleError(null); + dismissConsoleError(); }; const handleProjectDeleted = async () => { From 945c4209e875554621a78d3dce3ba5b99e678d2e Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:02:16 +0000 Subject: [PATCH 40/52] Remove frivilous UI updates. --- src/components/Shakespeare/PreviewPane.tsx | 25 ++-------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index c45a2da2..6c0d43c7 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -537,12 +537,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }; - const handleClearMessages = () => { - clearErrors(); - setMessages([]); - setCopiedMessageIndex(null); - }; - const messageCount = messages.length; return ( @@ -574,21 +568,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - <> - {/* Clear button when messages exist */} - {messageCount > 0 && ( -
- -
- )} - {messages.map((msg, index) => ( + messages.map((msg, index) => (
- ))} - + )) )}
From 23c3cead899d7a3082dd3ff21e1affc484fae45b Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:09:09 +0000 Subject: [PATCH 41/52] Move non-tool logic out of tool file. --- src/components/ConsoleErrorProvider.test.tsx | 48 ++--- src/components/ConsoleErrorProvider.tsx | 16 +- src/components/Quilly.tsx | 2 +- src/components/Shakespeare/ChatPane.tsx | 3 +- src/components/Shakespeare/PreviewPane.tsx | 2 +- src/contexts/ConsoleErrorContext.ts | 2 +- src/lib/consoleMessages.test.ts | 168 ++++++++++++++++++ src/lib/consoleMessages.ts | 90 ++++++++++ src/lib/tools/ReadConsoleMessagesTool.test.ts | 161 ++++------------- src/lib/tools/ReadConsoleMessagesTool.ts | 103 ++--------- 10 files changed, 345 insertions(+), 250 deletions(-) create mode 100644 src/lib/consoleMessages.test.ts create mode 100644 src/lib/consoleMessages.ts diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx index ae6445cb..44305d8d 100644 --- a/src/components/ConsoleErrorProvider.test.tsx +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -3,7 +3,7 @@ import { renderHook, act, waitFor } from '@testing-library/react'; import { ReactNode } from 'react'; import { ConsoleErrorProvider } from './ConsoleErrorProvider'; import { useConsoleError } from '@/hooks/useConsoleError'; -import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages'; // Wrapper component for testing function TestWrapper({ children }: { children: ReactNode }) { @@ -23,7 +23,7 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -32,14 +32,14 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + expect(result.current.hasErrors).toBe(false); - + // Add an error message act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.hasErrors).toBe(true); expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError); expect(result.current.consoleError?.message).toBe('Console error detected: Test error message'); @@ -49,14 +49,14 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add non-error messages act(() => { addConsoleMessage('log', 'Test log message'); addConsoleMessage('warn', 'Test warning message'); addConsoleMessage('info', 'Test info message'); }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -65,24 +65,24 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add first error act(() => { addConsoleMessage('error', 'First error'); }); - + expect(result.current.consoleError?.message).toBe('Console error detected: First error'); - + // Add second error - should update to show latest error act(() => { addConsoleMessage('error', 'Second error'); }); - + // Wait for polling to detect the new error await waitFor(() => { expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); }); - + expect(result.current.consoleError?.logs).toHaveLength(2); }); @@ -90,20 +90,20 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add error to set state act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.hasErrors).toBe(true); expect(result.current.consoleError).not.toBeNull(); - + // Clear errors act(() => { result.current.clearErrors(); }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -112,19 +112,19 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add error to create console error act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.consoleError).not.toBeNull(); - + // Dismiss console error (this only clears the Quilly error, not the global state) act(() => { result.current.dismissConsoleError(); }); - + expect(result.current.consoleError).toBeNull(); // hasErrors should still be true since we only dismissed the Quilly display expect(result.current.hasErrors).toBe(true); @@ -134,7 +134,7 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add multiple errors and non-errors act(() => { addConsoleMessage('log', 'Log message'); @@ -144,16 +144,16 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('info', 'Info message'); addConsoleMessage('error', 'Third error'); }); - + // Wait for polling to detect all the new errors await waitFor(() => { expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); }); - + expect(result.current.consoleError?.logs).toHaveLength(3); expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([ 'First error', - 'Second error', + 'Second error', 'Third error' ]); }); diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx index b94297e5..da0ad912 100644 --- a/src/components/ConsoleErrorProvider.tsx +++ b/src/components/ConsoleErrorProvider.tsx @@ -1,12 +1,12 @@ import { useState, useEffect, useRef, useCallback, ReactNode } from 'react'; -import { - addErrorStateListener, +import { + addErrorStateListener, removeErrorStateListener, getHasConsoleErrors, getConsoleMessages, clearConsoleMessages, ProjectPreviewConsoleError -} from '@/lib/tools/ReadConsoleMessagesTool'; +} from '@/lib/consoleMessages'; import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; interface ConsoleErrorProviderProps { @@ -22,7 +22,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const updateConsoleError = useCallback(() => { const messages = getConsoleMessages(); const errorMessages = messages.filter(msg => msg.level === 'error'); - + if (errorMessages.length > 0) { const error = new ProjectPreviewConsoleError( `Console error detected: ${errorMessages[errorMessages.length - 1].message}`, @@ -40,7 +40,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { useEffect(() => { const handleErrorStateChange = (hasErrors: boolean) => { setHasErrors(hasErrors); - + if (hasErrors) { // Always update when we get an error state change updateConsoleError(); @@ -55,7 +55,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const checkForNewErrors = () => { const messages = getConsoleMessages(); const errorMessages = messages.filter(msg => msg.level === 'error'); - + if (errorMessages.length > lastErrorCountRef.current) { // New errors detected - update the console error updateConsoleError(); @@ -64,11 +64,11 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { // Listen for error state changes addErrorStateListener(handleErrorStateChange); - + // Initial sync setHasErrors(getHasConsoleErrors()); updateConsoleError(); - + // Poll for new errors (handles multiple errors being added) const interval = setInterval(checkForNewErrors, 100); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index b0b97f05..adb087b7 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -7,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings'; import { parseProviderModel } from '@/lib/parseProviderModel'; import { useAICredits } from '@/hooks/useAICredits'; import { CreditsDialog } from './CreditsDialog'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; export interface QuillyProps { diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e8626112..4b743237 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -34,7 +34,8 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 6c0d43c7..3d48cb77 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,7 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; -import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool'; +import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages'; import { useConsoleError } from '@/hooks/useConsoleError'; import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; diff --git a/src/contexts/ConsoleErrorContext.ts b/src/contexts/ConsoleErrorContext.ts index ed576ce4..d01ea220 100644 --- a/src/contexts/ConsoleErrorContext.ts +++ b/src/contexts/ConsoleErrorContext.ts @@ -1,5 +1,5 @@ import { createContext } from 'react'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; export interface ConsoleErrorContextValue { hasErrors: boolean; diff --git a/src/lib/consoleMessages.test.ts b/src/lib/consoleMessages.test.ts new file mode 100644 index 00000000..31a895ba --- /dev/null +++ b/src/lib/consoleMessages.test.ts @@ -0,0 +1,168 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + addConsoleMessage, + clearConsoleMessages, + getConsoleMessages, + getHasConsoleErrors, + addErrorStateListener, + removeErrorStateListener, + ProjectPreviewConsoleError +} from './consoleMessages'; + +describe('Console Messages System', () => { + beforeEach(() => { + clearConsoleMessages(); + }); + + describe('addConsoleMessage', () => { + it('should add messages to the global store', () => { + addConsoleMessage('log', 'Test log message'); + addConsoleMessage('error', 'Test error message'); + + const messages = getConsoleMessages(); + expect(messages).toHaveLength(2); + expect(messages[0]).toEqual({ level: 'log', message: 'Test log message' }); + expect(messages[1]).toEqual({ level: 'error', message: 'Test error message' }); + }); + + it('should update error state when error message is added', () => { + expect(getHasConsoleErrors()).toBe(false); + + addConsoleMessage('log', 'Log message'); + expect(getHasConsoleErrors()).toBe(false); + + addConsoleMessage('error', 'Error message'); + expect(getHasConsoleErrors()).toBe(true); + }); + + it('should only trigger error state once for multiple errors', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + addConsoleMessage('error', 'First error'); + expect(listener).toHaveBeenCalledTimes(1); + expect(listener).toHaveBeenCalledWith(true); + + addConsoleMessage('error', 'Second error'); + expect(listener).toHaveBeenCalledTimes(1); // Should not be called again + + removeErrorStateListener(listener); + }); + }); + + describe('getConsoleMessages', () => { + it('should return a copy of messages array', () => { + addConsoleMessage('info', 'Test message'); + + const messages1 = getConsoleMessages(); + const messages2 = getConsoleMessages(); + + expect(messages1).toEqual(messages2); + expect(messages1).not.toBe(messages2); // Different array instances + }); + + it('should return empty array when no messages', () => { + const messages = getConsoleMessages(); + expect(messages).toEqual([]); + }); + }); + + describe('clearConsoleMessages', () => { + it('should clear all messages and reset error state', () => { + addConsoleMessage('error', 'Error message'); + addConsoleMessage('log', 'Log message'); + + expect(getConsoleMessages()).toHaveLength(2); + expect(getHasConsoleErrors()).toBe(true); + + clearConsoleMessages(); + + expect(getConsoleMessages()).toHaveLength(0); + expect(getHasConsoleErrors()).toBe(false); + }); + + it('should notify listeners when error state changes', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + addConsoleMessage('error', 'Error message'); + expect(listener).toHaveBeenCalledWith(true); + + clearConsoleMessages(); + expect(listener).toHaveBeenCalledWith(false); + expect(listener).toHaveBeenCalledTimes(2); + + removeErrorStateListener(listener); + }); + + it('should not notify listeners if no error state change', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + // No errors added, so clearing should not trigger listener + clearConsoleMessages(); + expect(listener).not.toHaveBeenCalled(); + + removeErrorStateListener(listener); + }); + }); + + describe('Error State Listeners', () => { + it('should add and remove listeners correctly', () => { + const listener1 = vi.fn(); + const listener2 = vi.fn(); + + addErrorStateListener(listener1); + addErrorStateListener(listener2); + + addConsoleMessage('error', 'Test error'); + + expect(listener1).toHaveBeenCalledWith(true); + expect(listener2).toHaveBeenCalledWith(true); + + removeErrorStateListener(listener1); + clearConsoleMessages(); + + expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear) + expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear + + removeErrorStateListener(listener2); + }); + + it('should handle listener errors gracefully', () => { + const faultyListener = vi.fn(() => { + throw new Error('Listener error'); + }); + const workingListener = vi.fn(); + + addErrorStateListener(faultyListener); + addErrorStateListener(workingListener); + + // Should not throw despite faulty listener + expect(() => { + addConsoleMessage('error', 'Test error'); + }).not.toThrow(); + + expect(faultyListener).toHaveBeenCalled(); + expect(workingListener).toHaveBeenCalled(); + + removeErrorStateListener(faultyListener); + removeErrorStateListener(workingListener); + }); + }); + + describe('ProjectPreviewConsoleError', () => { + it('should create error with console logs', () => { + const logs = [ + { level: 'error' as const, message: 'Test error' } + ]; + const error = new ProjectPreviewConsoleError('Test message', logs); + + expect(error.message).toBe('Test message'); + expect(error.name).toBe('ProjectPreviewConsoleError'); + expect(error.logs).toEqual(logs); + expect(error instanceof Error).toBe(true); + expect(error instanceof ProjectPreviewConsoleError).toBe(true); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/consoleMessages.ts b/src/lib/consoleMessages.ts new file mode 100644 index 00000000..f22f7a61 --- /dev/null +++ b/src/lib/consoleMessages.ts @@ -0,0 +1,90 @@ +/** + * Global console message storage and state management. + * This module handles the core console message system that the AI tool reads from. + */ + +export interface ConsoleMessage { + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; +} + +/** + * Custom error class for project preview console errors + */ +export class ProjectPreviewConsoleError extends Error { + public readonly logs: ConsoleMessage[]; + + constructor(message: string, logs: ConsoleMessage[]) { + super(message); + this.name = 'ProjectPreviewConsoleError'; + this.logs = logs; + } +} + +// Global console messages storage +const consoleMessages: ConsoleMessage[] = []; + +// Boolean-based error detection system +let hasConsoleErrors = false; +const errorStateListeners: Array<(hasErrors: boolean) => void> = []; + +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const consoleMessage: ConsoleMessage = { + level, + message, + }; + + consoleMessages.push(consoleMessage); + + // Only update boolean state on first error + if (level === 'error' && !hasConsoleErrors) { + hasConsoleErrors = true; + + // Notify boolean state listeners + errorStateListeners.forEach(listener => { + try { + listener(true); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } +}; + +export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { + errorStateListeners.push(listener); +}; + +export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { + const index = errorStateListeners.indexOf(listener); + if (index > -1) { + errorStateListeners.splice(index, 1); + } +}; + +export const getHasConsoleErrors = (): boolean => { + return hasConsoleErrors; +}; + +export const getConsoleMessages = (): ConsoleMessage[] => { + return [...consoleMessages]; +}; + +export const clearConsoleMessages = () => { + consoleMessages.length = 0; + + // Reset error state + const hadErrors = hasConsoleErrors; + hasConsoleErrors = false; + + // Notify listeners if state changed + if (hadErrors) { + errorStateListeners.forEach(listener => { + try { + listener(false); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } +}; \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index d31c11f0..256570c7 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -1,13 +1,6 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { - ReadConsoleMessagesTool, - addConsoleMessage, - clearConsoleMessages, - ProjectPreviewConsoleError, - addErrorStateListener, - removeErrorStateListener, - getHasConsoleErrors -} from './ReadConsoleMessagesTool'; +import { describe, it, expect, beforeEach } from 'vitest'; +import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool'; +import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages'; describe('ReadConsoleMessagesTool', () => { beforeEach(() => { @@ -64,131 +57,47 @@ describe('ReadConsoleMessagesTool', () => { expect(result).toBe('No console messages found for level: debug.'); }); -}); -describe('ProjectPreviewConsoleError', () => { - it('should create error with console logs', () => { - const logs = [ - { level: 'error' as const, message: 'Test error' } - ]; - const error = new ProjectPreviewConsoleError('Test message', logs); + it('should handle all filter levels', async () => { + const tool = new ReadConsoleMessagesTool(); - expect(error.message).toBe('Test message'); - expect(error.name).toBe('ProjectPreviewConsoleError'); - expect(error.logs).toEqual(logs); - expect(error instanceof Error).toBe(true); - expect(error instanceof ProjectPreviewConsoleError).toBe(true); + // Test each filter level + const errorResult = await tool.execute({ filter: 'error' }); + expect(errorResult).toContain('[ERROR] Network request failed'); + + const warnResult = await tool.execute({ filter: 'warn' }); + expect(warnResult).toContain('[WARN] Deprecated API used'); + + const logResult = await tool.execute({ filter: 'log' }); + expect(logResult).toContain('[LOG] App started'); + + const infoResult = await tool.execute({ filter: 'info' }); + expect(infoResult).toContain('[INFO] User logged in'); }); -}); -describe('Console Error State Management', () => { - beforeEach(() => { + it('should format messages correctly', async () => { clearConsoleMessages(); + addConsoleMessage('error', 'Test error with special chars: <>&"'); + + const tool = new ReadConsoleMessagesTool(); + const result = await tool.execute({}); + + expect(result).toContain('[ERROR] Test error with special chars: <>&"'); }); - it('should track error state with boolean', () => { - expect(getHasConsoleErrors()).toBe(false); + it('should handle limit edge cases', async () => { + const tool = new ReadConsoleMessagesTool(); - // Add non-error messages - should not change state - addConsoleMessage('log', 'Test log message'); - addConsoleMessage('warn', 'Test warning message'); - expect(getHasConsoleErrors()).toBe(false); + // Limit of 0 should return no messages + const zeroResult = await tool.execute({ limit: 0 }); + expect(zeroResult).toBe('No console messages found.'); - // Add error message - should change state - addConsoleMessage('error', 'Test error message'); - expect(getHasConsoleErrors()).toBe(true); + // Negative limit should return all messages + const negativeResult = await tool.execute({ limit: -1 }); + expect(negativeResult).toContain('Found 4 console messages'); - // Add another error - should remain true - addConsoleMessage('error', 'Another error'); - expect(getHasConsoleErrors()).toBe(true); - }); - - it('should trigger error state listener when error state changes', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - - // Add non-error messages - should not trigger - addConsoleMessage('log', 'Test log message'); - addConsoleMessage('warn', 'Test warning message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).not.toHaveBeenCalled(); - - // Add error message - should trigger with true - addConsoleMessage('error', 'Test error message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(1); - expect(errorStateListener).toHaveBeenCalledWith(true); - - // Add another error - should not trigger again (already true) - addConsoleMessage('error', 'Another error'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(1); // Still only called once - - removeErrorStateListener(errorStateListener); - }); - - it('should reset error state when clearing messages', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - - // Add error to set state to true - addConsoleMessage('error', 'Test error message'); - expect(getHasConsoleErrors()).toBe(true); - - // Clear messages - should reset state and notify - clearConsoleMessages(); - expect(getHasConsoleErrors()).toBe(false); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(2); - expect(errorStateListener).toHaveBeenNthCalledWith(1, true); // First call when error added - expect(errorStateListener).toHaveBeenNthCalledWith(2, false); // Second call when cleared - - removeErrorStateListener(errorStateListener); - }); - - it('should remove error state listener correctly', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - removeErrorStateListener(errorStateListener); - - // Add an error message - addConsoleMessage('error', 'Test error message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(errorStateListener).not.toHaveBeenCalled(); - }); - - it('should handle listener errors gracefully', async () => { - const faultyListener = vi.fn(() => { - throw new Error('Listener error'); - }); - const workingListener = vi.fn(); - - addErrorStateListener(faultyListener); - addErrorStateListener(workingListener); - - // Should not throw despite faulty listener - expect(() => { - addConsoleMessage('error', 'Test error message'); - }).not.toThrow(); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(faultyListener).toHaveBeenCalled(); - expect(workingListener).toHaveBeenCalled(); - - removeErrorStateListener(faultyListener); - removeErrorStateListener(workingListener); + // Limit larger than available should return all + const largeResult = await tool.execute({ limit: 100 }); + expect(largeResult).toContain('Found 4 console messages'); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index a7cbb26c..52853686 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -1,9 +1,5 @@ import { Tool } from './Tool'; - -export interface ConsoleMessage { - level: 'log' | 'warn' | 'error' | 'info' | 'debug'; - message: string; -} +import { getConsoleMessages } from '@/lib/consoleMessages'; export interface ReadConsoleMessagesParams { filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all'; @@ -11,94 +7,25 @@ export interface ReadConsoleMessagesParams { } /** - * Custom error class for project preview console errors + * AI tool for reading console messages from the project preview. + * This tool allows AI assistants to access console logs for debugging assistance. */ -export class ProjectPreviewConsoleError extends Error { - public readonly logs: ConsoleMessage[]; - - constructor(message: string, logs: ConsoleMessage[]) { - super(message); - this.name = 'ProjectPreviewConsoleError'; - this.logs = logs; - } -} - -// Simple global console messages storage -const consoleMessages: ConsoleMessage[] = []; - -// Boolean-based error detection system -let hasConsoleErrors = false; -const errorStateListeners: Array<(hasErrors: boolean) => void> = []; - -export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // If this is an error, update boolean state - if (level === 'error' && !hasConsoleErrors) { - hasConsoleErrors = true; - - // Notify boolean state listeners - errorStateListeners.forEach(listener => { - try { - listener(true); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } -}; - -export const getConsoleMessages = (): ConsoleMessage[] => { - return [...consoleMessages]; -}; - -export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { - errorStateListeners.push(listener); -}; - -export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { - const index = errorStateListeners.indexOf(listener); - if (index > -1) { - errorStateListeners.splice(index, 1); - } -}; - -export const getHasConsoleErrors = (): boolean => { - return hasConsoleErrors; -}; - -export const clearConsoleMessages = () => { - consoleMessages.length = 0; - - // Reset error state - const hadErrors = hasConsoleErrors; - hasConsoleErrors = false; - - // Notify listeners if state changed - if (hadErrors) { - errorStateListeners.forEach(listener => { - try { - listener(false); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } -}; - export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; - // Filter and limit messages in one chain - const filteredMessages = getConsoleMessages() - .filter(msg => filter === 'all' || msg.level === filter) - .slice(limit && limit > 0 ? -limit : 0); + // Filter messages first + let filteredMessages = getConsoleMessages() + .filter(msg => filter === 'all' || msg.level === filter); + + // Apply limit if specified and positive + if (limit !== undefined && limit >= 0) { + if (limit === 0) { + filteredMessages = []; + } else { + filteredMessages = filteredMessages.slice(-limit); + } + } if (filteredMessages.length === 0) { return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`; From 111ab724e5c07818e02d81393bf2b8ba4ecf0b71 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:13:25 +0000 Subject: [PATCH 42/52] Remove and simplify some logic. --- src/components/ConsoleErrorProvider.test.tsx | 18 ++--- src/components/ConsoleErrorProvider.tsx | 70 +++++-------------- src/components/Shakespeare/PreviewPane.tsx | 8 +-- src/lib/consoleMessages.test.ts | 59 ++++++---------- src/lib/consoleMessages.ts | 63 +++++------------ src/lib/tools/ReadConsoleMessagesTool.test.ts | 18 ++--- src/lib/tools/ReadConsoleMessagesTool.ts | 22 ++---- 7 files changed, 78 insertions(+), 180 deletions(-) diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx index 44305d8d..3ef2b767 100644 --- a/src/components/ConsoleErrorProvider.test.tsx +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach } from 'vitest'; -import { renderHook, act, waitFor } from '@testing-library/react'; +import { renderHook, act } from '@testing-library/react'; import { ReactNode } from 'react'; import { ConsoleErrorProvider } from './ConsoleErrorProvider'; import { useConsoleError } from '@/hooks/useConsoleError'; @@ -61,7 +61,7 @@ describe('ConsoleErrorProvider', () => { expect(result.current.consoleError).toBeNull(); }); - it('should update consoleError with latest error message', async () => { + it('should update consoleError with latest error message', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); @@ -78,11 +78,7 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('error', 'Second error'); }); - // Wait for polling to detect the new error - await waitFor(() => { - expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); - }); - + expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); expect(result.current.consoleError?.logs).toHaveLength(2); }); @@ -130,7 +126,7 @@ describe('ConsoleErrorProvider', () => { expect(result.current.hasErrors).toBe(true); }); - it('should include all error messages in console error logs', async () => { + it('should include all error messages in console error logs', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); @@ -145,11 +141,7 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('error', 'Third error'); }); - // Wait for polling to detect all the new errors - await waitFor(() => { - expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); - }); - + expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); expect(result.current.consoleError?.logs).toHaveLength(3); expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([ 'First error', diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx index da0ad912..b033ed64 100644 --- a/src/components/ConsoleErrorProvider.tsx +++ b/src/components/ConsoleErrorProvider.tsx @@ -1,7 +1,7 @@ -import { useState, useEffect, useRef, useCallback, ReactNode } from 'react'; +import { useState, useEffect, useCallback, ReactNode } from 'react'; import { - addErrorStateListener, - removeErrorStateListener, + addConsoleMessageListener, + removeConsoleMessageListener, getHasConsoleErrors, getConsoleMessages, clearConsoleMessages, @@ -16,67 +16,29 @@ interface ConsoleErrorProviderProps { export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors()); const [consoleError, setConsoleError] = useState(null); - const lastErrorCountRef = useRef(0); - // Update console error with latest error information - const updateConsoleError = useCallback(() => { - const messages = getConsoleMessages(); - const errorMessages = messages.filter(msg => msg.level === 'error'); + const updateState = useCallback(() => { + const hasConsoleErrors = getHasConsoleErrors(); + setHasErrors(hasConsoleErrors); - if (errorMessages.length > 0) { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${errorMessages[errorMessages.length - 1].message}`, + if (hasConsoleErrors) { + const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error'); + const latestError = errorMessages[errorMessages.length - 1]; + setConsoleError(new ProjectPreviewConsoleError( + `Console error detected: ${latestError.message}`, errorMessages - ); - setConsoleError(error); - lastErrorCountRef.current = errorMessages.length; + )); } else { setConsoleError(null); - lastErrorCountRef.current = 0; } }, []); - // Handle error state changes from the global console system useEffect(() => { - const handleErrorStateChange = (hasErrors: boolean) => { - setHasErrors(hasErrors); + addConsoleMessageListener(updateState); + updateState(); // Initial sync - if (hasErrors) { - // Always update when we get an error state change - updateConsoleError(); - } else { - // Clear console error when state resets - setConsoleError(null); - lastErrorCountRef.current = 0; - } - }; - - // Check for new errors periodically when we have errors - const checkForNewErrors = () => { - const messages = getConsoleMessages(); - const errorMessages = messages.filter(msg => msg.level === 'error'); - - if (errorMessages.length > lastErrorCountRef.current) { - // New errors detected - update the console error - updateConsoleError(); - } - }; - - // Listen for error state changes - addErrorStateListener(handleErrorStateChange); - - // Initial sync - setHasErrors(getHasConsoleErrors()); - updateConsoleError(); - - // Poll for new errors (handles multiple errors being added) - const interval = setInterval(checkForNewErrors, 100); - - return () => { - removeErrorStateListener(handleErrorStateChange); - clearInterval(interval); - }; - }, [updateConsoleError]); + return () => removeConsoleMessageListener(updateState); + }, [updateState]); const clearErrors = useCallback(() => { clearConsoleMessages(); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 3d48cb77..3b23828e 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -518,14 +518,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const ConsoleDropdown = () => { const [isOpen, setIsOpen] = useState(false); const [copiedMessageIndex, setCopiedMessageIndex] = useState(null); - const [messages, setMessages] = useState([]); - // Only fetch messages when dropdown opens - useEffect(() => { - if (isOpen) { - setMessages(getConsoleMessages()); - } - }, [isOpen]); + const messages = isOpen ? getConsoleMessages() : []; const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => { try { diff --git a/src/lib/consoleMessages.test.ts b/src/lib/consoleMessages.test.ts index 31a895ba..7b402c0d 100644 --- a/src/lib/consoleMessages.test.ts +++ b/src/lib/consoleMessages.test.ts @@ -4,8 +4,8 @@ import { clearConsoleMessages, getConsoleMessages, getHasConsoleErrors, - addErrorStateListener, - removeErrorStateListener, + addConsoleMessageListener, + removeConsoleMessageListener, ProjectPreviewConsoleError } from './consoleMessages'; @@ -35,28 +35,27 @@ describe('Console Messages System', () => { expect(getHasConsoleErrors()).toBe(true); }); - it('should only trigger error state once for multiple errors', () => { + it('should notify listeners when messages are added', () => { const listener = vi.fn(); - addErrorStateListener(listener); + addConsoleMessageListener(listener); addConsoleMessage('error', 'First error'); expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith(true); addConsoleMessage('error', 'Second error'); - expect(listener).toHaveBeenCalledTimes(1); // Should not be called again + expect(listener).toHaveBeenCalledTimes(2); - removeErrorStateListener(listener); + removeConsoleMessageListener(listener); }); }); describe('getConsoleMessages', () => { it('should return a copy of messages array', () => { addConsoleMessage('info', 'Test message'); - + const messages1 = getConsoleMessages(); const messages2 = getConsoleMessages(); - + expect(messages1).toEqual(messages2); expect(messages1).not.toBe(messages2); // Different array instances }); @@ -81,52 +80,40 @@ describe('Console Messages System', () => { expect(getHasConsoleErrors()).toBe(false); }); - it('should notify listeners when error state changes', () => { + it('should notify listeners when messages are cleared', () => { const listener = vi.fn(); - addErrorStateListener(listener); + addConsoleMessageListener(listener); addConsoleMessage('error', 'Error message'); - expect(listener).toHaveBeenCalledWith(true); + expect(listener).toHaveBeenCalledTimes(1); clearConsoleMessages(); - expect(listener).toHaveBeenCalledWith(false); expect(listener).toHaveBeenCalledTimes(2); - removeErrorStateListener(listener); - }); - - it('should not notify listeners if no error state change', () => { - const listener = vi.fn(); - addErrorStateListener(listener); - - // No errors added, so clearing should not trigger listener - clearConsoleMessages(); - expect(listener).not.toHaveBeenCalled(); - - removeErrorStateListener(listener); + removeConsoleMessageListener(listener); }); }); - describe('Error State Listeners', () => { + describe('Message Listeners', () => { it('should add and remove listeners correctly', () => { const listener1 = vi.fn(); const listener2 = vi.fn(); - addErrorStateListener(listener1); - addErrorStateListener(listener2); + addConsoleMessageListener(listener1); + addConsoleMessageListener(listener2); addConsoleMessage('error', 'Test error'); - expect(listener1).toHaveBeenCalledWith(true); - expect(listener2).toHaveBeenCalledWith(true); + expect(listener1).toHaveBeenCalledTimes(1); + expect(listener2).toHaveBeenCalledTimes(1); - removeErrorStateListener(listener1); + removeConsoleMessageListener(listener1); clearConsoleMessages(); expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear) expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear - removeErrorStateListener(listener2); + removeConsoleMessageListener(listener2); }); it('should handle listener errors gracefully', () => { @@ -135,8 +122,8 @@ describe('Console Messages System', () => { }); const workingListener = vi.fn(); - addErrorStateListener(faultyListener); - addErrorStateListener(workingListener); + addConsoleMessageListener(faultyListener); + addConsoleMessageListener(workingListener); // Should not throw despite faulty listener expect(() => { @@ -146,8 +133,8 @@ describe('Console Messages System', () => { expect(faultyListener).toHaveBeenCalled(); expect(workingListener).toHaveBeenCalled(); - removeErrorStateListener(faultyListener); - removeErrorStateListener(workingListener); + removeConsoleMessageListener(faultyListener); + removeConsoleMessageListener(workingListener); }); }); diff --git a/src/lib/consoleMessages.ts b/src/lib/consoleMessages.ts index f22f7a61..a707e463 100644 --- a/src/lib/consoleMessages.ts +++ b/src/lib/consoleMessages.ts @@ -23,47 +23,36 @@ export class ProjectPreviewConsoleError extends Error { // Global console messages storage const consoleMessages: ConsoleMessage[] = []; +const listeners: Array<() => void> = []; -// Boolean-based error detection system -let hasConsoleErrors = false; -const errorStateListeners: Array<(hasErrors: boolean) => void> = []; +const notifyListeners = () => { + listeners.forEach(listener => { + try { + listener(); + } catch (err) { + console.warn('Console message listener failed:', err); + } + }); +}; export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // Only update boolean state on first error - if (level === 'error' && !hasConsoleErrors) { - hasConsoleErrors = true; - - // Notify boolean state listeners - errorStateListeners.forEach(listener => { - try { - listener(true); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } + consoleMessages.push({ level, message }); + notifyListeners(); }; -export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { - errorStateListeners.push(listener); +export const addConsoleMessageListener = (listener: () => void) => { + listeners.push(listener); }; -export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { - const index = errorStateListeners.indexOf(listener); +export const removeConsoleMessageListener = (listener: () => void) => { + const index = listeners.indexOf(listener); if (index > -1) { - errorStateListeners.splice(index, 1); + listeners.splice(index, 1); } }; export const getHasConsoleErrors = (): boolean => { - return hasConsoleErrors; + return consoleMessages.some(msg => msg.level === 'error'); }; export const getConsoleMessages = (): ConsoleMessage[] => { @@ -72,19 +61,5 @@ export const getConsoleMessages = (): ConsoleMessage[] => { export const clearConsoleMessages = () => { consoleMessages.length = 0; - - // Reset error state - const hadErrors = hasConsoleErrors; - hasConsoleErrors = false; - - // Notify listeners if state changed - if (hadErrors) { - errorStateListeners.forEach(listener => { - try { - listener(false); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } + notifyListeners(); }; \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 256570c7..bf2de6c6 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -85,19 +85,15 @@ describe('ReadConsoleMessagesTool', () => { expect(result).toContain('[ERROR] Test error with special chars: <>&"'); }); - it('should handle limit edge cases', async () => { + it('should handle limit correctly', async () => { const tool = new ReadConsoleMessagesTool(); - // Limit of 0 should return no messages - const zeroResult = await tool.execute({ limit: 0 }); - expect(zeroResult).toBe('No console messages found.'); + // Limit should return only the most recent messages + const limitedResult = await tool.execute({ limit: 2 }); + expect(limitedResult).toContain('Found 2 console messages'); - // Negative limit should return all messages - const negativeResult = await tool.execute({ limit: -1 }); - expect(negativeResult).toContain('Found 4 console messages'); - - // Limit larger than available should return all - const largeResult = await tool.execute({ limit: 100 }); - expect(largeResult).toContain('Found 4 console messages'); + // No limit should return all messages + const allResult = await tool.execute({}); + expect(allResult).toContain('Found 4 console messages'); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index 52853686..1f8e5904 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -14,31 +14,23 @@ export class ReadConsoleMessagesTool implements Tool async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; - // Filter messages first - let filteredMessages = getConsoleMessages() + let messages = getConsoleMessages() .filter(msg => filter === 'all' || msg.level === filter); - // Apply limit if specified and positive - if (limit !== undefined && limit >= 0) { - if (limit === 0) { - filteredMessages = []; - } else { - filteredMessages = filteredMessages.slice(-limit); - } + if (limit && limit > 0) { + messages = messages.slice(-limit); } - if (filteredMessages.length === 0) { + if (messages.length === 0) { return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`; } - const formattedMessages = filteredMessages + const formatted = messages .map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`) .join('\n'); - const plural = filteredMessages.length !== 1 ? 's' : ''; - const levelInfo = filter !== 'all' ? ` (level: ${filter})` : ''; - - return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`; + const suffix = filter !== 'all' ? ` (level: ${filter})` : ''; + return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`; } description = 'Read console messages from the project preview. Can filter by level and limit results.'; From c72170f19cdb7daf35f0628d6abb54f06065f9b1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 15:05:09 -0500 Subject: [PATCH 43/52] Build by actually mimicking Vite's handling of index.html --- src/lib/build/fsPlugin.ts | 16 ++++- src/lib/build/index.ts | 96 +++++++++++++++++++----------- src/lib/build/shakespearePlugin.ts | 20 +++++++ 3 files changed, 96 insertions(+), 36 deletions(-) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index cb53dd4e..1352e274 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -16,9 +16,15 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { }); build.onResolve({ filter: /.*/ }, async (args) => { - let resolved: string; + // Skip resolving paths from external URLs + if (/^https?:\/\//.test(args.importer)) { + return; + } - if (args.path.startsWith("@/")) { + let resolved: string; + if (args.path.startsWith("/")) { + resolved = args.path; + } else if (args.path.startsWith("@/")) { resolved = join(cwd, args.path.slice(2)); } else if (args.kind === "entry-point") { resolved = join(cwd, args.path); @@ -28,6 +34,12 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { return; } + // Security: prevent accessing files outside the project directory + const projectDir = join(cwd, ".."); + if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) { + throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); + } + // Vite query parameters https://vite.dev/guide/assets const [cleaned, query] = resolved.split("?"); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 6817bcb2..9d6a0d1a 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,3 +1,4 @@ +import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; @@ -32,25 +33,47 @@ async function bundle( ); const doc = domParser.parseFromString(indexHtmlText, "text/html"); + const entryPoints: string[] = []; + const entryScripts: Record = {}; + + // Find all module scripts with relative paths in index.html + for (const script of doc.scripts) { + const scriptSrc = script.getAttribute("src"); + + if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) { + const path = join(projectPath, scriptSrc); + + // Files in the public directory take precedence over source files + if (scriptSrc.startsWith("/")) { + if (await fileExists(fs, join(projectPath, "public", scriptSrc))) { + continue; + } + } + + entryPoints.push(path); + entryScripts[path] = script; + } + } + + // Enable Tailwind CSS if a config file is present + for (const path of ["tailwind.config.ts", "tailwind.config.js"]) { + if (await fileExists(fs, join(projectPath, path))) { + entryPoints.push(`shakespeare:${path}`); + break; + } + } const results = await esbuild.build({ - stdin: { - contents: ` - import "@/main.tsx"; - import tailwindConfig from "@/../tailwind.config.ts"; - import "https://esm.sh/tailwindcss-cdn@3"; - tailwind.config = tailwindConfig; - `, - loader: "tsx", - }, + entryPoints, bundle: true, write: false, format: "esm", target, outdir: "/", jsx: "automatic", + metafile: true, plugins: [ - shakespearePlugin(), // Takes precedence over esmPlugin + shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], @@ -62,18 +85,32 @@ async function bundle( const dist: Record = {}; for (const file of results.outputFiles) { - const relativePath = file.path.replace(/^\//, ""); - if (relativePath === "stdin.js") { - dist["main.js"] = file.contents; - } else if (relativePath === "stdin.css") { - dist["main.css"] = file.contents; - } else { - dist[relativePath] = file.contents; + const ext = file.path.split('.').pop(); + const filename = `${file.path.split('/').pop()?.split('.')?.[0] || "chunk"}-${file.hash}.${ext}`; + const entryPoint = results.metafile.outputs[file.path.slice(1)]?.entryPoint?.replace(/^fs:/, ''); + const script = entryPoint ? entryScripts[entryPoint] : null; + + if (script) { + script.setAttribute("src", "/" + filename); + dist[filename] = file.contents; + } else if (ext === "js") { + const script = document.createElement("script"); + script.type = "module"; + script.src = "/" + filename; + doc.head.appendChild(script); + dist[filename] = file.contents; + } else if (ext === "css") { + // Embed stylesheets as Tailwind CSS styles + const style = doc.createElement("style"); + style.setAttribute("type", "text/tailwindcss"); + style.textContent = file.text; + doc.head.appendChild(style); } } - // Update index.html with proper script and link tags - updateIndexHtml(doc, dist); + // HACK: Remove existing CSP header for now. + // TODO: Parse CSP and ensure esm.sh is allowed. + doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove(); const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -156,20 +193,11 @@ export async function buildProject(options: BuildProjectOptions): Promise<{ }; } -function updateIndexHtml(doc: Document, dist: Record): void { - const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); - - if (!entrypoint) { - throw new Error("No entrypoint script found in index.html"); - } - - entrypoint.setAttribute("src", "/main.js"); - - const css = dist["main.css"]; - if (css) { - const style = doc.createElement("style"); - style.setAttribute("type", "text/tailwindcss"); - style.textContent = new TextDecoder().decode(css); - doc.head.appendChild(style); +async function fileExists(fs: JSRuntimeFS, path: string): Promise { + try { + const stat = await fs.stat(path); + return stat.isFile(); + } catch { + return false; } } \ No newline at end of file diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts index c315be66..ec272afc 100644 --- a/src/lib/build/shakespearePlugin.ts +++ b/src/lib/build/shakespearePlugin.ts @@ -10,6 +10,26 @@ export function shakespearePlugin(): Plugin { name: "shakespeare", setup(build) { + // Handle Tailwind CSS configuration files + build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-tailwind", + }; + }); + + build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => { + const { pathname } = new URL(args.path); + return { + contents: ` + import tailwindConfig from "@/../${pathname}"; + import "https://esm.sh/tailwindcss-cdn@3"; + tailwind.config = tailwindConfig; + `, + loader: "js", + }; + }); + // Handle "sonner" imports with a dummy API build.onResolve({ filter: /^sonner$/ }, (args) => { return { From 51ce9c61efd1dd9b575c26f607a80a7379c6d03e Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:30:02 +0000 Subject: [PATCH 44/52] Remove spurrious migration comment. --- src/pages/ProjectView.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index a2b23c9e..212191f8 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -82,8 +82,6 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); - // Console error handling is now managed by useQuillyConsoleErrors hook - const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { From 225c90f5564a3c9ae3de0264ad038237c0d55811 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 15:42:15 -0500 Subject: [PATCH 45/52] Surgically add esm.sh to existing CSP of index.html --- src/lib/build/index.test.ts | 64 ++++++++++++---- src/lib/build/index.ts | 27 ++++++- src/lib/csp.test.ts | 145 ++++++++++++++++++++++++++++++++++++ src/lib/csp.ts | 87 ++++++++++++++++++++++ 4 files changed, 306 insertions(+), 17 deletions(-) create mode 100644 src/lib/csp.test.ts create mode 100644 src/lib/csp.ts diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index 8934a324..fe2d7ef0 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -11,12 +11,26 @@ vi.mock('../esbuild', () => ({ { path: '/stdin.js', contents: new Uint8Array([1, 2, 3]), + text: '', + hash: 'abc123', }, { path: '/stdin.css', contents: new Uint8Array([4, 5, 6]), + text: 'body { margin: 0; }', + hash: 'def456', }, ], + metafile: { + outputs: { + 'stdin.js': { + entryPoint: 'fs:/test/project/src/main.tsx', + }, + 'stdin.css': { + entryPoint: undefined, + }, + }, + }, })), })), })); @@ -52,9 +66,25 @@ describe('buildProject', () => { documentElement: { outerHTML: '', }, - querySelector: vi.fn(() => ({ - setAttribute: vi.fn(), - })), + querySelector: vi.fn((selector: string) => { + if (selector === 'meta[http-equiv="content-security-policy"]') { + // Return null for CSP meta tag (no CSP present in test) + return null; + } + return { + setAttribute: vi.fn(), + getAttribute: vi.fn(), + }; + }), + scripts: [ + { + getAttribute: vi.fn((attr: string) => { + if (attr === 'src') return '/src/main.tsx'; + return null; + }), + type: 'module', + }, + ], head: { appendChild: vi.fn(), }, @@ -133,11 +163,13 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + // Public files should be copied to filesystem, not included in files object // Verify copyFiles was called for public directory expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public'); @@ -190,11 +222,13 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should still include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should still include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + // Should not include any public files in bundle expect(Object.keys(result.files)).not.toContain('favicon.ico'); @@ -246,13 +280,15 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); - // Should have exactly 3 files (main.js, main.css, index.html) - expect(Object.keys(result.files)).toHaveLength(3); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + + // Should have exactly 2 files (stdin-abc123.js, index.html) + expect(Object.keys(result.files)).toHaveLength(2); // Should try to copy public files but directory is empty expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 9d6a0d1a..8dd0bb96 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,6 +1,7 @@ import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; +import { addDomainToCSP } from "@/lib/csp"; import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; @@ -108,9 +109,15 @@ async function bundle( } } - // HACK: Remove existing CSP header for now. - // TODO: Parse CSP and ensure esm.sh is allowed. - doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove(); + // Parse CSP and ensure esm.sh is allowed for necessary directives + const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]"); + if (cspMeta) { + const cspContent = cspMeta.getAttribute("content"); + if (cspContent) { + const updatedCSP = updateCSPForEsmSh(cspContent); + cspMeta.setAttribute("content", updatedCSP); + } + } const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -200,4 +207,18 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise { } catch { return false; } +} + +/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */ +export function updateCSPForEsmSh(csp: string): string { + const esmShDirectives = [ + 'script-src', // For JavaScript modules + 'img-src', // For images + 'media-src', // For video/audio + 'font-src', // For fonts + 'style-src', // For CSS + 'connect-src' // For fetch/XHR requests to esm.sh + ]; + + return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives); } \ No newline at end of file diff --git a/src/lib/csp.test.ts b/src/lib/csp.test.ts new file mode 100644 index 00000000..8702eba2 --- /dev/null +++ b/src/lib/csp.test.ts @@ -0,0 +1,145 @@ +import { describe, it, expect } from 'vitest'; +import { + parseCSP, + stringifyCSP, + addSourceToDirective, + addDomainToCSP, + type CSPDirectives +} from './csp'; + +describe('parseCSP', () => { + it('should parse basic CSP with multiple directives', () => { + const csp = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *"; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'default-src': ["'self'"], + 'script-src': ["'self'", "'unsafe-inline'"], + 'img-src': ['*'] + }); + }); + + it('should handle directives without sources', () => { + const csp = "upgrade-insecure-requests; block-all-mixed-content"; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'upgrade-insecure-requests': [], + 'block-all-mixed-content': [] + }); + }); + + it('should handle empty or whitespace-only CSP', () => { + expect(parseCSP('')).toEqual({}); + expect(parseCSP(' ')).toEqual({}); + expect(parseCSP(';;;')).toEqual({}); + }); + + it('should handle extra whitespace and semicolons', () => { + const csp = " default-src 'self' ; script-src 'self' ; "; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'default-src': ["'self'"], + 'script-src': ["'self'"] + }); + }); +}); + +describe('stringifyCSP', () => { + it('should convert directives back to CSP string', () => { + const directives: CSPDirectives = { + 'default-src': ["'self'"], + 'script-src': ["'self'", "'unsafe-inline'"], + 'img-src': ['*'] + }; + + const result = stringifyCSP(directives); + expect(result).toBe("default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *"); + }); + + it('should handle directives without sources', () => { + const directives: CSPDirectives = { + 'upgrade-insecure-requests': [], + 'default-src': ["'self'"] + }; + + const result = stringifyCSP(directives); + expect(result).toBe("upgrade-insecure-requests; default-src 'self'"); + }); + + it('should handle empty directives object', () => { + expect(stringifyCSP({})).toBe(''); + }); +}); + +describe('addSourceToDirective', () => { + it('should add new source to existing sources', () => { + const sources = ["'self'", "'unsafe-inline'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", "'unsafe-inline'", 'https://example.com']); + }); + + it('should not duplicate existing sources', () => { + const sources = ["'self'", 'https://example.com']; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", 'https://example.com']); + }); + + it('should replace none with new source', () => { + const sources = ["'none'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(['https://example.com']); + }); + + it('should replace none even with other sources present', () => { + const sources = ["'self'", "'none'", "'unsafe-inline'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", 'https://example.com', "'unsafe-inline'"]); + }); + + it('should handle empty sources array', () => { + const sources: string[] = []; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(['https://example.com']); + }); +}); + +describe('addDomainToCSP', () => { + it('should add domain to specified directives', () => { + const csp = "default-src 'self'; script-src 'self'; img-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']); + + expect(result).toContain('script-src \'self\' https://cdn.example.com'); + expect(result).toContain('img-src \'self\' https://cdn.example.com'); + expect(result).toContain('default-src \'self\''); // unchanged + }); + + it('should not modify directives that do not exist', () => { + const csp = "default-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']); + + expect(result).toBe("default-src 'self'"); + }); + + it('should handle multiple domains being added', () => { + const csp = "script-src 'self'"; + let result = addDomainToCSP(csp, 'https://cdn1.example.com', ['script-src']); + result = addDomainToCSP(result, 'https://cdn2.example.com', ['script-src']); + + expect(result).toBe("script-src 'self' https://cdn1.example.com https://cdn2.example.com"); + }); + + it('should replace none in specified directives', () => { + const csp = "default-src 'self'; script-src 'none'; img-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src']); + + expect(result).toContain('script-src https://cdn.example.com'); + expect(result).toContain('img-src \'self\''); // unchanged + }); +}); \ No newline at end of file diff --git a/src/lib/csp.ts b/src/lib/csp.ts new file mode 100644 index 00000000..bd42baed --- /dev/null +++ b/src/lib/csp.ts @@ -0,0 +1,87 @@ +/** + * Content Security Policy (CSP) utilities for managing and updating CSP directives + */ + +export interface CSPDirectives { + [directive: string]: string[]; +} + +/** + * Parses a CSP string into a structured format + */ +export function parseCSP(csp: string): CSPDirectives { + const directives: CSPDirectives = {}; + + // Split by semicolon and parse each directive + csp.split(';').forEach(directive => { + const trimmed = directive.trim(); + if (!trimmed) return; + + const parts = trimmed.split(/\s+/); + const directiveName = parts[0]; + const sources = parts.slice(1); + + directives[directiveName] = sources; + }); + + return directives; +} + +/** + * Converts CSP directives back to a string format + */ +export function stringifyCSP(directives: CSPDirectives): string { + const directiveStrings: string[] = []; + + Object.entries(directives).forEach(([directiveName, sources]) => { + if (sources.length > 0) { + directiveStrings.push(`${directiveName} ${sources.join(' ')}`); + } else { + directiveStrings.push(directiveName); + } + }); + + return directiveStrings.join('; '); +} + +/** + * Adds a source to a CSP directive, handling special cases + */ +export function addSourceToDirective(sources: string[], newSource: string): string[] { + // Don't add if already present + if (sources.includes(newSource)) { + return sources; + } + + // If 'none' is present, replace it with the new source + if (sources.includes("'none'")) { + const noneIndex = sources.indexOf("'none'"); + const newSources = [...sources]; + newSources[noneIndex] = newSource; + return newSources; + } + + // Add to existing sources + return [...sources, newSource]; +} + +/** + * Updates CSP directives to allow a specific domain for multiple directive types + */ +export function addDomainToCSP( + csp: string, + domain: string, + directiveTypes: string[] +): string { + const directives = parseCSP(csp); + + // Add domain to each relevant directive if it exists + directiveTypes.forEach(directiveName => { + const sources = directives[directiveName]; + if (sources) { + directives[directiveName] = addSourceToDirective(sources, domain); + } + }); + + return stringifyCSP(directives); +} From 97f5481ec7e5256215bbe583fceb66965d469c31 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:58:56 +0000 Subject: [PATCH 46/52] Only clear console messages when project actually changes. --- src/components/Shakespeare/PreviewPane.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 3b23828e..3d93a3e1 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -457,6 +457,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o }, [selectedFile, loadFileContent]); // Reset selected file and navigation history when projectId changes + const prevProjectIdRef = useRef(); useEffect(() => { setSelectedFile(null); setFileContent(''); @@ -468,8 +469,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o setNavigationHistory(['/']); setHistoryIndex(0); - // Clear console messages for new project - clearErrors(); + // Only clear console messages when projectId actually changes (not on initial mount) + if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) { + clearErrors(); + } + prevProjectIdRef.current = projectId; }, [projectId, clearErrors]); useEffect(() => { From 0b7f9cd2cbe60f07a75cc2bec1f0f33a3d158c4a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 16:24:03 -0500 Subject: [PATCH 47/52] Update browserlist --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2d331915..e2fec05c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4668,9 +4668,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001716", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz", - "integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==", + "version": "1.0.30001746", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz", + "integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==", "dev": true, "funding": [ { From cbf85313af09d186f1459bd297dc8efbfa04e6f8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:30:12 -0500 Subject: [PATCH 48/52] Enable sourcemap, fix output filenames --- src/lib/build/index.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 8dd0bb96..a424c05b 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -73,6 +73,10 @@ async function bundle( outdir: "/", jsx: "automatic", metafile: true, + sourcemap: true, + entryNames: "[name]-[hash]", + chunkNames: "[name]-[hash]", + assetNames: "[name]-[hash]", plugins: [ shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), @@ -87,8 +91,8 @@ async function bundle( for (const file of results.outputFiles) { const ext = file.path.split('.').pop(); - const filename = `${file.path.split('/').pop()?.split('.')?.[0] || "chunk"}-${file.hash}.${ext}`; - const entryPoint = results.metafile.outputs[file.path.slice(1)]?.entryPoint?.replace(/^fs:/, ''); + const filename = `${file.path.slice(1)}`; + const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, ''); const script = entryPoint ? entryScripts[entryPoint] : null; if (script) { @@ -106,6 +110,8 @@ async function bundle( style.setAttribute("type", "text/tailwindcss"); style.textContent = file.text; doc.head.appendChild(style); + } else { + dist[filename] = file.contents; } } From d4c775828f45eea31b1b6827253c3f12d3567dee Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:36:42 -0500 Subject: [PATCH 49/52] Fix build tests --- src/lib/build/index.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index fe2d7ef0..b8f52ac9 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -9,13 +9,13 @@ vi.mock('../esbuild', () => ({ build: vi.fn(() => ({ outputFiles: [ { - path: '/stdin.js', + path: '/stdin-abc123.js', contents: new Uint8Array([1, 2, 3]), text: '', hash: 'abc123', }, { - path: '/stdin.css', + path: '/stdin-def456.css', contents: new Uint8Array([4, 5, 6]), text: 'body { margin: 0; }', hash: 'def456', @@ -23,10 +23,10 @@ vi.mock('../esbuild', () => ({ ], metafile: { outputs: { - 'stdin.js': { + 'stdin-abc123.js': { entryPoint: 'fs:/test/project/src/main.tsx', }, - 'stdin.css': { + 'stdin-def456.css': { entryPoint: undefined, }, }, From aaf30db257005b54922cb7c107198012330a6724 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:46:08 -0500 Subject: [PATCH 50/52] Add DeepSeek as a preset provider Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/58 --- src/lib/aiProviderPresets.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lib/aiProviderPresets.ts b/src/lib/aiProviderPresets.ts index 108a2fc9..55cf204e 100644 --- a/src/lib/aiProviderPresets.ts +++ b/src/lib/aiProviderPresets.ts @@ -64,6 +64,13 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [ apiKeysURL: "https://console.x.ai", tosURL: "https://x.ai/legal", }, + { + id: "deepseek", + name: "Deepseek", + baseURL: "https://api.deepseek.com/v1", + apiKeysURL: "https://platform.deepseek.com/api_keys", + tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html", + }, ]; // Helper function to get a specific preset by ID From 5f2faaad61920e79a448bd971cda5d29f6a44edc Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:57:36 -0500 Subject: [PATCH 51/52] Fix xAI tool definitions Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/57 --- src/lib/tools/openai-adapter.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/lib/tools/openai-adapter.ts b/src/lib/tools/openai-adapter.ts index 3ae99d7c..e10d2a41 100644 --- a/src/lib/tools/openai-adapter.ts +++ b/src/lib/tools/openai-adapter.ts @@ -16,6 +16,8 @@ export function toolToOpenAI(name: string, tool: Tool): OpenAI if (tool.inputSchema) { functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema); + } else { + functionDef.parameters = {}; } return { From 388afd0b1675226ce954d44f25d109962ed0441b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:59:29 -0500 Subject: [PATCH 52/52] Enable sourcemap in Shakespeare itself --- vite.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vite.config.ts b/vite.config.ts index 7eb55ca5..b8a44cc8 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -13,6 +13,7 @@ export default defineConfig(() => ({ react(), ], build: { + sourcemap: true, rollupOptions: { output: { manualChunks(id) {