Spaces:
Running
Running
Download frontend/components/ChatWindow.tsx from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/frontend/components/ChatWindow.tsx
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/frontend/components/ChatWindow.tsx
-
curl -L -o ChatWindow.tsx https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/frontend/components/ChatWindow.tsx
19.2 kB
| 'use client' | |
| import { useState, useRef, useEffect } from 'react' | |
| import { Message, Lead, leadsApi } from '@/lib/api' | |
| import { Bot, Loader2, X } from 'lucide-react' | |
| import { AnimatePresence, motion } from 'framer-motion' | |
| import { useToast } from '@/contexts/ToastContext' | |
| import { ClientCard } from './ClientCard' | |
| import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient' | |
| import { BookingModal } from '@/components/bookings/BookingModal' | |
| import { useChatWebSocket } from '@/hooks/useChatWebSocket' | |
| // Import refactored sub-components | |
| import { ChatHeader } from './ChatWindow/ChatHeader' | |
| import { MessageBubble } from './ChatWindow/MessageBubble' | |
| import { MessageInput } from './ChatWindow/MessageInput' | |
| import { TypingIndicator } from './ChatWindow/TypingIndicator' | |
| import { ConfirmModal } from '@/components/ui/ConfirmModal' | |
| import { ImageViewer } from '@/components/ui/ImageViewer' | |
| // ============================================================================ | |
| // Types | |
| // ============================================================================ | |
| interface ChatWindowProps { | |
| messages: Message[] | |
| leadId?: string | |
| tenantId?: string | |
| conversationId?: string | |
| lead?: Lead | |
| conversation?: any | |
| isLoading?: boolean | |
| isAnalyzing?: boolean | |
| onRefresh?: () => void | |
| onLeadRefresh?: () => void | |
| onLeadUpdate?: (leadData: any) => void | |
| onConversationUpdate?: (data: any) => void // New prop for silent updates | |
| onTakeover?: () => void | |
| onBack?: () => void | |
| onToggleLeadsList?: () => void | |
| isLeadsListOpen?: boolean | |
| onOpenMobileDrawer?: () => void | |
| } | |
| // ============================================================================ | |
| // Helper Functions | |
| // ============================================================================ | |
| function shouldShowDateSeparator(currentMsg: Message, prevMsg: Message | null): boolean { | |
| if (!prevMsg) return true | |
| const currentDate = new Date(currentMsg.created_at).toDateString() | |
| const prevDate = new Date(prevMsg.created_at).toDateString() | |
| return currentDate !== prevDate | |
| } | |
| function getDateLabel(dateString: string): string { | |
| const date = new Date(dateString) | |
| const today = new Date() | |
| const yesterday = new Date(today) | |
| yesterday.setDate(yesterday.getDate() - 1) | |
| if (date.toDateString() === today.toDateString()) return 'Сегодня' | |
| if (date.toDateString() === yesterday.toDateString()) return 'Вчера' | |
| return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' }) | |
| } | |
| // ============================================================================ | |
| // Main Component | |
| // ============================================================================ | |
| export function ChatWindow({ | |
| messages, | |
| leadId, | |
| tenantId, | |
| conversationId, | |
| lead, | |
| conversation, | |
| isLoading, | |
| isAnalyzing, | |
| onRefresh, | |
| onLeadRefresh, | |
| onLeadUpdate, | |
| onConversationUpdate, | |
| onTakeover, | |
| onBack, | |
| onToggleLeadsList, | |
| isLeadsListOpen, | |
| onOpenMobileDrawer, | |
| }: ChatWindowProps) { | |
| // State | |
| const [inputMessage, setInputMessage] = useState('') | |
| const [isSending, setIsSending] = useState(false) | |
| const [optimisticMessages, setOptimisticMessages] = useState<Message[]>([]) | |
| const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([]) | |
| const [isTogglingAI, setIsTogglingAI] = useState(false) | |
| const lastInteractionTime = useRef<number>(0) | |
| const [localAIActive, setLocalAIActive] = useState<boolean>(() => { | |
| // Initial state priority: Lead has the latest mode status from the list | |
| if (lead && typeof lead.human_takeover === 'boolean') { | |
| return !lead.human_takeover | |
| } | |
| if (conversation && typeof conversation.human_takeover === 'boolean') { | |
| return !conversation.human_takeover | |
| } | |
| return true // Default to ON if no data yet | |
| }) | |
| const [isBookingModalOpen, setIsBookingModalOpen] = useState(false) | |
| const [isTraining, setIsTraining] = useState(false) | |
| const [isTrainConfirmOpen, setIsTrainConfirmOpen] = useState(false) | |
| const [viewerData, setViewerData] = useState<{ src: string; alt: string; isOpen: boolean }>({ | |
| src: '', | |
| alt: '', | |
| isOpen: false | |
| }) | |
| const toast = useToast() | |
| const messagesEndRef = useRef<HTMLDivElement>(null) | |
| // Computed values | |
| const isConversationStale = conversation && conversation.lead_id !== leadId | |
| const isAIActive = localAIActive | |
| // Sync local state with props | |
| useEffect(() => { | |
| // GUARD 1: If we are currently toggling, ignore incoming prop updates | |
| if (isTogglingAI) return | |
| // GUARD 2: Temporal lockout. If the user interacted in the last 3s, | |
| // ignore server updates to allow DB/Cache propagation to settle. | |
| // This solves the ON -> OFF -> ON -> OFF "ping-pong" effect. | |
| if (Date.now() - lastInteractionTime.current < 3000) return | |
| // Determine the next state based on available data | |
| let nextValue: boolean | undefined = undefined | |
| // 1. If we have a fresh conversation (matching current lead), it's the ultimate truth | |
| if (conversation && !isConversationStale && typeof conversation.human_takeover === 'boolean') { | |
| nextValue = !conversation.human_takeover | |
| } | |
| // 2. If no fresh conversation yet, use lead data (which we now pass from the list) | |
| else if (lead && typeof lead.human_takeover === 'boolean') { | |
| nextValue = !lead.human_takeover | |
| } | |
| if (nextValue !== undefined && nextValue !== localAIActive) { | |
| setLocalAIActive(nextValue) | |
| } | |
| }, [conversation?.human_takeover, lead?.human_takeover, isConversationStale, isTogglingAI]) | |
| const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages] | |
| .filter((msg, index, self) => index === self.findIndex((t) => t.id === msg.id)) | |
| .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()) | |
| // ============================================================================ | |
| // Effects | |
| // ============================================================================ | |
| const scrollToBottom = () => { | |
| messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) | |
| } | |
| useEffect(() => { | |
| scrollToBottom() | |
| }, [messages, optimisticMessages, realtimeMessages, isAnalyzing]) | |
| useEffect(() => { | |
| if (!leadId || !tenantId || !isRealtimeEnabled()) return | |
| setRealtimeMessages([]) | |
| const unsubscribe = subscribeToMessages(conversationId || '', (newMessage) => { | |
| setRealtimeMessages(prev => { | |
| if (prev.some(m => m.id === newMessage.id)) return prev | |
| return [...prev, newMessage] | |
| }) | |
| // If we got a real message from us, clear optimistic state to avoid duplication | |
| if (newMessage.sender_type === 'human' || newMessage.sender_type === 'ai') { | |
| setOptimisticMessages(prev => prev.filter(m => | |
| m.content !== newMessage.content || m.sender_type !== newMessage.sender_type | |
| )) | |
| } | |
| }) | |
| return () => { unsubscribe() } | |
| }, [leadId, tenantId, conversationId]) | |
| // WebSocket real-time updates (instant, doesn't require page refresh) | |
| const { isConnected: wsConnected } = useChatWebSocket({ | |
| leadId, | |
| onNewMessage: (newMessage) => { | |
| console.log('🔔 WebSocket: New message received', newMessage.id, newMessage.content?.substring(0, 50)) | |
| // Clear matching optimistic messages immediately to prevent duplication | |
| if (newMessage.sender_type === 'human' || newMessage.sender_type === 'ai') { | |
| setOptimisticMessages(prev => prev.filter(m => | |
| m.content !== newMessage.content || m.sender_type !== newMessage.sender_type | |
| )) | |
| } | |
| setRealtimeMessages(prev => { | |
| // Check if message already exists | |
| const existingIndex = prev.findIndex(m => m.id === newMessage.id) | |
| if (existingIndex >= 0) { | |
| // UPDATE existing message (e.g., add media_url after voice upload) | |
| console.log('🔄 Updating existing message with new data', newMessage.id) | |
| const updated = [...prev] | |
| updated[existingIndex] = { | |
| ...prev[existingIndex], | |
| ...newMessage, | |
| // Merge media fields if new ones are provided | |
| media_url: newMessage.media_url || prev[existingIndex].media_url, | |
| media_type: newMessage.media_type || prev[existingIndex].media_type, | |
| media_name: newMessage.media_name || prev[existingIndex].media_name, | |
| } | |
| return updated | |
| } | |
| console.log('✅ Adding new message to realtimeMessages', newMessage.id) | |
| return [...prev, newMessage] | |
| }) | |
| }, | |
| // When lead data is updated (e.g., name extracted), refresh to update AI Summary | |
| onLeadUpdated: (updatedLead) => { | |
| console.log('📋 WebSocket: Lead updated', updatedLead?.name) | |
| // 1. Direct state update for instant UI response | |
| onLeadUpdate?.(updatedLead) | |
| // 2. Fallback to full refresh to ensure all related data (lists etc) are synced | |
| onLeadRefresh?.() || onRefresh?.() | |
| } | |
| }) | |
| // ============================================================================ | |
| // Handlers | |
| // ============================================================================ | |
| const handleToggleAI = async () => { | |
| if (!leadId || isTogglingAI) return | |
| const prevValue = localAIActive | |
| const newValue = !prevValue | |
| // 1. Optimistic Update & Lockout | |
| lastInteractionTime.current = Date.now() | |
| setLocalAIActive(newValue) | |
| setIsTogglingAI(true) | |
| try { | |
| const result = await leadsApi.toggleAI(leadId, newValue) | |
| // 2. Silent refresh of lead data & conversation state | |
| if (onLeadRefresh) onLeadRefresh() | |
| if (onConversationUpdate) { | |
| // Update parent state with actual values from server | |
| onConversationUpdate({ | |
| ...conversation, | |
| human_takeover: result.human_takeover | |
| }) | |
| } | |
| } catch (error) { | |
| console.error('Error toggling AI:', error) | |
| // 3. Rollback on failure | |
| setLocalAIActive(prevValue) | |
| toast.error('Ошибка переключения режима AI') | |
| } finally { | |
| setIsTogglingAI(false) | |
| } | |
| } | |
| const handleDeleteMessage = async (messageId: string) => { | |
| if (!confirm('Удалить сообщение?')) return | |
| try { | |
| const token = localStorage.getItem('auth_token') | |
| if (!token) throw new Error('Не авторизован') | |
| const response = await fetch( | |
| `${process.env.NEXT_PUBLIC_API_URL}/api/v1/chats/messages/${messageId}`, | |
| { | |
| method: 'DELETE', | |
| headers: { 'Authorization': `Bearer ${token}` } | |
| } | |
| ) | |
| if (!response.ok) { | |
| const err = await response.json().catch(() => ({})) | |
| throw new Error(err.detail || 'Failed to delete') | |
| } | |
| // Remove from local state | |
| setOptimisticMessages(prev => prev.filter(m => m.id !== messageId)) | |
| setRealtimeMessages(prev => prev.filter(m => m.id !== messageId)) | |
| // Refresh to get updated list | |
| if (onRefresh) onRefresh() | |
| } catch (error: any) { | |
| console.error('Error deleting message:', error) | |
| alert(error.message || 'Ошибка удаления сообщения') | |
| } | |
| } | |
| const handleSendMessage = async (e: React.FormEvent, file?: File | null, audioBlob?: Blob | null) => { | |
| e.preventDefault() | |
| const textToSend = inputMessage.trim() || (audioBlob ? '🎤 Голосовое сообщение' : (file ? `📎 Файл: ${file.name}` : '')) | |
| if (!textToSend && !file && !audioBlob) return | |
| if (!leadId || !conversationId) return | |
| const tempId = Date.now().toString() | |
| const optimisticMessage: Message = { | |
| id: tempId, | |
| conversation_id: conversationId, | |
| sender_type: 'human', | |
| content: textToSend, | |
| created_at: new Date().toISOString(), | |
| // Use createObjectURL for validation/preview, ideally revoking it later | |
| media_url: file ? URL.createObjectURL(file) : (audioBlob ? URL.createObjectURL(audioBlob) : undefined), | |
| media_type: file ? file.type : (audioBlob ? 'audio/webm' : undefined), | |
| media_name: file ? file.name : (audioBlob ? 'voice.webm' : undefined) | |
| } | |
| setOptimisticMessages(prev => [...prev, optimisticMessage]) | |
| setInputMessage('') | |
| setIsSending(true) | |
| try { | |
| if (file || audioBlob) { | |
| await leadsApi.sendMessageWithMedia(leadId, conversationId, textToSend, file, audioBlob) | |
| } else { | |
| await leadsApi.sendMessage(leadId, conversationId, textToSend) | |
| } | |
| setOptimisticMessages(prev => prev.filter(m => m.id !== tempId)) | |
| } catch (error) { | |
| console.error('Error sending message:', error) | |
| setOptimisticMessages(prev => prev.filter(m => m.id !== tempId)) | |
| alert('Не удалось отправить сообщение') | |
| } finally { | |
| setIsSending(false) | |
| } | |
| } | |
| const handleTrainAI = async () => { | |
| if (!leadId || !conversationId || allMessages.length < 2) { | |
| toast.warning('Недостаточно сообщений для обучения') | |
| return | |
| } | |
| setIsTrainConfirmOpen(true) | |
| } | |
| const handleConfirmTrain = async () => { | |
| setIsTraining(true) | |
| try { | |
| const token = localStorage.getItem('auth_token') | |
| if (!token) throw new Error('Не авторизован') | |
| const response = await fetch( | |
| `${process.env.NEXT_PUBLIC_API_URL}/api/v1/ai-training/from-chat`, | |
| { | |
| method: 'POST', | |
| headers: { | |
| 'Authorization': `Bearer ${token}`, | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| conversation_id: conversationId, | |
| lead_id: leadId | |
| }) | |
| } | |
| ) | |
| if (!response.ok) { | |
| const err = await response.json().catch(() => ({})) | |
| throw new Error(err.detail || 'Failed to save training example') | |
| } | |
| toast.success('Диалог сохранён для обучения AI!') | |
| } catch (error: any) { | |
| console.error('Error training AI:', error) | |
| toast.error(error.message || 'Ошибка сохранения') | |
| } finally { | |
| setIsTraining(false) | |
| setIsTrainConfirmOpen(false) | |
| } | |
| } | |
| // ============================================================================ | |
| // Render | |
| // ============================================================================ | |
| return ( | |
| <div | |
| className="flex flex-col h-full bg-transparent font-['Inter'] relative overflow-hidden" | |
| style={{ | |
| // paddingTop: 'var(--header-height-mobile)', // REMOVED: layout.tsx already adds this | |
| // paddingBottom: 'var(--footer-height-mobile)' // REMOVED: layout.tsx already adds this | |
| }} | |
| > | |
| {/* Background Atmosphere - Synced with Main Layout */} | |
| <div className="absolute inset-0 pointer-events-none overflow-hidden -z-10"> | |
| <div className="absolute top-0 right-0 w-[60%] h-[40%] bg-cyan-500/5 blur-[120px] rounded-full" /> | |
| <div className="absolute bottom-0 left-0 w-[60%] h-[40%] bg-indigo-500/5 blur-[120px] rounded-full" /> | |
| </div> | |
| {/* Header */} | |
| <ChatHeader | |
| lead={lead} | |
| isAnalyzing={isAnalyzing} | |
| isAIActive={isAIActive} | |
| isTogglingAI={isTogglingAI} | |
| isLeadsListOpen={isLeadsListOpen} | |
| onToggleLeadsList={onToggleLeadsList} | |
| onBack={onBack} | |
| onToggleAI={handleToggleAI} | |
| onOpenMobileDrawer={onOpenMobileDrawer} | |
| onOpenBookingModal={() => setIsBookingModalOpen(true)} | |
| onTrainAI={handleTrainAI} | |
| /> | |
| {/* Messages Area */} | |
| <div | |
| className="flex-1 overflow-y-auto px-4 md:px-6 space-y-6 scrollbar-thin scrollbar-thumb-white/10 scroll-smooth" | |
| style={{ | |
| WebkitOverflowScrolling: 'touch', | |
| willChange: 'scroll-position', | |
| transform: 'translateZ(0)' | |
| }} | |
| > | |
| {/* Top spacer to show content blurring behind header when scrolling */} | |
| <div className="h-4 shrink-0" /> | |
| {isLoading ? ( | |
| <div className="flex items-center justify-center h-full"> | |
| <Loader2 className="w-8 h-8 animate-spin text-indigo-500" /> | |
| </div> | |
| ) : allMessages.length === 0 ? ( | |
| <div className="flex flex-col items-center justify-center h-[calc(100%-2rem)] text-slate-500"> | |
| <div className="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center border border-white/10 mb-4"> | |
| <Bot className="w-8 h-8 text-slate-600" /> | |
| </div> | |
| <p className="text-sm font-medium text-slate-400">История сообщений пуста</p> | |
| <p className="text-xs mt-1 text-slate-500">Начните диалог первым</p> | |
| </div> | |
| ) : ( | |
| <div className="py-4"> | |
| {allMessages.map((msg, index) => { | |
| const isMe = msg.sender_type === 'human' || msg.sender_type === 'ai' | |
| const isAI = msg.sender_type === 'ai' | |
| const prevMsg = index > 0 ? allMessages[index - 1] : null | |
| const showDate = shouldShowDateSeparator(msg, prevMsg) | |
| const isSequence = prevMsg && | |
| ((isMe && (prevMsg.sender_type === 'human' || prevMsg.sender_type === 'ai')) || | |
| (!isMe && (prevMsg.sender_type !== 'human' && prevMsg.sender_type !== 'ai'))) && | |
| !showDate | |
| return ( | |
| <MessageBubble | |
| key={msg.id} | |
| message={msg} | |
| isMe={isMe} | |
| isAI={isAI} | |
| isSequence={!!isSequence} | |
| showDate={showDate} | |
| dateLabel={getDateLabel(msg.created_at)} | |
| onDelete={handleDeleteMessage} | |
| onImageClick={(src, alt) => setViewerData({ src, alt, isOpen: true })} | |
| /> | |
| ) | |
| })} | |
| <TypingIndicator isVisible={!!isAnalyzing} /> | |
| </div> | |
| )} | |
| <div ref={messagesEndRef} className="h-4 shrink-0" /> | |
| </div> | |
| {/* Input Area */} | |
| <MessageInput | |
| value={inputMessage} | |
| onChange={setInputMessage} | |
| onSubmit={handleSendMessage} | |
| isSending={isSending} | |
| /> | |
| {/* Booking Modal */} | |
| <AnimatePresence> | |
| {isBookingModalOpen && leadId && ( | |
| <BookingModal | |
| isOpen={isBookingModalOpen} | |
| onClose={() => setIsBookingModalOpen(false)} | |
| leadId={leadId} | |
| leadName={lead?.name || undefined} | |
| /> | |
| )} | |
| </AnimatePresence> | |
| <ImageViewer | |
| src={viewerData.src} | |
| alt={viewerData.alt} | |
| isOpen={viewerData.isOpen} | |
| onClose={() => setViewerData(prev => ({ ...prev, isOpen: false }))} | |
| /> | |
| {/* Train AI Confirmation Modal */} | |
| <ConfirmModal | |
| isOpen={isTrainConfirmOpen} | |
| onClose={() => setIsTrainConfirmOpen(false)} | |
| onConfirm={handleConfirmTrain} | |
| title="Обучение AI" | |
| message="Сохранить этот диалог как пример для обучения AI? Это поможет AI лучше понимать ваших клиентов." | |
| confirmText="Обучить AI" | |
| isLoading={isTraining} | |
| /> | |
| </div> | |
| ) | |
| } | |