diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index ac24918e..d198abde 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -35,13 +35,15 @@ import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; -import { ConsoleMessage } from '@/types/console'; + import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { saveFileToTmp } from '@/lib/fileUtils'; + import { useGit } from '@/hooks/useGit'; import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; +import { useProjectConsoleMessages } from '@/hooks/useProjectConsoleMessages'; import { QuillySVG } from '@/components/ui/QuillySVG'; @@ -97,7 +99,6 @@ interface ChatPaneProps { onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; - consoleMessages?: ConsoleMessage[]; } export interface ChatPaneRef { @@ -112,7 +113,7 @@ export const ChatPane = forwardRef(({ onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, - consoleMessages, + }, ref) => { const { t } = useTranslation(); const [input, setInput] = useState(''); @@ -144,6 +145,7 @@ export const ChatPane = forwardRef(({ const { git } = useGit(); const { user } = useCurrentUser(); const { models } = useProviderModels(); + const { messages: consoleMessages } = useProjectConsoleMessages(projectId); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; @@ -260,7 +262,7 @@ export const ChatPane = forwardRef(({ // Function to suggest error fix // Clean alert hooks with proper interfaces const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); - const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); + const consoleAlert = useConsoleErrorAlert(messages, projectId, isBuildLoading, internalIsLoading); // Scroll to bottom when alerts appear useEffect(() => { @@ -400,6 +402,10 @@ export const ChatPane = forwardRef(({ setAttachedFiles(prev => [...prev, ...files]); }; + const handleSend = useCallback(async () => { + await sendMessage(input, providerModel); + }, [input, sendMessage, providerModel]); + const send = useCallback(async (input: string, attachedFiles: File[]) => { if ((!input.trim() && attachedFiles.length === 0) || isLoading) return; @@ -464,10 +470,6 @@ export const ChatPane = forwardRef(({ } }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]); - const handleSend = useCallback(async () => { - await send(input, attachedFiles); - }, [input, attachedFiles, send]); - const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); @@ -530,9 +532,9 @@ export const ChatPane = forwardRef(({ } }), [internalStartNewSession]); - const suggestErrorFix = useCallback(async (errorMessage: string) => { - await send(errorMessage, attachedFiles); - }, [send, attachedFiles]); + const suggestErrorFix = useCallback(async () => { + await send('Read the console messages and fix any errors.', []); + }, [send]); return (
@@ -630,7 +632,7 @@ export const ChatPane = forwardRef(({ onDismiss={consoleAlert.dismiss} action={{ label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`, - onClick: () => suggestErrorFix(consoleAlert.errorSummary || '') + onClick: () => suggestErrorFix() }} /> )} diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index f8acca00..19b28c7b 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; -import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages'; +import { useProjectConsoleMessages, addProjectConsoleMessage } from '@/hooks/useProjectConsoleMessages'; import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; -import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, Trash2, Download, X } from 'lucide-react'; +import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; @@ -17,7 +17,6 @@ import { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, - DropdownMenuSeparator, } from '@/components/ui/dropdown-menu'; import { Popover, @@ -25,7 +24,7 @@ import { PopoverTrigger, } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; -import { ConsoleMessage } from '@/types/console'; +import type { ConsoleMessage } from '@/types/console'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; @@ -43,8 +42,6 @@ interface PreviewPaneProps { projectName?: string; onFirstInteraction?: () => void; isPreviewable?: boolean; - consoleMessages?: ConsoleMessage[]; - setConsoleMessages?: React.Dispatch>; }; } @@ -86,8 +83,6 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr projectName, onFirstInteraction, isPreviewable = true, - consoleMessages: externalConsoleMessages = [], - setConsoleMessages: externalSetConsoleMessages, } = config; const { t } = useTranslation(); const [selectedFile, setSelectedFile] = useState(null); @@ -99,17 +94,16 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); -const [copiedMessageId, setCopiedMessageId] = useState(null); + const [deployDialogOpen, setDeployDialogOpen] = useState(false); - // Use external state if provided, otherwise use internal state - const [internalConsoleMessages, setInternalConsoleMessages] = useState([]); - const consoleMessages = externalConsoleMessages || internalConsoleMessages; - const setConsoleMessages = externalSetConsoleMessages || setInternalConsoleMessages; const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); - const { messages: consoleMessages } = useConsoleMessages(); + + + // Use project-specific console messages + const { messages: consoleMessages } = useProjectConsoleMessages(projectId); const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); const [searchParams, setSearchParams] = useSearchParams(); @@ -281,23 +275,12 @@ const [copiedMessageId, setCopiedMessageId] = useState(null); normalizedLevel = params.level as ConsoleMessage['level']; } - // Add to global console messages - addConsoleMessage(normalizedLevel, params.message); - - // Also update local state if provided (for external systems) - if (setConsoleMessages !== setInternalConsoleMessages) { - const newMessage: ConsoleMessage = { - id: Date.now() + Math.random(), - level: normalizedLevel, - message: params.message, - timestamp: Date.now(), - }; - setConsoleMessages(prev => [...prev, newMessage]); - } + // Add to project-specific console messages + addProjectConsoleMessage(projectId, normalizedLevel, params.message); // Log to parent console for debugging with appropriate level console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); - }, [setConsoleMessages, setInternalConsoleMessages]); + }, [projectId]); const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; @@ -477,30 +460,6 @@ const [copiedMessageId, setCopiedMessageId] = useState(null); const [isOpen, setIsOpen] = useState(false); const copiedMessageRef = useRef(null); const [_, setCopyUpdate] = useState(0); - - const getLevelColor = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return 'text-red-500'; - case 'warn': return 'text-yellow-500'; - case 'info': return 'text-blue-500'; - case 'debug': return 'text-gray-500'; - default: return 'text-gray-400'; - } - }; - - const getLevelIcon = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return '!'; - case 'warn': return '⚠'; - case 'info': return 'ℹ'; - case 'debug': return '🔍'; - default: return '•'; - } - }; - - const clearConsole = () => { - clearConsoleMessages(); - }; const copyMessageToClipboard = async (msg: ConsoleMessage) => { try { await navigator.clipboard.writeText(msg.message); diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index 9a100f85..76f37d07 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -1,6 +1,6 @@ import { useState, useCallback, useMemo } from 'react'; import type { AIMessage } from '@/lib/SessionManager'; -import { useConsoleMessages } from './useConsoleMessages'; +import { useProjectConsoleMessages } from './useProjectConsoleMessages'; export interface ConsoleErrorAlert { hasError: boolean; @@ -11,10 +11,11 @@ export interface ConsoleErrorAlert { export const useConsoleErrorAlert = ( aiMessages: AIMessage[], + projectId?: string | null, isBuilding?: boolean, isLoading?: boolean ): ConsoleErrorAlert => { - const { messages } = useConsoleMessages(); + const { messages } = useProjectConsoleMessages(projectId || null); const [dismissedErrorSummary, setDismissedErrorSummary] = useState(''); const { hasError, errorSummary, errorCount } = useMemo(() => { @@ -38,7 +39,7 @@ export const useConsoleErrorAlert = ( const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago const recentErrors = messages.filter(msg => msg.level === 'error' && - msg.timestamp > recentTimeThreshold + msg.timestamp && msg.timestamp > recentTimeThreshold ); if (recentErrors.length === 0) { diff --git a/src/hooks/useProjectConsoleMessages.ts b/src/hooks/useProjectConsoleMessages.ts new file mode 100644 index 00000000..47db8660 --- /dev/null +++ b/src/hooks/useProjectConsoleMessages.ts @@ -0,0 +1,117 @@ +import { useState, useCallback, useEffect } from 'react'; +import type { ConsoleMessage } from '@/types/console'; + +export interface ProjectConsoleMessages { + [projectId: string]: ConsoleMessage[]; +} + +// Project-specific console messages storage +const projectConsoleMessages: ProjectConsoleMessages = {}; +const listeners: Map void>> = new Map(); + +const notifyListeners = (projectId: string) => { + const projectListeners = listeners.get(projectId); + if (projectListeners) { + const messages = projectConsoleMessages[projectId] || []; + projectListeners.forEach(listener => listener([...messages])); + } +}; + +export const useProjectConsoleMessages = (projectId: string | null) => { + const [messages, setMessages] = useState([]); + + + + const clearMessages = useCallback(() => { + if (!projectId) return; + + projectConsoleMessages[projectId] = []; + notifyListeners(projectId); + }, [projectId]); + + const getErrors = useCallback(() => { + if (!projectId) return []; + return (projectConsoleMessages[projectId] || []).filter(msg => msg.level === 'error'); + }, [projectId]); + + const getRecentErrors = useCallback((since: number = Date.now() - 10000) => { + if (!projectId) return []; + return (projectConsoleMessages[projectId] || []).filter( + msg => msg.level === 'error' && msg.timestamp && msg.timestamp > since + ); + }, [projectId]); + + const getAllMessages = useCallback(() => { + if (!projectId) return []; + return projectConsoleMessages[projectId] || []; + }, [projectId]); + + // Subscribe to project-specific state changes + useEffect(() => { + if (!projectId) return; + + const listener = (newMessages: ConsoleMessage[]) => { + setMessages(newMessages); + }; + + // Initialize listeners for this project if not exists + if (!listeners.has(projectId)) { + listeners.set(projectId, new Set()); + } + + const projectListeners = listeners.get(projectId)!; + projectListeners.add(listener); + + // Initialize with current messages + setMessages(projectConsoleMessages[projectId] || []); + + return () => { + projectListeners.delete(listener); + // Clean up empty listener sets + if (projectListeners.size === 0) { + listeners.delete(projectId); + } + }; + }, [projectId]); + + return { + messages, + clearMessages, + getErrors, + getRecentErrors, + getAllMessages, + }; +}; + +// Export functions for external use (like PreviewPane) +export const addProjectConsoleMessage = (projectId: string, level: ConsoleMessage['level'], message: string) => { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), + level, + message, + timestamp: Date.now(), + }; + + // Initialize project messages if not exists + if (!projectConsoleMessages[projectId]) { + projectConsoleMessages[projectId] = []; + } + + // Add to project-specific messages + projectConsoleMessages[projectId] = [...projectConsoleMessages[projectId], newMessage]; + notifyListeners(projectId); +}; + +export const clearProjectConsoleMessages = (projectId: string) => { + projectConsoleMessages[projectId] = []; + notifyListeners(projectId); +}; + +export const getProjectConsoleMessages = (projectId: string): ConsoleMessage[] => { + return projectConsoleMessages[projectId] || []; +}; + +// Clear all console messages for a project (called when switching projects) +export const clearAllProjectConsoleMessages = (projectId: string) => { + clearProjectConsoleMessages(projectId); +}; \ No newline at end of file diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index ac874ebc..c0e0f7e9 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -20,8 +20,8 @@ import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; -import { ConsoleMessage } from '@/types/console'; -import { useConsoleMessages, clearConsoleMessages } from '@/hooks/useConsoleMessages'; + +import { useProjectConsoleMessages } from '@/hooks/useProjectConsoleMessages'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -32,7 +32,7 @@ export function ProjectView() { const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); - const [consoleMessages, setConsoleMessages] = useState([]); + const { clearMessages } = useProjectConsoleMessages(projectId || null); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); const navigate = useNavigate(); @@ -64,25 +64,19 @@ export function ProjectView() { const projectData = await projectsManager.getProject(projectId); setProject(projectData); // Clear console messages when switching projects - setConsoleMessages([]); - // Also clear global console messages - clearConsoleMessages(); + clearMessages(); } catch (error) { console.error('Failed to load project:', error); } finally { setIsLoading(false); } - }, [projectId, projectsManager, setConsoleMessages]); + }, [projectId, projectsManager, clearMessages]); useEffect(() => { loadProject(); }, [loadProject]); - // Sync console messages with global state - const { messages: globalMessages } = useConsoleMessages(); - useEffect(() => { - setConsoleMessages(globalMessages); - }, [globalMessages]); + // Reset view state when projectId changes useEffect(() => { @@ -104,6 +98,15 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); + // Clear console messages when projectId changes or component unmounts + useEffect(() => { + return () => { + if (projectId) { + clearMessages(); + } + }; + }, [projectId, clearMessages]); + const runBuild = async () => { if (build.isPending || !project) return; updateMetadata('Shakespeare', `Building ${project.name}...`); @@ -270,8 +273,6 @@ export function ProjectView() { config={{ projectName: project.name, onFirstInteraction: handleFirstInteraction, - consoleMessages, - setConsoleMessages, }} /> ) : ( @@ -436,7 +437,7 @@ export function ProjectView() { onLoadingChange={handleAILoadingChange} isLoading={isAILoading} isBuildLoading={build.isPending} - consoleMessages={consoleMessages} + /> ) : (
@@ -465,8 +466,6 @@ export function ProjectView() { projectName: project.name, onFirstInteraction: handleFirstInteraction, isPreviewable, - consoleMessages, - setConsoleMessages, }} /> ) : ( diff --git a/src/types/console.ts b/src/types/console.ts index da42e6d6..537331b5 100644 --- a/src/types/console.ts +++ b/src/types/console.ts @@ -2,4 +2,5 @@ export interface ConsoleMessage { id: number; level: 'log' | 'warn' | 'error' | 'info' | 'debug'; message: string; + timestamp?: number; } \ No newline at end of file