import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { motion } from 'framer-motion'; import { Switch } from '~/components/ui/Switch'; import { logStore, type LogEntry } from '~/lib/stores/logs'; import { useStore } from '@nanostores/react'; import { classNames } from '~/utils/classNames'; import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; import { Dialog, DialogRoot, DialogTitle } from '~/components/ui/Dialog'; import { jsPDF } from 'jspdf'; import { toast } from 'react-toastify'; interface SelectOption { value: string; label: string; icon?: string; color?: string; } const logLevelOptions: SelectOption[] = [ { value: 'all', label: 'All Types', icon: 'i-ph:funnel', color: '#9333ea', }, { value: 'provider', label: 'LLM', icon: 'i-ph:robot', color: '#10b981', }, { value: 'api', label: 'API', icon: 'i-ph:cloud', color: '#3b82f6', }, { value: 'error', label: 'Errors', icon: 'i-ph:warning-circle', color: '#ef4444', }, { value: 'warning', label: 'Warnings', icon: 'i-ph:warning', color: '#f59e0b', }, { value: 'info', label: 'Info', icon: 'i-ph:info', color: '#3b82f6', }, { value: 'debug', label: 'Debug', icon: 'i-ph:bug', color: '#6b7280', }, ]; interface LogEntryItemProps { log: LogEntry; isExpanded: boolean; use24Hour: boolean; showTimestamp: boolean; } const LogEntryItem = ({ log, isExpanded: forceExpanded, use24Hour, showTimestamp }: LogEntryItemProps) => { const [localExpanded, setLocalExpanded] = useState(forceExpanded); useEffect(() => { setLocalExpanded(forceExpanded); }, [forceExpanded]); const timestamp = useMemo(() => { const date = new Date(log.timestamp); return date.toLocaleTimeString('en-US', { hour12: !use24Hour }); }, [log.timestamp, use24Hour]); const style = useMemo(() => { if (log.category === 'provider') { return { icon: 'i-ph:robot', color: 'text-emerald-500 dark:text-emerald-400', bg: 'hover:bg-emerald-500/10 dark:hover:bg-emerald-500/20', badge: 'text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10', }; } if (log.category === 'api') { return { icon: 'i-ph:cloud', color: 'text-blue-500 dark:text-blue-400', bg: 'hover:bg-blue-500/10 dark:hover:bg-blue-500/20', badge: 'text-blue-500 bg-blue-50 dark:bg-blue-500/10', }; } switch (log.level) { case 'error': return { icon: 'i-ph:warning-circle', color: 'text-red-500 dark:text-red-400', bg: 'hover:bg-red-500/10 dark:hover:bg-red-500/20', badge: 'text-red-500 bg-red-50 dark:bg-red-500/10', }; case 'warning': return { icon: 'i-ph:warning', color: 'text-yellow-500 dark:text-yellow-400', bg: 'hover:bg-yellow-500/10 dark:hover:bg-yellow-500/20', badge: 'text-yellow-500 bg-yellow-50 dark:bg-yellow-500/10', }; case 'debug': return { icon: 'i-ph:bug', color: 'text-gray-500 dark:text-gray-400', bg: 'hover:bg-gray-500/10 dark:hover:bg-gray-500/20', badge: 'text-gray-500 bg-gray-50 dark:bg-gray-500/10', }; default: return { icon: 'i-ph:info', color: 'text-blue-500 dark:text-blue-400', bg: 'hover:bg-blue-500/10 dark:hover:bg-blue-500/20', badge: 'text-blue-500 bg-blue-50 dark:bg-blue-500/10', }; } }, [log.level, log.category]); const renderDetails = (details: any) => { if (log.category === 'provider') { return (
Model: {details.model} Tokens: {details.totalTokens} Duration: {details.duration}ms
{details.prompt && (
Prompt:
                {details.prompt}
              
)} {details.response && (
Response:
                {details.response}
              
)}
); } if (log.category === 'api') { return (
{details.method} Status: {details.statusCode} Duration: {details.duration}ms
{details.url}
{details.request && (
Request:
                {JSON.stringify(details.request, null, 2)}
              
)} {details.response && (
Response:
                {JSON.stringify(details.response, null, 2)}
              
)} {details.error && (
Error:
                {JSON.stringify(details.error, null, 2)}
              
)}
); } return (
        {JSON.stringify(details, null, 2)}
      
); }; return (
{log.message}
{log.details && ( <> {localExpanded && renderDetails(log.details)} )}
{log.level}
{log.category && (
{log.category}
)}
{showTimestamp && }
); }; interface ExportFormat { id: string; label: string; icon: string; handler: () => void; } export function EventLogsTab() { const logs = useStore(logStore.logs); const [selectedLevel, setSelectedLevel] = useState<'all' | string>('all'); const [searchQuery, setSearchQuery] = useState(''); const [use24Hour, setUse24Hour] = useState(false); const [autoExpand, setAutoExpand] = useState(false); const [showTimestamps, setShowTimestamps] = useState(true); const [showLevelFilter, setShowLevelFilter] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false); const levelFilterRef = useRef(null); const filteredLogs = useMemo(() => { const allLogs = Object.values(logs); if (selectedLevel === 'all') { return allLogs.filter((log) => searchQuery ? log.message.toLowerCase().includes(searchQuery.toLowerCase()) : true, ); } return allLogs.filter((log) => { const matchesType = log.category === selectedLevel || log.level === selectedLevel; const matchesSearch = searchQuery ? log.message.toLowerCase().includes(searchQuery.toLowerCase()) : true; return matchesType && matchesSearch; }); }, [logs, selectedLevel, searchQuery]); // Add performance tracking on mount useEffect(() => { const startTime = performance.now(); logStore.logInfo('Event Logs tab mounted', { type: 'component_mount', message: 'Event Logs tab component mounted', component: 'EventLogsTab', }); return () => { const duration = performance.now() - startTime; logStore.logPerformanceMetric('EventLogsTab', 'mount-duration', duration); }; }, []); // Log filter changes const handleLevelFilterChange = useCallback( (newLevel: string) => { logStore.logInfo('Log level filter changed', { type: 'filter_change', message: `Log level filter changed from ${selectedLevel} to ${newLevel}`, component: 'EventLogsTab', previousLevel: selectedLevel, newLevel, }); setSelectedLevel(newLevel as string); setShowLevelFilter(false); }, [selectedLevel], ); // Log search changes with debounce useEffect(() => { const timeoutId = setTimeout(() => { if (searchQuery) { logStore.logInfo('Log search performed', { type: 'search', message: `Search performed with query "${searchQuery}" (${filteredLogs.length} results)`, component: 'EventLogsTab', query: searchQuery, resultsCount: filteredLogs.length, }); } }, 1000); return () => clearTimeout(timeoutId); }, [searchQuery, filteredLogs.length]); // Enhanced refresh handler const handleRefresh = useCallback(async () => { const startTime = performance.now(); setIsRefreshing(true); try { await logStore.refreshLogs(); const duration = performance.now() - startTime; logStore.logSuccess('Logs refreshed successfully', { type: 'refresh', message: `Successfully refreshed ${Object.keys(logs).length} logs`, component: 'EventLogsTab', duration, logsCount: Object.keys(logs).length, }); } catch (error) { logStore.logError('Failed to refresh logs', error, { type: 'refresh_error', message: 'Failed to refresh logs', component: 'EventLogsTab', }); } finally { setTimeout(() => setIsRefreshing(false), 500); } }, [logs]); // Log preference changes const handlePreferenceChange = useCallback((type: string, value: boolean) => { logStore.logInfo('Log preference changed', { type: 'preference_change', message: `Log preference "${type}" changed to ${value}`, component: 'EventLogsTab', preference: type, value, }); switch (type) { case 'timestamps': setShowTimestamps(value); break; case '24hour': setUse24Hour(value); break; case 'autoExpand': setAutoExpand(value); break; } }, []); // Close filters when clicking outside useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (levelFilterRef.current && !levelFilterRef.current.contains(event.target as Node)) { setShowLevelFilter(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); const selectedLevelOption = logLevelOptions.find((opt) => opt.value === selectedLevel); // Export functions const exportAsJSON = () => { try { const exportData = { timestamp: new Date().toISOString(), logs: filteredLogs, filters: { level: selectedLevel, searchQuery, }, preferences: { use24Hour, showTimestamps, autoExpand, }, }; const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `bolt-event-logs-${new Date().toISOString()}.json`; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); toast.success('Event logs exported successfully as JSON'); } catch (error) { console.error('Failed to export JSON:', error); toast.error('Failed to export event logs as JSON'); } }; const exportAsCSV = () => { try { // Convert logs to CSV format const headers = ['Timestamp', 'Level', 'Category', 'Message', 'Details']; const csvData = [ headers, ...filteredLogs.map((log) => [ new Date(log.timestamp).toISOString(), log.level, log.category || '', log.message, log.details ? JSON.stringify(log.details) : '', ]), ]; const csvContent = csvData .map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')) .join('\n'); const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `bolt-event-logs-${new Date().toISOString()}.csv`; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); toast.success('Event logs exported successfully as CSV'); } catch (error) { console.error('Failed to export CSV:', error); toast.error('Failed to export event logs as CSV'); } }; const exportAsPDF = () => { try { // Create new PDF document const doc = new jsPDF(); const lineHeight = 7; let yPos = 20; const margin = 20; const pageWidth = doc.internal.pageSize.getWidth(); const maxLineWidth = pageWidth - 2 * margin; // Helper function to add section header const addSectionHeader = (title: string) => { // Check if we need a new page if (yPos > doc.internal.pageSize.getHeight() - 30) { doc.addPage(); yPos = margin; } doc.setFillColor('#F3F4F6'); doc.rect(margin - 2, yPos - 5, pageWidth - 2 * (margin - 2), lineHeight + 6, 'F'); doc.setFont('helvetica', 'bold'); doc.setTextColor('#111827'); doc.setFontSize(12); doc.text(title.toUpperCase(), margin, yPos); yPos += lineHeight * 2; }; // Add title and header doc.setFillColor('#6366F1'); doc.rect(0, 0, pageWidth, 50, 'F'); doc.setTextColor('#FFFFFF'); doc.setFontSize(24); doc.setFont('helvetica', 'bold'); doc.text('Event Logs Report', margin, 35); // Add subtitle with bolt.diy doc.setFontSize(12); doc.setFont('helvetica', 'normal'); doc.text('bolt.diy - AI Development Platform', margin, 45); yPos = 70; // Add report summary section addSectionHeader('Report Summary'); doc.setFontSize(10); doc.setFont('helvetica', 'normal'); doc.setTextColor('#374151'); const summaryItems = [ { label: 'Generated', value: new Date().toLocaleString() }, { label: 'Total Logs', value: filteredLogs.length.toString() }, { label: 'Filter Applied', value: selectedLevel === 'all' ? 'All Types' : selectedLevel }, { label: 'Search Query', value: searchQuery || 'None' }, { label: 'Time Format', value: use24Hour ? '24-hour' : '12-hour' }, ]; summaryItems.forEach((item) => { doc.setFont('helvetica', 'bold'); doc.text(`${item.label}:`, margin, yPos); doc.setFont('helvetica', 'normal'); doc.text(item.value, margin + 60, yPos); yPos += lineHeight; }); yPos += lineHeight * 2; // Add statistics section addSectionHeader('Log Statistics'); // Calculate statistics const stats = { error: filteredLogs.filter((log) => log.level === 'error').length, warning: filteredLogs.filter((log) => log.level === 'warning').length, info: filteredLogs.filter((log) => log.level === 'info').length, debug: filteredLogs.filter((log) => log.level === 'debug').length, provider: filteredLogs.filter((log) => log.category === 'provider').length, api: filteredLogs.filter((log) => log.category === 'api').length, }; // Create two columns for statistics const leftStats = [ { label: 'Error Logs', value: stats.error, color: '#DC2626' }, { label: 'Warning Logs', value: stats.warning, color: '#F59E0B' }, { label: 'Info Logs', value: stats.info, color: '#3B82F6' }, ]; const rightStats = [ { label: 'Debug Logs', value: stats.debug, color: '#6B7280' }, { label: 'LLM Logs', value: stats.provider, color: '#10B981' }, { label: 'API Logs', value: stats.api, color: '#3B82F6' }, ]; const colWidth = (pageWidth - 2 * margin) / 2; // Draw statistics in two columns leftStats.forEach((stat, index) => { doc.setTextColor(stat.color); doc.setFont('helvetica', 'bold'); doc.text(stat.value.toString(), margin, yPos); doc.setTextColor('#374151'); doc.setFont('helvetica', 'normal'); doc.text(stat.label, margin + 20, yPos); if (rightStats[index]) { doc.setTextColor(rightStats[index].color); doc.setFont('helvetica', 'bold'); doc.text(rightStats[index].value.toString(), margin + colWidth, yPos); doc.setTextColor('#374151'); doc.setFont('helvetica', 'normal'); doc.text(rightStats[index].label, margin + colWidth + 20, yPos); } yPos += lineHeight; }); yPos += lineHeight * 2; // Add logs section addSectionHeader('Event Logs'); // Helper function to add a log entry with improved formatting const addLogEntry = (log: LogEntry) => { const entryHeight = 20 + (log.details ? 40 : 0); // Estimate entry height // Check if we need a new page if (yPos + entryHeight > doc.internal.pageSize.getHeight() - 20) { doc.addPage(); yPos = margin; } // Add timestamp and level const timestamp = new Date(log.timestamp).toLocaleString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: !use24Hour, }); // Draw log level badge background const levelColors: Record = { error: '#FEE2E2', warning: '#FEF3C7', info: '#DBEAFE', debug: '#F3F4F6', }; const textColors: Record = { error: '#DC2626', warning: '#F59E0B', info: '#3B82F6', debug: '#6B7280', }; const levelWidth = doc.getTextWidth(log.level.toUpperCase()) + 10; doc.setFillColor(levelColors[log.level] || '#F3F4F6'); doc.roundedRect(margin, yPos - 4, levelWidth, lineHeight + 4, 1, 1, 'F'); // Add log level text doc.setTextColor(textColors[log.level] || '#6B7280'); doc.setFont('helvetica', 'bold'); doc.setFontSize(8); doc.text(log.level.toUpperCase(), margin + 5, yPos); // Add timestamp doc.setTextColor('#6B7280'); doc.setFont('helvetica', 'normal'); doc.setFontSize(9); doc.text(timestamp, margin + levelWidth + 10, yPos); // Add category if present if (log.category) { const categoryX = margin + levelWidth + doc.getTextWidth(timestamp) + 20; doc.setFillColor('#F3F4F6'); const categoryWidth = doc.getTextWidth(log.category) + 10; doc.roundedRect(categoryX, yPos - 4, categoryWidth, lineHeight + 4, 2, 2, 'F'); doc.setTextColor('#6B7280'); doc.text(log.category, categoryX + 5, yPos); } yPos += lineHeight * 1.5; // Add message doc.setTextColor('#111827'); doc.setFontSize(10); const messageLines = doc.splitTextToSize(log.message, maxLineWidth - 10); doc.text(messageLines, margin + 5, yPos); yPos += messageLines.length * lineHeight; // Add details if present if (log.details) { doc.setTextColor('#6B7280'); doc.setFontSize(8); const detailsStr = JSON.stringify(log.details, null, 2); const detailsLines = doc.splitTextToSize(detailsStr, maxLineWidth - 15); // Add details background doc.setFillColor('#F9FAFB'); doc.roundedRect(margin + 5, yPos - 2, maxLineWidth - 10, detailsLines.length * lineHeight + 8, 1, 1, 'F'); doc.text(detailsLines, margin + 10, yPos + 4); yPos += detailsLines.length * lineHeight + 10; } // Add separator line doc.setDrawColor('#E5E7EB'); doc.setLineWidth(0.1); doc.line(margin, yPos, pageWidth - margin, yPos); yPos += lineHeight * 1.5; }; // Add all logs filteredLogs.forEach((log) => { addLogEntry(log); }); // Add footer to all pages const totalPages = doc.internal.pages.length - 1; for (let i = 1; i <= totalPages; i++) { doc.setPage(i); doc.setFontSize(8); doc.setTextColor('#9CA3AF'); // Add page numbers doc.text(`Page ${i} of ${totalPages}`, pageWidth / 2, doc.internal.pageSize.getHeight() - 10, { align: 'center', }); // Add footer text doc.text('Generated by bolt.diy', margin, doc.internal.pageSize.getHeight() - 10); const dateStr = new Date().toLocaleDateString(); doc.text(dateStr, pageWidth - margin, doc.internal.pageSize.getHeight() - 10, { align: 'right' }); } // Save the PDF doc.save(`bolt-event-logs-${new Date().toISOString()}.pdf`); toast.success('Event logs exported successfully as PDF'); } catch (error) { console.error('Failed to export PDF:', error); toast.error('Failed to export event logs as PDF'); } }; const exportAsText = () => { try { const textContent = filteredLogs .map((log) => { const timestamp = new Date(log.timestamp).toLocaleString(); let content = `[${timestamp}] ${log.level.toUpperCase()}: ${log.message}\n`; if (log.category) { content += `Category: ${log.category}\n`; } if (log.details) { content += `Details:\n${JSON.stringify(log.details, null, 2)}\n`; } return content + '-'.repeat(80) + '\n'; }) .join('\n'); const blob = new Blob([textContent], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `bolt-event-logs-${new Date().toISOString()}.txt`; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); toast.success('Event logs exported successfully as text file'); } catch (error) { console.error('Failed to export text file:', error); toast.error('Failed to export event logs as text file'); } }; const exportFormats: ExportFormat[] = [ { id: 'json', label: 'Export as JSON', icon: 'i-ph:file-js', handler: exportAsJSON, }, { id: 'csv', label: 'Export as CSV', icon: 'i-ph:file-csv', handler: exportAsCSV, }, { id: 'pdf', label: 'Export as PDF', icon: 'i-ph:file-pdf', handler: exportAsPDF, }, { id: 'txt', label: 'Export as Text', icon: 'i-ph:file-text', handler: exportAsText, }, ]; const ExportButton = () => { const [isOpen, setIsOpen] = useState(false); const handleOpenChange = useCallback((open: boolean) => { setIsOpen(open); }, []); const handleFormatClick = useCallback((handler: () => void) => { handler(); setIsOpen(false); }, []); return (
Export Event Logs
{exportFormats.map((format) => ( ))}
); }; return (
{logLevelOptions.map((option) => ( handleLevelFilterChange(option.value)} >
{option.label} ))}
handlePreferenceChange('timestamps', value)} className="data-[state=checked]:bg-purple-500" /> Show Timestamps
handlePreferenceChange('24hour', value)} className="data-[state=checked]:bg-purple-500" /> 24h Time
handlePreferenceChange('autoExpand', value)} className="data-[state=checked]:bg-purple-500" /> Auto Expand
setSearchQuery(e.target.value)} className={classNames( 'w-full px-4 py-2 pl-10 rounded-lg', 'bg-[#FAFAFA] dark:bg-[#0A0A0A]', 'border border-[#E5E5E5] dark:border-[#1A1A1A]', 'text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400', 'focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500', 'transition-all duration-200', )} />
{filteredLogs.length === 0 ? (

No Logs Found

Try adjusting your search or filters

) : ( filteredLogs.map((log) => ( )) )}
); }