feat(canvas): Canvas V3 - Bug fixes and study workflow improvements

Bug Fixes:
- Fix Atomizer Assistant error with reconnect button and error state handling
- Enable connection/edge deletion with keyboard Delete/Backspace keys
- Fix drag & drop positioning using screenToFlowPosition correctly
- Fix loadFromConfig to create all node types and edges properly

UI/UX Improvements:
- Minimal responsive header with context breadcrumb
- Better contrast with white text on dark backgrounds
- Larger font sizes in NodePalette for readability
- Study-aware header showing selected study name

New Features:
- Enhanced ExecuteDialog with Create/Update mode toggle
- Select existing study to update or create new study
- Home page Canvas Builder button for quick access
- Home navigation button in CanvasView header

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-16 11:34:41 -05:00
parent 62f3ab03ba
commit 62284a995e
7 changed files with 525 additions and 173 deletions

View File

@@ -1,13 +1,14 @@
import { useCallback, useRef, useState, DragEvent } from 'react';
import { useCallback, useRef, useState, useEffect, DragEvent } from 'react';
import ReactFlow, {
Background,
Controls,
MiniMap,
ReactFlowProvider,
ReactFlowInstance,
Edge,
} from 'reactflow';
import 'reactflow/dist/style.css';
import { MessageCircle, Plug, X } from 'lucide-react';
import { MessageCircle, Plug, X, AlertCircle, RefreshCw } from 'lucide-react';
import { nodeTypes } from './nodes';
import { NodePalette } from './palette/NodePalette';
@@ -29,16 +30,21 @@ function CanvasFlow() {
nodes,
edges,
selectedNode,
selectedEdge,
onNodesChange,
onEdgesChange,
onConnect,
addNode,
selectNode,
selectEdge,
deleteSelected,
validation,
validate,
toIntent,
} = useCanvasStore();
const [chatError, setChatError] = useState<string | null>(null);
const {
messages,
isThinking,
@@ -49,9 +55,19 @@ function CanvasFlow() {
analyzeIntent,
sendMessage,
} = useCanvasChat({
onError: (error) => console.error('Canvas chat error:', error),
onError: (error) => {
console.error('Canvas chat error:', error);
setChatError(error);
},
});
const handleReconnect = useCallback(() => {
setChatError(null);
// Force refresh chat connection by toggling panel
setShowChat(false);
setTimeout(() => setShowChat(true), 100);
}, []);
const onDragOver = useCallback((event: DragEvent) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
@@ -62,12 +78,12 @@ function CanvasFlow() {
event.preventDefault();
const type = event.dataTransfer.getData('application/reactflow') as NodeType;
if (!type || !reactFlowInstance.current || !reactFlowWrapper.current) return;
if (!type || !reactFlowInstance.current) return;
const bounds = reactFlowWrapper.current.getBoundingClientRect();
// screenToFlowPosition expects screen coordinates directly
const position = reactFlowInstance.current.screenToFlowPosition({
x: event.clientX - bounds.left,
y: event.clientY - bounds.top,
x: event.clientX,
y: event.clientY,
});
addNode(type, position);
@@ -84,7 +100,32 @@ function CanvasFlow() {
const onPaneClick = useCallback(() => {
selectNode(null);
}, [selectNode]);
selectEdge(null);
}, [selectNode, selectEdge]);
const onEdgeClick = useCallback(
(_: React.MouseEvent, edge: Edge) => {
selectEdge(edge.id);
},
[selectEdge]
);
// Keyboard handler for Delete/Backspace
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Delete' || event.key === 'Backspace') {
// Don't delete if focus is on an input
const target = event.target as HTMLElement;
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
return;
}
deleteSelected();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [deleteSelected]);
const handleValidate = () => {
const result = validate();
@@ -112,8 +153,9 @@ function CanvasFlow() {
}
};
const handleExecute = async (studyName: string, autoRun: boolean) => {
const handleExecute = async (studyName: string, autoRun: boolean, _mode: 'create' | 'update', _existingStudyId?: string) => {
const intent = toIntent();
// For now, both modes use the same executeIntent - backend will handle the mode distinction
await executeIntent(intent, studyName, autoRun);
setShowExecuteDialog(false);
setShowChat(true);
@@ -128,7 +170,14 @@ function CanvasFlow() {
<div className="flex-1 relative" ref={reactFlowWrapper}>
<ReactFlow
nodes={nodes}
edges={edges}
edges={edges.map(e => ({
...e,
style: {
stroke: e.id === selectedEdge ? '#60a5fa' : '#6b7280',
strokeWidth: e.id === selectedEdge ? 3 : 2,
},
animated: e.id === selectedEdge,
}))}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
@@ -136,9 +185,11 @@ function CanvasFlow() {
onDragOver={onDragOver}
onDrop={onDrop}
onNodeClick={onNodeClick}
onEdgeClick={onEdgeClick}
onPaneClick={onPaneClick}
nodeTypes={nodeTypes}
fitView
deleteKeyCode={null}
className="bg-dark-900"
>
<Background color="#374151" gap={20} />
@@ -211,12 +262,27 @@ function CanvasFlow() {
<X size={18} />
</button>
</div>
<ChatPanel
messages={messages}
isThinking={isThinking || isExecuting}
onSendMessage={sendMessage}
isConnected={isConnected}
/>
{chatError ? (
<div className="flex-1 flex flex-col items-center justify-center p-6 text-center">
<AlertCircle size={32} className="text-red-400 mb-3" />
<p className="text-white font-medium mb-1">Connection Error</p>
<p className="text-sm text-dark-400 mb-4">{chatError}</p>
<button
onClick={handleReconnect}
className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-500 text-white rounded-lg transition-colors"
>
<RefreshCw size={16} />
Reconnect
</button>
</div>
) : (
<ChatPanel
messages={messages}
isThinking={isThinking || isExecuting}
onSendMessage={sendMessage}
isConnected={isConnected}
/>
)}
</div>
) : selectedNode ? (
<NodeConfigPanel nodeId={selectedNode} />

View File

@@ -25,9 +25,9 @@ function BaseNodeComponent({
return (
<div
className={`
relative px-3 py-2.5 rounded-lg border min-w-[160px] max-w-[200px]
bg-dark-850 shadow-lg transition-all duration-150
${selected ? 'border-primary-400 ring-2 ring-primary-400/20' : 'border-dark-600'}
relative px-4 py-3 rounded-xl border min-w-[180px] max-w-[220px]
bg-dark-800 shadow-xl transition-all duration-150
${selected ? 'border-primary-400 ring-2 ring-primary-400/30 shadow-primary-500/20' : 'border-dark-600'}
${!data.configured ? 'border-dashed border-dark-500' : ''}
${hasErrors ? 'border-red-500/70' : ''}
`}
@@ -36,31 +36,31 @@ function BaseNodeComponent({
<Handle
type="target"
position={Position.Left}
className="!w-2.5 !h-2.5 !bg-dark-500 !border-2 !border-dark-700 hover:!bg-primary-400 hover:!border-primary-500 transition-colors"
className="!w-3 !h-3 !bg-dark-400 !border-2 !border-dark-600 hover:!bg-primary-400 hover:!border-primary-500 transition-colors"
/>
)}
<div className="flex items-center gap-2">
<div className="flex items-center gap-2.5">
<div className={`${iconColor} flex-shrink-0`}>
{icon}
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-white text-sm truncate">{data.label}</div>
<div className="font-semibold text-white text-sm truncate">{data.label}</div>
</div>
{!data.configured && (
<div className="w-1.5 h-1.5 rounded-full bg-amber-400 flex-shrink-0" />
<div className="w-2 h-2 rounded-full bg-amber-400 flex-shrink-0 animate-pulse" />
)}
</div>
{children && (
<div className="mt-1.5 text-xs text-dark-400 truncate">
<div className="mt-2 text-xs text-dark-300 truncate">
{children}
</div>
)}
{hasErrors && (
<div className="mt-1.5 flex items-center gap-1 text-xs text-red-400">
<AlertCircle size={10} />
<div className="mt-2 flex items-center gap-1.5 text-xs text-red-400">
<AlertCircle size={12} />
<span className="truncate">{data.errors![0]}</span>
</div>
)}
@@ -69,7 +69,7 @@ function BaseNodeComponent({
<Handle
type="source"
position={Position.Right}
className="!w-2.5 !h-2.5 !bg-dark-500 !border-2 !border-dark-700 hover:!bg-primary-400 hover:!border-primary-500 transition-colors"
className="!w-3 !h-3 !bg-dark-400 !border-2 !border-dark-600 hover:!bg-primary-400 hover:!border-primary-500 transition-colors"
/>
)}
</div>

View File

@@ -37,31 +37,31 @@ export function NodePalette() {
};
return (
<div className="w-56 bg-dark-850 border-r border-dark-700 flex flex-col">
<div className="w-60 bg-dark-850 border-r border-dark-700 flex flex-col">
<div className="p-4 border-b border-dark-700">
<h3 className="text-xs font-semibold text-dark-400 uppercase tracking-wider">
<h3 className="text-sm font-semibold text-dark-300 uppercase tracking-wider">
Components
</h3>
<p className="text-xs text-dark-500 mt-1">
<p className="text-xs text-dark-400 mt-1">
Drag to canvas
</p>
</div>
<div className="flex-1 overflow-y-auto p-3 space-y-1.5">
<div className="flex-1 overflow-y-auto p-3 space-y-2">
{PALETTE_ITEMS.map((item) => (
<div
key={item.type}
draggable
onDragStart={(e) => onDragStart(e, item.type)}
className="flex items-center gap-2.5 px-3 py-2.5 bg-dark-800/50 rounded-lg border border-dark-700/50
className="flex items-center gap-3 px-3 py-3 bg-dark-800/50 rounded-lg border border-dark-700/50
cursor-grab hover:border-primary-500/50 hover:bg-dark-800
active:cursor-grabbing transition-all group"
>
<div className={`${item.color} opacity-80 group-hover:opacity-100 transition-opacity`}>
<div className={`${item.color} opacity-90 group-hover:opacity-100 transition-opacity`}>
{item.icon}
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-dark-200 text-sm leading-tight">{item.label}</div>
<div className="text-[10px] text-dark-500 truncate">{item.description}</div>
<div className="font-semibold text-white text-sm leading-tight">{item.label}</div>
<div className="text-xs text-dark-400 truncate">{item.description}</div>
</div>
</div>
))}

View File

@@ -1,14 +1,19 @@
/**
* Execute Dialog - Prompts for study name before executing canvas intent
* Execute Dialog - Choose to update existing study or create new one
*/
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { FilePlus, RefreshCw, FolderOpen } from 'lucide-react';
import { useStudy } from '../../../context/StudyContext';
type ExecuteMode = 'create' | 'update';
interface ExecuteDialogProps {
isOpen: boolean;
onClose: () => void;
onExecute: (studyName: string, autoRun: boolean) => void;
onExecute: (studyName: string, autoRun: boolean, mode: ExecuteMode, existingStudyId?: string) => void;
isExecuting: boolean;
defaultStudyId?: string; // Pre-selected study when editing
}
export function ExecuteDialog({
@@ -16,31 +21,68 @@ export function ExecuteDialog({
onClose,
onExecute,
isExecuting,
defaultStudyId,
}: ExecuteDialogProps) {
const { studies } = useStudy();
const [mode, setMode] = useState<ExecuteMode>('create');
const [studyName, setStudyName] = useState('');
const [selectedStudyId, setSelectedStudyId] = useState<string>('');
const [autoRun, setAutoRun] = useState(false);
const [error, setError] = useState<string | null>(null);
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
if (defaultStudyId) {
setMode('update');
setSelectedStudyId(defaultStudyId);
} else {
setMode('create');
setSelectedStudyId(studies[0]?.id || '');
}
setStudyName('');
setAutoRun(false);
setError(null);
}
}, [isOpen, defaultStudyId, studies]);
if (!isOpen) return null;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Validate study name
const trimmed = studyName.trim();
if (!trimmed) {
setError('Study name is required');
return;
}
if (mode === 'create') {
// Validate study name
const trimmed = studyName.trim();
if (!trimmed) {
setError('Study name is required');
return;
}
// Check for valid snake_case
if (!/^[a-z][a-z0-9_]*$/.test(trimmed)) {
setError('Study name must be snake_case (lowercase letters, numbers, underscores)');
return;
}
// Check for valid snake_case
if (!/^[a-z][a-z0-9_]*$/.test(trimmed)) {
setError('Study name must be snake_case (lowercase letters, numbers, underscores)');
return;
}
setError(null);
onExecute(trimmed, autoRun);
setError(null);
onExecute(trimmed, autoRun, 'create');
} else {
// Update mode
if (!selectedStudyId) {
setError('Please select a study to update');
return;
}
const selectedStudy = studies.find(s => s.id === selectedStudyId);
if (!selectedStudy) {
setError('Selected study not found');
return;
}
setError(null);
onExecute(selectedStudy.id, autoRun, 'update', selectedStudyId);
}
};
const handleClose = () => {
@@ -52,39 +94,106 @@ export function ExecuteDialog({
return (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 backdrop-blur-sm">
<div className="bg-dark-850 rounded-xl shadow-2xl w-full max-w-md p-6 border border-dark-700">
<h2 className="text-xl font-semibold text-white mb-4">
<div className="bg-dark-850 rounded-xl shadow-2xl w-full max-w-lg p-6 border border-dark-700">
<h2 className="text-xl font-semibold text-white mb-2">
Execute with Claude
</h2>
<p className="text-dark-400 text-sm mb-6">
Choose to create a new study or update an existing one
</p>
{/* Mode Tabs */}
<div className="flex gap-2 mb-6">
<button
type="button"
onClick={() => { setMode('create'); setError(null); }}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border transition-all ${
mode === 'create'
? 'bg-primary-600/20 border-primary-500 text-primary-400'
: 'bg-dark-800 border-dark-600 text-dark-400 hover:border-dark-500'
}`}
>
<FilePlus size={18} />
<span className="font-medium">Create New Study</span>
</button>
<button
type="button"
onClick={() => { setMode('update'); setError(null); }}
disabled={studies.length === 0}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border transition-all ${
mode === 'update'
? 'bg-amber-600/20 border-amber-500 text-amber-400'
: 'bg-dark-800 border-dark-600 text-dark-400 hover:border-dark-500'
} ${studies.length === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
>
<RefreshCw size={18} />
<span className="font-medium">Update Existing</span>
</button>
</div>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label
htmlFor="study-name"
className="block text-sm font-medium text-dark-300 mb-1"
>
Study Name
</label>
<input
id="study-name"
type="text"
value={studyName}
onChange={(e) => setStudyName(e.target.value.toLowerCase().replace(/\s+/g, '_'))}
placeholder="my_optimization_study"
className="w-full px-3 py-2 bg-dark-800 border border-dark-600 text-white placeholder-dark-400 rounded-lg font-mono focus:ring-2 focus:ring-primary-500 focus:border-primary-500 focus:outline-none transition-colors"
disabled={isExecuting}
autoFocus
/>
{error && (
<p className="mt-1 text-sm text-red-400">{error}</p>
)}
<p className="mt-1 text-xs text-dark-500">
Use snake_case (e.g., bracket_mass_v1, mirror_wfe_optimization)
</p>
</div>
{mode === 'create' ? (
/* Create New Study */
<div className="mb-4">
<label
htmlFor="study-name"
className="block text-sm font-medium text-dark-300 mb-2"
>
Study Name
</label>
<input
id="study-name"
type="text"
value={studyName}
onChange={(e) => setStudyName(e.target.value.toLowerCase().replace(/\s+/g, '_'))}
placeholder="my_optimization_study"
className="w-full px-3 py-2.5 bg-dark-800 border border-dark-600 text-white placeholder-dark-500 rounded-lg font-mono focus:ring-2 focus:ring-primary-500 focus:border-primary-500 focus:outline-none transition-colors"
disabled={isExecuting}
autoFocus
/>
<p className="mt-2 text-xs text-dark-500">
Use snake_case (e.g., bracket_mass_v1, mirror_wfe_optimization)
</p>
</div>
) : (
/* Update Existing Study */
<div className="mb-4">
<label
htmlFor="existing-study"
className="block text-sm font-medium text-dark-300 mb-2"
>
Select Study to Update
</label>
<div className="relative">
<FolderOpen size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-dark-500 pointer-events-none" />
<select
id="existing-study"
value={selectedStudyId}
onChange={(e) => setSelectedStudyId(e.target.value)}
className="w-full pl-10 pr-3 py-2.5 bg-dark-800 border border-dark-600 text-white rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 focus:outline-none transition-colors appearance-none cursor-pointer"
disabled={isExecuting}
>
{studies.map((study) => (
<option key={study.id} value={study.id}>
{study.name || study.id} ({study.progress.current} trials)
</option>
))}
</select>
</div>
<p className="mt-2 text-xs text-amber-500/80">
Warning: This will overwrite the study's optimization_config.json
</p>
</div>
)}
{error && (
<div className="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
<p className="text-sm text-red-400">{error}</p>
</div>
)}
<div className="mb-6">
<label className="flex items-center gap-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={autoRun}
@@ -93,7 +202,7 @@ export function ExecuteDialog({
className="w-4 h-4 rounded bg-dark-800 border-dark-600 text-primary-500 focus:ring-primary-500"
/>
<span className="text-sm text-dark-300">
Start optimization immediately after creation
Start optimization immediately after {mode === 'create' ? 'creation' : 'update'}
</span>
</label>
</div>
@@ -103,23 +212,33 @@ export function ExecuteDialog({
type="button"
onClick={handleClose}
disabled={isExecuting}
className="px-4 py-2 text-dark-300 hover:text-white disabled:opacity-50 transition-colors"
className="px-4 py-2.5 text-dark-300 hover:text-white disabled:opacity-50 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isExecuting}
className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition-colors"
className={`px-5 py-2.5 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition-colors font-medium ${
mode === 'create'
? 'bg-primary-600 text-white hover:bg-primary-500'
: 'bg-amber-600 text-white hover:bg-amber-500'
}`}
>
{isExecuting ? (
<>
<span className="animate-spin">⏳</span>
Executing...
Processing...
</>
) : mode === 'create' ? (
<>
<FilePlus size={16} />
Create & Send to Claude
</>
) : (
<>
Send to Claude
<RefreshCw size={16} />
Update & Send to Claude
</>
)}
</button>

View File

@@ -8,6 +8,7 @@ interface CanvasState {
nodes: Node<CanvasNodeData>[];
edges: Edge[];
selectedNode: string | null;
selectedEdge: string | null;
validation: ValidationResult;
// Actions
@@ -17,7 +18,9 @@ interface CanvasState {
addNode: (type: NodeType, position: { x: number; y: number }) => void;
updateNodeData: (nodeId: string, data: Partial<CanvasNodeData>) => void;
selectNode: (nodeId: string | null) => void;
selectEdge: (edgeId: string | null) => void;
deleteSelected: () => void;
deleteEdge: (edgeId: string) => void;
validate: () => ValidationResult;
toIntent: () => OptimizationIntent;
clear: () => void;
@@ -94,6 +97,7 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
nodes: [],
edges: [],
selectedNode: null,
selectedEdge: null,
validation: { valid: false, errors: [], warnings: [] },
onNodesChange: (changes) => {
@@ -129,11 +133,26 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
},
selectNode: (nodeId) => {
set({ selectedNode: nodeId });
set({ selectedNode: nodeId, selectedEdge: null });
},
selectEdge: (edgeId) => {
set({ selectedEdge: edgeId, selectedNode: null });
},
deleteSelected: () => {
const { selectedNode, nodes, edges } = get();
const { selectedNode, selectedEdge, nodes, edges } = get();
// Delete selected edge
if (selectedEdge) {
set({
edges: edges.filter((e) => e.id !== selectedEdge),
selectedEdge: null,
});
return;
}
// Delete selected node
if (!selectedNode) return;
set({
@@ -143,6 +162,13 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
});
},
deleteEdge: (edgeId) => {
set({
edges: get().edges.filter((e) => e.id !== edgeId),
selectedEdge: null,
});
},
validate: () => {
const { nodes, edges } = get();
const result = validateGraph(nodes, edges);
@@ -160,6 +186,7 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
nodes: [],
edges: [],
selectedNode: null,
selectedEdge: null,
validation: { valid: false, errors: [], warnings: [] },
});
nodeIdCounter = 0;
@@ -305,77 +332,177 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
nodes,
edges,
selectedNode: null,
selectedEdge: null,
validation: { valid: false, errors: [], warnings: [] },
});
},
loadFromConfig: (config) => {
// Convert optimization_config.json format to intent format, then load
const intent: OptimizationIntent = {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: config.model?.path,
type: config.model?.type,
},
solver: {
type: config.solver?.solution ? `SOL${config.solver.solution}` : undefined,
},
design_variables: (config.design_variables || []).map(dv => ({
name: dv.expression_name || dv.name,
min: dv.lower,
max: dv.upper,
})),
extractors: [], // Will be inferred from objectives
objectives: (config.objectives || []).map(obj => ({
name: obj.name,
direction: (obj.direction as 'minimize' | 'maximize') || 'minimize',
weight: obj.weight || 1,
extractor: obj.extractor || '',
})),
constraints: (config.constraints || []).map(con => ({
name: con.name,
operator: con.type === 'upper' ? '<=' : '>=',
value: con.value || 0,
extractor: con.extractor || '',
})),
optimization: {
method: config.method,
max_trials: config.max_trials,
},
surrogate: config.surrogate ? {
enabled: true,
type: config.surrogate.type,
min_trials: config.surrogate.min_trials,
} : undefined,
// Complete rewrite: Create all nodes and edges directly from config
nodeIdCounter = 0;
const nodes: Node<CanvasNodeData>[] = [];
const edges: Edge[] = [];
// Column positions for proper layout
const COLS = {
modelDvar: 50,
solver: 280,
extractor: 510,
objCon: 740,
algo: 970,
surrogate: 1200,
};
const ROW_HEIGHT = 100;
const START_Y = 50;
// Helper to create node
const createNode = (type: NodeType, x: number, y: number, data: Partial<CanvasNodeData>): string => {
const id = getNodeId();
nodes.push({
id,
type,
position: { x, y },
data: { ...getDefaultData(type), ...data, configured: true } as CanvasNodeData,
});
return id;
};
// 1. Model node
const modelId = createNode('model', COLS.modelDvar, START_Y, {
label: config.study_name || 'Model',
filePath: config.model?.path,
fileType: config.model?.type as 'prt' | 'fem' | 'sim' | undefined,
});
// 2. Solver node
const solverType = config.solver?.solution ? `SOL${config.solver.solution}` : undefined;
const solverId = createNode('solver', COLS.solver, START_Y, {
label: 'Solver',
solverType: solverType as any,
});
edges.push({ id: `e_model_solver`, source: modelId, target: solverId });
// 3. Design variables (column 0, below model)
let dvRow = 1;
for (const dv of config.design_variables || []) {
const dvId = createNode('designVar', COLS.modelDvar, START_Y + dvRow * ROW_HEIGHT, {
label: dv.expression_name || dv.name,
expressionName: dv.expression_name || dv.name,
minValue: dv.lower,
maxValue: dv.upper,
});
edges.push({ id: `e_dv_${dvRow}_model`, source: dvId, target: modelId });
dvRow++;
}
// 4. Extractors - infer from objectives and constraints
const extractorNames: Record<string, string> = {
'E1': 'Displacement', 'E2': 'Frequency', 'E3': 'Solid Stress',
'E4': 'BDF Mass', 'E5': 'CAD Mass', 'E8': 'Zernike (OP2)',
'E9': 'Zernike (CSV)', 'E10': 'Zernike (RMS)',
};
// Infer extractors from objectives and constraints
const extractorIds = new Set<string>();
for (const obj of intent.objectives) {
for (const obj of config.objectives || []) {
if (obj.extractor) extractorIds.add(obj.extractor);
}
for (const con of intent.constraints) {
for (const con of config.constraints || []) {
if (con.extractor) extractorIds.add(con.extractor);
}
const extractorNames: Record<string, string> = {
'E1': 'Displacement',
'E2': 'Frequency',
'E3': 'Solid Stress',
'E4': 'BDF Mass',
'E5': 'CAD Mass',
'E8': 'Zernike (OP2)',
'E9': 'Zernike (CSV)',
'E10': 'Zernike (RMS)',
};
// If no extractors found, add a default based on objectives
if (extractorIds.size === 0 && (config.objectives?.length || 0) > 0) {
extractorIds.add('E5'); // Default to CAD Mass
}
intent.extractors = Array.from(extractorIds).map(id => ({
id,
name: extractorNames[id] || id,
}));
let extRow = 0;
const extractorMap: Record<string, string> = {};
for (const extId of extractorIds) {
const nodeId = createNode('extractor', COLS.extractor, START_Y + extRow * ROW_HEIGHT, {
label: extractorNames[extId] || extId,
extractorId: extId,
extractorName: extractorNames[extId] || extId,
});
extractorMap[extId] = nodeId;
edges.push({ id: `e_solver_ext_${extRow}`, source: solverId, target: nodeId });
extRow++;
}
get().loadFromIntent(intent);
// 5. Objectives
let objRow = 0;
const objIds: string[] = [];
for (const obj of config.objectives || []) {
const objId = createNode('objective', COLS.objCon, START_Y + objRow * ROW_HEIGHT, {
label: obj.name,
name: obj.name,
direction: (obj.direction as 'minimize' | 'maximize') || 'minimize',
weight: obj.weight || 1,
});
objIds.push(objId);
// Connect to extractor
const extNodeId = obj.extractor ? extractorMap[obj.extractor] : Object.values(extractorMap)[0];
if (extNodeId) {
edges.push({ id: `e_ext_obj_${objRow}`, source: extNodeId, target: objId });
}
objRow++;
}
// 6. Constraints
let conRow = objRow;
const conIds: string[] = [];
for (const con of config.constraints || []) {
const conId = createNode('constraint', COLS.objCon, START_Y + conRow * ROW_HEIGHT, {
label: con.name,
name: con.name,
operator: (con.type === 'upper' ? '<=' : '>=') as any,
value: con.value || 0,
});
conIds.push(conId);
// Connect to extractor
const extNodeId = con.extractor ? extractorMap[con.extractor] : Object.values(extractorMap)[0];
if (extNodeId) {
edges.push({ id: `e_ext_con_${conRow}`, source: extNodeId, target: conId });
}
conRow++;
}
// 7. Algorithm node
const method = config.method || (config as any).optimization?.sampler || 'TPE';
const maxTrials = config.max_trials || (config as any).optimization?.n_trials || 100;
const algoId = createNode('algorithm', COLS.algo, START_Y, {
label: 'Algorithm',
method: method as any,
maxTrials: maxTrials,
});
// Connect objectives to algorithm
for (let i = 0; i < objIds.length; i++) {
edges.push({ id: `e_obj_${i}_algo`, source: objIds[i], target: algoId });
}
// Connect constraints to algorithm
for (let i = 0; i < conIds.length; i++) {
edges.push({ id: `e_con_${i}_algo`, source: conIds[i], target: algoId });
}
// 8. Surrogate node (if enabled)
if (config.surrogate) {
const surId = createNode('surrogate', COLS.surrogate, START_Y, {
label: 'Surrogate',
enabled: true,
modelType: config.surrogate.type as any,
minTrials: config.surrogate.min_trials,
});
edges.push({ id: `e_algo_sur`, source: algoId, target: surId });
}
set({
nodes,
edges,
selectedNode: null,
selectedEdge: null,
validation: { valid: false, errors: [], warnings: [] },
});
},
}));

View File

@@ -1,17 +1,21 @@
import { useState } from 'react';
import { ClipboardList, Download, Trash2 } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { ClipboardList, Download, Trash2, Layers, Home, ChevronRight } from 'lucide-react';
import { AtomizerCanvas } from '../components/canvas/AtomizerCanvas';
import { TemplateSelector } from '../components/canvas/panels/TemplateSelector';
import { ConfigImporter } from '../components/canvas/panels/ConfigImporter';
import { useCanvasStore } from '../hooks/useCanvasStore';
import { useStudy } from '../context/StudyContext';
import { CanvasTemplate } from '../lib/canvas/templates';
export function CanvasView() {
const [showTemplates, setShowTemplates] = useState(false);
const [showImporter, setShowImporter] = useState(false);
const [notification, setNotification] = useState<string | null>(null);
const navigate = useNavigate();
const { nodes, clear } = useCanvasStore();
const { nodes, edges, clear } = useCanvasStore();
const { selectedStudy } = useStudy();
const handleTemplateSelect = (template: CanvasTemplate) => {
showNotification(`Loaded template: ${template.name}`);
@@ -35,38 +39,59 @@ export function CanvasView() {
return (
<div className="h-screen flex flex-col bg-dark-900">
{/* Header with actions */}
<header className="bg-dark-850 border-b border-dark-700 px-6 py-3 flex items-center justify-between">
<div>
<h1 className="text-xl font-bold text-white">
Optimization Canvas
</h1>
<p className="text-sm text-dark-400">
Drag components from the palette to build your optimization workflow
</p>
{/* Minimal Header */}
<header className="flex-shrink-0 h-12 bg-dark-850 border-b border-dark-700 px-4 flex items-center justify-between">
<div className="flex items-center gap-3">
{/* Home button */}
<button
onClick={() => navigate('/')}
className="p-1.5 rounded-lg text-dark-400 hover:text-white hover:bg-dark-700 transition-colors"
title="Back to Home"
>
<Home size={18} />
</button>
{/* Breadcrumb */}
<div className="flex items-center gap-2">
<Layers size={18} className="text-primary-400" />
<span className="text-sm font-medium text-white">Canvas Builder</span>
{selectedStudy && (
<>
<ChevronRight size={14} className="text-dark-500" />
<span className="text-sm text-primary-400 font-medium">
{selectedStudy.name || selectedStudy.id}
</span>
</>
)}
</div>
{/* Stats */}
<span className="text-xs text-dark-500 tabular-nums ml-2">
{nodes.length} node{nodes.length !== 1 ? 's' : ''} {edges.length} edge{edges.length !== 1 ? 's' : ''}
</span>
</div>
{/* Action Buttons */}
<div className="flex items-center gap-2">
<button
onClick={() => setShowTemplates(true)}
className="px-4 py-2 bg-gradient-to-r from-primary-600 to-purple-600 text-white rounded-lg hover:from-primary-500 hover:to-purple-500 transition-all shadow-sm flex items-center gap-2"
className="px-3 py-1.5 bg-primary-600 hover:bg-primary-500 text-white text-sm rounded-lg transition-colors flex items-center gap-1.5"
>
<ClipboardList size={18} />
<ClipboardList size={14} />
Templates
</button>
<button
onClick={() => setShowImporter(true)}
className="px-4 py-2 bg-dark-700 text-dark-200 rounded-lg hover:bg-dark-600 hover:text-white transition-colors flex items-center gap-2 border border-dark-600"
className="px-3 py-1.5 bg-dark-700 text-dark-200 hover:bg-dark-600 hover:text-white text-sm rounded-lg transition-colors flex items-center gap-1.5 border border-dark-600"
>
<Download size={18} />
<Download size={14} />
Import
</button>
<button
onClick={handleClear}
className="px-4 py-2 bg-dark-700 text-dark-200 rounded-lg hover:bg-red-900/50 hover:text-red-400 hover:border-red-500/50 transition-colors flex items-center gap-2 border border-dark-600"
className="px-3 py-1.5 bg-dark-700 text-dark-200 hover:bg-red-900/50 hover:text-red-400 text-sm rounded-lg transition-colors flex items-center gap-1.5 border border-dark-600"
>
<Trash2 size={18} />
<Trash2 size={14} />
Clear
</button>
</div>

View File

@@ -17,7 +17,8 @@ import {
Folder,
FolderOpen,
Maximize2,
X
X,
Layers
} from 'lucide-react';
import { useStudy } from '../context/StudyContext';
import { Study } from '../types';
@@ -172,19 +173,33 @@ const Home: React.FC = () => {
className="h-10 md:h-12"
/>
</div>
<button
onClick={() => refreshStudies()}
disabled={isLoading}
className="flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 hover:border-primary-400/40"
style={{
background: 'rgba(8, 15, 26, 0.85)',
border: '1px solid rgba(0, 212, 230, 0.2)',
color: '#fff'
}}
>
<RefreshCw className={`w-4 h-4 text-primary-400 ${isLoading ? 'animate-spin' : ''}`} />
Refresh
</button>
<div className="flex items-center gap-3">
<button
onClick={() => navigate('/canvas')}
className="flex items-center gap-2 px-4 py-2 rounded-lg transition-all font-medium hover:-translate-y-0.5"
style={{
background: 'linear-gradient(135deg, #00d4e6 0%, #0891b2 100%)',
color: '#000',
boxShadow: '0 4px 15px rgba(0, 212, 230, 0.3)'
}}
>
<Layers className="w-4 h-4" />
Canvas Builder
</button>
<button
onClick={() => refreshStudies()}
disabled={isLoading}
className="flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 hover:border-primary-400/40"
style={{
background: 'rgba(8, 15, 26, 0.85)',
border: '1px solid rgba(0, 212, 230, 0.2)',
color: '#fff'
}}
>
<RefreshCw className={`w-4 h-4 text-primary-400 ${isLoading ? 'animate-spin' : ''}`} />
Refresh
</button>
</div>
</div>
</div>
</header>