diff --git a/package-lock.json b/package-lock.json index 9abe5dc9..1a1d3b9c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5100,9 +5100,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": [ { diff --git a/src/App.tsx b/src/App.tsx index 45c68be2..45b189bf 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,6 +16,7 @@ import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { SessionManagerProvider } from '@/components/SessionManagerProvider'; import { FSProvider } from '@/components/FSProvider'; +import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; @@ -73,22 +74,24 @@ export function App() { - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx new file mode 100644 index 00000000..3ef2b767 --- /dev/null +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -0,0 +1,152 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { ReactNode } from 'react'; +import { ConsoleErrorProvider } from './ConsoleErrorProvider'; +import { useConsoleError } from '@/hooks/useConsoleError'; +import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages'; + +// Wrapper component for testing +function TestWrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +describe('ConsoleErrorProvider', () => { + beforeEach(() => { + clearConsoleMessages(); + }); + + it('should provide initial state with no errors', () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + expect(result.current.hasErrors).toBe(false); + expect(result.current.consoleError).toBeNull(); + }); + + it('should update hasErrors when console error is added', async () => { + 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'); + }); + + it('should not update hasErrors for non-error messages', async () => { + 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(); + }); + + it('should update consoleError with latest error message', () => { + 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'); + }); + + expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); + expect(result.current.consoleError?.logs).toHaveLength(2); + }); + + it('should clear errors when clearErrors is called', async () => { + 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(); + }); + + it('should dismiss console error when dismissConsoleError is called', async () => { + 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); + }); + + it('should include all error messages in console error logs', () => { + const { result } = renderHook(() => useConsoleError(), { + wrapper: TestWrapper, + }); + + // Add multiple errors and non-errors + act(() => { + addConsoleMessage('log', 'Log message'); + addConsoleMessage('error', 'First error'); + addConsoleMessage('warn', 'Warning message'); + addConsoleMessage('error', 'Second error'); + addConsoleMessage('info', 'Info message'); + addConsoleMessage('error', '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', + 'Second error', + 'Third error' + ]); + }); +}); \ No newline at end of file diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx new file mode 100644 index 00000000..b033ed64 --- /dev/null +++ b/src/components/ConsoleErrorProvider.tsx @@ -0,0 +1,63 @@ +import { useState, useEffect, useCallback, ReactNode } from 'react'; +import { + addConsoleMessageListener, + removeConsoleMessageListener, + getHasConsoleErrors, + getConsoleMessages, + clearConsoleMessages, + ProjectPreviewConsoleError +} from '@/lib/consoleMessages'; +import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; + +interface ConsoleErrorProviderProps { + children: ReactNode; +} + +export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { + const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors()); + const [consoleError, setConsoleError] = useState(null); + + const updateState = useCallback(() => { + const hasConsoleErrors = getHasConsoleErrors(); + setHasErrors(hasConsoleErrors); + + 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 + )); + } else { + setConsoleError(null); + } + }, []); + + useEffect(() => { + addConsoleMessageListener(updateState); + updateState(); // Initial sync + + return () => removeConsoleMessageListener(updateState); + }, [updateState]); + + const clearErrors = useCallback(() => { + clearConsoleMessages(); + }, []); + + const dismissConsoleError = useCallback(() => { + setConsoleError(null); + }, []); + + const value = { + hasErrors, + consoleError, + clearErrors, + dismissConsoleError, + }; + + return ( + + {children} + + ); +} \ No newline at end of file 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 + + +
- + +
+ 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 ( - - - - - - - {(isConfigured && models.length >= 5) && ( - - )} - - -
-

{t('noModelsFound')}

-

{t('tryCustomModel')}

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

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

+
+
+ )} + + + + + + + {(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')} - - - - - - + + + + +
+ ); } \ No newline at end of file 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 d6d740f4..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'; @@ -763,7 +764,6 @@ export const ChatPane = forwardRef(({ (); useEffect(() => { setSelectedFile(null); setFileContent(''); @@ -463,7 +468,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o setCurrentPath('/'); setNavigationHistory(['/']); setHistoryIndex(0); - }, [projectId]); + + // 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(() => { checkForBuiltProject(); @@ -512,6 +523,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const [isOpen, setIsOpen] = useState(false); const [copiedMessageIndex, setCopiedMessageIndex] = useState(null); + const messages = isOpen ? getConsoleMessages() : []; + const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => { try { await navigator.clipboard.writeText(msg.message); @@ -522,9 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }; - const consoleMessages = getConsoleMessages(); - const messageCount = consoleMessages.length; - const hasErrors = consoleMessages.some(msg => msg.level === 'error'); + const messageCount = messages.length; return ( @@ -535,7 +546,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o className="h-8 w-8 p-0 relative" > - {hasErrors && ( + {hasConsoleErrors && ( )} @@ -555,7 +566,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - consoleMessages.map((msg, index) => ( + messages.map((msg, index) => (
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/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 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.test.ts b/src/lib/build/index.test.ts index 8934a324..b8f52ac9 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -9,14 +9,28 @@ 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', }, ], + metafile: { + outputs: { + 'stdin-abc123.js': { + entryPoint: 'fs:/test/project/src/main.tsx', + }, + 'stdin-def456.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 6817bcb2..a424c05b 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,5 +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"; @@ -32,25 +34,51 @@ 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, + sourcemap: true, + entryNames: "[name]-[hash]", + chunkNames: "[name]-[hash]", + assetNames: "[name]-[hash]", plugins: [ - shakespearePlugin(), // Takes precedence over esmPlugin + shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], @@ -62,18 +90,40 @@ 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; + const ext = file.path.split('.').pop(); + const filename = `${file.path.slice(1)}`; + const entryPoint = results.metafile.outputs[filename]?.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); } else { - dist[relativePath] = file.contents; + dist[filename] = file.contents; } } - // Update index.html with proper script and link tags - updateIndexHtml(doc, dist); + // 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); @@ -156,20 +206,25 @@ 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"); +async function fileExists(fs: JSRuntimeFS, path: string): Promise { + try { + const stat = await fs.stat(path); + return stat.isFile(); + } catch { + return false; } +} - entrypoint.setAttribute("src", "/main.js"); +/** 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 + ]; - 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); - } + return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives); } \ 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 { diff --git a/src/lib/consoleMessages.test.ts b/src/lib/consoleMessages.test.ts new file mode 100644 index 00000000..7b402c0d --- /dev/null +++ b/src/lib/consoleMessages.test.ts @@ -0,0 +1,155 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + addConsoleMessage, + clearConsoleMessages, + getConsoleMessages, + getHasConsoleErrors, + addConsoleMessageListener, + removeConsoleMessageListener, + 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 notify listeners when messages are added', () => { + const listener = vi.fn(); + addConsoleMessageListener(listener); + + addConsoleMessage('error', 'First error'); + expect(listener).toHaveBeenCalledTimes(1); + + addConsoleMessage('error', 'Second error'); + expect(listener).toHaveBeenCalledTimes(2); + + 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 + }); + + 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 messages are cleared', () => { + const listener = vi.fn(); + addConsoleMessageListener(listener); + + addConsoleMessage('error', 'Error message'); + expect(listener).toHaveBeenCalledTimes(1); + + clearConsoleMessages(); + expect(listener).toHaveBeenCalledTimes(2); + + removeConsoleMessageListener(listener); + }); + }); + + describe('Message Listeners', () => { + it('should add and remove listeners correctly', () => { + const listener1 = vi.fn(); + const listener2 = vi.fn(); + + addConsoleMessageListener(listener1); + addConsoleMessageListener(listener2); + + addConsoleMessage('error', 'Test error'); + + expect(listener1).toHaveBeenCalledTimes(1); + expect(listener2).toHaveBeenCalledTimes(1); + + removeConsoleMessageListener(listener1); + clearConsoleMessages(); + + expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear) + expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear + + removeConsoleMessageListener(listener2); + }); + + it('should handle listener errors gracefully', () => { + const faultyListener = vi.fn(() => { + throw new Error('Listener error'); + }); + const workingListener = vi.fn(); + + addConsoleMessageListener(faultyListener); + addConsoleMessageListener(workingListener); + + // Should not throw despite faulty listener + expect(() => { + addConsoleMessage('error', 'Test error'); + }).not.toThrow(); + + expect(faultyListener).toHaveBeenCalled(); + expect(workingListener).toHaveBeenCalled(); + + removeConsoleMessageListener(faultyListener); + removeConsoleMessageListener(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..a707e463 --- /dev/null +++ b/src/lib/consoleMessages.ts @@ -0,0 +1,65 @@ +/** + * 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[] = []; +const listeners: Array<() => 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) => { + consoleMessages.push({ level, message }); + notifyListeners(); +}; + +export const addConsoleMessageListener = (listener: () => void) => { + listeners.push(listener); +}; + +export const removeConsoleMessageListener = (listener: () => void) => { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } +}; + +export const getHasConsoleErrors = (): boolean => { + return consoleMessages.some(msg => msg.level === 'error'); +}; + +export const getConsoleMessages = (): ConsoleMessage[] => { + return [...consoleMessages]; +}; + +export const clearConsoleMessages = () => { + consoleMessages.length = 0; + notifyListeners(); +}; \ 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); +} diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 1b2647ef..bf2de6c6 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -1,12 +1,6 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { - ReadConsoleMessagesTool, - addConsoleMessage, - clearConsoleMessages, - ProjectPreviewConsoleError, - addErrorListener, - removeErrorListener -} from './ReadConsoleMessagesTool'; +import { describe, it, expect, beforeEach } from 'vitest'; +import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool'; +import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages'; describe('ReadConsoleMessagesTool', () => { beforeEach(() => { @@ -63,106 +57,43 @@ 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 Listeners', () => { - 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 trigger error listener when console error is added', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); + it('should handle limit correctly', async () => { + const tool = new ReadConsoleMessagesTool(); - // Add an error message - addConsoleMessage('error', 'Test error message'); + // Limit should return only the most recent messages + const limitedResult = await tool.execute({ limit: 2 }); + expect(limitedResult).toContain('Found 2 console messages'); - // 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' - }) - ]) - }) - ); - - removeErrorListener(errorListener); - }); - - it('should not trigger error listener for non-error messages', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); - - // Add non-error messages - 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(errorListener).not.toHaveBeenCalled(); - - removeErrorListener(errorListener); - }); - - it('should remove error listener correctly', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); - removeErrorListener(errorListener); - - // Add an error message - addConsoleMessage('error', 'Test error message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(errorListener).not.toHaveBeenCalled(); - }); - - it('should handle listener errors gracefully', async () => { - const faultyListener = vi.fn(() => { - throw new Error('Listener error'); - }); - const workingListener = vi.fn(); - - addErrorListener(faultyListener); - addErrorListener(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(); - - removeErrorListener(faultyListener); - removeErrorListener(workingListener); + // 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 f2396b40..1f8e5904 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,87 +7,30 @@ 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[] = []; -const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; - -export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - 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') - ); - - errorListeners.forEach(listener => { - try { - listener(error); - } catch (err) { - console.warn('Error listener failed:', err); - } - }); - } -}; - -export const getConsoleMessages = (): ConsoleMessage[] => { - return [...consoleMessages]; -}; - -export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - errorListeners.push(listener); -}; - -export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - const index = errorListeners.indexOf(listener); - if (index > -1) { - errorListeners.splice(index, 1); - } -}; - -export const clearConsoleMessages = () => { - consoleMessages.length = 0; -}; - 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); + let messages = getConsoleMessages() + .filter(msg => filter === 'all' || msg.level === filter); - if (filteredMessages.length === 0) { + if (limit && limit > 0) { + messages = messages.slice(-limit); + } + + 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.'; 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 { diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 4b5d926b..212191f8 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,16 +82,6 @@ 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); - }, []); - const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { @@ -113,7 +104,7 @@ export function ProjectView() { }; const handleDismissConsoleError = () => { - setConsoleError(null); + dismissConsoleError(); }; const handleProjectDeleted = async () => { 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) {