From 931733ba16e4f3940c07202c7f8708ac705a1365 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 1 Oct 2025 16:35:19 -0500 Subject: [PATCH 01/18] Add warning to model selector if a free model is chosen --- src/components/ModelSelector.test.tsx | 235 +++++++++++++++++++++++++- src/components/ModelSelector.tsx | 169 +++++++++++++----- 2 files changed, 360 insertions(+), 44 deletions(-) diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index b5c7102b..56d15fb9 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -1,5 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { Decimal } from 'decimal.js'; import { TestApp } from '@/test/TestApp'; import { ModelSelector } from './ModelSelector'; @@ -12,6 +14,10 @@ vi.mock('@/hooks/useProviderModels', () => ({ useProviderModels: vi.fn(), })); +vi.mock('@/hooks/useIsMobile', () => ({ + useIsMobile: vi.fn(), +})); + vi.mock('react-router-dom', async (importOriginal) => { const actual = await importOriginal() as Record; return { @@ -22,9 +28,11 @@ vi.mock('react-router-dom', async (importOriginal) => { import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; +import { useIsMobile } from '@/hooks/useIsMobile'; const mockUseAISettings = vi.mocked(useAISettings); const mockUseProviderModels = vi.mocked(useProviderModels); +const mockUseIsMobile = vi.mocked(useIsMobile); describe('ModelSelector', () => { const mockOnChange = vi.fn(); @@ -41,7 +49,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); mockUseProviderModels.mockReturnValue({ @@ -50,6 +58,8 @@ describe('ModelSelector', () => { error: null, refetch: vi.fn(), }); + + mockUseIsMobile.mockReturnValue(false); }); it('hides recently used section when less than 5 models and all recently used are available', async () => { @@ -77,7 +87,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -124,7 +134,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -173,7 +183,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -216,7 +226,7 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + }); render( @@ -237,4 +247,219 @@ describe('ModelSelector', () => { // Recently used section should NOT be visible expect(screen.queryByText('Recently Used')).not.toBeInTheDocument(); }); + + it('shows caution icon for free models', async () => { + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + const paidModel = { + fullId: 'provider1/paid-model', + provider: 'provider1', + id: 'paid-model', + pricing: { + prompt: new Decimal('0.01'), + completion: new Decimal('0.02'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel, paidModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + // Test with free model selected + const { rerender } = render( + + + + ); + + // Should show caution icon for free model + expect(screen.getByTestId('triangle-alert')).toBeInTheDocument(); + + // Test with paid model selected + rerender( + + + + ); + + // Should not show caution icon for paid model + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('does not show caution icon when no model is selected', () => { + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + // Should not show caution icon when no model is selected + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('does not show caution icon for models without pricing information', () => { + const modelWithoutPricing = { + fullId: 'provider1/unknown-pricing', + provider: 'provider1', + id: 'unknown-pricing', + // No pricing property + }; + + mockUseProviderModels.mockReturnValue({ + models: [modelWithoutPricing], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + // Should not show caution icon for models without pricing info + expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument(); + }); + + it('shows tooltip when hovering over caution icon', async () => { + const user = userEvent.setup(); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionIcon = screen.getByTestId('triangle-alert'); + expect(cautionIcon).toBeInTheDocument(); + + // Hover over the caution icon + await user.hover(cautionIcon); + + // 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); + }); + }); + + it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => { + const user = userEvent.setup(); + mockUseIsMobile.mockReturnValue(true); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionButton = screen.getByRole('button', { name: 'Free model warning' }); + expect(cautionButton).toBeInTheDocument(); + expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile + + // Click to open tooltip - just verify the click works without errors + await user.click(cautionButton); + + // 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); + }); + + // The button should still be clickable (no errors) + await user.click(cautionButton); + expect(cautionButton).toBeInTheDocument(); + }); + + it('makes caution icon not focusable on desktop', () => { + mockUseIsMobile.mockReturnValue(false); + + const freeModel = { + fullId: 'provider1/free-model', + provider: 'provider1', + id: 'free-model', + pricing: { + prompt: new Decimal('0'), + completion: new Decimal('0'), + }, + }; + + mockUseProviderModels.mockReturnValue({ + models: [freeModel], + isLoading: false, + error: null, + refetch: vi.fn(), + }); + + render( + + + + ); + + const cautionButton = screen.getByRole('button', { name: 'Free model warning' }); + expect(cautionButton).toBeInTheDocument(); + expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop + }); }); \ No newline at end of file diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 767f510c..76257bba 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -1,14 +1,16 @@ -import { useState, useMemo } from 'react'; +import { useState, useMemo, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; +import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'; import { Skeleton } from '@/components/ui/skeleton'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; +import { useIsMobile } from '@/hooks/useIsMobile'; import { cn } from '@/lib/utils'; interface ModelSelectorProps { @@ -32,6 +34,7 @@ export function ModelSelector({ }: ModelSelectorProps) { const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); + const [isTooltipOpen, setIsTooltipOpen] = useState(false); // Use controlled state if provided, otherwise use local state const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; @@ -42,6 +45,7 @@ export function ModelSelector({ const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); const { models, isLoading, error, refetch } = useProviderModels(); const navigate = useNavigate(); + const isMobile = useIsMobile(); const defaultPlaceholder = t('selectOrEnterModel'); @@ -82,9 +86,43 @@ export function ModelSelector({ return !allRecentlyUsedAreAvailable; }, [recentlyUsedModels, models]); + // Check if the current model is free + const isCurrentModelFree = useMemo(() => { + if (!value) return false; + + const currentModel = models.find(model => model.fullId === value); + if (!currentModel?.pricing) return false; + + return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0); + }, [value, models]); + // Don't auto-initialize with recently used models // Let the parent component handle initialization + // Close tooltip when clicking outside on mobile + useEffect(() => { + if (!isMobile || !isTooltipOpen) return; + + const handleClickOutside = (event: MouseEvent | TouchEvent) => { + const target = event.target as Element; + // Check if the click is outside the tooltip and trigger + if (!target.closest('[data-radix-tooltip-content]') && + !target.closest('[data-radix-tooltip-trigger]') && + !target.closest('[data-testid="triangle-alert"]')) { + setIsTooltipOpen(false); + } + }; + + // Add both click and touch event listeners + document.addEventListener('click', handleClickOutside, true); + document.addEventListener('touchstart', handleClickOutside, true); + + return () => { + document.removeEventListener('click', handleClickOutside, true); + document.removeEventListener('touchstart', handleClickOutside, true); + }; + }, [isMobile, isTooltipOpen]); + const handleSelect = (selectedValue: string) => { if (selectedValue === '__custom__') { setIsCustomInput(true); @@ -125,47 +163,98 @@ export function ModelSelector({ if (isCustomInput) { return ( -
- setCustomValue(e.target.value)} - onKeyDown={handleCustomKeyDown} - onBlur={handleCustomSubmit} - placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" - className="h-8 text-xs" - autoFocus - /> - -
+ +
+ 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 02/18] 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 03/18] 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 04/18] 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 06/18] 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 07/18] 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 08/18] 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 09/18] 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 10/18] 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 11/18] 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 12/18] 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 13/18] 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 14/18] 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 15/18] 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 16/18] 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 17/18] 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 18/18] 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) {