import React, { useState, useEffect } from 'react'; import { History, Clock, CheckCircle, XCircle, ChevronRight, Activity, Search, Filter, Trash2, ArrowRight, Zap, Download } from 'lucide-react'; import { HistoryService } from '../services/api'; import { useAppContext } from './AppContext'; const HistoryPage = () => { const { importSession, addToast } = useAppContext(); const [history, setHistory] = useState([]); const [isLoading, setIsLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); const [expandedSessionId, setExpandedSessionId] = useState(null); const [expandedStepId, setExpandedStepId] = useState(null); useEffect(() => { fetchHistory(); }, []); const handleImport = (session) => { importSession(session); // Navigate to testing page const event = new CustomEvent('nav-change', { detail: 'testing' }); window.dispatchEvent(event); }; const fetchHistory = async () => { setIsLoading(true); try { const data = await HistoryService.getHistory(); setHistory(data); } catch (e) { console.error("Failed to fetch history", e); } finally { setIsLoading(false); } }; const handleExportSession = async (sessionId) => { try { await HistoryService.exportSession(sessionId); } catch (e) { console.error("Export failed", e); addToast('error', "Failed to export session."); } }; const handleDeleteSession = async (sessionId) => { if (!window.confirm("Are you sure you want to delete this test session?")) return; try { await HistoryService.deleteHistorySession(sessionId); setHistory(prev => prev.filter(item => item.session_id !== sessionId)); if (expandedSessionId === sessionId) setExpandedSessionId(null); } catch (e) { console.error("Delete failed", e); addToast('error', "Failed to delete session."); } }; const handleClearAll = async () => { if (!window.confirm("CRITICAL: This will permanently wipe ALL test history. Proceed?")) return; try { await HistoryService.clearAllHistory(); setHistory([]); setExpandedSessionId(null); } catch (e) { console.error("Clear failed", e); addToast('error', "Failed to clear history."); } }; // Grouping logic: Create a map of sessions, then convert to array const sessionsMap = (history || []).reduce((acc, curr) => { if (!curr) return acc; const sid = curr.session_id || 'unknown'; if (!acc[sid]) { acc[sid] = { session_id: sid, spec_id: curr.spec_id, spec_name: curr.spec_name || 'Unknown Spec', scenario: curr.scenario || 'No scenario text', timestamp: curr.timestamp, steps: [], status: 'success' }; } acc[sid].steps.push(curr); if (curr.analysis?.status === 'failure') acc[sid].status = 'failure'; // Capture context variables from the session metadata if (curr.context_variables && Object.keys(curr.context_variables).length > 0) { if (!acc[sid].context_variables) acc[sid].context_variables = {}; Object.assign(acc[sid].context_variables, curr.context_variables); } // Capture step definition if it exists (for restoration) if (curr.step_definition) { if (!acc[sid].plan_steps) acc[sid].plan_steps = {}; acc[sid].plan_steps[curr.step] = curr.step_definition; } // Keep the most recent timestamp as session timestamp if (new Date(curr.timestamp) > new Date(acc[sid].timestamp)) { acc[sid].timestamp = curr.timestamp; } return acc; }, {}); // Sort steps within sessions and convert map to sorted array const groupedSessions = Object.values(sessionsMap) .map(s => { // Reconstruct the plan from plan_steps or fallback to minimal info from steps const stepsForImport = Object.keys(s.plan_steps || {}).length > 0 ? Object.values(s.plan_steps).sort((a,b) => a.step - b.step) : s.steps.map(st => ({ step: st.step, endpoint: st.request.method + ' ' + st.request.url.split('/').pop(), purpose: st.analysis?.response_summary?.slice(0, 50) || 'Step execution' })).sort((a,b) => a.step - b.step); return { ...s, stepsForImport, steps: s.steps.sort((a, b) => a.step - b.step) }; }) .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)); const filteredSessions = groupedSessions.filter(s => s.spec_name.toLowerCase().includes(searchQuery.toLowerCase()) || s.scenario.toLowerCase().includes(searchQuery.toLowerCase()) || s.steps.some(st => (st.analysis?.response_summary || '').toLowerCase().includes(searchQuery.toLowerCase())) ); const formatDate = (dateStr) => { const d = new Date(dateStr); return d.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }; return (
{/* Header */}

Execution History

{groupedSessions.length} sessions
setSearchQuery(e.target.value)} className="bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] text-[var(--text-primary)] pl-9 pr-4 py-1.5 text-xs rounded-lg outline-none focus:border-[var(--accent-primary)] w-64 transition-all" />
{groupedSessions.length > 0 && ( )}
{isLoading ? (

Loading history records...

) : filteredSessions.length === 0 ? (

No History Found

Run some test scenarios on the Workflow page to see execution logs appear here.

) : (
{filteredSessions.map((session) => (
{/* Session Header (Collapsible) */}
setExpandedSessionId(expandedSessionId === session.session_id ? null : session.session_id)} className="p-4 flex items-center cursor-pointer select-none" >
{session.status === 'success' ? : }
{session.spec_name} • {session.steps.length} steps
{session.scenario}
{formatDate(session.timestamp)}
{/* Session Steps (Expanded View) */} {expandedSessionId === session.session_id && (
{/* Session Extraction History */} {session.context_variables && Object.keys(session.context_variables).length > 0 && (

Session Extraction History

{Object.entries(session.context_variables).map(([k, v]) => (
{k} "{String(v)}"
))}
)}
{session.steps.map((item) => (
setExpandedStepId(expandedStepId === item.id ? null : item.id)} className="p-3 flex items-center justify-between cursor-pointer hover:bg-[var(--bg-tertiary)] transition-colors" >
Step {item.step} {item.request.method} {item.request.url.split('/').pop()}
{/* Step Details */} {expandedStepId === item.id && (
{/* AI Analysis Result */}
AI Step Analysis

{item.analysis?.response_summary || "Summary not available."}

{item.analysis?.extracted_variables && Object.keys(item.analysis.extracted_variables).length > 0 && (
{Object.entries(item.analysis.extracted_variables).map(([k, v]) => (
{k}: "{String(v)}"
))}
)}
{/* Request/Response Grid */}
Request Details
{item.request.method} {item.request.url}
{item.request.headers && Object.keys(item.request.headers).length > 0 && (
Headers
{Object.entries(item.request.headers).map(([k,v]) => (
{k}: {v}
))}
)} {item.request.query_params && Object.keys(item.request.query_params).length > 0 && (
Query Params
{Object.entries(item.request.query_params).map(([k,v]) => (
{k}={v}
))}
)} {item.request.body &&
Body
{JSON.stringify(item.request.body, null, 2)}
} {item.request.form_data && Object.keys(item.request.form_data).length > 0 && (
Form Data
{JSON.stringify(item.request.form_data, null, 2)}
)} {item.request.files && Object.keys(item.request.files).length > 0 && (
Files
{Object.entries(item.request.files).map(([k,v]) => (
{k}: {v}
))}
)}
Response Body ({item.response.status_code})
                                            {(() => {
                                               try { return JSON.stringify(JSON.parse(item.response.body), null, 2); } 
                                               catch { return item.response.body; }
                                            })()}
                                          
)}
))}
)}
))}
)}
); }; export default HistoryPage;