import React, { useState, useEffect, useCallback } from 'react';
import { useAuth, api } from '@nexus/shared';
import {
Activity, Database, Brain, Clock,
AlertCircle, RefreshCcw,
Cpu, Workflow, Shield, Search, Zap, Layout,
ChevronLeft, ChevronRight
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import styles from './InfraMonitor.module.css';
interface HealthNode {
status: 'UP' | 'DOWN' | 'DEGRADED';
latency_ms: number;
pending_jobs?: number;
}
interface SystemStatus {
database: HealthNode;
redis: HealthNode;
ollama: HealthNode;
timestamp: string;
}
interface InfraHistory {
DATABASE: number[];
REDIS: number[];
OLLAMA: number[];
}
interface WorkflowStep {
name: string;
status: 'success' | 'error' | 'pending' | 'skipped';
timestamp: string;
}
interface AIWorkflow {
id: string;
entity_id: string;
workflow_type: string;
current_stage: string;
steps: WorkflowStep[];
total_duration_ms: number;
}
interface AIInteraction {
id: string;
ticket_id: string | null;
agent_name: string;
status: string;
output_data: any;
duration_ms?: any;
created_at: string;
}
const getAgentIcon = (name: string) => {
const n = name.toLowerCase();
if (n.includes('triage')) return ;
if (n.includes('suggestion')) return ;
if (n.includes('remediation')) return ;
if (n.includes('search')) return ;
return ;
};
const Sparkline = ({ data, color, loading }: { data: number[], color: string, loading: boolean }) => {
if (loading || data.length === 0) return
;
// Safeguard: Ensure we have at least 2 points to draw a line,
// or handle the single point case by duplicating it.
const chartData = data.length === 1 ? [data[0], data[0]] : data;
const min = Math.min(...chartData);
const max = Math.max(...chartData);
const range = max - min || 1;
const width = 200;
const height = 40;
const points = chartData.map((val, i) => {
const x = (i / (chartData.length - 1)) * width;
const y = height - ((val - min) / range) * height;
// Final NaN safeguard
return `${isNaN(x) ? 0 : x},${isNaN(y) ? height : y}`;
}).join(' ');
const areaPoints = `${points} ${width},${height} 0,${height}`;
return (
);
};
const StatusCard = ({ title, node, history, icon: Icon, color, loading }: {
title: string,
node: HealthNode | undefined,
history: number[],
icon: any,
color: string,
loading: boolean
}) => (
{loading &&
}
{node?.status === 'UP' ? `${node.latency_ms.toFixed(1)}` : '---'}
{node?.status === 'UP' && ms }
Avg Latency
{node?.pending_jobs !== undefined && (
Process Queue
{node.pending_jobs}
)}
);
const PAGE_SIZE = 6;
const InfraMonitor: React.FC = () => {
useAuth();
const [status, setStatus] = useState(null);
const [history, setHistory] = useState({ DATABASE: [], REDIS: [], OLLAMA: [] });
const [workflows, setWorkflows] = useState([]);
const [interactions, setInteractions] = useState([]);
const [loading, setLoading] = useState(true);
const [lastRefreshed, setLastRefreshed] = useState(new Date());
// Search and Pagination State
const [searchTicketId, setSearchTicketId] = useState('');
const [wfOffset, setWfOffset] = useState(0);
const [intOffset, setIntOffset] = useState(0);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const params: any = {};
if (searchTicketId.length === 36) { // Valid UUID length
params.ticket_id = searchTicketId;
}
const [statusRes, historyRes, workflowRes, interactionRes] = await Promise.all([
api.get('system/status/'),
api.get('system/history/'),
api.get('system/workflows/', { params: { ...params, offset: wfOffset, limit: PAGE_SIZE } }),
api.get('system/interactions/', { params: { ...params, offset: intOffset, limit: PAGE_SIZE } })
]);
if (statusRes.data) setStatus(statusRes.data);
if (historyRes.data) {
const grouped: InfraHistory = { DATABASE: [], REDIS: [], OLLAMA: [] };
historyRes.data.forEach((entry: any) => {
if (grouped[entry.service_name as keyof InfraHistory]) {
grouped[entry.service_name as keyof InfraHistory].push(entry.latency_ms);
}
});
setHistory(grouped);
}
if (workflowRes.data) setWorkflows(workflowRes.data);
if (interactionRes.data) setInteractions(interactionRes.data);
} catch (err) {
console.error('Failed to monitor sys stats', err);
} finally {
setTimeout(() => {
setLoading(false);
setLastRefreshed(new Date());
}, 400);
}
}, [searchTicketId, wfOffset, intOffset]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleSearch = (e: React.ChangeEvent) => {
setSearchTicketId(e.target.value);
setWfOffset(0);
setIntOffset(0);
};
return (
{/* Aggregated Workflows */}
Service Logic
Ticket Resolution Pipelines
setWfOffset(Math.max(0, wfOffset - PAGE_SIZE))}
>
Prev
setWfOffset(wfOffset + PAGE_SIZE)}
>
Next
{workflows.map((wf, idx) => (
{wf.workflow_type}
#{wf.entity_id.slice(0,6)}
{wf.current_stage}
{wf.total_duration_ms.toFixed(0)}ms
{wf.steps.map((step, sIdx) => (
{sIdx < wf.steps.length - 1 &&
}
))}
))}
{workflows.length === 0 && !loading && (
No historical workflows found matching query.
)}
{/* Granular Interactions */}
Live Autonomous Reasoning
setIntOffset(Math.max(0, intOffset - PAGE_SIZE))}
>
Prev
setIntOffset(intOffset + PAGE_SIZE)}
>
Next
{interactions.map((interaction, idx) => {
const steps = interaction.output_data?.processed_steps || [];
const errors = interaction.output_data?.errors || [];
const duration = typeof interaction.duration_ms === 'number' ? interaction.duration_ms : interaction.duration_ms?.total || 0;
return (
{getAgentIcon(interaction.agent_name)}
{interaction.agent_name.replace('_node', '')}
{duration.toFixed(0)}ms
{new Date(interaction.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
{interaction.ticket_id &&
TICKET #{interaction.ticket_id.slice(0,6)}
}
{steps.map((s: any, sIdx: number) => (
{sIdx < steps.length - 1 &&
}
))}
{steps.length === 0 &&
Node initiating...
}
{(errors.length > 0 || interaction.status === 'error') && (
{errors[0] || 'Unresponsive agent node. Reviewing local inference logs.'}
)}
);
})}
{interactions.length === 0 && !loading && (
No granular interactions found matching query.
)}
);
};
export default InfraMonitor;