Spaces:
Paused

nexus / frontend /apps /internal /src /components /InfraMonitor.tsx
dushyantsingh0
fix: allow staff cross-workspace live events via WebSockets
49c5dff
Raw History Blame Contribute Delete
17.7 kB
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 <Shield size={18} />;
if (n.includes('suggestion')) return <Zap size={18} />;
if (n.includes('remediation')) return <Cpu size={18} />;
if (n.includes('search')) return <Search size={18} />;
return <Brain size={18} />;
};
const Sparkline = ({ data, color, loading }: { data: number[], color: string, loading: boolean }) => {
if (loading || data.length === 0) return <div style={{ height: 40 }} />;
// 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 (
<div className={styles.sparklineContainer}>
<svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none">
<defs>
<linearGradient id={`grad-${color}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={color} stopOpacity="0.4" />
<stop offset="100%" stopColor={color} stopOpacity="0" />
</linearGradient>
</defs>
<motion.path
d={`M ${points}`}
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 1.5, ease: "easeInOut" }}
/>
<motion.polygon
points={areaPoints}
fill={`url(#grad-${color})`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5, duration: 1 }}
/>
</svg>
</div>
);
};
const StatusCard = ({ title, node, history, icon: Icon, color, loading }: {
title: string,
node: HealthNode | undefined,
history: number[],
icon: any,
color: string,
loading: boolean
}) => (
<div className={styles.card}>
<div className={styles.cardTopBorder} style={{ background: color }} />
{loading && <div className={styles.shimmerOverlay} />}
<div className={`${styles.cardHeader} ${loading ? styles.fading : ''}`}>
<div className={styles.cardTitle}>
<Icon size={18} color={color} strokeWidth={2.5} />
{title}
</div>
<div className={`${styles.statusOrb} ${node?.status || 'DOWN'}`} />
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
<div>
<div className={`${styles.statValue} ${loading ? styles.fading : ''}`}>
{node?.status === 'UP' ? `${node.latency_ms.toFixed(1)}` : '---'}
{node?.status === 'UP' && <span style={{ fontSize: '1rem', marginLeft: '4px', opacity: 0.6 }}>ms</span>}
</div>
<div className={styles.statLabel}>Avg Latency</div>
</div>
<div style={{ width: '40%', marginBottom: '10px' }}>
<Sparkline data={history} color={color} loading={loading} />
</div>
</div>
<div className={`${styles.metrics} ${loading ? styles.fading : ''}`}>
{node?.pending_jobs !== undefined && (
<div className={styles.metricItem}>
<div className={styles.metricLabel}>Process Queue</div>
<div className={styles.metricValue}>{node.pending_jobs}</div>
</div>
)}
<div className={styles.metricItem}>
<div className={styles.metricLabel}>Protocol</div>
<div className={styles.metricValue}>TLS 1.3</div>
</div>
</div>
</div>
);
const PAGE_SIZE = 6;
const InfraMonitor: React.FC = () => {
useAuth();
const [status, setStatus] = useState<SystemStatus | null>(null);
const [history, setHistory] = useState<InfraHistory>({ DATABASE: [], REDIS: [], OLLAMA: [] });
const [workflows, setWorkflows] = useState<AIWorkflow[]>([]);
const [interactions, setInteractions] = useState<AIInteraction[]>([]);
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<HTMLInputElement>) => {
setSearchTicketId(e.target.value);
setWfOffset(0);
setIntOffset(0);
};
return (
<div className={styles.container}>
<header className={styles.header}>
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
>
<h1>Nexus Control</h1>
<p>Real-time infrastructure health and autonomous agent auditing</p>
</motion.div>
<div style={{ display: 'flex', alignItems: 'center', gap: '2rem' }}>
<div className={styles.searchInputWrapper}>
<Search size={16} className={styles.searchIcon} />
<input
type="text"
className={styles.searchInput}
placeholder="Search Ticket ID (UUID)..."
value={searchTicketId}
onChange={handleSearch}
/>
</div>
<div style={{ textAlign: 'right' }}>
<button
className={styles.refreshBtn}
onClick={fetchData}
disabled={loading}
>
<RefreshCcw size={16} className={loading ? 'spinning' : ''} />
Diagnostics
</button>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', color: 'var(--text3)', fontSize: '0.75rem', marginTop: '1rem', fontWeight: 600 }}>
<Clock size={12} />
Sync: {lastRefreshed.toLocaleTimeString()}
</div>
</div>
</div>
</header>
<section className={styles.grid}>
<StatusCard
title="Database Cluster"
node={status?.database}
history={history.DATABASE}
icon={Database}
color="#3b82f6"
loading={loading}
/>
<StatusCard
title="Workflow Queue"
node={status?.redis}
history={history.REDIS}
icon={Zap}
color="#ec4899"
loading={loading}
/>
<StatusCard
title="Inference Node"
node={status?.ollama}
history={history.OLLAMA}
icon={Brain}
color="#8b5cf6"
loading={loading}
/>
</section>
<div className={styles.sectionGrid}>
{/* Aggregated Workflows */}
<section className={styles.section}>
<div className={styles.sectionHeader}>
<div>
<div className={styles.sectionTitle}>
<Layout size={22} color="var(--accent)" />
Service Logic
</div>
<div className={styles.sectionSub}>Ticket Resolution Pipelines</div>
</div>
<div className={styles.pagination}>
<button
className={styles.pageBtn}
disabled={loading || wfOffset === 0}
onClick={() => setWfOffset(Math.max(0, wfOffset - PAGE_SIZE))}
>
<ChevronLeft size={14} /> Prev
</button>
<button
className={styles.pageBtn}
disabled={loading || workflows.length < PAGE_SIZE}
onClick={() => setWfOffset(wfOffset + PAGE_SIZE)}
>
Next <ChevronRight size={14} />
</button>
</div>
</div>
<div className={styles.list}>
<AnimatePresence mode="popLayout">
{workflows.map((wf, idx) => (
<motion.div
key={wf.id}
className={styles.item}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: idx * 0.05 }}
>
<div className={styles.itemMeta}>
<div className={styles.typeBadge}>
<Workflow size={14} color="var(--accent)" />
{wf.workflow_type}
<span className={styles.idTag}>#{wf.entity_id.slice(0,6)}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
<div className={styles.statusBadge}>{wf.current_stage}</div>
<div style={{ fontSize: '0.75rem', fontWeight: 900, color: 'var(--text3)' }}>
{wf.total_duration_ms.toFixed(0)}<span style={{ fontSize: '0.6rem', opacity: 0.6, marginLeft: '2px' }}>ms</span>
</div>
</div>
</div>
<div className={styles.track}>
{wf.steps.map((step, sIdx) => (
<React.Fragment key={sIdx}>
<div className={styles.step}>
<div className={`${styles.node} ${step.status}`} />
<div className={styles.nodeLabel}>{step.name}</div>
</div>
{sIdx < wf.steps.length - 1 && <div className={styles.connector} />}
</React.Fragment>
))}
</div>
</motion.div>
))}
{workflows.length === 0 && !loading && (
<div style={{ textAlign: 'center', padding: '4rem', color: 'var(--text3)' }}>
No historical workflows found matching query.
</div>
)}
</AnimatePresence>
</div>
</section>
{/* Granular Interactions */}
<section className={styles.section} style={{ background: 'rgba(255, 255, 255, 0.8)' }}>
<div className={styles.sectionHeader}>
<div>
<div className={styles.sectionTitle}>
<Activity size={22} color="#ec4899" />
Agent Audit
</div>
<div className={styles.sectionSub}>Live Autonomous Reasoning</div>
</div>
<div className={styles.pagination}>
<button
className={styles.pageBtn}
disabled={loading || intOffset === 0}
onClick={() => setIntOffset(Math.max(0, intOffset - PAGE_SIZE))}
>
<ChevronLeft size={14} /> Prev
</button>
<button
className={styles.pageBtn}
disabled={loading || interactions.length < PAGE_SIZE}
onClick={() => setIntOffset(intOffset + PAGE_SIZE)}
>
Next <ChevronRight size={14} />
</button>
</div>
</div>
<div className={styles.list}>
{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 (
<motion.div
key={interaction.id}
className={styles.item}
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: idx * 0.03 }}
>
<div className={styles.itemMeta}>
<div className={styles.agentHeader}>
<div className={styles.agentIcon}>{getAgentIcon(interaction.agent_name)}</div>
<div className={styles.agentName}>{interaction.agent_name.replace('_node', '')}</div>
<div style={{ marginLeft: '1rem', fontSize: '0.75rem', fontWeight: 900, color: 'var(--text3)' }}>
{duration.toFixed(0)}<span style={{ fontSize: '0.6rem', opacity: 0.6, marginLeft: '2px' }}>ms</span>
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--text3)' }}>
{new Date(interaction.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
</div>
{interaction.ticket_id && <div style={{ fontSize: '0.65rem', color: 'var(--accent)', fontWeight: 600 }}>TICKET #{interaction.ticket_id.slice(0,6)}</div>}
</div>
</div>
<div className={styles.track}>
{steps.map((s: any, sIdx: number) => (
<React.Fragment key={sIdx}>
<div className={styles.step}>
<div className={`${styles.node} ${s.status}`} />
<div className={styles.nodeLabel}>{s.name}</div>
</div>
{sIdx < steps.length - 1 && <div className={styles.connector} />}
</React.Fragment>
))}
{steps.length === 0 && <div style={{ fontSize: '0.7rem', color: 'var(--text3)', fontStyle: 'italic' }}>Node initiating...</div>}
</div>
{(errors.length > 0 || interaction.status === 'error') && (
<div className={styles.errorAura}>
<div className={styles.errorTitle}>
<AlertCircle size={14} />
Trace failure pinpointed
</div>
<div className={styles.errorText}>
{errors[0] || 'Unresponsive agent node. Reviewing local inference logs.'}
</div>
</div>
)}
</motion.div>
);
})}
{interactions.length === 0 && !loading && (
<div style={{ textAlign: 'center', padding: '4rem', color: 'var(--text3)' }}>
No granular interactions found matching query.
</div>
)}
</div>
</section>
</div>
</div>
);
};
export default InfraMonitor;