import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo } from 'react'; import { useSearchParams } from 'react-router-dom'; 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 { Send, Square, Loader2, ChevronDown } 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 type { AIMessage } from '@/lib/SessionManager'; 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 { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { makeSystemPrompt } from '@/lib/system'; import { assistantContentEmpty } from '@/lib/ai-messages'; interface ChatPaneProps { projectId: string; projectName: string; onNewChat?: () => void; onBuild?: () => void; onDeploy?: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; isDeployLoading?: boolean; } export interface ChatPaneRef { startNewSession: () => void; } export const ChatPane = forwardRef(({ projectId, projectName, onNewChat: _onNewChat, onBuild: _onBuild, onDeploy: _onDeploy, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, isDeployLoading: externalIsDeployLoading }, ref) => { const [input, setInput] = useState(''); const [systemPrompt, setSystemPrompt] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; const isDeployLoading = externalIsDeployLoading || 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] || ''; }); const [searchParams, setSearchParams] = useSearchParams(); const { fs: browserFS } = useFS(); const { user } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; const customTools = useMemo(() => { const baseTools = { git_commit: new GitCommitTool(browserFS, cwd), text_editor_view: new TextEditorViewTool(browserFS, cwd), text_editor_write: new TextEditorWriteTool(browserFS, cwd), text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), npm_add_package: new NpmAddPackageTool(browserFS, cwd), npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), build_project: new BuildProjectTool(browserFS, 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(browserFS, cwd), }; // Add deploy tool only if user is logged in if (user && user.signer) { return { ...baseTools, deploy_project: new DeployProjectTool(browserFS, cwd, user.signer, projectId), }; } return baseTools; }, [browserFS, cwd, user, projectId]); // 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]); useEffect(() => { makeSystemPrompt({ cwd, fs: browserFS, mode: "agent", name: "Shakespeare", profession: "software extraordinaire", tools: Object.values(tools), }).then(setSystemPrompt) }, [browserFS, cwd, tools]); const { messages, streamingMessage, isLoading: internalIsLoading, totalCost, lastInputTokens, sendMessage, startGeneration, stopGeneration, startNewSession: internalStartNewSession, } = useAIChat({ projectId, projectName, tools, customTools, systemPrompt, onUpdateMetadata: (title, description) => { updateMetadata(title, description); } }); // 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]); // Check for autostart parameter and trigger AI generation useEffect(() => { const autostart = searchParams.get('autostart'); const urlModel = searchParams.get('model'); if (autostart === 'true' && isConfigured && messages.length > 0 && !isLoading) { const lastMessage = messages[messages.length - 1]; // If the last message is from the user, auto-start the AI if (lastMessage.role === 'user') { // Use model from URL if available, otherwise use current selection const modelToUse = urlModel?.trim() || providerModel.trim(); if (modelToUse) { // Update provider model if it came from URL if (urlModel?.trim() && urlModel.trim() !== providerModel) { setProviderModel(urlModel.trim()); } // Clear the autostart and model parameters so they don't trigger again const newSearchParams = new URLSearchParams(searchParams); newSearchParams.delete('autostart'); newSearchParams.delete('model'); setSearchParams(newSearchParams, { replace: true }); // Start AI generation addRecentlyUsedModel(modelToUse); startGeneration(modelToUse); } } } }, [searchParams, setSearchParams, isConfigured, messages, isLoading, startGeneration, providerModel, setProviderModel, addRecentlyUsedModel]); // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ enabled: isLoading || isBuildLoading || isDeployLoading, title: 'Shakespeare', artist: `Working on ${projectName}...`, artwork: [ { src: '/favicon.png', sizes: '512x512', type: 'image/png' } ] }); // Function to check if user is at the bottom of the scroll area const checkScrollPosition = () => { if (!scrollAreaRef.current) return; const container = scrollAreaRef.current; const threshold = 100; // 100px threshold const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold; setShowScrollToBottom(!isNearBottom && container.scrollHeight > container.clientHeight); }; // Function to scroll to bottom const scrollToBottom = () => { if (scrollAreaRef.current) { scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; } }; // Add scroll event listener useEffect(() => { const container = scrollAreaRef.current; if (!container) return; container.addEventListener('scroll', checkScrollPosition); // Check initial position checkScrollPosition(); return () => { container.removeEventListener('scroll', checkScrollPosition); }; }, []); 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; } // Update scroll button visibility checkScrollPosition(); } }, [messages, streamingMessage, isLoading]); const handleSend = async () => { if (!input.trim() || isLoading || !providerModel.trim()) return; const messageContent = input; const modelToUse = providerModel.trim(); setInput(''); // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); try { await sendMessage(messageContent, modelToUse); } catch (error) { console.error('AI chat error:', error); // Error handling is done in the useAIChat hook } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; // 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]); if (!isConfigured) { return (
🤖

AI Assistant Not Configured

Please configure your AI settings to start building with AI assistance.

Use the menu in the top bar to access AI Settings.

); } return (
{messages.map((message, index) => { // Skip assistant messages with no content if (message.role === 'assistant' && assistantContentEmpty(message.content)) { return null; } // 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?.tool_calls?.[0]?.type === 'function' && (
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
)}
{/* Scroll to bottom button */} {showScrollToBottom && (
)}
{/* Chat Input Container */}