feat: Add panel management, validation, and error handling to canvas

Phase 1 - Panel Management System:
- Create usePanelStore.ts for centralized panel state management
- Add PanelContainer.tsx for draggable floating panels
- Create FloatingIntrospectionPanel.tsx (persistent, doesn't disappear on node click)
- Create ResultsPanel.tsx for trial result details
- Refactor NodeConfigPanelV2 to use panel store for introspection
- Integrate PanelContainer into CanvasView

Phase 2 - Pre-run Validation:
- Create specValidator.ts with comprehensive validation rules
- Add ValidationPanel (enhanced version with error navigation)
- Add Validate button to SpecRenderer with status indicator
- Block run if validation fails
- Check for: design vars, objectives, extractors, bounds, connections

Phase 3 - Error Handling & Recovery:
- Create ErrorPanel.tsx for displaying optimization errors
- Add error classification (nx_crash, solver_fail, extractor_error, etc.)
- Add recovery suggestions based on error type
- Update status endpoint to return error info
- Add _get_study_error_info helper to check error_status.json and DB
- Integrate error detection into status polling

Documentation:
- Add CANVAS_ROBUSTNESS_PLAN.md with full implementation plan
This commit is contained in:
2026-01-21 21:35:31 -05:00
parent e1c59a51c1
commit c224b16ac3
12 changed files with 2853 additions and 29 deletions

View File

@@ -11,7 +11,7 @@
*/
import { useCallback, useRef, useEffect, useMemo, useState, DragEvent } from 'react';
import { Play, Square, Loader2, Eye, EyeOff } from 'lucide-react';
import { Play, Square, Loader2, Eye, EyeOff, CheckCircle, AlertCircle } from 'lucide-react';
import ReactFlow, {
Background,
Controls,
@@ -38,8 +38,10 @@ import {
useSelectedEdgeId,
} from '../../hooks/useSpecStore';
import { useSpecWebSocket } from '../../hooks/useSpecWebSocket';
import { usePanelStore } from '../../hooks/usePanelStore';
import { ConnectionStatusIndicator } from './ConnectionStatusIndicator';
import { CanvasNodeData } from '../../lib/canvas/schema';
import { validateSpec, canRunOptimization } from '../../lib/validation/specValidator';
// ============================================================================
// Drag-Drop Helpers
@@ -202,11 +204,18 @@ function SpecRendererInner({
const wsStudyId = enableWebSocket ? storeStudyId : null;
const { status: wsStatus } = useSpecWebSocket(wsStudyId);
// Panel store for validation and error panels
const { setValidationData, addError, openPanel } = usePanelStore();
// Optimization execution state
const [isRunning, setIsRunning] = useState(false);
const [isStarting, setIsStarting] = useState(false);
const [bestTrial, setBestTrial] = useState<any>(null);
const [showResults, setShowResults] = useState(false);
const [validationStatus, setValidationStatus] = useState<'valid' | 'invalid' | 'unchecked'>('unchecked');
// Track last seen error timestamp to avoid duplicates
const lastErrorTimestamp = useRef<number>(0);
// Poll optimization status
useEffect(() => {
@@ -226,19 +235,119 @@ function SpecRendererInner({
setShowResults(true);
}
}
// Handle errors from the optimization process
if (data.error && data.error_timestamp && data.error_timestamp > lastErrorTimestamp.current) {
lastErrorTimestamp.current = data.error_timestamp;
// Classify the error based on the message
let errorType: 'nx_crash' | 'solver_fail' | 'extractor_error' | 'config_error' | 'system_error' | 'unknown' = 'unknown';
const errorMsg = data.error.toLowerCase();
if (errorMsg.includes('nx') || errorMsg.includes('siemens') || errorMsg.includes('journal')) {
errorType = 'nx_crash';
} else if (errorMsg.includes('solver') || errorMsg.includes('nastran') || errorMsg.includes('convergence')) {
errorType = 'solver_fail';
} else if (errorMsg.includes('extractor') || errorMsg.includes('extract') || errorMsg.includes('op2')) {
errorType = 'extractor_error';
} else if (errorMsg.includes('config') || errorMsg.includes('spec') || errorMsg.includes('parameter')) {
errorType = 'config_error';
} else if (errorMsg.includes('system') || errorMsg.includes('permission') || errorMsg.includes('disk')) {
errorType = 'system_error';
}
// Generate suggestions based on error type
const suggestions: string[] = [];
switch (errorType) {
case 'nx_crash':
suggestions.push('Check if NX is running and licensed');
suggestions.push('Verify the model file is not corrupted');
suggestions.push('Try closing and reopening NX');
break;
case 'solver_fail':
suggestions.push('Check the mesh quality in the FEM file');
suggestions.push('Verify boundary conditions are properly defined');
suggestions.push('Review the solver settings');
break;
case 'extractor_error':
suggestions.push('Verify the OP2 file was created successfully');
suggestions.push('Check if the extractor type matches the analysis');
suggestions.push('For custom extractors, review the code for errors');
break;
case 'config_error':
suggestions.push('Run validation to check the spec');
suggestions.push('Verify all design variables have valid bounds');
break;
default:
suggestions.push('Check the optimization logs for more details');
}
addError({
type: errorType,
trial: data.current_trial,
message: data.error,
details: data.error_details,
recoverable: errorType !== 'config_error',
suggestions,
timestamp: data.error_timestamp || Date.now(),
});
}
// Handle failed status
if (data.status === 'failed' && data.error) {
setIsRunning(false);
}
}
} catch (e) {
// Silent fail on polling
// Silent fail on polling - network issues shouldn't spam errors
console.debug('Status poll failed:', e);
}
};
checkStatus();
const interval = setInterval(checkStatus, 3000);
return () => clearInterval(interval);
}, [studyId]);
}, [studyId, addError]);
// Validate the spec and show results in panel
const handleValidate = useCallback(() => {
if (!spec) return;
const result = validateSpec(spec);
setValidationData(result);
setValidationStatus(result.valid ? 'valid' : 'invalid');
// Auto-open validation panel if there are issues
if (!result.valid || result.warnings.length > 0) {
openPanel('validation');
}
return result;
}, [spec, setValidationData, openPanel]);
const handleRun = async () => {
if (!studyId) return;
if (!studyId || !spec) return;
// Validate before running
const validation = handleValidate();
if (!validation || !validation.valid) {
// Show validation panel with errors
return;
}
// Also do a quick sanity check
const { canRun, reason } = canRunOptimization(spec);
if (!canRun) {
addError({
type: 'config_error',
message: reason || 'Cannot run optimization',
recoverable: false,
suggestions: ['Check the validation panel for details'],
timestamp: Date.now(),
});
return;
}
setIsStarting(true);
try {
const res = await fetch(`/api/optimization/studies/${studyId}/run`, {
@@ -251,8 +360,19 @@ function SpecRendererInner({
throw new Error(err.detail || 'Failed to start');
}
setIsRunning(true);
setValidationStatus('unchecked'); // Clear validation status when running
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start optimization');
const errorMessage = e instanceof Error ? e.message : 'Failed to start optimization';
setError(errorMessage);
// Also add to error panel for persistence
addError({
type: 'system_error',
message: errorMessage,
recoverable: true,
suggestions: ['Check if the backend is running', 'Verify the study configuration'],
timestamp: Date.now(),
});
} finally {
setIsStarting(false);
}
@@ -261,10 +381,22 @@ function SpecRendererInner({
const handleStop = async () => {
if (!studyId) return;
try {
await fetch(`/api/optimization/studies/${studyId}/stop`, { method: 'POST' });
const res = await fetch(`/api/optimization/studies/${studyId}/stop`, { method: 'POST' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.detail || 'Failed to stop');
}
setIsRunning(false);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to stop optimization');
const errorMessage = e instanceof Error ? e.message : 'Failed to stop optimization';
setError(errorMessage);
addError({
type: 'system_error',
message: errorMessage,
recoverable: false,
suggestions: ['The optimization may still be running in the background'],
timestamp: Date.now(),
});
}
};
@@ -637,6 +769,7 @@ function SpecRendererInner({
{/* Action Buttons */}
<div className="absolute bottom-4 right-4 z-10 flex gap-2">
{/* Results toggle */}
{bestTrial && (
<button
onClick={() => setShowResults(!showResults)}
@@ -652,26 +785,54 @@ function SpecRendererInner({
</button>
)}
{/* Validate button - shows validation status */}
<button
onClick={handleValidate}
className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors border ${
validationStatus === 'valid'
? 'bg-green-600/20 text-green-400 border-green-500/50 hover:bg-green-600/30'
: validationStatus === 'invalid'
? 'bg-red-600/20 text-red-400 border-red-500/50 hover:bg-red-600/30'
: 'bg-dark-800 text-dark-300 border-dark-600 hover:text-white hover:border-dark-500'
}`}
title="Validate spec before running"
>
{validationStatus === 'valid' ? (
<CheckCircle size={16} />
) : validationStatus === 'invalid' ? (
<AlertCircle size={16} />
) : (
<CheckCircle size={16} />
)}
<span className="text-sm font-medium">Validate</span>
</button>
{/* Run/Stop button */}
{isRunning ? (
<button
onClick={handleStop}
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-500 shadow-lg transition-colors font-medium"
>
<Square size={16} fill="currentColor" />
Stop Optimization
Stop
</button>
) : (
<button
onClick={handleRun}
disabled={isStarting}
className="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-500 shadow-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
disabled={isStarting || validationStatus === 'invalid'}
className={`flex items-center gap-2 px-4 py-2 rounded-lg shadow-lg transition-colors font-medium ${
validationStatus === 'invalid'
? 'bg-dark-700 text-dark-400 cursor-not-allowed'
: 'bg-emerald-600 text-white hover:bg-emerald-500 disabled:opacity-50 disabled:cursor-not-allowed'
}`}
title={validationStatus === 'invalid' ? 'Fix validation errors first' : 'Start optimization'}
>
{isStarting ? (
<Loader2 size={16} className="animate-spin" />
) : (
<Play size={16} fill="currentColor" />
)}
Run Optimization
Run
</button>
)}
</div>

View File

@@ -0,0 +1,255 @@
/**
* ErrorPanel - Displays optimization errors with recovery options
*
* Shows errors that occurred during optimization with:
* - Error classification (NX crash, solver failure, etc.)
* - Recovery suggestions
* - Ability to dismiss individual errors
* - Support for multiple simultaneous errors
*/
import { useMemo } from 'react';
import {
X,
AlertTriangle,
AlertOctagon,
RefreshCw,
Minimize2,
Maximize2,
Trash2,
Bug,
Cpu,
FileWarning,
Settings,
Server,
} from 'lucide-react';
import { useErrorPanel, usePanelStore, OptimizationError } from '../../../hooks/usePanelStore';
interface ErrorPanelProps {
onClose: () => void;
onRetry?: (trial?: number) => void;
onSkipTrial?: (trial: number) => void;
}
export function ErrorPanel({ onClose, onRetry, onSkipTrial }: ErrorPanelProps) {
const panel = useErrorPanel();
const { minimizePanel, dismissError, clearErrors } = usePanelStore();
const sortedErrors = useMemo(() => {
return [...panel.errors].sort((a, b) => b.timestamp - a.timestamp);
}, [panel.errors]);
if (!panel.open || panel.errors.length === 0) return null;
// Minimized view
if (panel.minimized) {
return (
<div
className="bg-dark-850 border border-red-500/50 rounded-lg shadow-xl flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-dark-800 transition-colors"
onClick={() => minimizePanel('error')}
>
<AlertOctagon size={16} className="text-red-400" />
<span className="text-sm text-white font-medium">
{panel.errors.length} Error{panel.errors.length !== 1 ? 's' : ''}
</span>
<Maximize2 size={14} className="text-dark-400" />
</div>
);
}
return (
<div className="bg-dark-850 border border-red-500/30 rounded-xl w-[420px] max-h-[500px] flex flex-col shadow-xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-dark-700 bg-red-500/5">
<div className="flex items-center gap-2">
<AlertOctagon size={18} className="text-red-400" />
<span className="font-medium text-white">
Optimization Errors ({panel.errors.length})
</span>
</div>
<div className="flex items-center gap-1">
{panel.errors.length > 1 && (
<button
onClick={clearErrors}
className="p-1.5 text-dark-400 hover:text-red-400 hover:bg-red-500/10 rounded transition-colors"
title="Clear all errors"
>
<Trash2 size={14} />
</button>
)}
<button
onClick={() => minimizePanel('error')}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
title="Minimize"
>
<Minimize2 size={14} />
</button>
<button
onClick={onClose}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
>
<X size={14} />
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-3 space-y-3">
{sortedErrors.map((error) => (
<ErrorItem
key={error.timestamp}
error={error}
onDismiss={() => dismissError(error.timestamp)}
onRetry={onRetry}
onSkipTrial={onSkipTrial}
/>
))}
</div>
</div>
);
}
// ============================================================================
// Error Item Component
// ============================================================================
interface ErrorItemProps {
error: OptimizationError;
onDismiss: () => void;
onRetry?: (trial?: number) => void;
onSkipTrial?: (trial: number) => void;
}
function ErrorItem({ error, onDismiss, onRetry, onSkipTrial }: ErrorItemProps) {
const icon = getErrorIcon(error.type);
const typeLabel = getErrorTypeLabel(error.type);
const timeAgo = getTimeAgo(error.timestamp);
return (
<div className="bg-dark-800 rounded-lg border border-dark-700 overflow-hidden">
{/* Error header */}
<div className="flex items-start gap-3 p-3">
<div className="p-2 bg-red-500/10 rounded-lg flex-shrink-0">
{icon}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-medium text-red-400 uppercase tracking-wide">
{typeLabel}
</span>
{error.trial !== undefined && (
<span className="text-xs text-dark-500">
Trial #{error.trial}
</span>
)}
<span className="text-xs text-dark-600 ml-auto">
{timeAgo}
</span>
</div>
<p className="text-sm text-white">{error.message}</p>
{error.details && (
<p className="text-xs text-dark-400 mt-1 font-mono bg-dark-900 p-2 rounded mt-2 max-h-20 overflow-y-auto">
{error.details}
</p>
)}
</div>
<button
onClick={onDismiss}
className="p-1 text-dark-500 hover:text-white hover:bg-dark-700 rounded transition-colors flex-shrink-0"
title="Dismiss"
>
<X size={14} />
</button>
</div>
{/* Suggestions */}
{error.suggestions.length > 0 && (
<div className="px-3 pb-3">
<p className="text-xs text-dark-500 mb-1.5">Suggestions:</p>
<ul className="text-xs text-dark-300 space-y-1">
{error.suggestions.map((suggestion, idx) => (
<li key={idx} className="flex items-start gap-1.5">
<span className="text-dark-500">-</span>
<span>{suggestion}</span>
</li>
))}
</ul>
</div>
)}
{/* Actions */}
{error.recoverable && (
<div className="flex items-center gap-2 px-3 pb-3">
{onRetry && (
<button
onClick={() => onRetry(error.trial)}
className="flex items-center gap-1.5 px-3 py-1.5 bg-primary-600 hover:bg-primary-500
text-white text-xs font-medium rounded transition-colors"
>
<RefreshCw size={12} />
Retry{error.trial !== undefined ? ' Trial' : ''}
</button>
)}
{onSkipTrial && error.trial !== undefined && (
<button
onClick={() => onSkipTrial(error.trial!)}
className="flex items-center gap-1.5 px-3 py-1.5 bg-dark-700 hover:bg-dark-600
text-dark-200 text-xs font-medium rounded transition-colors"
>
Skip Trial
</button>
)}
</div>
)}
</div>
);
}
// ============================================================================
// Helper Functions
// ============================================================================
function getErrorIcon(type: OptimizationError['type']) {
switch (type) {
case 'nx_crash':
return <Cpu size={16} className="text-red-400" />;
case 'solver_fail':
return <AlertTriangle size={16} className="text-amber-400" />;
case 'extractor_error':
return <FileWarning size={16} className="text-orange-400" />;
case 'config_error':
return <Settings size={16} className="text-blue-400" />;
case 'system_error':
return <Server size={16} className="text-purple-400" />;
default:
return <Bug size={16} className="text-red-400" />;
}
}
function getErrorTypeLabel(type: OptimizationError['type']) {
switch (type) {
case 'nx_crash':
return 'NX Crash';
case 'solver_fail':
return 'Solver Failure';
case 'extractor_error':
return 'Extractor Error';
case 'config_error':
return 'Configuration Error';
case 'system_error':
return 'System Error';
default:
return 'Unknown Error';
}
}
function getTimeAgo(timestamp: number): string {
const seconds = Math.floor((Date.now() - timestamp) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
export default ErrorPanel;

View File

@@ -0,0 +1,481 @@
/**
* FloatingIntrospectionPanel - Persistent introspection panel using store
*
* This is a wrapper around the existing IntrospectionPanel that:
* 1. Gets its state from usePanelStore instead of local state
* 2. Persists data when the panel is closed and reopened
* 3. Can be opened from anywhere without losing state
*/
import { useState, useEffect, useCallback, useMemo } from 'react';
import {
X,
Search,
RefreshCw,
Plus,
ChevronDown,
ChevronRight,
FileBox,
Cpu,
SlidersHorizontal,
AlertTriangle,
Scale,
Link,
Box,
Settings2,
GitBranch,
File,
Grid3x3,
Target,
Zap,
Layers,
Minimize2,
Maximize2,
} from 'lucide-react';
import {
useIntrospectionPanel,
usePanelStore,
IntrospectionData,
} from '../../../hooks/usePanelStore';
import { useSpecStore } from '../../../hooks/useSpecStore';
interface FloatingIntrospectionPanelProps {
onClose: () => void;
}
// Reuse types from original IntrospectionPanel
interface Expression {
name: string;
value: number;
rhs?: string;
min?: number;
max?: number;
unit?: string;
units?: string;
type: string;
source?: string;
}
interface ExpressionsResult {
user: Expression[];
internal: Expression[];
total_count: number;
user_count: number;
}
interface ModelFileInfo {
name: string;
stem: string;
type: string;
description?: string;
size_kb: number;
has_cache: boolean;
}
interface ModelFilesResponse {
files: {
sim: ModelFileInfo[];
afm: ModelFileInfo[];
fem: ModelFileInfo[];
idealized: ModelFileInfo[];
prt: ModelFileInfo[];
};
all_files: ModelFileInfo[];
}
export function FloatingIntrospectionPanel({ onClose }: FloatingIntrospectionPanelProps) {
const panel = useIntrospectionPanel();
const {
minimizePanel,
updateIntrospectionResult,
setIntrospectionLoading,
setIntrospectionError,
setIntrospectionFile,
} = usePanelStore();
const { addNode } = useSpecStore();
// Local UI state
const [expandedSections, setExpandedSections] = useState<Set<string>>(
new Set(['expressions', 'extractors', 'file_deps', 'fea_results', 'fem_mesh', 'sim_solutions', 'sim_bcs'])
);
const [searchTerm, setSearchTerm] = useState('');
const [modelFiles, setModelFiles] = useState<ModelFilesResponse | null>(null);
const [isLoadingFiles, setIsLoadingFiles] = useState(false);
const data = panel.data;
const result = data?.result;
const isLoading = data?.isLoading || false;
const error = data?.error;
// Fetch available files when studyId changes
const fetchAvailableFiles = useCallback(async () => {
if (!data?.studyId) return;
setIsLoadingFiles(true);
try {
const res = await fetch(`/api/optimization/studies/${data.studyId}/nx/parts`);
if (res.ok) {
const filesData = await res.json();
setModelFiles(filesData);
}
} catch (e) {
console.error('Failed to fetch model files:', e);
} finally {
setIsLoadingFiles(false);
}
}, [data?.studyId]);
// Run introspection
const runIntrospection = useCallback(async (fileName?: string) => {
if (!data?.filePath && !data?.studyId) return;
setIntrospectionLoading(true);
setIntrospectionError(null);
try {
let res;
if (data?.studyId) {
const endpoint = fileName
? `/api/optimization/studies/${data.studyId}/nx/introspect/${encodeURIComponent(fileName)}`
: `/api/optimization/studies/${data.studyId}/nx/introspect`;
res = await fetch(endpoint);
} else {
res = await fetch('/api/nx/introspect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_path: data?.filePath }),
});
}
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.detail || 'Introspection failed');
}
const responseData = await res.json();
updateIntrospectionResult(responseData.introspection || responseData);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to introspect model';
setIntrospectionError(msg);
console.error('Introspection error:', e);
}
}, [data?.filePath, data?.studyId, setIntrospectionLoading, setIntrospectionError, updateIntrospectionResult]);
// Fetch files list on mount
useEffect(() => {
fetchAvailableFiles();
}, [fetchAvailableFiles]);
// Run introspection when panel opens or selected file changes
useEffect(() => {
if (panel.open && data && !result && !isLoading) {
runIntrospection(data.selectedFile);
}
}, [panel.open, data?.selectedFile]); // eslint-disable-line react-hooks/exhaustive-deps
const handleFileChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newFile = e.target.value;
setIntrospectionFile(newFile);
runIntrospection(newFile);
};
const toggleSection = (section: string) => {
setExpandedSections((prev) => {
const next = new Set(prev);
if (next.has(section)) next.delete(section);
else next.add(section);
return next;
});
};
// Handle both array format (old) and object format (new API)
const allExpressions: Expression[] = useMemo(() => {
if (!result?.expressions) return [];
if (Array.isArray(result.expressions)) {
return result.expressions as Expression[];
}
const exprObj = result.expressions as ExpressionsResult;
return [...(exprObj.user || []), ...(exprObj.internal || [])];
}, [result?.expressions]);
const filteredExpressions = allExpressions.filter((e) =>
e.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const addExpressionAsDesignVar = (expr: Expression) => {
const minValue = expr.min ?? expr.value * 0.5;
const maxValue = expr.max ?? expr.value * 1.5;
addNode('dv', {
name: expr.name,
expression_name: expr.name,
type: 'continuous',
bounds: { min: minValue, max: maxValue },
baseline: expr.value,
units: expr.unit || expr.units,
enabled: true,
});
};
if (!panel.open) return null;
// Minimized view
if (panel.minimized) {
return (
<div
className="bg-dark-850 border border-dark-700 rounded-lg shadow-xl flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-dark-800 transition-colors"
onClick={() => minimizePanel('introspection')}
>
<Search size={16} className="text-primary-400" />
<span className="text-sm text-white font-medium">
Model Introspection
{data?.selectedFile && <span className="text-dark-400 ml-1">({data.selectedFile})</span>}
</span>
<Maximize2 size={14} className="text-dark-400" />
</div>
);
}
return (
<div className="bg-dark-850 border border-dark-700 rounded-xl w-80 max-h-[70vh] flex flex-col shadow-xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-dark-700">
<div className="flex items-center gap-2">
<Search size={16} className="text-primary-400" />
<span className="font-medium text-white text-sm">
Model Introspection
{data?.selectedFile && <span className="text-primary-400 ml-1">({data.selectedFile})</span>}
</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={() => runIntrospection(data?.selectedFile)}
disabled={isLoading}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
title="Refresh"
>
<RefreshCw size={14} className={isLoading ? 'animate-spin' : ''} />
</button>
<button
onClick={() => minimizePanel('introspection')}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
title="Minimize"
>
<Minimize2 size={14} />
</button>
<button
onClick={onClose}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
>
<X size={14} />
</button>
</div>
</div>
{/* File Selector + Search */}
<div className="px-4 py-2 border-b border-dark-700 space-y-2">
{data?.studyId && modelFiles && modelFiles.all_files.length > 0 && (
<div className="flex items-center gap-2">
<label className="text-xs text-dark-400 whitespace-nowrap">File:</label>
<select
value={data?.selectedFile || ''}
onChange={handleFileChange}
disabled={isLoading || isLoadingFiles}
className="flex-1 px-2 py-1.5 bg-dark-800 border border-dark-600 rounded-lg
text-sm text-white focus:outline-none focus:border-primary-500
disabled:opacity-50"
>
<option value="">Default (Assembly)</option>
{modelFiles.files.sim.length > 0 && (
<optgroup label="Simulation (.sim)">
{modelFiles.files.sim.map(f => (
<option key={f.name} value={f.name}>
{f.stem} ({f.size_kb > 1000 ? `${(f.size_kb/1024).toFixed(1)}MB` : `${f.size_kb}KB`})
</option>
))}
</optgroup>
)}
{modelFiles.files.afm.length > 0 && (
<optgroup label="Assembly FEM (.afm)">
{modelFiles.files.afm.map(f => (
<option key={f.name} value={f.name}>
{f.stem} ({f.size_kb > 1000 ? `${(f.size_kb/1024).toFixed(1)}MB` : `${f.size_kb}KB`})
</option>
))}
</optgroup>
)}
{modelFiles.files.fem.length > 0 && (
<optgroup label="FEM (.fem)">
{modelFiles.files.fem.map(f => (
<option key={f.name} value={f.name}>
{f.stem} ({f.size_kb > 1000 ? `${(f.size_kb/1024).toFixed(1)}MB` : `${f.size_kb}KB`})
</option>
))}
</optgroup>
)}
{modelFiles.files.prt.length > 0 && (
<optgroup label="Geometry (.prt)">
{modelFiles.files.prt.map(f => (
<option key={f.name} value={f.name}>
{f.stem} ({f.size_kb > 1000 ? `${(f.size_kb/1024).toFixed(1)}MB` : `${f.size_kb}KB`})
</option>
))}
</optgroup>
)}
{modelFiles.files.idealized.length > 0 && (
<optgroup label="Idealized (_i.prt)">
{modelFiles.files.idealized.map(f => (
<option key={f.name} value={f.name}>
{f.stem} ({f.size_kb > 1000 ? `${(f.size_kb/1024).toFixed(1)}MB` : `${f.size_kb}KB`})
</option>
))}
</optgroup>
)}
</select>
{isLoadingFiles && (
<RefreshCw size={12} className="animate-spin text-dark-400" />
)}
</div>
)}
<input
type="text"
placeholder="Filter expressions..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-3 py-1.5 bg-dark-800 border border-dark-600 rounded-lg
text-sm text-white placeholder-dark-500 focus:outline-none focus:border-primary-500"
/>
</div>
{/* Content */}
<div className="flex-1 overflow-auto">
{isLoading ? (
<div className="flex items-center justify-center h-32 text-dark-500">
<RefreshCw size={20} className="animate-spin mr-2" />
Analyzing model...
</div>
) : error ? (
<div className="p-4 text-red-400 text-sm">{error}</div>
) : result ? (
<div className="p-2 space-y-2">
{/* Solver Type */}
{result.solver_type && (
<div className="p-2 bg-dark-800 rounded-lg">
<div className="flex items-center gap-2 text-sm">
<Cpu size={14} className="text-violet-400" />
<span className="text-dark-300">Solver:</span>
<span className="text-white font-medium">{result.solver_type as string}</span>
</div>
</div>
)}
{/* Expressions Section */}
<div className="border border-dark-700 rounded-lg overflow-hidden">
<button
onClick={() => toggleSection('expressions')}
className="w-full flex items-center justify-between px-3 py-2 bg-dark-800 hover:bg-dark-750 transition-colors"
>
<div className="flex items-center gap-2">
<SlidersHorizontal size={14} className="text-emerald-400" />
<span className="text-sm font-medium text-white">
Expressions ({filteredExpressions.length})
</span>
</div>
{expandedSections.has('expressions') ? (
<ChevronDown size={14} className="text-dark-400" />
) : (
<ChevronRight size={14} className="text-dark-400" />
)}
</button>
{expandedSections.has('expressions') && (
<div className="p-2 space-y-1 max-h-48 overflow-y-auto">
{filteredExpressions.length === 0 ? (
<p className="text-xs text-dark-500 text-center py-2">
No expressions found
</p>
) : (
filteredExpressions.map((expr) => (
<div
key={expr.name}
className="flex items-center justify-between p-2 bg-dark-850 rounded hover:bg-dark-750 group transition-colors"
>
<div className="flex-1 min-w-0">
<p className="text-sm text-white truncate">{expr.name}</p>
<p className="text-xs text-dark-500">
{expr.value} {expr.units || expr.unit || ''}
{expr.source === 'inferred' && (
<span className="ml-1 text-amber-500">(inferred)</span>
)}
</p>
</div>
<button
onClick={() => addExpressionAsDesignVar(expr)}
className="p-1.5 text-dark-500 hover:text-primary-400 hover:bg-dark-700 rounded
opacity-0 group-hover:opacity-100 transition-all"
title="Add as Design Variable"
>
<Plus size={14} />
</button>
</div>
))
)}
</div>
)}
</div>
{/* Mass Properties Section */}
{result.mass_properties && (
<div className="border border-dark-700 rounded-lg overflow-hidden">
<button
onClick={() => toggleSection('mass')}
className="w-full flex items-center justify-between px-3 py-2 bg-dark-800 hover:bg-dark-750 transition-colors"
>
<div className="flex items-center gap-2">
<Scale size={14} className="text-blue-400" />
<span className="text-sm font-medium text-white">Mass Properties</span>
</div>
{expandedSections.has('mass') ? (
<ChevronDown size={14} className="text-dark-400" />
) : (
<ChevronRight size={14} className="text-dark-400" />
)}
</button>
{expandedSections.has('mass') && (
<div className="p-2 space-y-1">
{(result.mass_properties as Record<string, unknown>).mass_kg !== undefined && (
<div className="flex justify-between p-2 bg-dark-850 rounded text-xs">
<span className="text-dark-400">Mass</span>
<span className="text-white font-mono">
{((result.mass_properties as Record<string, unknown>).mass_kg as number).toFixed(4)} kg
</span>
</div>
)}
</div>
)}
</div>
)}
{/* More sections can be added here following the same pattern as the original IntrospectionPanel */}
</div>
) : (
<div className="p-4 text-center text-dark-500 text-sm">
Click refresh to analyze the model
</div>
)}
</div>
</div>
);
}
export default FloatingIntrospectionPanel;

View File

@@ -17,8 +17,8 @@ import {
useSelectedNodeId,
useSelectedNode,
} from '../../../hooks/useSpecStore';
import { usePanelStore } from '../../../hooks/usePanelStore';
import { FileBrowser } from './FileBrowser';
import { IntrospectionPanel } from './IntrospectionPanel';
import {
DesignVariable,
Extractor,
@@ -272,7 +272,15 @@ interface SpecConfigProps {
}
function ModelNodeConfig({ spec }: SpecConfigProps) {
const [showIntrospection, setShowIntrospection] = useState(false);
const { setIntrospectionData, openPanel } = usePanelStore();
const handleOpenIntrospection = () => {
// Set up introspection data and open the panel
setIntrospectionData({
filePath: spec.model.sim?.path || '',
studyId: useSpecStore.getState().studyId || undefined,
});
};
return (
<>
@@ -300,7 +308,7 @@ function ModelNodeConfig({ spec }: SpecConfigProps) {
{spec.model.sim?.path && (
<button
onClick={() => setShowIntrospection(true)}
onClick={handleOpenIntrospection}
className="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-primary-500/20
hover:bg-primary-500/30 border border-primary-500/30 rounded-lg
text-primary-400 text-sm font-medium transition-colors"
@@ -309,16 +317,8 @@ function ModelNodeConfig({ spec }: SpecConfigProps) {
Introspect Model
</button>
)}
{showIntrospection && spec.model.sim?.path && (
<div className="fixed top-20 right-96 z-40">
<IntrospectionPanel
filePath={spec.model.sim.path}
studyId={useSpecStore.getState().studyId || undefined}
onClose={() => setShowIntrospection(false)}
/>
</div>
)}
{/* Note: IntrospectionPanel is now rendered by PanelContainer, not here */}
</>
);
}

View File

@@ -0,0 +1,207 @@
/**
* PanelContainer - Orchestrates all floating panels in the canvas view
*
* This component renders floating panels (Introspection, Validation, Error, Results)
* in a portal, positioned absolutely within the canvas area.
*
* Features:
* - Draggable panels
* - Z-index management (click to bring to front)
* - Keyboard shortcuts (Escape to close all)
* - Position persistence via usePanelStore
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import {
usePanelStore,
useIntrospectionPanel,
useValidationPanel,
useErrorPanel,
useResultsPanel,
PanelPosition,
} from '../../../hooks/usePanelStore';
import { FloatingIntrospectionPanel } from './FloatingIntrospectionPanel';
import { FloatingValidationPanel } from './ValidationPanel';
import { ErrorPanel } from './ErrorPanel';
import { ResultsPanel } from './ResultsPanel';
interface PanelContainerProps {
/** Container element to render panels into (defaults to document.body) */
container?: HTMLElement;
/** Callback when retry is requested from error panel */
onRetry?: (trial?: number) => void;
/** Callback when skip trial is requested */
onSkipTrial?: (trial: number) => void;
}
type PanelName = 'introspection' | 'validation' | 'error' | 'results';
export function PanelContainer({ container, onRetry, onSkipTrial }: PanelContainerProps) {
const { closePanel, setPanelPosition, closeAllPanels } = usePanelStore();
const introspectionPanel = useIntrospectionPanel();
const validationPanel = useValidationPanel();
const errorPanel = useErrorPanel();
const resultsPanel = useResultsPanel();
// Track which panel is on top (for z-index)
const [topPanel, setTopPanel] = useState<PanelName | null>(null);
// Dragging state
const [dragging, setDragging] = useState<{ panel: PanelName; offset: { x: number; y: number } } | null>(null);
const dragRef = useRef<{ panel: PanelName; offset: { x: number; y: number } } | null>(null);
// Escape key to close all panels
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
closeAllPanels();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [closeAllPanels]);
// Mouse move handler for dragging
useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
if (!dragRef.current) return;
const { panel, offset } = dragRef.current;
const newPosition: PanelPosition = {
x: e.clientX - offset.x,
y: e.clientY - offset.y,
};
// Clamp to viewport
newPosition.x = Math.max(0, Math.min(window.innerWidth - 100, newPosition.x));
newPosition.y = Math.max(0, Math.min(window.innerHeight - 50, newPosition.y));
setPanelPosition(panel, newPosition);
};
const handleMouseUp = () => {
dragRef.current = null;
setDragging(null);
};
if (dragging) {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
}, [dragging, setPanelPosition]);
// Start dragging a panel
const handleDragStart = useCallback((panel: PanelName, e: React.MouseEvent, position: PanelPosition) => {
const offset = {
x: e.clientX - position.x,
y: e.clientY - position.y,
};
dragRef.current = { panel, offset };
setDragging({ panel, offset });
setTopPanel(panel);
}, []);
// Click to bring panel to front
const handlePanelClick = useCallback((panel: PanelName) => {
setTopPanel(panel);
}, []);
// Get z-index for a panel
const getZIndex = (panel: PanelName) => {
const baseZ = 100;
if (panel === topPanel) return baseZ + 10;
return baseZ;
};
// Render a draggable wrapper
const renderDraggable = (
panel: PanelName,
position: PanelPosition,
isOpen: boolean,
children: React.ReactNode
) => {
if (!isOpen) return null;
return (
<div
key={panel}
className="fixed select-none"
style={{
left: position.x,
top: position.y,
zIndex: getZIndex(panel),
cursor: dragging?.panel === panel ? 'grabbing' : 'default',
}}
onClick={() => handlePanelClick(panel)}
>
{/* Drag handle - the header area */}
<div
className="absolute top-0 left-0 right-0 h-12 cursor-grab active:cursor-grabbing"
onMouseDown={(e) => handleDragStart(panel, e, position)}
style={{ zIndex: 1 }}
/>
{/* Panel content */}
<div className="relative" style={{ zIndex: 0 }}>
{children}
</div>
</div>
);
};
// Determine what to render
const panels = (
<>
{/* Introspection Panel */}
{renderDraggable(
'introspection',
introspectionPanel.position || { x: 100, y: 100 },
introspectionPanel.open,
<FloatingIntrospectionPanel onClose={() => closePanel('introspection')} />
)}
{/* Validation Panel */}
{renderDraggable(
'validation',
validationPanel.position || { x: 150, y: 150 },
validationPanel.open,
<FloatingValidationPanel onClose={() => closePanel('validation')} />
)}
{/* Error Panel */}
{renderDraggable(
'error',
errorPanel.position || { x: 200, y: 100 },
errorPanel.open,
<ErrorPanel
onClose={() => closePanel('error')}
onRetry={onRetry}
onSkipTrial={onSkipTrial}
/>
)}
{/* Results Panel */}
{renderDraggable(
'results',
resultsPanel.position || { x: 250, y: 150 },
resultsPanel.open,
<ResultsPanel onClose={() => closePanel('results')} />
)}
</>
);
// Use portal if container specified, otherwise render in place
if (container) {
return createPortal(panels, container);
}
return panels;
}
export default PanelContainer;

View File

@@ -0,0 +1,179 @@
/**
* ResultsPanel - Shows detailed trial results
*
* Displays the parameters, objectives, and constraints for a specific trial.
* Can be opened by clicking on result badges on nodes.
*/
import {
X,
Minimize2,
Maximize2,
CheckCircle,
XCircle,
Trophy,
SlidersHorizontal,
Target,
AlertTriangle,
Clock,
} from 'lucide-react';
import { useResultsPanel, usePanelStore } from '../../../hooks/usePanelStore';
interface ResultsPanelProps {
onClose: () => void;
}
export function ResultsPanel({ onClose }: ResultsPanelProps) {
const panel = useResultsPanel();
const { minimizePanel } = usePanelStore();
const data = panel.data;
if (!panel.open || !data) return null;
const timestamp = new Date(data.timestamp).toLocaleTimeString();
// Minimized view
if (panel.minimized) {
return (
<div
className="bg-dark-850 border border-dark-700 rounded-lg shadow-xl flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-dark-800 transition-colors"
onClick={() => minimizePanel('results')}
>
<Trophy size={16} className={data.isBest ? 'text-amber-400' : 'text-dark-400'} />
<span className="text-sm text-white font-medium">
Trial #{data.trialNumber}
</span>
<Maximize2 size={14} className="text-dark-400" />
</div>
);
}
return (
<div className="bg-dark-850 border border-dark-700 rounded-xl w-80 max-h-[500px] flex flex-col shadow-xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-dark-700">
<div className="flex items-center gap-2">
<Trophy size={18} className={data.isBest ? 'text-amber-400' : 'text-dark-400'} />
<span className="font-medium text-white">
Trial #{data.trialNumber}
</span>
{data.isBest && (
<span className="px-1.5 py-0.5 text-xs bg-amber-500/20 text-amber-400 rounded">
Best
</span>
)}
</div>
<div className="flex items-center gap-1">
<button
onClick={() => minimizePanel('results')}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
title="Minimize"
>
<Minimize2 size={14} />
</button>
<button
onClick={onClose}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
>
<X size={14} />
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{/* Status */}
<div className="flex items-center gap-3">
{data.isFeasible ? (
<div className="flex items-center gap-1.5 text-green-400">
<CheckCircle size={16} />
<span className="text-sm font-medium">Feasible</span>
</div>
) : (
<div className="flex items-center gap-1.5 text-red-400">
<XCircle size={16} />
<span className="text-sm font-medium">Infeasible</span>
</div>
)}
<div className="flex items-center gap-1.5 text-dark-400 ml-auto">
<Clock size={14} />
<span className="text-xs">{timestamp}</span>
</div>
</div>
{/* Parameters */}
<div>
<h4 className="text-xs font-medium text-dark-400 uppercase tracking-wide mb-2 flex items-center gap-1.5">
<SlidersHorizontal size={12} />
Parameters
</h4>
<div className="space-y-1">
{Object.entries(data.params).map(([name, value]) => (
<div key={name} className="flex justify-between p-2 bg-dark-800 rounded text-sm">
<span className="text-dark-300">{name}</span>
<span className="text-white font-mono">{formatValue(value)}</span>
</div>
))}
</div>
</div>
{/* Objectives */}
<div>
<h4 className="text-xs font-medium text-dark-400 uppercase tracking-wide mb-2 flex items-center gap-1.5">
<Target size={12} />
Objectives
</h4>
<div className="space-y-1">
{Object.entries(data.objectives).map(([name, value]) => (
<div key={name} className="flex justify-between p-2 bg-dark-800 rounded text-sm">
<span className="text-dark-300">{name}</span>
<span className="text-primary-400 font-mono">{formatValue(value)}</span>
</div>
))}
</div>
</div>
{/* Constraints (if any) */}
{data.constraints && Object.keys(data.constraints).length > 0 && (
<div>
<h4 className="text-xs font-medium text-dark-400 uppercase tracking-wide mb-2 flex items-center gap-1.5">
<AlertTriangle size={12} />
Constraints
</h4>
<div className="space-y-1">
{Object.entries(data.constraints).map(([name, constraint]) => (
<div
key={name}
className={`flex justify-between p-2 rounded text-sm ${
constraint.feasible ? 'bg-dark-800' : 'bg-red-500/10 border border-red-500/20'
}`}
>
<span className="text-dark-300 flex items-center gap-1.5">
{constraint.feasible ? (
<CheckCircle size={12} className="text-green-400" />
) : (
<XCircle size={12} className="text-red-400" />
)}
{name}
</span>
<span className={`font-mono ${constraint.feasible ? 'text-white' : 'text-red-400'}`}>
{formatValue(constraint.value)}
</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
}
function formatValue(value: number): string {
if (Math.abs(value) < 0.001 || Math.abs(value) >= 10000) {
return value.toExponential(3);
}
return value.toFixed(4).replace(/\.?0+$/, '');
}
export default ResultsPanel;

View File

@@ -1,10 +1,41 @@
/**
* ValidationPanel - Displays spec validation errors and warnings
*
* Shows a list of validation issues that need to be fixed before
* running an optimization. Supports auto-navigation to problematic nodes.
*
* Can be used in two modes:
* 1. Legacy mode: Pass validation prop directly (for backward compatibility)
* 2. Store mode: Uses usePanelStore for persistent state
*/
import { useMemo } from 'react';
import {
X,
AlertCircle,
AlertTriangle,
CheckCircle,
ChevronRight,
Minimize2,
Maximize2,
} from 'lucide-react';
import { useValidationPanel, usePanelStore, ValidationError as StoreValidationError } from '../../../hooks/usePanelStore';
import { useSpecStore } from '../../../hooks/useSpecStore';
import { ValidationResult } from '../../../lib/canvas/validation';
interface ValidationPanelProps {
// ============================================================================
// Legacy Props Interface (for backward compatibility)
// ============================================================================
interface LegacyValidationPanelProps {
validation: ValidationResult;
}
export function ValidationPanel({ validation }: ValidationPanelProps) {
/**
* Legacy ValidationPanel - Inline display for canvas overlay
* Kept for backward compatibility with AtomizerCanvas
*/
export function ValidationPanel({ validation }: LegacyValidationPanelProps) {
return (
<div className="absolute top-4 left-1/2 transform -translate-x-1/2 max-w-md w-full z-10">
{validation.errors.length > 0 && (
@@ -30,3 +61,199 @@ export function ValidationPanel({ validation }: ValidationPanelProps) {
</div>
);
}
// ============================================================================
// New Floating Panel (uses store)
// ============================================================================
interface FloatingValidationPanelProps {
onClose: () => void;
}
export function FloatingValidationPanel({ onClose }: FloatingValidationPanelProps) {
const panel = useValidationPanel();
const { minimizePanel } = usePanelStore();
const { setSelectedNodeId } = useSpecStore();
const { errors, warnings, valid } = useMemo(() => {
if (!panel.data) {
return { errors: [], warnings: [], valid: true };
}
return {
errors: panel.data.errors || [],
warnings: panel.data.warnings || [],
valid: panel.data.valid,
};
}, [panel.data]);
const handleNavigateToNode = (nodeId?: string) => {
if (nodeId) {
setSelectedNodeId(nodeId);
}
};
if (!panel.open) return null;
// Minimized view
if (panel.minimized) {
return (
<div
className="bg-dark-850 border border-dark-700 rounded-lg shadow-xl flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-dark-800 transition-colors"
onClick={() => minimizePanel('validation')}
>
{valid ? (
<CheckCircle size={16} className="text-green-400" />
) : (
<AlertCircle size={16} className="text-red-400" />
)}
<span className="text-sm text-white font-medium">
Validation {valid ? 'Passed' : `(${errors.length} errors)`}
</span>
<Maximize2 size={14} className="text-dark-400" />
</div>
);
}
return (
<div className="bg-dark-850 border border-dark-700 rounded-xl w-96 max-h-[500px] flex flex-col shadow-xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-dark-700">
<div className="flex items-center gap-2">
{valid ? (
<CheckCircle size={18} className="text-green-400" />
) : (
<AlertCircle size={18} className="text-red-400" />
)}
<span className="font-medium text-white">
{valid ? 'Validation Passed' : 'Validation Issues'}
</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={() => minimizePanel('validation')}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
title="Minimize"
>
<Minimize2 size={14} />
</button>
<button
onClick={onClose}
className="p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded transition-colors"
>
<X size={14} />
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-3 space-y-2">
{valid && errors.length === 0 && warnings.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<CheckCircle size={40} className="text-green-400 mb-3" />
<p className="text-white font-medium">All checks passed!</p>
<p className="text-sm text-dark-400 mt-1">
Your spec is ready to run.
</p>
</div>
) : (
<>
{/* Errors */}
{errors.length > 0 && (
<div className="space-y-2">
<h4 className="text-xs font-medium text-red-400 uppercase tracking-wide flex items-center gap-1">
<AlertCircle size={12} />
Errors ({errors.length})
</h4>
{errors.map((error, idx) => (
<ValidationItem
key={`error-${idx}`}
item={error}
severity="error"
onNavigate={() => handleNavigateToNode(error.nodeId)}
/>
))}
</div>
)}
{/* Warnings */}
{warnings.length > 0 && (
<div className="space-y-2 mt-4">
<h4 className="text-xs font-medium text-amber-400 uppercase tracking-wide flex items-center gap-1">
<AlertTriangle size={12} />
Warnings ({warnings.length})
</h4>
{warnings.map((warning, idx) => (
<ValidationItem
key={`warning-${idx}`}
item={warning}
severity="warning"
onNavigate={() => handleNavigateToNode(warning.nodeId)}
/>
))}
</div>
)}
</>
)}
</div>
{/* Footer */}
{!valid && (
<div className="px-4 py-3 border-t border-dark-700 bg-dark-800/50">
<p className="text-xs text-dark-400">
Fix all errors before running the optimization.
Warnings can be ignored but may cause issues.
</p>
</div>
)}
</div>
);
}
// ============================================================================
// Validation Item Component
// ============================================================================
interface ValidationItemProps {
item: StoreValidationError;
severity: 'error' | 'warning';
onNavigate: () => void;
}
function ValidationItem({ item, severity, onNavigate }: ValidationItemProps) {
const isError = severity === 'error';
const bgColor = isError ? 'bg-red-500/10' : 'bg-amber-500/10';
const borderColor = isError ? 'border-red-500/30' : 'border-amber-500/30';
const iconColor = isError ? 'text-red-400' : 'text-amber-400';
return (
<div
className={`p-3 rounded-lg border ${bgColor} ${borderColor} group cursor-pointer hover:bg-opacity-20 transition-colors`}
onClick={onNavigate}
>
<div className="flex items-start gap-2">
{isError ? (
<AlertCircle size={16} className={`${iconColor} flex-shrink-0 mt-0.5`} />
) : (
<AlertTriangle size={16} className={`${iconColor} flex-shrink-0 mt-0.5`} />
)}
<div className="flex-1 min-w-0">
<p className="text-sm text-white">{item.message}</p>
{item.path && (
<p className="text-xs text-dark-400 mt-1 font-mono">{item.path}</p>
)}
{item.suggestion && (
<p className="text-xs text-dark-300 mt-2 italic">{item.suggestion}</p>
)}
</div>
{item.nodeId && (
<ChevronRight
size={16}
className="text-dark-500 group-hover:text-white transition-colors flex-shrink-0"
/>
)}
</div>
</div>
);
}
export default ValidationPanel;