import React, { useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { Info, Network, ArrowRight, ChevronLeft, ChevronRight, AlertTriangle, Cpu, Hash, ExternalLink, Zap, } from "lucide-react"; import { TemporalNode, TemporalLink, GraphFrame } from "@/types/temporal"; import { UniversalNode, UniversalLink, UniversalGraphData, FailureItem, } from "@/types/graph-visualization"; import { KnowledgeGraph, OptimizationRecommendation } from "@/types"; import { MonacoEditorWithHighlights, Range, } from "@/components/shared/MonacoEditorWithHighlights"; import { InteractiveSystemSummary } from "@/components/shared/InteractiveSystemSummary"; // Entity-type-specific importance definitions from the multi-agent knowledge extractor const ENTITY_IMPORTANCE_BY_TYPE = { Agent: { HIGH: "Core agents that coordinate or manage other agents", MEDIUM: "Supporting agents with specialized but non-critical functions", LOW: "Auxiliary agents with very specific or rare functions", }, Task: { HIGH: "Critical tasks that are essential for system function or user goals", MEDIUM: "Standard operational tasks that support the main workflow", LOW: "Simple tasks with minimal impact on overall system success", }, Tool: { HIGH: "Essential tools that multiple agents depend on", MEDIUM: "Commonly used tools that enhance functionality", LOW: "Rarely used tools or utilities", }, Input: { HIGH: "Primary inputs that drive the entire workflow", MEDIUM: "Secondary inputs that provide additional context", LOW: "Optional inputs that provide minor enhancements", }, Output: { HIGH: "Final outputs that represent the main system deliverables", MEDIUM: "Intermediate outputs that feed into other processes", LOW: "Diagnostic or logging outputs", }, Human: { HIGH: "Key human stakeholders who make critical decisions", MEDIUM: "Regular human users who provide routine input", LOW: "Occasional human observers or reviewers", }, }; // Fallback combined definitions for unknown entity types const ENTITY_IMPORTANCE_DEFINITIONS = { HIGH: "Core agents that coordinate or manage other agents • Critical tasks that are essential for system function or user goals • Essential tools that multiple agents depend on • Primary inputs that drive the entire workflow • Final outputs that represent the main system deliverables • Key human stakeholders who make critical decisions", MEDIUM: "Supporting agents with specialized but non-critical functions • Standard operational tasks that support the main workflow • Commonly used tools that enhance functionality • Secondary inputs that provide additional context • Intermediate outputs that feed into other processes • Regular human users who provide routine input", LOW: "Auxiliary agents with very specific or rare functions • Simple tasks with minimal impact on overall system success • Rarely used tools or utilities • Optional inputs that provide minor enhancements • Diagnostic or logging outputs • Occasional human observers or reviewers", }; const RELATION_IMPORTANCE_DEFINITIONS = { HIGH: "Critical data flows that are essential for system operation • Core agent-task assignments that drive main functionality • Essential tool usage that multiple workflows depend on • Primary input consumption that initiates key processes • Final output delivery to key stakeholders • Critical intervention relationships that prevent failures", MEDIUM: "Standard operational workflows and data processing • Common agent-task interactions in normal operation • Regular tool usage that supports functionality • Secondary input processing that provides context • Intermediate output generation for downstream processes • Routine human interactions and feedback loops", LOW: "Auxiliary connections with minimal system impact • Optional workflow steps that can be skipped • Rarely used tool interactions or utilities • Diagnostic or logging data flows • Backup or redundant relationships • Occasional human oversight or monitoring", }; interface ElementInfoSidebarProps { selectedElement: | TemporalNode | TemporalLink | UniversalNode | UniversalLink | FailureItem | null; selectedElementType: "node" | "link" | "failure" | null; currentData: GraphFrame | UniversalGraphData; failures?: { id: string; risk_type: string; description: string; }[]; optimizations?: OptimizationRecommendation[]; onFailureSelect?: (failure: any) => void; // New props for System and Trace tabs knowledgeGraph?: KnowledgeGraph; numberedLines?: string[]; highlightRanges?: Range[]; showTraceTab?: boolean; // Callback for showing trace with highlighting onShowInTrace?: (ranges: Range[]) => void; // New callback for entity clicks from summary onEntitySelect?: (entityId: string) => void; } export const ElementInfoSidebar: React.FC = ({ selectedElement, selectedElementType, currentData, failures = [], optimizations = [], onFailureSelect, knowledgeGraph, numberedLines = [], highlightRanges = [], showTraceTab = true, onShowInTrace, onEntitySelect, }) => { const [isCollapsed, setIsCollapsed] = useState(false); // Default to system tab when knowledge graph is available, otherwise failures if they exist, otherwise system const getDefaultTab = () => { if (knowledgeGraph) { return "system"; } if (!selectedElement && failures.length > 0) { return "failures"; } if (!selectedElement && optimizations.length > 0) { return "optimizations"; } return "system"; }; const [activeTab, setActiveTab] = useState< "failures" | "system" | "trace" | "optimizations" >(getDefaultTab()); // Remove automatic tab switching - let user control tabs manually // useEffect(() => { // if ( // selectedElement && // selectedElementType && // selectedElementType !== "failure" // ) { // // When user selects a node/link (not failure), switch to details tab // setActiveTab("details"); // } else if (!selectedElement && failures.length > 0) { // // When nothing is selected but failures exist, show failures // setActiveTab("failures"); // } // }, [selectedElement, selectedElementType, failures.length]); console.log("ElementInfoSidebar props:", { selectedElement, selectedElementType, currentData: currentData ? { nodes: currentData.nodes.length, links: currentData.links.length } : null, }); if (isCollapsed) { return (
); } const renderContent = () => { if (!selectedElement || !selectedElementType) { return (

No Selection

Click on a node or relation to view its details

); } if (selectedElementType === "node") { return renderNodeInfo(selectedElement as TemporalNode | UniversalNode); } else if (selectedElementType === "link") { return renderLinkInfo(selectedElement as TemporalLink | UniversalLink); } else { // For failures, don't show details here - let failures tab handle it return (

Failure Selected

View failure details in the Failures tab

); } }; const renderNodeInfo = (node: TemporalNode | UniversalNode) => { // Find connections for this node const connections = currentData.links.filter( (link) => (typeof link.source === "object" ? link.source.id : link.source) === node.id || (typeof link.target === "object" ? link.target.id : link.target) === node.id ); // Get importance from node data const importance = (node as any).importance; return ( Node Details {/* Main Info Section - Improved layout to prevent overflow */}

{node.name || node.id}

{node.type || "Unknown"} {/* Moved importance badge here */} {importance && (
{importance}

{importance} Importance

{ENTITY_IMPORTANCE_BY_TYPE[ node.type as keyof typeof ENTITY_IMPORTANCE_BY_TYPE ]?.[ importance as keyof typeof ENTITY_IMPORTANCE_BY_TYPE.Agent ] || ENTITY_IMPORTANCE_DEFINITIONS[ importance as keyof typeof ENTITY_IMPORTANCE_DEFINITIONS ] ?.split("•")[0] ?.trim() || "No definition available"}

)}
{/* Show in Trace button for nodes - Icon only to save space */} {showTraceTab && ((node as any).raw_text_ref || (node as any).raw_prompt_ref) && Array.isArray( (node as any).raw_text_ref || (node as any).raw_prompt_ref ) && ((node as any).raw_text_ref || (node as any).raw_prompt_ref) .length > 0 && (

Show in Trace

)}
{/* Connections Section - Simplified */} {connections.length > 0 && (

Connections ({connections.length})

{connections.map((link, index) => { const isSource = (typeof link.source === "object" ? link.source.id : link.source) === node.id; const connectedNodeId = isSource ? typeof link.target === "object" ? link.target.id : link.target : typeof link.source === "object" ? link.source.id : link.source; const connectedNode = currentData.nodes.find( (n) => n.id === connectedNodeId ); return (
{connectedNode?.name || connectedNodeId}
{link.type || "related"}
); })}
)}
); }; const renderLinkInfo = (link: TemporalLink | UniversalLink) => { const sourceId = typeof link.source === "object" ? link.source.id : link.source; const targetId = typeof link.target === "object" ? link.target.id : link.target; const sourceNode = currentData.nodes.find((n) => n.id === sourceId); const targetNode = currentData.nodes.find((n) => n.id === targetId); // Get importance from link data const importance = (link as any).importance; return ( Relation Details {/* Main Info Section - Improved layout to match Node Details */}

{link.type || "Relation"}

{link.type || "Unknown"} {/* Importance badge inline - matching Node Details */} {importance && (
{importance}

{importance} Importance

{RELATION_IMPORTANCE_DEFINITIONS[ importance as keyof typeof RELATION_IMPORTANCE_DEFINITIONS ] ?.split("•")[0] ?.trim() || "No definition available"}

)}
{/* Show in Trace button for relations - Icon only to save space */} {showTraceTab && ((link as any).raw_text_ref || (link as any).raw_prompt_ref || (link as any).interaction_prompt_ref) && Array.isArray( (link as any).raw_text_ref || (link as any).raw_prompt_ref || (link as any).interaction_prompt_ref ) && ( (link as any).raw_text_ref || (link as any).raw_prompt_ref || (link as any).interaction_prompt_ref ).length > 0 && (

Show in Trace

)}
{/* Connection Section - Simplified to match Node Details style */}

Connection

Source: {sourceNode?.name || sourceId}
Target: {targetNode?.name || targetId}
); }; const renderFailuresContent = () => { if (failures.length === 0) { return (

No Failures

No failures detected in this trace

); } return (

Failures detected in trace:

{failures.map((failure) => { // Use enriched failure data if available, otherwise fallback to basic lookup const affectedElementName = (failure as any).displayName || ((failure as any).affected_id ? (failure as any).affected_id : null); const hasMatchedElement = !!(failure as any).matchedElement; return ( onFailureSelect?.(failure)} > {/* Header with risk type and Show in Trace button */}
{failure.risk_type === "EXECUTION_ERROR" && ( <> EXECUTION )} {failure.risk_type === "AGENT_ERROR" && ( <> AGENT )} {failure.risk_type === "PLANNING_ERROR" && ( <> PLANNING )} {failure.risk_type === "RETRIEVAL_ERROR" && ( <> RETRIEVAL )} {failure.risk_type === "HALLUCINATION" && ( <> HALLUCINATION )} {![ "EXECUTION_ERROR", "AGENT_ERROR", "PLANNING_ERROR", "RETRIEVAL_ERROR", "HALLUCINATION", ].includes(failure.risk_type) && ( <> OTHER )}
{/* Show in Trace button - Only show if trace references exist */} {showTraceTab && (failure as any).raw_text_ref && Array.isArray((failure as any).raw_text_ref) && (failure as any).raw_text_ref.length > 0 && ( )}
{/* Description */}

{failure.description}

{/* Affected Element - Always show if affected_id exists */} {(failure as any).affected_id && (
Affects: {affectedElementName || (failure as any).affected_id} {!hasMatchedElement && ( (element not found in graph) )}
)}
); })}
); }; const renderOptimizationsContent = () => { console.log( "🔧 renderOptimizationsContent called, optimizations:", optimizations ); return (

Recommendations for improving this system:

{optimizations.map((opt) => { const knownTypes = [ "WORKFLOW_SIMPLIFICATION", "AGENT_MERGING", "TASK_CONSOLIDATION", "TOOL_ENHANCEMENT", "PROMPT_REFINEMENT", ] as const; return (
{opt.recommendation_type === "WORKFLOW_SIMPLIFICATION" && ( <> WORKFLOW )} {opt.recommendation_type === "AGENT_MERGING" && ( <> AGENTS )} {opt.recommendation_type === "TASK_CONSOLIDATION" && ( <> TASKS )} {opt.recommendation_type === "TOOL_ENHANCEMENT" && ( <> TOOLS )} {opt.recommendation_type === "PROMPT_REFINEMENT" && ( <> PROMPTS )} {!knownTypes.includes(opt.recommendation_type as any) && ( <> OTHER )}
{showTraceTab && opt.raw_text_ref && Array.isArray(opt.raw_text_ref) && opt.raw_text_ref.length > 0 && ( )}

{opt.description}

{(opt as any).affected_nodes && (opt as any).affected_nodes.length > 0 && (
Affects: {(opt as any).affected_nodes.map( (node: { id: string; name: string }) => ( onEntitySelect?.(node.id)} > {node.name}

{node.name}

) )}
)}
); })}
); }; // Add System content renderer (based on TraceViewerSidebar) const renderSystemContent = () => { if (!knowledgeGraph) { return (

System Information

No system data available for this view

); } return (
{/* System Hero Section */}
{knowledgeGraph.system_name && (

{knowledgeGraph.system_name}

)} {knowledgeGraph.system_summary && ( onEntitySelect?.(entityId)} selectedNodeId={ selectedElement && selectedElementType === "node" ? selectedElement.id : null } /> )}
{/* Subtle background pattern */}
{/* Details Section - Merged from Details tab */}
{renderContent()}
); }; // Add Trace content renderer using the new MonacoEditorWithHighlights component const renderTraceContent = () => { if (!numberedLines || numberedLines.length === 0) { return (

No Trace Data

No trace content available for this view

); } return ( ); }; return (
{knowledgeGraph && ( System )} Failures {optimizations.length > 0 && ( Optimization )} {showTraceTab && numberedLines.length > 0 && ( Trace )}
{/* Content */}
{activeTab === "failures" ? renderFailuresContent() : activeTab === "system" ? renderSystemContent() : activeTab === "trace" ? renderTraceContent() : activeTab === "optimizations" ? renderOptimizationsContent() : renderSystemContent()}
{/* Footer with navigation hint */} {activeTab === "trace" && highlightRanges.length > 0 && (
Press {"<"} {">"} to navigate
)}
); };