import React, { useRef, useState, useEffect } from 'react'; import { Upload, FileText, Clock, Check, Loader2, AlertTriangle } from 'lucide-react'; import { api } from '../lib/api'; import Constellation from './Constellation'; import EngineChain from './EngineChain'; const ACCEPTED = ['.pdf', '.txt', '.md']; const PIPELINE = [ 'Reading the document', 'Indexing passages for retrieval', 'Extracting entities & relations', 'Weaving the graph', ]; // When each pipeline step starts (ms after upload begins); the last one holds until the server replies. const STEP_TIMINGS = [0, 1200, 2800, 5200]; const formatCountdown = (seconds) => { const h = Math.floor(seconds / 3600); const m = Math.floor((seconds % 3600) / 60); const s = seconds % 60; return `${h > 0 ? `${h}h ` : ''}${m}m ${s}s`; }; const WelcomeScreen = ({ onUploadSuccess, onUploadError, autoTrigger, chain }) => { const fileInputRef = useRef(null); const hasTriggeredRef = useRef(false); // Guard against StrictMode double-fire const [isUploading, setIsUploading] = useState(false); const [isDragging, setIsDragging] = useState(false); const [fileName, setFileName] = useState(''); const [step, setStep] = useState(0); const [error, setError] = useState(null); const [retryIn, setRetryIn] = useState(0); // Auto-click upload if triggered from the "New document" button useEffect(() => { if (autoTrigger && fileInputRef.current && !hasTriggeredRef.current) { hasTriggeredRef.current = true; fileInputRef.current.click(); } }, [autoTrigger]); // Auto-countdown for rate limit errors useEffect(() => { if (!retryIn) return; const timer = setInterval(() => { setRetryIn((prev) => { if (prev <= 1) { setError(null); // Clear error when timer hits 0 return 0; } return prev - 1; }); }, 1000); return () => clearInterval(timer); }, [retryIn]); // Walk through the pipeline labels while the server works useEffect(() => { if (!isUploading) return; setStep(0); const timers = STEP_TIMINGS.slice(1).map((ms, i) => setTimeout(() => setStep(i + 1), ms)); return () => timers.forEach(clearTimeout); }, [isUploading]); const uploadFile = async (file) => { if (!file) return; const extension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase(); if (!ACCEPTED.includes(extension)) { setError(`"${file.name}" isn't supported. Use a PDF, TXT or Markdown file.`); return; } setFileName(file.name); setIsUploading(true); setError(null); setRetryIn(0); const formData = new FormData(); formData.append('file', file); try { const response = await api.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, }); if (!response.data?.nodes?.length) { throw new Error('No concepts could be extracted from this document.'); } onUploadSuccess(response.data); } catch (err) { console.error('Upload failed:', err); const errorMsg = err.response?.data?.detail || err.message || 'Failed to upload document. Please try again.'; // Check for wait time in error message const match = String(errorMsg).match(/wait (\d+)s/); if (match && match[1]) { setRetryIn(parseInt(match[1], 10)); } setError(String(errorMsg)); onUploadError?.(); } finally { setIsUploading(false); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const onDrop = (e) => { e.preventDefault(); setIsDragging(false); if (!isUploading) uploadFile(e.dataTransfer.files?.[0]); }; return (
{/* Aurora glows */}

CogniGraph

Turn any document into a 3D knowledge graph you can talk to.

{/* Upload portal */}
!isUploading && fileInputRef.current?.click()} onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && !isUploading && fileInputRef.current?.click()} onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }} onDragLeave={(e) => !e.currentTarget.contains(e.relatedTarget) && setIsDragging(false)} onDrop={onDrop} className={`portal glass mt-12 w-full max-w-xl rounded-[28px] px-6 py-8 text-left transition-transform duration-300 animate-fade-up [animation-delay:240ms] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-aurora-teal/60 sm:px-8 ${isUploading ? 'cursor-progress' : 'cursor-pointer hover:-translate-y-0.5'} ${isDragging ? 'scale-[1.02]' : ''}`} > {isUploading ? (

{fileName}

Building your knowledge graph…

    {PIPELINE.map((label, i) => { const done = i < step; const active = i === step; return (
  1. {done ? : active ? : null} {label}
  2. ); })}
) : (

{isDragging ? 'Release to map it' : 'Drop a document here'}

or browse your files

PDF · TXT · MD

)}
{error && (
{retryIn > 0 ? : }

{retryIn > 0 ? `Every AI provider is rate-limited. Retry in ${formatCountdown(retryIn)}.` : error}

)} uploadFile(e.target.files[0])} accept={ACCEPTED.join(',')} /> {/* Engine chain */}

AI fallback chain

); }; export default WelcomeScreen;