import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react'; import { useSearchParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Skeleton } from '@/components/ui/skeleton'; import { CircularProgress } from '@/components/ui/circular-progress'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { FileAttachment } from '@/components/ui/file-attachment'; import { OnboardingDialog } from '@/components/OnboardingDialog'; import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAIChat } from '@/hooks/useAIChat'; import { useProviderModels } from '@/hooks/useProviderModels'; import { ModelSelector } from '@/components/ModelSelector'; import { AIMessageItem } from '@/components/AIMessageItem'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool'; import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; import { GitCommitTool } from '@/lib/tools/GitCommitTool'; import { BuildProjectTool } from '@/lib/tools/BuildProjectTool'; import { DeployProjectTool } from '@/lib/tools/DeployProjectTool'; import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool'; import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool'; import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool'; import { NostrReadTagTool } from '@/lib/tools/NostrReadTagTool'; import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool'; 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 } 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'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { Quilly } from '@/components/Quilly'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; // Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; onNewChat: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; consoleError?: ProjectPreviewConsoleError | null; onDismissConsoleError?: () => void; isTextChat?: boolean; // Whether this is a text chat (no tools) vs a project chat } export interface ChatPaneRef { startNewSession: () => void; } export const ChatPane = forwardRef(({ projectId, onNewChat, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, consoleError, onDismissConsoleError, isTextChat = false, }, ref) => { const { t } = useTranslation(); const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); const { user } = useCurrentUser(); const { models } = useProviderModels(); const [input, setInput] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [attachedFiles, setAttachedFiles] = useState([]); const [isDragOver, setIsDragOver] = useState(false); const [scrolledProjects] = useState(() => new Set()); const [showOnboarding, setShowOnboarding] = useState(false); const [isStuck, setIsStuck] = useState(false); const [aiError, setAIError] = useState(null); // Determine which error to show - console error takes priority over AI errors const displayError = consoleError || aiError; // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; const scrollAreaRef = useRef(null); const { isConfigured, settings, addRecentlyUsedModel } = useAISettings(); const [providerModel, setProviderModel] = useState(() => { // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; }); // State to control model selector dropdown const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false); const [shouldAutostart, setShouldAutostart] = useState(false); const autostartedRef = useRef(false); useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { setProviderModel(settings.recentlyUsedModels[0]); } }, [providerModel, settings.recentlyUsedModels]); useEffect(() => { const urlModel = searchParams.get('model'); const autostart = searchParams.get('autostart'); if (urlModel && !providerModel) { setProviderModel(urlModel); } if (autostart === 'true') { setShouldAutostart(true); } // Clear the autostart and model parameters const newSearchParams = new URLSearchParams(searchParams); newSearchParams.delete('autostart'); newSearchParams.delete('model'); setSearchParams(newSearchParams, { replace: true }); }, [providerModel, searchParams, setSearchParams]) // Reset error state when navigating between projects and switching models useEffect(() => { setAIError(null); }, [projectId, providerModel]); // Initialize AI chat with tools const cwd = isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`; const customTools = useMemo(() => { // For text chats, return empty tools object if (isTextChat) { return {}; } const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd), text_editor_write: new TextEditorWriteTool(fs, cwd), text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd), npm_add_package: new NpmAddPackageTool(fs, cwd), npm_remove_package: new NpmRemovePackageTool(fs, cwd), build_project: new BuildProjectTool(fs, cwd), typecheck: new TypecheckTool(fs, cwd), nostr_read_nip: new NostrReadNipTool(), nostr_fetch_event: new NostrFetchEventTool(), nostr_read_kind: new NostrReadKindTool(), nostr_read_tag: new NostrReadTagTool(), nostr_read_protocol: new NostrReadProtocolTool(), nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_generate_kind: new NostrGenerateKindTool(), shell: new ShellTool(fs, cwd, git), read_console_messages: new ReadConsoleMessagesTool(), }; // Add deploy tool only if user is logged in if (user && user.signer) { return { ...baseTools, deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId), }; } return baseTools; }, [fs, git, cwd, user, projectId, isTextChat]); // Convert tools to OpenAI format const tools = useMemo(() => { const result: Record = {}; for (const [name, tool] of Object.entries(customTools)) { result[name] = toolToOpenAI(name, tool as Tool); } return result; }, [customTools]); // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ enabled: externalIsLoading || isBuildLoading, title: 'Shakespeare', artist: `Working on ${projectId}...`, artwork: [ { src: '/shakespeare.png', sizes: '512x512', type: 'image/png' } ] }); // Memoize the metadata update callback to avoid unnecessary re-renders const onUpdateMetadata = useCallback((title: string, description: string) => { updateMetadata(title, description); }, [updateMetadata]); // Handle AI errors from the SessionManager const onAIError = useCallback((error: Error) => { setAIError(error); }, []); const { messages, streamingMessage, isLoading: internalIsLoading, totalCost, lastInputTokens, addMessage, sendMessage, startGeneration, stopGeneration, startNewSession: internalStartNewSession, } = useAIChat({ projectId, tools, customTools, onUpdateMetadata, onAIError, isTextChat, }); // Handle console error help requests const handleConsoleErrorHelp = useCallback(async () => { const tool = new ReadConsoleMessagesTool(); const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`; await addMessage({ role: 'assistant', content: 'Let me take a look at the console messages to help diagnose the issue.', tool_calls: [ { id: toolCallId, type: 'function', function: { name: 'read_console_messages', arguments: '{}', } } ] }); await addMessage({ role: 'tool', content: await tool.execute({ filter: 'error' }), tool_call_id: toolCallId, }); await startGeneration(providerModel); }, [addMessage, providerModel, startGeneration]); // Handle error dismissal const handleErrorDismiss = useCallback(() => { if (consoleError && onDismissConsoleError) { onDismissConsoleError(); } else { setAIError(null); } }, [consoleError, onDismissConsoleError]); // Use external loading state if provided, otherwise use internal state const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading; // Calculate context usage percentage const currentModel = useMemo(() => { if (!providerModel.trim()) return null; return models.find(model => model.fullId === providerModel.trim()); }, [models, providerModel]); const contextUsagePercentage = useMemo(() => { if (!currentModel?.contextLength || !lastInputTokens) return 0; return Math.min((lastInputTokens / currentModel.contextLength) * 100, 100); }, [currentModel, lastInputTokens]); // Notify parent of loading state changes useEffect(() => { if (onLoadingChange) { onLoadingChange(internalIsLoading); } }, [internalIsLoading, onLoadingChange]); // Timer to detect when AI appears stuck during tool generation useEffect(() => { // Start a 2-second timer const timer = streamingMessage ? setTimeout(() => setIsStuck(true), 2000) : undefined; return () => { setIsStuck(false); clearTimeout(timer); }; }, [streamingMessage]); // Function to scroll to bottom const scrollToBottom = useCallback(() => { if (scrollAreaRef.current) { scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; } }, []); // Function to open model selector dropdown const openModelSelector = useCallback(() => { setIsModelSelectorOpen(true); }, []); // Scroll to bottom when any error occurs (AI error or console error) useEffect(() => { if (displayError) { scrollToBottom(); } }, [displayError, scrollToBottom]); // Check for autostart parameter and trigger AI generation useEffect(() => { if (autostartedRef.current) return; if (shouldAutostart && providerModel && isConfigured) { // Start AI generation addRecentlyUsedModel(providerModel); startGeneration(providerModel); autostartedRef.current = true; } }, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]); // Simple scroll event listener useEffect(() => { const container = scrollAreaRef.current; if (!container) return; const handleScroll = () => { const threshold = 100; const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold; const hasScrollableContent = container.scrollHeight > container.clientHeight; setShowScrollToBottom(!isNearBottom && hasScrollableContent); }; container.addEventListener('scroll', handleScroll); // Check immediately handleScroll(); return () => { container.removeEventListener('scroll', handleScroll); }; }, [messages]); // Re-run when messages change to ensure proper setup useEffect(() => { if (scrollAreaRef.current && (messages || streamingMessage)) { // Check if user was already at or near the bottom (within 100px threshold) const threshold = 100; const container = scrollAreaRef.current; const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold; // Only auto-scroll if user was already near the bottom if (isNearBottom) { container.scrollTop = container.scrollHeight; } } }, [messages, streamingMessage, isLoading]); // Scroll to bottom when first visiting a project (including page refresh) useEffect(() => { if (projectId && !scrolledProjects.has(projectId)) { // Small delay to ensure messages have loaded const timer = setTimeout(() => { scrollToBottom(); scrolledProjects.add(projectId); }, 100); return () => clearTimeout(timer); } }, [projectId, scrolledProjects, scrollToBottom]); const handleFileSelect = (file: File) => { setAttachedFiles(prev => [...prev, file]); }; const handleFileRemove = (fileToRemove: File) => { setAttachedFiles(prev => prev.filter(file => file !== fileToRemove)); }; // Drag and drop handlers const handleDragEnter = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragOver(true); }; const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); if (!isDragOver) { setIsDragOver(true); } }; const handleDragLeave = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); // Only reset drag state if we're actually leaving the container // This prevents flickering when dragging over child elements const container = e.currentTarget; const relatedTarget = e.relatedTarget as Node; if (!container.contains(relatedTarget)) { setIsDragOver(false); } }; const handleDrop = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragOver(false); if (isLoading || !providerModel.trim()) return; const files = Array.from(e.dataTransfer.files); if (files.length === 0) return; // Add all files without validation setAttachedFiles(prev => [...prev, ...files]); }; const send = useCallback(async (input: string, attachedFiles: File[]) => { if ((!input.trim() && attachedFiles.length === 0) || isLoading) return; // If AI is not configured, show onboarding dialog if (!isConfigured) { setShowOnboarding(true); return; } // If configured but no model selected, don't proceed if (!providerModel.trim()) return; setAIError(null); const modelToUse = providerModel.trim(); // Build message content as text parts const contentParts: Array = []; // Add user input as text part if present if (input.trim()) { contentParts.push({ type: 'text', text: input.trim() }); } // Process attached files and add as separate text parts if (attachedFiles.length > 0) { const filePromises = attachedFiles.map(async (file) => { try { const savedPath = await saveFileToTmp(fs, file); return `Added file: ${savedPath}`; } catch (error) { console.error('Failed to save file:', error); return `Failed to save file: ${file.name}`; } }); const fileResults = await Promise.all(filePromises); // Add each file as a separate text part fileResults.forEach(fileResult => { contentParts.push({ type: 'text', text: fileResult }); }); } setInput(''); setAttachedFiles([]); // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); // Send as text parts if we have multiple parts, otherwise send as string for simplicity const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts; await sendMessage(messageContent, modelToUse); }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]); const handleSend = useCallback(async () => { await send(input, attachedFiles); }, [input, attachedFiles, send]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; const handlePaste = async (e: React.ClipboardEvent) => { const items = e.clipboardData?.items; if (!items) return; for (let i = 0; i < items.length; i++) { const item = items[i]; // Check if the item is an image if (item.type.startsWith('image/')) { e.preventDefault(); // Prevent default paste behavior for images const file = item.getAsFile(); if (file) { // Generate a filename with timestamp const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const extension = file.type.split('/')[1] || 'png'; const filename = `pasted-image-${timestamp}.${extension}`; // Create a new File object with the generated name const namedFile = new File([file], filename, { type: file.type }); // Add to attached files setAttachedFiles(prev => [...prev, namedFile]); } break; // Only handle the first image found } } }; // Handle textarea focus - show onboarding if not configured const handleTextareaFocus = () => { if (!isConfigured) { setShowOnboarding(true); } if (onFirstInteraction) { onFirstInteraction(); } }; // Handle first user interaction to enable audio context const handleFirstInteraction = () => { // This will be handled automatically by the useKeepAlive hook // when isLoading becomes true after user interaction if (onFirstInteraction) { onFirstInteraction(); } }; // Expose startNewSession function via ref useImperativeHandle(ref, () => ({ startNewSession: () => { internalStartNewSession(); } }), [internalStartNewSession]); return (
{/* Empty state when no messages and not loading */} {messages.length === 0 && !streamingMessage && !isLoading && (

{t('welcomeToShakespeare')}

{t('aiAssistantReady')}

{t('askMeFeatures')}

{t('requestEdits')}

{t('getHelp')}

{t('buildDeploy')}

)} {messages.map((message, index) => { // Find the corresponding tool call for tool messages let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined; if (message.role === 'tool') { // Look backwards to find the assistant message with matching tool call for (let i = index - 1; i >= 0; i--) { const prevMessage = messages[i]; if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) { toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id); if (toolCall) break; } } } return ( ); })} {streamingMessage && ( streamingMessage.content || streamingMessage.reasoning_content ? ( <> {/* Show loading skeleton if AI appears stuck generating tools */} {isStuck && (
)} ) : ( !(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
) ) )} {streamingMessage?.tool_calls?.[0]?.type === 'function' && (
{t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
)} {/* Error Alert (Console or AI) */} {displayError && ( )}
{/* Scroll to bottom button */} {showScrollToBottom && (
)}
{/* Chat Input Container */}