import React, { useEffect, useLayoutEffect, useMemo, useRef, useState, useCallback } from "react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import remarkMath from "remark-math"; import rehypeKatex from "rehype-katex"; import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; import { motion, AnimatePresence } from "framer-motion"; import "katex/dist/katex.min.css"; import { SendHorizontal, Sparkles, Globe, ArrowRight, ArrowUp, Plus, Menu, Copy, RefreshCw, Paperclip, Mic, X, Check, ChevronDown, Search, BookOpen, Wrench, Brain, PenLine, ClipboardList, Zap, CheckCircle2 } from "lucide-react"; import { clsx } from "clsx"; import { twMerge } from "tailwind-merge"; import ErrorBoundary from "./ErrorBoundary.jsx"; import AudioVisualizer from "./AudioVisualizer.jsx"; function cn(...inputs) { return twMerge(clsx(inputs)); } const allowedLinkProtocols = new Set(["http:", "https:", "mailto:", "tel:"]); function sanitizeLinkUrl(url) { if (typeof url !== "string" || !url) return ""; const trimmed = url.trim(); if (trimmed.startsWith("#")) return trimmed; try { const parsed = new URL(trimmed, "https://local.invalid"); if (allowedLinkProtocols.has(parsed.protocol)) return trimmed; return ""; } catch (error) { return ""; } } const markdownSchema = { ...defaultSchema, attributes: { ...defaultSchema.attributes, a: [ ...(defaultSchema.attributes?.a || []), ["target", "_blank"], ["rel", "noopener noreferrer"] ], code: [...(defaultSchema.attributes?.code || []), "className"], // Allow KaTeX elements and attributes span: [ ...(defaultSchema.attributes?.span || []), "className", "style", "aria-hidden" ], annotation: ["encoding"], semantics: [] }, tagNames: [ ...(defaultSchema.tagNames || []), "math", "annotation", "semantics", "mtext", "mn", "mo", "mi", "mspace", "mover", "munder", "munderover", "msup", "msub", "msubsup", "mfrac", "mroot", "msqrt", "mtable", "mtr", "mtd", "mlabeledtr", "mrow", "menclose", "mstyle", "mpadded", "mphantom" ] }; function MarkdownContent({ content }) { const [copiedCode, setCopiedCode] = React.useState(null); const handleCopyCode = useCallback((code, index) => { navigator.clipboard?.writeText(code); setCopiedCode(index); setTimeout(() => setCopiedCode(null), 2000); }, []); const components = useMemo(() => ({ a: (props) => ( ), pre: ({ children, ...props }) => { const codeContent = React.Children.toArray(children) .map(child => { if (React.isValidElement(child) && child.props?.children) { return typeof child.props.children === 'string' ? child.props.children : ''; } return ''; }) .join(''); const index = Math.random().toString(36).substr(2, 9); return (
            {children}
          
); }, code: ({ inline, className, children, ...props }) => { if (inline) { return ( {children} ); } return ( {children} ); }, table: ({ children, ...props }) => (
{children}
), thead: ({ children, ...props }) => ( {children} ), th: ({ children, ...props }) => ( {children} ), td: ({ children, ...props }) => ( {children} ), tr: ({ children, ...props }) => ( {children} ), ul: ({ children, ...props }) => ( ), ol: ({ children, ...props }) => (
    {children}
), li: ({ children, ordered, ...props }) => (
  • • {children}
  • ), h1: ({ children, ...props }) => (

    {children}

    ), h2: ({ children, ...props }) => (

    {children}

    ), h3: ({ children, ...props }) => (

    {children}

    ), p: ({ children, ...props }) => (

    {children}

    ), strong: ({ children, ...props }) => ( {children} ), em: ({ children, ...props }) => ( {children} ), blockquote: ({ children, ...props }) => (
    {children}
    ), hr: (props) => (
    ) }), [copiedCode, handleCopyCode]); return (
    {content || ""}
    ); } function extractSources(text) { const urls = Array.from( new Set( (text.match(/https?:\/\/[^\s)]+/g) || []).map((item) => item.replace(/[.,)\]]$/, "") ) ) ); return urls; } // Memoized Message Row Component const MessageRow = React.memo(({ msg, index, isLastAssistant, isStreaming, showSearching, activityLabels, onMessageChange, onSend, activeSession, onCopy }) => { const sources = msg.content ? extractSources(msg.content) : []; const hasActivities = Array.isArray(msg.activities) && msg.activities.length > 0; const [copied, setCopied] = React.useState(false); // Only show phase animation for the LAST assistant message AND when streaming let phase = null; let activeToolName = null; const toolActivities = hasActivities ? msg.activities.filter(a => a.startsWith("tool:")).map(a => a.slice(5)) : []; if (isStreaming && isLastAssistant && msg.role === "assistant") { if (toolActivities.length > 0) { phase = "tool"; activeToolName = toolActivities[toolActivities.length - 1]; } else if (!hasActivities) { phase = showSearching ? "searching" : "thinking"; } else if (msg.activities.includes("reasoning")) { phase = "reasoning"; } else if (msg.activities.includes("searching")) { phase = "searching"; } else if (msg.activities.includes("reading")) { phase = "reading"; } else if (msg.activities.includes("planning")) { phase = "planning"; } else if (msg.activities.includes("executing")) { phase = "executing"; } else if (msg.activities.includes("writing")) { phase = "writing"; } else { phase = "thinking"; } } const handleCopy = () => { navigator.clipboard?.writeText(msg.content); setCopied(true); setTimeout(() => setCopied(false), 2000); }; return (
    {msg.role === "user" ? "You" : "Vector"}
    {/* Activity panel — shows while streaming OR persists after streaming for completed steps */} {msg.role === "assistant" && (msg.agentSteps?.length > 0 || phase) && ( )}
    {msg.role === "assistant" ? (
    ) : (
    {msg.content}
    )} {isStreaming && isLastAssistant && msg.role === "assistant" && ( )}
    {msg.role === "assistant" && msg.content && !isStreaming && (
    {sources.length > 0 && (
    {sources.map((item, idx) => ( {new URL(item).hostname.replace('www.', '')} ))}
    )}
    )}
    ); }); export default function ChatArea({ activeSession, isStreaming, message, onMessageChange, onSend, onSelectFollowUp, activityLabels, toggleSidebar, sidebarOpen, features = { uploads: false, stt: false } }) { const scrollRef = useRef(null); const messagesEndRef = useRef(null); const userScrolledRef = useRef(false); const lastScrollTopRef = useRef(0); useEffect(() => { const el = scrollRef.current; if (!el) return; let timeoutId = null; const onScroll = () => { el.classList.add("scrolling"); if (timeoutId) clearTimeout(timeoutId); timeoutId = setTimeout(() => el.classList.remove("scrolling"), 150); // Detect if user manually scrolled up const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 50; const scrolledUp = el.scrollTop < lastScrollTopRef.current; if (scrolledUp && !isAtBottom) { userScrolledRef.current = true; } else if (isAtBottom) { userScrolledRef.current = false; } lastScrollTopRef.current = el.scrollTop; }; el.addEventListener("scroll", onScroll, { passive: true }); return () => { el.removeEventListener("scroll", onScroll); if (timeoutId) clearTimeout(timeoutId); }; }, []); // Track streaming time for "Searching..." status const [showSearching, setShowSearching] = React.useState(false); const statusTimerRef = React.useRef(null); useEffect(() => { if (isStreaming) { setShowSearching(false); if (statusTimerRef.current) clearTimeout(statusTimerRef.current); statusTimerRef.current = setTimeout(() => setShowSearching(true), 2000); return () => { if (statusTimerRef.current) clearTimeout(statusTimerRef.current); }; } else { setShowSearching(false); } }, [isStreaming]); // Smart auto-scroll: only scroll if user hasn't manually scrolled up useEffect(() => { const el = scrollRef.current; if (!el) return; // Don't auto-scroll if user has scrolled up if (userScrolledRef.current) return; // Instant scroll to bottom during streaming to prevent jarring motion // Use smooth scroll only when not streaming const scrollToBottom = () => { el.scrollTo({ top: el.scrollHeight, behavior: isStreaming ? 'instant' : 'smooth' }); }; // Use requestAnimationFrame for smoother scrolling during streaming const rafId = requestAnimationFrame(scrollToBottom); return () => cancelAnimationFrame(rafId); }, [activeSession?.messages, isStreaming]); // Reset user scroll flag when new message starts useEffect(() => { if (isStreaming) { userScrolledRef.current = false; } }, [isStreaming]); const isEmpty = !activeSession?.messages || activeSession.messages.length === 0; return (
    {/* Mobile Header */}
    Vector
    {/* Main Content Area */}
    {isEmpty ? ( /* Empty State / Hero Section */

    Where knowledge begins

    {[ "How does AI work?", "Write a Python script", "Latest tech news" ].map((suggestion, i) => ( ))}
    ) : ( /* Chat Messages */
    {activeSession?.messages.map((msg, index) => { const isLastAssistant = msg.role === "assistant" && index === (activeSession?.messages?.length || 0) - 1; return ( ); })}
    )}
    {/* Footer Input Area */} {!isEmpty && (
    )}
    ); } function SearchInput({ value, onChange, onSend, disabled, isHero = false, features = {} }) { const fileInputRef = React.useRef(null); const textareaRef = React.useRef(null); const textareaScrollTimeoutRef = React.useRef(null); const [isRecording, setIsRecording] = React.useState(false); const [selectedFiles, setSelectedFiles] = React.useState([]); const [audioStream, setAudioStream] = React.useState(null); const [interimTranscript, setInterimTranscript] = React.useState(""); const recognitionRef = React.useRef(null); const isRecordingRef = React.useRef(false); // Ref to avoid stale closure in onend const finalTranscriptRef = React.useRef(""); // Ref to track accumulated transcript const maxTextareaHeight = isHero ? 100 : 120; const minTextareaHeight = 44; // Check for Speech Recognition support const SpeechRecognition = typeof window !== 'undefined' ? (window.SpeechRecognition || window.webkitSpeechRecognition) : null; useLayoutEffect(() => { const el = textareaRef.current; if (!el) return; el.style.height = "0px"; const unclamped = el.scrollHeight; const next = Math.max(minTextareaHeight, Math.min(unclamped, maxTextareaHeight)); el.style.height = `${next}px`; el.style.overflowY = unclamped > maxTextareaHeight ? "auto" : "hidden"; }, [value, isHero, maxTextareaHeight, minTextareaHeight]); const handleSend = () => { if ((value.trim() || selectedFiles.length > 0) && !disabled) { onSend(selectedFiles); setSelectedFiles([]); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const handleKeyDown = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; const handleTextareaScroll = (e) => { const el = e.currentTarget; el.classList.add("scrolling"); if (textareaScrollTimeoutRef.current) clearTimeout(textareaScrollTimeoutRef.current); textareaScrollTimeoutRef.current = setTimeout(() => { el.classList.remove("scrolling"); }, 150); }; const handleFileSelect = (e) => { const files = Array.from(e.target.files || []); if (files.length > 0) { setSelectedFiles(prev => [...prev, ...files]); } if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const removeFile = (index) => { setSelectedFiles(prev => prev.filter((_, i) => i !== index)); }; const handleMicClick = async () => { if (isRecording) { // Stop recording isRecordingRef.current = false; if (recognitionRef.current) { recognitionRef.current.stop(); } if (audioStream) { audioStream.getTracks().forEach(track => track.stop()); setAudioStream(null); } setIsRecording(false); setInterimTranscript(""); } else { // Check browser support if (!SpeechRecognition) { console.error('Speech Recognition not supported in this browser'); alert('Speech-to-text is not supported in this browser. Please use Chrome, Edge, or Safari.'); return; } try { // Get audio stream for visualizer const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); setAudioStream(stream); // Set up Speech Recognition const recognition = new SpeechRecognition(); recognitionRef.current = recognition; recognition.continuous = true; recognition.interimResults = true; recognition.lang = 'en-US'; // Use ref to track accumulated text (avoids stale closure issues) finalTranscriptRef.current = value; recognition.onresult = (event) => { let interim = ''; for (let i = event.resultIndex; i < event.results.length; i++) { const transcript = event.results[i][0].transcript; if (event.results[i].isFinal) { finalTranscriptRef.current = (finalTranscriptRef.current ? finalTranscriptRef.current + ' ' : '') + transcript; onChange(finalTranscriptRef.current); } else { interim += transcript; } } setInterimTranscript(interim); }; recognition.onerror = (event) => { console.error('Speech recognition error:', event.error); isRecordingRef.current = false; if (audioStream) { audioStream.getTracks().forEach(track => track.stop()); setAudioStream(null); } setIsRecording(false); setInterimTranscript(""); }; recognition.onend = () => { // Restart if still in recording mode — use ref to get current value if (recognitionRef.current && isRecordingRef.current) { try { recognitionRef.current.start(); } catch (e) { // Ignore — may fail if already started } } }; recognition.start(); isRecordingRef.current = true; setIsRecording(true); } catch (err) { console.error('Microphone access denied:', err); } } }; // Cleanup on unmount React.useEffect(() => { return () => { if (recognitionRef.current) { try { recognitionRef.current.stop(); } catch (e) { } } if (audioStream) { audioStream.getTracks().forEach(track => track.stop()); } }; }, [audioStream]); return (
    {/* File attachments preview */} {selectedFiles.length > 0 && (
    {selectedFiles.map((file, index) => (
    {file.name}
    ))}
    )} {/* Main floating input bar */}
    {/* Plus/Attach button */} {/* Audio Visualizer or Text input */} {isRecording && audioStream ? (
    {/* Show interim transcript as user speaks */} {interimTranscript && (
    {interimTranscript}...
    )} {!interimTranscript && value && (
    "{value.slice(-50)}{value.length > 50 ? '...' : ''}"
    )} {!interimTranscript && !value && (
    Listening... speak now
    )} {/* Cancel and Done buttons */}
    ) : (