transformation-ui / src /components /ProcessingStatus.tsx
Rajavignesh
Updating processing status for chat look
5fa54cc
Raw History Blame Contribute Delete
67.4 kB
import React, { useState, useRef, useEffect, useCallback } from 'react'; import { Box, Typography, Card, CardContent, CircularProgress, Chip, IconButton, Divider, Alert, LinearProgress, Dialog, DialogTitle, DialogContent, DialogActions, Tooltip, Button, Accordion, AccordionSummary, AccordionDetails, TextField, Avatar, InputAdornment, Paper, } from '@mui/material'; import { ExpandMore as ExpandMoreIcon, Refresh as RefreshIcon, Code as CodeIcon, UnfoldMore as ExpandAllIcon, UnfoldLess as CollapseAllIcon, ContentCopy as CopyIcon, Download as DownloadIcon, PlayArrow as EnableScrollIcon, Pause as DisableScrollIcon, Send as SendIcon, SmartToy as BotIcon, Person as PersonIcon, } from '@mui/icons-material'; import { API_BASE_URI, WEBSOCKET_BASE_URI } from '../constants'; interface ProcessingMessage { type?: string; message: string; progress_percentage?: number; request_id?: string; timestamp: string; stats?: { status: string; number_of_records: number; request_id: string; record_count: number; }; error?: string; isUser?: boolean; } interface PreviewItem { id: string; type: 'json' | 'curl' | 'pdf'; content: string; timestamp: string; isMinified: boolean; pdfUrl?: string; filename?: string; } interface ProcessingStatusProps { fileType: 'Shell' | 'MSAG' | 'Dx Supplementary'; folderPath: string; environment: string; inputType: 'file' | 'json'; json_content?: string; isLoading: boolean; onLoadingChange: (loading: boolean) => void; onStatusChange: (status: 'idle' | 'loading' | 'success' | 'error') => void; triggerProcessing?: boolean; onProcessingComplete?: () => void; } // TypewriterText component for typewriting animation const TypewriterText: React.FC<{ text: string; speed?: number; onComplete?: () => void; isJson?: boolean; isCurl?: boolean; onJsonClick?: () => void; onCurlClick?: () => void; }> = ({ text, speed = 20, onComplete, isJson = false, isCurl = false, onJsonClick, onCurlClick }) => { const [displayText, setDisplayText] = useState(''); const [isComplete, setIsComplete] = useState(false); // Check if this is a Phase or Step heading const isPhaseHeading = text.startsWith("Phase: "); const isStepHeading = text.startsWith("Step: "); useEffect(() => { if (text.length === 0) { setIsComplete(true); onComplete?.(); return; } let index = 0; const timer = setInterval(() => { if (index < text.length) { setDisplayText(text.slice(0, index + 1)); index++; } else { setIsComplete(true); onComplete?.(); clearInterval(timer); } }, speed); return () => clearInterval(timer); }, [text, speed, onComplete]); if (isJson) { const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="body2" sx={{ flex: 1 }}> JSON: {preview} </Typography> {isComplete && ( <Tooltip title="View JSON"> <IconButton size="small" onClick={onJsonClick} sx={{ color: 'primary.main', '&:hover': { backgroundColor: 'primary.light', color: 'primary.contrastText', } }} > <CodeIcon fontSize="small" /> </IconButton> </Tooltip> )} </Box> ); } if (isCurl) { const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="body2" sx={{ flex: 1 }}> CURL: {preview} </Typography> {isComplete && ( <Tooltip title="View CURL Command"> <IconButton size="small" onClick={onCurlClick} sx={{ color: 'warning.main', '&:hover': { backgroundColor: 'warning.light', color: 'warning.contrastText', } }} > <CodeIcon fontSize="small" /> </IconButton> </Tooltip> )} </Box> ); } // Render Phase headings with H1 styling during animation if (isPhaseHeading) { return ( <Typography variant="h6" sx={{ fontWeight: 700, color: 'primary.main', fontSize: '1.1rem', mt: 1, mb: 0.5, borderBottom: '2px solid', borderColor: 'primary.main', paddingBottom: 0.5, textTransform: 'uppercase', letterSpacing: '0.5px' }} > {displayText.replace(/^Phase:\s*/, '')} {!isComplete && ( <Box component="span" sx={{ display: 'inline-block', width: '2px', height: '1em', backgroundColor: 'primary.main', marginLeft: '1px', animation: 'blink 1s infinite', '@keyframes blink': { '0%, 50%': { opacity: 1 }, '51%, 100%': { opacity: 0 }, }, }} /> )} </Typography> ); } // Render Step headings with sub-heading styling during animation if (isStepHeading) { return ( <Typography variant="subtitle1" sx={{ fontWeight: 600, color: 'secondary.main', fontSize: '0.95rem', mt: 0.5, mb: 0.25, paddingLeft: 2, borderLeft: '3px solid', borderColor: 'secondary.main' }} > {displayText.replace(/^Step:\s*/, '')} {!isComplete && ( <Box component="span" sx={{ display: 'inline-block', width: '2px', height: '1em', backgroundColor: 'secondary.main', marginLeft: '1px', animation: 'blink 1s infinite', '@keyframes blink': { '0%, 50%': { opacity: 1 }, '51%, 100%': { opacity: 0 }, }, }} /> )} </Typography> ); } return ( <Typography variant="body2"> {displayText} {!isComplete && ( <Box component="span" sx={{ display: 'inline-block', width: '2px', height: '1em', backgroundColor: 'primary.main', marginLeft: '1px', animation: 'blink 1s infinite', '@keyframes blink': { '0%, 50%': { opacity: 1 }, '51%, 100%': { opacity: 0 }, }, }} /> )} </Typography> ); }; const ProcessingStatus: React.FC<ProcessingStatusProps> = ({ fileType, folderPath, environment, inputType, json_content, isLoading, onLoadingChange, onStatusChange, triggerProcessing, onProcessingComplete }) => { const [loadStatus, setLoadStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle'); const [accordionExpanded, setAccordionExpanded] = useState(true); const [processingMessages, setProcessingMessages] = useState<ProcessingMessage[]>([]); const [currentProgress, setCurrentProgress] = useState(0); const [finalStats, setFinalStats] = useState<ProcessingMessage['stats'] | null>(null); const [connectionError, setConnectionError] = useState<string | null>(null); const [isConnecting, setIsConnecting] = useState(false); const [hasConnected, setHasConnected] = useState(false); const wsRef = useRef<WebSocket | null>(null); // Refs for autoscroll functionality - target the scrollable Box containers const loadingLogRef = useRef<HTMLDivElement | null>(null); const completeLogRef = useRef<HTMLDivElement | null>(null); const errorLogRef = useRef<HTMLDivElement | null>(null); // JSON Dialog state const [jsonDialogOpen, setJsonDialogOpen] = useState(false); const [selectedJsonContent, setSelectedJsonContent] = useState<string>(''); const [isJsonExpanded, setIsJsonExpanded] = useState(true); // Curl Dialog state const [curlDialogOpen, setCurlDialogOpen] = useState(false); const [selectedCurlContent, setSelectedCurlContent] = useState<string>(''); const [isCurlExpanded, setIsCurlExpanded] = useState(true); // Download state const [isDownloading, setIsDownloading] = useState(false); // State for typewriting animation const [completedMessages, setCompletedMessages] = useState<Set<number>>(new Set()); // State for delayed progress and completion updates const [pendingProgressUpdate, setPendingProgressUpdate] = useState<number | null>(null); const [pendingCompletionData, setPendingCompletionData] = useState<{ stats: ProcessingMessage['stats']; progress: number; } | null>(null); // State to track current phase and step const [currentPhase, setCurrentPhase] = useState<string>(''); const [currentStep, setCurrentStep] = useState<string>(''); // State for auto-scroll functionality const [autoScrollEnabled, setAutoScrollEnabled] = useState<boolean>(true); // Ref for the main scrollable container const mainContainerRef = useRef<HTMLDivElement | null>(null); // State for preview items (JSON/CURL/PDF) const [previewItems, setPreviewItems] = useState<PreviewItem[]>([]); const [activePreviewId, setActivePreviewId] = useState<string | null>(null); // State for customized processing tooltip const [processingTooltip, setProcessingTooltip] = useState<'Processing' | 'Thinking' | 'Validating'>('Processing'); const [isThinkingMode, setIsThinkingMode] = useState(false); const [isValidatingMode, setIsValidatingMode] = useState(false); // Chat interface state const [userInput, setUserInput] = useState(''); const [hasUserInteracted, setHasUserInteracted] = useState(false); const [isInputDisabled, setIsInputDisabled] = useState(false); // State for JSON delay timer const [jsonDelayTimer, setJsonDelayTimer] = useState<NodeJS.Timeout | null>(null); // Helper function to add preview item (moved before loadPdfPreview) const addPreviewItem = useCallback((type: 'json' | 'curl' | 'pdf', content: string, pdfUrl?: string, filename?: string) => { const newItem: PreviewItem = { id: `${type}-${Date.now()}-${Math.random()}`, type, content, timestamp: new Date().toLocaleTimeString(), isMinified: false, pdfUrl, filename }; setPreviewItems(prev => { // Minify all existing items and add new item at the beginning (top) const minifiedItems = prev.map(item => ({ ...item, isMinified: true })); return [newItem, ...minifiedItems]; }); setActivePreviewId(newItem.id); }, []); // Function to load PDF from API endpoint (moved before useEffect) const loadPdfPreview = useCallback(async (filename: string) => { try { const response = await fetch(`http://localhost:3000/${filename}`); if (!response.ok) { console.error(`Failed to load PDF: ${response.statusText}`); return; } // Create blob URL for PDF preview const blob = await response.blob(); const pdfUrl = window.URL.createObjectURL(blob); // Add PDF to preview items addPreviewItem('pdf', filename, pdfUrl, filename); } catch (error) { console.error('PDF loading failed:', error); } }, [addPreviewItem]); // Effect to handle processing trigger - allow reconnection for new processing requests useEffect(() => { // Only connect if trigger is true, we're not already connecting, AND user has interacted (typed input) if (!triggerProcessing || isConnecting || !hasUserInteracted) { return; } // Validate required parameters if (!environment || (inputType === 'file' && !folderPath)) { console.warn('Missing required parameters for WebSocket connection'); return; } const connectWebSocket = () => { // Close any existing connection first if (wsRef.current) { wsRef.current.close(); wsRef.current = null; } setIsConnecting(true); try { const ws = new WebSocket(`${WEBSOCKET_BASE_URI}/ws`); wsRef.current = ws; ws.onopen = () => { console.log('WebSocket connected'); setConnectionError(null); setHasConnected(true); setIsConnecting(false); // Send the initial processing request with input_type, environment and filetype const request = { input_type: inputType, environment: environment, filetype: fileType, ...(inputType === 'file' && { foldername: folderPath }) }; ws.send(JSON.stringify(request)); // If input type is json, send the json content as a separate message if (inputType === 'json' && json_content) { ws.send(JSON.stringify({ json: json_content })); } }; ws.onmessage = (event) => { try { const data: ProcessingMessage = JSON.parse(event.data); if (data.error) { setConnectionError(data.error); setLoadStatus('error'); onLoadingChange(false); onStatusChange('error'); return; } // Check for Display messages and load PDF preview if (isDisplayMessage(data.message)) { const filename = extractFilename(data.message); loadPdfPreview(filename); // Don't add Display messages to the processing messages log return; } // Special handling for JSON messages during "Thinking" mode if (isThinkingMode && isValidJSON(data.message)) { // Clear any existing timer if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); } // Set a 1.5 second delay before displaying the message and changing tooltip const timer = setTimeout(() => { // Add the delayed message to processing messages setProcessingMessages(prev => [...prev, data]); // Change tooltip from "Thinking" to "Processing" setIsThinkingMode(false); setProcessingTooltip('Processing'); // Clear the timer setJsonDelayTimer(null); // Handle progress updates if (data.progress_percentage !== undefined) { setPendingProgressUpdate(data.progress_percentage); } }, 1500); // 1.5 seconds delay setJsonDelayTimer(timer); return; // Don't process this message immediately } // Track current phase and step from messages if (data.message.startsWith("Phase: ")) { setCurrentPhase(data.message.replace(/^Phase:\s*/, '')); setCurrentStep(''); // Reset step when new phase starts } else if (data.message.startsWith("Step: ")) { setCurrentStep(data.message.replace(/^Step:\s*/, '')); } // Add message to processing messages (normal flow) setProcessingMessages(prev => [...prev, data]); // Store progress updates for later application (don't apply immediately) if (data.progress_percentage !== undefined) { setPendingProgressUpdate(data.progress_percentage); } // Store completion data ONLY for very specific final completion indicators if (data.type === 'completion' && data.stats) { // This is an explicit completion message with stats from the server setPendingCompletionData({ stats: data.stats, progress: 100 }); } else if (data.message.toLowerCase().trim() === 'data processing completed' || (data.message.toLowerCase().includes('data processing completed') && !data.message.toLowerCase().includes('step') && !data.message.toLowerCase().includes('phase') && data.message.length < 50)) { // Ensure it's a short final message, not a detailed step // Only trigger on the final summary "Data processing Completed" message let recordCount = 0; const recordMatch = data.message.match(/(\d+)\s+records?\s+found/i); if (recordMatch) { recordCount = parseInt(recordMatch[1]); } const stats = { status: 'Complete', number_of_records: recordCount, record_count: recordCount, request_id: Date.now().toString() }; setPendingCompletionData({ stats: stats, progress: 100 }); } } catch (error) { console.error('Error parsing WebSocket message:', error); setConnectionError('Failed to parse server response'); setLoadStatus('error'); onLoadingChange(false); onStatusChange('error'); } }; ws.onerror = (error) => { console.error('WebSocket error:', error); setConnectionError('Failed to connect to processing server. Make sure the backend is running on port 8000.'); setLoadStatus('error'); setIsConnecting(false); onLoadingChange(false); onStatusChange('error'); }; ws.onclose = () => { console.log('WebSocket disconnected'); wsRef.current = null; setIsConnecting(false); }; } catch (error) { console.error('Failed to create WebSocket connection:', error); setConnectionError('Failed to initialize WebSocket connection'); setLoadStatus('error'); setIsConnecting(false); onLoadingChange(false); onStatusChange('error'); } }; // Initialize processing state setLoadStatus('loading'); setAccordionExpanded(true); setProcessingMessages([]); setCurrentProgress(0); setFinalStats(null); setConnectionError(null); setCompletedMessages(new Set()); setCurrentPhase(''); setCurrentStep(''); setHasConnected(false); // Reset connection state for new processing session onLoadingChange(true); onStatusChange('loading'); // Start the connection connectWebSocket(); }, [triggerProcessing, isConnecting, hasConnected, environment, inputType, folderPath, json_content, fileType, onLoadingChange, onStatusChange, isThinkingMode, jsonDelayTimer, loadPdfPreview, hasUserInteracted]); // Include necessary dependencies // Cleanup WebSocket on component unmount useEffect(() => { return () => { if (wsRef.current) { wsRef.current.close(); } // Clear any pending JSON delay timer to prevent memory leaks if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); } }; }, [jsonDelayTimer]); // Effect to handle delayed progress and completion updates useEffect(() => { const lastMessageIndex = processingMessages.length - 1; const isLastMessageComplete = completedMessages.has(lastMessageIndex); const allMessagesComplete = processingMessages.length > 0 && processingMessages.every((_, index) => completedMessages.has(index)); // Only apply updates if ALL messages have completed their animations if (allMessagesComplete && processingMessages.length > 0) { // Apply pending progress update if (pendingProgressUpdate !== null) { setCurrentProgress(pendingProgressUpdate); setPendingProgressUpdate(null); } // Apply pending completion update only after ALL messages are done if (pendingCompletionData) { setFinalStats(pendingCompletionData.stats); setLoadStatus('success'); onLoadingChange(false); onStatusChange('success'); setCurrentProgress(pendingCompletionData.progress); setPendingCompletionData(null); onProcessingComplete?.(); } } else if (isLastMessageComplete && pendingProgressUpdate !== null && !pendingCompletionData) { // Apply progress updates for non-completion messages immediately after they finish setCurrentProgress(pendingProgressUpdate); setPendingProgressUpdate(null); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [completedMessages, processingMessages.length, pendingProgressUpdate, pendingCompletionData, onLoadingChange, onStatusChange, onProcessingComplete]); // Autoscroll functionality - scroll to bottom when new messages are added useEffect(() => { if (processingMessages.length > 0 && autoScrollEnabled) { // Scroll individual log containers to bottom if (loadingLogRef.current && loadStatus === 'loading') { loadingLogRef.current.scrollTop = loadingLogRef.current.scrollHeight; } if (completeLogRef.current && loadStatus === 'success') { completeLogRef.current.scrollTop = completeLogRef.current.scrollHeight; } if (errorLogRef.current && loadStatus === 'error') { errorLogRef.current.scrollTop = errorLogRef.current.scrollHeight; } // Auto-scroll the main container to bottom to show latest content if (mainContainerRef.current) { mainContainerRef.current.scrollTop = mainContainerRef.current.scrollHeight; } } }, [processingMessages, loadStatus, autoScrollEnabled]); // Helper function to detect if a string is valid JSON const isValidJSON = (str: string): boolean => { try { JSON.parse(str); return true; } catch (e) { return false; } }; // Helper function to format JSON with proper indentation const formatJSON = (jsonString: string, indent: number = 2): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed, null, indent); } catch (e) { return jsonString; } }; // Helper function to minify JSON const minifyJSON = (jsonString: string): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed); } catch (e) { return jsonString; } }; // Helper function to detect if a string is a curl command const isCurlCommand = (str: string): boolean => { return str.trim().startsWith('curl'); }; // Helper function to format curl command with proper indentation const formatCurl = (curlString: string): string => { // Basic curl formatting - split on common flags and add line breaks return curlString .replace(/\s+/g, ' ') // Normalize whitespace .replace(/\s-([a-zA-Z])/g, ' \\\n -$1') // Add line breaks before flags .replace(/\s(https?:\/\/[^\s]+)/g, ' \\\n $1') // Add line breaks before URLs .replace(/\s--([a-zA-Z-]+)/g, ' \\\n --$1') // Add line breaks before long flags .trim(); }; // Helper function to minify curl command const minifyCurl = (curlString: string): string => { return curlString.replace(/\s+/g, ' ').trim(); }; // Helper function to detect if a string is a Display message const isDisplayMessage = (str: string): boolean => { return str.startsWith('Display: '); }; // Helper function to extract filename from Display message const extractFilename = (displayMessage: string): string => { return displayMessage.replace(/^Display:\s*/, '').trim(); }; // Helper function to detect JSON content const detectJsonContent = (text: string): string | null => { try { // Look for JSON-like patterns const jsonMatch = text.match(/\{[\s\S]*\}/); if (jsonMatch) { const potentialJson = jsonMatch[0]; JSON.parse(potentialJson); // Validate it's valid JSON return potentialJson; } } catch (e) { // Not valid JSON } return null; }; // Helper function to detect CURL content const detectCurlContent = (text: string): string | null => { const curlMatch = text.match(/curl\s+[\s\S]*?(?=\n\n|\n"|$)/); return curlMatch ? curlMatch[0] : null; }; // Helper function to format JSON for preview const formatJsonPreview = (jsonString: string): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed, null, 2); } catch (e) { return jsonString; } }; // Helper function to format CURL for preview const formatCurlPreview = (curlString: string): string => { return curlString .replace(/\s+--/g, ' \\\n --') .replace(/\s+-([a-zA-Z])/g, ' \\\n -$1') .replace(/\s+(https?:\/\/[^\s]+)/g, ' \\\n $1') .trim(); }; // Ref for the preview container to handle auto-scroll to top const previewContainerRef = useRef<HTMLDivElement | null>(null); // Auto-scroll to top when new preview items are added useEffect(() => { if (previewItems.length > 0 && previewContainerRef.current) { // Scroll to top to show the latest item previewContainerRef.current.scrollTop = 0; } }, [previewItems.length]); // Function to toggle preview item minification const togglePreviewMinification = (id: string) => { setPreviewItems(prev => prev.map(item => item.id === id ? { ...item, isMinified: !item.isMinified } : item ) ); setActivePreviewId(id); }; // Function to handle JSON dialog const handleOpenJsonDialog = (jsonContent: string) => { setSelectedJsonContent(jsonContent); setJsonDialogOpen(true); setIsJsonExpanded(true); }; const handleCloseJsonDialog = () => { setJsonDialogOpen(false); setSelectedJsonContent(''); }; const handleCopyJson = () => { navigator.clipboard.writeText(selectedJsonContent); }; // Function to handle curl dialog const handleOpenCurlDialog = (curlContent: string) => { setSelectedCurlContent(curlContent); setCurlDialogOpen(true); setIsCurlExpanded(true); }; const handleCloseCurlDialog = () => { setCurlDialogOpen(false); setSelectedCurlContent(''); }; const handleCopyCurl = () => { navigator.clipboard.writeText(selectedCurlContent); }; // Function to handle Excel download const handleDownload = async (requestId: string) => { setIsDownloading(true); try { const response = await fetch(`${API_BASE_URI}/${requestId}/download`); if (!response.ok) { throw new Error(`Download failed: ${response.statusText}`); } // Get the filename from the response headers or use a default const contentDisposition = response.headers.get('content-disposition'); let filename = `Benefit_Agent_Report.xlsx`; if (contentDisposition) { const filenameMatch = contentDisposition.match(/filename="?(.+)"?/); if (filenameMatch) { filename = filenameMatch[1]; } } // Convert response to blob and download const blob = await response.blob(); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); // Cleanup document.body.removeChild(link); window.URL.revokeObjectURL(url); } catch (error) { console.error('Download failed:', error); setConnectionError(`Failed to download Excel: ${error instanceof Error ? error.message : 'Unknown error'}`); } finally { setIsDownloading(false); } }; // Function to render message content with typewriting animation const renderMessageContent = (message: string, index: number) => { const isLastMessage = index === processingMessages.length - 1; const shouldAnimate = isLastMessage && loadStatus === 'loading' && !completedMessages.has(index); const handleAnimationComplete = () => { setCompletedMessages(prev => new Set([...Array.from(prev), index])); // After animation completes, check for JSON/CURL content const jsonContent = detectJsonContent(message); if (jsonContent) { addPreviewItem('json', jsonContent); } const curlContent = detectCurlContent(message); if (curlContent) { addPreviewItem('curl', curlContent); } }; // Check if message is a Phase heading const isPhaseHeading = message.startsWith("Phase: "); // Check if message is a Step sub-heading const isStepHeading = message.startsWith("Step: "); // For non-animated messages, check for JSON/CURL content immediately if (!shouldAnimate && !completedMessages.has(index)) { const jsonContent = detectJsonContent(message); if (jsonContent) { addPreviewItem('json', jsonContent); } const curlContent = detectCurlContent(message); if (curlContent) { addPreviewItem('curl', curlContent); } setCompletedMessages(prev => new Set([...Array.from(prev), index])); } if (isValidJSON(message)) { if (shouldAnimate) { return ( <TypewriterText text={message} onComplete={handleAnimationComplete} isJson={true} onJsonClick={() => handleOpenJsonDialog(message)} /> ); } // Static display for completed messages const preview = message.length > 50 ? message.substring(0, 50) + '...' : message; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="body2" sx={{ flex: 1 }}> JSON: {preview} </Typography> <Tooltip title="View JSON"> <IconButton size="small" onClick={() => handleOpenJsonDialog(message)} sx={{ color: 'primary.main', '&:hover': { backgroundColor: 'primary.light', color: 'primary.contrastText', } }} > <CodeIcon fontSize="small" /> </IconButton> </Tooltip> </Box> ); } if (isCurlCommand(message)) { if (shouldAnimate) { return ( <TypewriterText text={message} onComplete={handleAnimationComplete} isCurl={true} onCurlClick={() => handleOpenCurlDialog(message)} /> ); } // Static display for completed messages const preview = message.length > 50 ? message.substring(0, 50) + '...' : message; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="body2" sx={{ flex: 1 }}> CURL: {preview} </Typography> <Tooltip title="View CURL Command"> <IconButton size="small" onClick={() => handleOpenCurlDialog(message)} sx={{ color: 'warning.main', '&:hover': { backgroundColor: 'warning.light', color: 'warning.contrastText', } }} > <CodeIcon fontSize="small" /> </IconButton> </Tooltip> </Box> ); } if (shouldAnimate) { return ( <TypewriterText text={message} onComplete={handleAnimationComplete} /> ); } // Render Phase headings with H1 styling if (isPhaseHeading) { return ( <Typography variant="h6" sx={{ fontWeight: 700, color: 'primary.main', fontSize: '1.1rem', mt: 1, mb: 0.5, borderBottom: '2px solid', borderColor: 'primary.main', paddingBottom: 0.5, textTransform: 'uppercase', letterSpacing: '0.5px' }} > {message.replace(/^Phase:\s*/, '')} </Typography> ); } // Render Step headings with sub-heading styling if (isStepHeading) { return ( <Typography variant="subtitle1" sx={{ fontWeight: 600, color: 'secondary.main', fontSize: '0.95rem', mt: 0.5, mb: 0.25, paddingLeft: 2, borderLeft: '3px solid', borderColor: 'secondary.main' }} > {message.replace(/^Step:\s*/, '')} </Typography> ); } return ( <Typography variant="body2"> {message} </Typography> ); }; // Effect to monitor processing messages and update tooltip state useEffect(() => { if (processingMessages.length === 0) { setProcessingTooltip('Processing'); setIsThinkingMode(false); setIsValidatingMode(false); return; } const latestMessage = processingMessages[processingMessages.length - 1]; const messageText = latestMessage.message.toLowerCase(); // Check for "Quality Assurance and Finalization" heading or status if (messageText.includes('quality assurance and finalization') || messageText.includes('quality assurance') || messageText.includes('finalization')) { setIsValidatingMode(true); setIsThinkingMode(false); setProcessingTooltip('Validating'); return; } // If we're in validating mode, stay in validating mode until completion if (isValidatingMode && !messageText.includes('complete')) { setProcessingTooltip('Validating'); return; } // Check for curl message - switch to "Thinking" if (isCurlCommand(latestMessage.message)) { setIsThinkingMode(true); setIsValidatingMode(false); setProcessingTooltip('Thinking'); return; } // Check for JSON message - revert to "Processing" from "Thinking" if (isThinkingMode && isValidJSON(latestMessage.message)) { setIsThinkingMode(false); setProcessingTooltip('Processing'); return; } // Default state - if not in special modes, show "Processing" if (!isThinkingMode && !isValidatingMode) { setProcessingTooltip('Processing'); } }, [processingMessages, isThinkingMode, isValidatingMode]); const clearData = () => { // Close WebSocket connection if open if (wsRef.current) { wsRef.current.close(); wsRef.current = null; // Clear the reference } // Clear any pending JSON delay timer if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); setJsonDelayTimer(null); } setLoadStatus('idle'); setProcessingMessages([]); setCurrentProgress(0); setFinalStats(null); setConnectionError(null); setIsDownloading(false); setCompletedMessages(new Set()); setCurrentPhase(''); setCurrentStep(''); setPreviewItems([]); setActivePreviewId(null); // Clear processing state setProcessingTooltip('Processing'); setIsThinkingMode(false); setIsValidatingMode(false); // Reset connection state completely setIsConnecting(false); setHasConnected(false); // Reset chat state setHasUserInteracted(false); setIsInputDisabled(false); setUserInput(''); onLoadingChange(false); onStatusChange('idle'); }; // Send chat message handler const handleSendMessage = () => { if (!userInput.trim()) return; // Add user message to the processing log const userMessage: ProcessingMessage = { message: userInput, timestamp: new Date().toLocaleTimeString(), isUser: true }; setProcessingMessages(prev => [...prev, userMessage]); setHasUserInteracted(true); setUserInput(''); setIsInputDisabled(true); // Disable input after sending, re-enable if reset }; // Key press handler for input const handleInputKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSendMessage(); } }; return ( <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}> {/* Processing Status Accordion */} <Accordion expanded={accordionExpanded} onChange={() => setAccordionExpanded(!accordionExpanded)} sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden', '& .MuiAccordionDetails-root': { flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: 0, maxHeight: 'calc(100vh - 220px)' } }} > <AccordionSummary expandIcon={<ExpandMoreIcon />} sx={{ backgroundColor: 'grey.50', '& .MuiAccordionSummary-content': { alignItems: 'center', }, }} > <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}> <Box sx={{ display: 'flex', alignItems: 'center' }}> <Typography variant="h6" sx={{ fontWeight: 600 }}> Processing Status {loadStatus === 'loading' && ( <Tooltip title={processingTooltip}> <Chip label={processingTooltip} color="primary" size="small" sx={{ ml: 2 }} /> </Tooltip> )} {loadStatus === 'success' && ( <Chip label="Completed" color="success" size="small" sx={{ ml: 2 }} /> )} {loadStatus === 'error' && ( <Chip label="Error" color="error" size="small" sx={{ ml: 2 }} /> )} </Typography> </Box> {/* Auto-scroll toggle button */} <Tooltip title={autoScrollEnabled ? "Disable auto-scroll" : "Enable auto-scroll"}> <IconButton size="small" onClick={(e) => { e.stopPropagation(); setAutoScrollEnabled(!autoScrollEnabled); }} sx={{ color: autoScrollEnabled ? 'primary.main' : 'text.secondary', '&:hover': { backgroundColor: autoScrollEnabled ? 'primary.light' : 'grey.200', }, }} > {autoScrollEnabled ? ( <DisableScrollIcon sx={{ fontSize: '1.2rem' }} /> ) : ( <EnableScrollIcon sx={{ fontSize: '1.2rem' }} /> )} </IconButton> </Tooltip> </Box> </AccordionSummary> <AccordionDetails sx={{ p: 3, flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: 0 }}> {connectionError && ( <Alert severity="error" sx={{ mb: 2, flexShrink: 0 }}> {connectionError} </Alert> )} {loadStatus === 'idle' && ( <Typography color="text.secondary"> Configure processing settings and click Load to begin processing. </Typography> )} {loadStatus === 'loading' && ( <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {/* Progress Bar */} <Box sx={{ mb: 3, flexShrink: 0 }}> <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}> <Typography variant="body2" color="text.secondary"> Processing Progress </Typography> <Typography variant="body2" color="text.secondary"> {currentProgress.toFixed(1)}% </Typography> </Box> <LinearProgress variant="determinate" value={currentProgress} sx={{ height: 6, borderRadius: 3, backgroundColor: 'grey.200', '& .MuiLinearProgress-bar': { borderRadius: 3, }, }} /> {currentPhase && ( <Typography variant="caption" color="primary.main" sx={{ mt: 1, display: 'block' }}> Current Phase: {currentPhase} {currentStep && ` - ${currentStep}`} </Typography> )} </Box> {/* Messages Container with Two Columns */} <Box sx={{ flex: 1, display: 'flex', gap: 2, overflow: 'hidden', minHeight: 0 }}> {/* Preview Items Column */} {previewItems.length > 0 && ( <Box sx={{ width: '300px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}> Preview Output </Typography> <Box ref={previewContainerRef} sx={{ flex: 1, overflow: 'auto', backgroundColor: 'grey.50', borderRadius: 1, p: 1, border: '1px solid', borderColor: 'grey.200' }} > {previewItems.map((item) => ( <Card key={item.id} sx={{ mb: 1, cursor: 'pointer', border: item.id === activePreviewId ? '2px solid' : '1px solid', borderColor: item.id === activePreviewId ? 'primary.main' : 'grey.300', transition: 'all 0.2s ease-in-out', '&:hover': { borderColor: 'primary.main', transform: 'translateY(-1px)', boxShadow: 2, } }} onClick={() => togglePreviewMinification(item.id)} > <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}> <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}> <Chip label={item.type.toUpperCase()} size="small" color={item.type === 'json' ? 'primary' : item.type === 'curl' ? 'warning' : 'info'} sx={{ fontSize: '0.7rem' }} /> <Typography variant="caption" color="text.secondary"> {item.timestamp} </Typography> </Box> {item.type === 'pdf' ? ( <Box> <Typography variant="body2" sx={{ fontWeight: 500, mb: 1 }}> {item.filename} </Typography> {item.isMinified ? ( <Typography variant="caption" color="text.secondary"> Click to view PDF </Typography> ) : ( item.pdfUrl && ( <Box sx={{ height: '200px', overflow: 'hidden', borderRadius: 1 }}> <embed src={item.pdfUrl} type="application/pdf" width="100%" height="100%" style={{ border: 'none' }} /> </Box> ) )} </Box> ) : ( <Box> <Typography variant="body2" sx={{ fontFamily: 'monospace', fontSize: '0.75rem', backgroundColor: 'grey.100', p: 1, borderRadius: 1, whiteSpace: item.isMinified ? 'nowrap' : 'pre-wrap', overflow: item.isMinified ? 'hidden' : 'auto', textOverflow: item.isMinified ? 'ellipsis' : 'unset', maxHeight: item.isMinified ? 'none' : '150px' }} > {item.isMinified ? (item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content) : (item.type === 'json' ? formatJsonPreview(item.content) : formatCurlPreview(item.content)) } </Typography> {!item.isMinified && ( <Box sx={{ mt: 1, display: 'flex', gap: 1 }}> <Tooltip title="Copy to clipboard"> <IconButton size="small" onClick={(e) => { e.stopPropagation(); navigator.clipboard.writeText(item.content); }} > <CopyIcon fontSize="small" /> </IconButton> </Tooltip> <Tooltip title="View full content"> <IconButton size="small" onClick={(e) => { e.stopPropagation(); if (item.type === 'json') { handleOpenJsonDialog(item.content); } else { handleOpenCurlDialog(item.content); } }} > <CodeIcon fontSize="small" /> </IconButton> </Tooltip> </Box> )} </Box> )} </CardContent> </Card> ))} </Box> </Box> )} {/* Processing Messages Column - Chat Interface */} <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}> Chat Assistant </Typography> <Box ref={loadingLogRef} sx={{ flex: 1, overflow: 'auto', backgroundColor: 'grey.50', borderRadius: 1, p: 2, border: '1px solid', borderColor: 'grey.200', mb: 2, display: 'flex', flexDirection: 'column' }} > {!hasUserInteracted && ( <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', flexDirection: 'column', opacity: 0.6 }}> <BotIcon sx={{ fontSize: 48, mb: 2, color: 'primary.main' }} /> <Typography variant="body1" align="center" gutterBottom> Hello! I'm your Benefit Agent Assistant. </Typography> <Typography variant="body2" align="center"> Type a message below to start processing your request. </Typography> </Box> )} {processingMessages.map((msg, index) => ( <Box key={index} sx={{ display: 'flex', justifyContent: msg.isUser ? 'flex-end' : 'flex-start', mb: 2, width: '100%' }}> {!msg.isUser && ( <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'primary.main' }}> <BotIcon fontSize="small" /> </Avatar> )} <Paper elevation={1} sx={{ p: 2, maxWidth: '85%', borderRadius: 2, backgroundColor: msg.isUser ? 'primary.main' : 'white', color: msg.isUser ? 'primary.contrastText' : 'text.primary', borderTopLeftRadius: !msg.isUser ? 0 : 12, borderTopRightRadius: msg.isUser ? 0 : 12, borderBottomLeftRadius: 12, borderBottomRightRadius: 12, '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } }} > {/* If it is a user message, just render text, otherwise use the complex renderer */} {msg.isUser ? ( <Typography variant="body2">{msg.message}</Typography> ) : ( renderMessageContent(msg.message, index) )} <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}> {msg.timestamp} </Typography> </Paper> {msg.isUser && ( <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}> <PersonIcon fontSize="small" /> </Avatar> )} </Box> ))} </Box> {/* Input Area */} <Box sx={{ display: 'flex', gap: 1 }}> <TextField fullWidth placeholder={hasUserInteracted ? "Processing in progress..." : "Type your request here to start..."} value={userInput} onChange={(e) => setUserInput(e.target.value)} onKeyDown={handleInputKeyPress} disabled={hasUserInteracted && isInputDisabled} size="small" variant="outlined" sx={{ backgroundColor: 'white' }} InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton onClick={handleSendMessage} disabled={!userInput.trim() || (hasUserInteracted && isInputDisabled)} color="primary" edge="end" > <SendIcon /> </IconButton> </InputAdornment> ), }} /> </Box> </Box> </Box> </Box> )} {loadStatus === 'success' && ( <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {/* Success Status Card */} <Card sx={{ mb: 3, flexShrink: 0 }}> <CardContent> <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}> <Typography variant="h6" color="success.main" sx={{ fontWeight: 600 }}> Processing Complete </Typography> <Chip label={`${currentProgress}% Complete`} color="success" variant="outlined" /> </Box> {finalStats && ( <Box> <Typography variant="body2" color="text.secondary" gutterBottom> Status: <strong>{finalStats.status}</strong> </Typography> <Typography variant="body2" color="text.secondary" gutterBottom> Records Processed: <strong>{finalStats.number_of_records}</strong> </Typography> <Typography variant="body2" color="text.secondary" gutterBottom> Request ID: <strong>{finalStats.request_id}</strong> </Typography> {/* Download Button */} <Box sx={{ mt: 2 }}> <Button variant="contained" color="success" startIcon={isDownloading ? <CircularProgress size={16} /> : <DownloadIcon />} disabled={isDownloading} onClick={() => handleDownload(finalStats.request_id)} sx={{ mr: 2 }} > {isDownloading ? 'Downloading...' : 'Download Excel Report'} </Button> <Button variant="outlined" onClick={clearData} startIcon={<RefreshIcon />} > Start New Processing </Button> </Box> </Box> )} </CardContent> </Card> {/* Completed Messages Log */} <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}> Conversation History </Typography> <Box ref={completeLogRef} sx={{ flex: 1, overflow: 'auto', backgroundColor: 'grey.50', borderRadius: 1, p: 2, border: '1px solid', borderColor: 'grey.200' }} > {processingMessages.map((msg, index) => ( <Box key={index} sx={{ display: 'flex', justifyContent: msg.isUser ? 'flex-end' : 'flex-start', mb: 2, width: '100%' }}> {!msg.isUser && ( <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'primary.main' }}> <BotIcon fontSize="small" /> </Avatar> )} <Paper elevation={1} sx={{ p: 2, maxWidth: '85%', borderRadius: 2, backgroundColor: msg.isUser ? 'primary.main' : 'white', color: msg.isUser ? 'primary.contrastText' : 'text.primary', borderTopLeftRadius: !msg.isUser ? 0 : 12, borderTopRightRadius: msg.isUser ? 0 : 12, borderBottomLeftRadius: 12, borderBottomRightRadius: 12, '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } }} > {msg.isUser ? ( <Typography variant="body2">{msg.message}</Typography> ) : ( renderMessageContent(msg.message, index) )} <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}> {msg.timestamp} </Typography> </Paper> {msg.isUser && ( <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}> <PersonIcon fontSize="small" /> </Avatar> )} </Box> ))} </Box> </Box> </Box> )} {loadStatus === 'error' && ( <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {/* Error Status Card */} <Card sx={{ mb: 3, flexShrink: 0, backgroundColor: 'error.light' }}> <CardContent> <Typography variant="h6" color="error.main" sx={{ fontWeight: 600, mb: 2 }}> Processing Failed </Typography> <Button variant="contained" color="error" onClick={clearData} startIcon={<RefreshIcon />} > Reset and Try Again </Button> </CardContent> </Card> {/* Error Messages Log */} {processingMessages.length > 0 && ( <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}> Conversation History </Typography> <Box ref={errorLogRef} sx={{ flex: 1, overflow: 'auto', backgroundColor: 'grey.50', borderRadius: 1, p: 2, border: '1px solid', borderColor: 'error.light' }} > {processingMessages.map((msg, index) => ( <Box key={index} sx={{ display: 'flex', justifyContent: msg.isUser ? 'flex-end' : 'flex-start', mb: 2, width: '100%' }}> {!msg.isUser && ( <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'error.main' }}> <BotIcon fontSize="small" /> </Avatar> )} <Paper elevation={1} sx={{ p: 2, maxWidth: '85%', borderRadius: 2, backgroundColor: msg.isUser ? 'primary.main' : 'white', color: msg.isUser ? 'primary.contrastText' : 'text.primary', borderTopLeftRadius: !msg.isUser ? 0 : 12, borderTopRightRadius: msg.isUser ? 0 : 12, borderBottomLeftRadius: 12, borderBottomRightRadius: 12, '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } }} > {msg.isUser ? ( <Typography variant="body2">{msg.message}</Typography> ) : ( renderMessageContent(msg.message, index) )} <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}> {msg.timestamp} </Typography> </Paper> {msg.isUser && ( <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}> <PersonIcon fontSize="small" /> </Avatar> )} </Box> ))} </Box> </Box> )} </Box> )} </AccordionDetails> </Accordion> {/* JSON Dialog */} <Dialog open={jsonDialogOpen} onClose={handleCloseJsonDialog} maxWidth="lg" fullWidth PaperProps={{ sx: { height: '80vh' } }} > <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 1 }}> <Typography variant="h6">JSON Content</Typography> <Box> <Tooltip title={isJsonExpanded ? "Minimize JSON" : "Format JSON"}> <IconButton onClick={() => setIsJsonExpanded(!isJsonExpanded)} size="small" sx={{ mr: 1 }} > {isJsonExpanded ? <CollapseAllIcon /> : <ExpandAllIcon />} </IconButton> </Tooltip> <Tooltip title="Copy to clipboard"> <IconButton onClick={handleCopyJson} size="small" sx={{ mr: 1 }} > <CopyIcon /> </IconButton> </Tooltip> </Box> </DialogTitle> <DialogContent sx={{ p: 0 }}> <Box sx={{ fontFamily: 'monospace', fontSize: '0.875rem', whiteSpace: 'pre-wrap', backgroundColor: 'grey.100', p: 2, height: '100%', overflow: 'auto', border: 'none', outline: 'none', resize: 'none', }} component="textarea" value={isJsonExpanded ? formatJSON(selectedJsonContent) : minifyJSON(selectedJsonContent)} readOnly /> </DialogContent> <DialogActions> <Button onClick={handleCloseJsonDialog}>Close</Button> </DialogActions> </Dialog> {/* CURL Dialog */} <Dialog open={curlDialogOpen} onClose={handleCloseCurlDialog} maxWidth="lg" fullWidth PaperProps={{ sx: { height: '80vh' } }} > <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 1 }}> <Typography variant="h6">CURL Command</Typography> <Box> <Tooltip title={isCurlExpanded ? "Minimize CURL" : "Format CURL"}> <IconButton onClick={() => setIsCurlExpanded(!isCurlExpanded)} size="small" sx={{ mr: 1 }} > {isCurlExpanded ? <CollapseAllIcon /> : <ExpandAllIcon />} </IconButton> </Tooltip> <Tooltip title="Copy to clipboard"> <IconButton onClick={handleCopyCurl} size="small" sx={{ mr: 1 }} > <CopyIcon /> </IconButton> </Tooltip> </Box> </DialogTitle> <DialogContent sx={{ p: 0 }}> <Box sx={{ fontFamily: 'monospace', fontSize: '0.875rem', whiteSpace: 'pre-wrap', backgroundColor: 'grey.100', p: 2, height: '100%', overflow: 'auto', border: 'none', outline: 'none', resize: 'none', }} component="textarea" value={isCurlExpanded ? formatCurl(selectedCurlContent) : minifyCurl(selectedCurlContent)} readOnly /> </DialogContent> <DialogActions> <Button onClick={handleCloseCurlDialog}>Close</Button> </DialogActions> </Dialog> </Box> ); }; export default ProcessingStatus;
import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
Box,
Typography,
Card,
CardContent,
CircularProgress,
Chip,
IconButton,
Divider,
Alert,
LinearProgress,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Tooltip,
Button,
Accordion,
AccordionSummary,
AccordionDetails,
TextField,
Avatar,
InputAdornment,
Paper,
} from '@mui/material';
import {
ExpandMore as ExpandMoreIcon,
Refresh as RefreshIcon,
Code as CodeIcon,
UnfoldMore as ExpandAllIcon,
UnfoldLess as CollapseAllIcon,
ContentCopy as CopyIcon,
Download as DownloadIcon,
PlayArrow as EnableScrollIcon,
Pause as DisableScrollIcon,
Send as SendIcon,
SmartToy as BotIcon,
Person as PersonIcon,
} from '@mui/icons-material';
import {
API_BASE_URI,
WEBSOCKET_BASE_URI
} from '../constants';
interface ProcessingMessage {
type?: string;
message: string;
progress_percentage?: number;
request_id?: string;
timestamp: string;
stats?: {
status: string;
number_of_records: number;
request_id: string;
record_count: number;
};
error?: string;
isUser?: boolean;
}
interface PreviewItem {
id: string;
type: 'json' | 'curl' | 'pdf';
content: string;
timestamp: string;
isMinified: boolean;
pdfUrl?: string;
filename?: string;
}
interface ProcessingStatusProps {
fileType: 'Shell' | 'MSAG' | 'Dx Supplementary';
folderPath: string;
environment: string;
inputType: 'file' | 'json';
json_content?: string;
isLoading: boolean;
onLoadingChange: (loading: boolean) => void;
onStatusChange: (status: 'idle' | 'loading' | 'success' | 'error') => void;
triggerProcessing?: boolean;
onProcessingComplete?: () => void;
}
// TypewriterText component for typewriting animation
const TypewriterText: React.FC<{
text: string;
speed?: number;
onComplete?: () => void;
isJson?: boolean;
isCurl?: boolean;
onJsonClick?: () => void;
onCurlClick?: () => void;
}> = ({ text, speed = 20, onComplete, isJson = false, isCurl = false, onJsonClick, onCurlClick }) => {
const [displayText, setDisplayText] = useState('');
const [isComplete, setIsComplete] = useState(false);
// Check if this is a Phase or Step heading
const isPhaseHeading = text.startsWith("Phase: ");
const isStepHeading = text.startsWith("Step: ");