feat(canvas): Add Phase 3+4 - Bidirectional sync, templates, and visual polish

Phase 3 - Bidirectional Sync:
- Add loadFromIntent and loadFromConfig to canvas store
- Create useIntentParser hook for parsing Claude messages
- Create ConfigImporter component (file upload, paste JSON, load study)
- Add import/clear buttons to CanvasView header

Phase 4 - Templates & Polish:
- Create template library with 5 presets:
  - Mass Minimization (single-objective)
  - Multi-Objective Pareto (NSGA-II)
  - Turbo Mode (with MLP surrogate)
  - Mirror Zernike (optical optimization)
  - Frequency Optimization (modal)
- Create TemplateSelector component with category filters
- Enhanced BaseNode with animations, glow effects, status indicators
- Add colorBg to all node types for visual distinction
- Add notification toast system
- Update all exports

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-14 20:30:28 -05:00
parent 1ae35382da
commit 5bd142780f
18 changed files with 1389 additions and 35 deletions

View File

@@ -1,7 +1,16 @@
// Main Canvas Component
export { AtomizerCanvas } from './AtomizerCanvas';
// Palette
export { NodePalette } from './palette/NodePalette';
// Panels
export { NodeConfigPanel } from './panels/NodeConfigPanel';
export { ValidationPanel } from './panels/ValidationPanel';
export { ExecuteDialog } from './panels/ExecuteDialog';
export { ChatPanel } from './panels/ChatPanel';
export { ConfigImporter } from './panels/ConfigImporter';
export { TemplateSelector } from './panels/TemplateSelector';
// Nodes
export * from './nodes';

View File

@@ -6,7 +6,7 @@ import { AlgorithmNodeData } from '../../../lib/canvas/schema';
function AlgorithmNodeComponent(props: NodeProps<AlgorithmNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🧠</span>} color="text-indigo-600">
<BaseNode {...props} icon={<span>🧠</span>} color="text-indigo-600" colorBg="bg-indigo-50">
{data.method && <div>{data.method}</div>}
{data.maxTrials && (
<div className="text-xs text-gray-400">{data.maxTrials} trials</div>

View File

@@ -5,6 +5,7 @@ import { BaseNodeData } from '../../../lib/canvas/schema';
interface BaseNodeProps extends NodeProps<BaseNodeData> {
icon: ReactNode;
color: string;
colorBg?: string;
children?: ReactNode;
inputs?: number;
outputs?: number;
@@ -15,56 +16,126 @@ function BaseNodeComponent({
selected,
icon,
color,
colorBg = 'bg-gray-50',
children,
inputs = 1,
outputs = 1,
}: BaseNodeProps) {
const hasError = data.errors && data.errors.length > 0;
const isConfigured = data.configured;
return (
<div
className={`
px-4 py-3 rounded-lg border-2 min-w-[180px] bg-white shadow-sm
transition-all duration-200
${selected ? 'border-blue-500 shadow-lg' : 'border-gray-200'}
${!data.configured ? 'border-dashed' : ''}
${data.errors?.length ? 'border-red-400' : ''}
group relative px-4 py-3 rounded-xl border-2 min-w-[200px] bg-white
transition-all duration-300 ease-out
${selected
? 'border-blue-500 shadow-xl shadow-blue-100 scale-[1.02]'
: 'border-gray-200 shadow-md hover:shadow-lg hover:border-gray-300'}
${!isConfigured ? 'border-dashed opacity-80' : ''}
${hasError ? 'border-red-400 shadow-red-100' : ''}
`}
style={{
animation: 'nodeAppear 0.3s ease-out',
}}
>
{/* Glow effect on selection */}
{selected && (
<div
className="absolute inset-0 -z-10 rounded-xl opacity-20"
style={{
background: 'radial-gradient(ellipse at center, #3b82f6 0%, transparent 70%)',
transform: 'scale(1.3)',
}}
/>
)}
{/* Input handles */}
{inputs > 0 && (
<Handle
type="target"
position={Position.Left}
className="w-3 h-3 !bg-gray-400"
className={`
!w-4 !h-4 !border-2 !border-white !shadow-md
transition-all duration-200
${selected ? '!bg-blue-500' : '!bg-gray-400 group-hover:!bg-gray-500'}
`}
style={{ left: -8 }}
/>
)}
{/* Header */}
<div className="flex items-center gap-2 mb-2">
<span className={`text-lg ${color}`}>{icon}</span>
<span className="font-medium text-gray-800">{data.label}</span>
{!data.configured && (
<span className="text-xs text-orange-500">!</span>
)}
<div className="flex items-center gap-3 mb-2">
<div className={`
w-8 h-8 rounded-lg ${colorBg} flex items-center justify-center
transition-transform duration-200
${selected ? 'scale-110' : 'group-hover:scale-105'}
`}>
<span className={`text-lg ${color}`}>{icon}</span>
</div>
<div className="flex-1">
<span className="font-semibold text-gray-800 text-sm">{data.label}</span>
{!isConfigured && (
<span className="ml-2 text-xs text-orange-500 animate-pulse">Needs config</span>
)}
</div>
</div>
{/* Content */}
{children && <div className="text-sm text-gray-600">{children}</div>}
{children && (
<div className="text-sm text-gray-600 mt-2 pl-11">
{children}
</div>
)}
{/* Status indicator */}
<div className="absolute top-2 right-2">
{hasError ? (
<span className="w-2 h-2 bg-red-500 rounded-full block animate-pulse" />
) : isConfigured ? (
<span className="w-2 h-2 bg-green-500 rounded-full block" />
) : (
<span className="w-2 h-2 bg-orange-400 rounded-full block" />
)}
</div>
{/* Errors */}
{data.errors?.length ? (
<div className="mt-2 text-xs text-red-500">
{data.errors[0]}
{hasError && (
<div className="mt-3 pt-2 border-t border-red-100">
<p className="text-xs text-red-600 flex items-center gap-1">
<span></span>
{data.errors?.[0]}
</p>
</div>
) : null}
)}
{/* Output handles */}
{outputs > 0 && (
<Handle
type="source"
position={Position.Right}
className="w-3 h-3 !bg-gray-400"
className={`
!w-4 !h-4 !border-2 !border-white !shadow-md
transition-all duration-200
${selected ? '!bg-blue-500' : '!bg-gray-400 group-hover:!bg-gray-500'}
`}
style={{ right: -8 }}
/>
)}
{/* Inline styles for animation */}
<style>{`
@keyframes nodeAppear {
from {
opacity: 0;
transform: scale(0.9) translateY(10px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
`}</style>
</div>
);
}

View File

@@ -6,7 +6,7 @@ import { ConstraintNodeData } from '../../../lib/canvas/schema';
function ConstraintNodeComponent(props: NodeProps<ConstraintNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🚧</span>} color="text-orange-600">
<BaseNode {...props} icon={<span>🚧</span>} color="text-orange-600" colorBg="bg-orange-50">
{data.name && <div>{data.name}</div>}
{data.operator && data.value !== undefined && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { DesignVarNodeData } from '../../../lib/canvas/schema';
function DesignVarNodeComponent(props: NodeProps<DesignVarNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>📐</span>} color="text-green-600">
<BaseNode {...props} icon={<span>📐</span>} color="text-green-600" colorBg="bg-green-50">
{data.expressionName && <div className="font-mono">{data.expressionName}</div>}
{data.minValue !== undefined && data.maxValue !== undefined && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { ExtractorNodeData } from '../../../lib/canvas/schema';
function ExtractorNodeComponent(props: NodeProps<ExtractorNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🔬</span>} color="text-cyan-600">
<BaseNode {...props} icon={<span>🔬</span>} color="text-cyan-600" colorBg="bg-cyan-50">
{data.extractorName && <div>{data.extractorName}</div>}
{data.extractorId && (
<div className="text-xs text-gray-400">{data.extractorId}</div>

View File

@@ -6,7 +6,7 @@ import { ModelNodeData } from '../../../lib/canvas/schema';
function ModelNodeComponent(props: NodeProps<ModelNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>📦</span>} color="text-blue-600" inputs={0}>
<BaseNode {...props} icon={<span>📦</span>} color="text-blue-600" colorBg="bg-blue-50" inputs={0}>
{data.filePath && (
<div className="truncate max-w-[150px]">{data.filePath.split('/').pop()}</div>
)}

View File

@@ -6,7 +6,7 @@ import { ObjectiveNodeData } from '../../../lib/canvas/schema';
function ObjectiveNodeComponent(props: NodeProps<ObjectiveNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🎯</span>} color="text-red-600">
<BaseNode {...props} icon={<span>🎯</span>} color="text-red-600" colorBg="bg-red-50">
{data.name && <div>{data.name}</div>}
{data.direction && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { SolverNodeData } from '../../../lib/canvas/schema';
function SolverNodeComponent(props: NodeProps<SolverNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span></span>} color="text-purple-600">
<BaseNode {...props} icon={<span></span>} color="text-purple-600" colorBg="bg-purple-50">
{data.solverType && <div>{data.solverType}</div>}
</BaseNode>
);

View File

@@ -6,7 +6,7 @@ import { SurrogateNodeData } from '../../../lib/canvas/schema';
function SurrogateNodeComponent(props: NodeProps<SurrogateNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🚀</span>} color="text-pink-600" outputs={0}>
<BaseNode {...props} icon={<span>🚀</span>} color="text-pink-600" colorBg="bg-pink-50" outputs={0}>
<div>{data.enabled ? 'Enabled' : 'Disabled'}</div>
{data.enabled && data.modelType && (
<div className="text-xs text-gray-400">{data.modelType}</div>

View File

@@ -0,0 +1,242 @@
/**
* ConfigImporter - Import optimization configs into canvas
*
* Supports:
* - File upload (optimization_config.json)
* - Paste JSON directly
* - Load from study directory
*/
import { useState, useRef } from 'react';
import { useCanvasStore, OptimizationConfig } from '../../../hooks/useCanvasStore';
interface ConfigImporterProps {
isOpen: boolean;
onClose: () => void;
onImport: (source: string) => void;
}
export function ConfigImporter({ isOpen, onClose, onImport }: ConfigImporterProps) {
const [tab, setTab] = useState<'file' | 'paste' | 'study'>('file');
const [jsonText, setJsonText] = useState('');
const [studyPath, setStudyPath] = useState('');
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { loadFromConfig } = useCanvasStore();
if (!isOpen) return null;
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setError(null);
setIsLoading(true);
try {
const text = await file.text();
const config = JSON.parse(text) as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport(`File: ${file.name}`);
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Invalid JSON file');
} finally {
setIsLoading(false);
}
};
const handlePasteImport = () => {
setError(null);
try {
const config = JSON.parse(jsonText) as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport('Pasted JSON');
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Invalid JSON');
}
};
const handleStudyLoad = async () => {
setError(null);
setIsLoading(true);
try {
// Call backend API to load study config
const response = await fetch(`/api/studies/${encodeURIComponent(studyPath)}/config`);
if (!response.ok) {
throw new Error(`Study not found: ${studyPath}`);
}
const config = await response.json() as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport(`Study: ${studyPath}`);
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load study');
} finally {
setIsLoading(false);
}
};
const validateConfig = (config: OptimizationConfig) => {
if (!config) {
throw new Error('Empty configuration');
}
// Must have at least one design variable or objective
const hasDesignVars = config.design_variables && config.design_variables.length > 0;
const hasObjectives = config.objectives && config.objectives.length > 0;
if (!hasDesignVars && !hasObjectives) {
throw new Error('Configuration must have design variables or objectives');
}
};
const handleClose = () => {
setJsonText('');
setStudyPath('');
setError(null);
setTab('file');
onClose();
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl w-full max-w-lg">
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
<h2 className="text-xl font-semibold text-gray-800">Import Configuration</h2>
<button
onClick={handleClose}
className="text-gray-500 hover:text-gray-700 text-xl"
>
&times;
</button>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200">
{[
{ id: 'file', label: 'Upload File' },
{ id: 'paste', label: 'Paste JSON' },
{ id: 'study', label: 'Load Study' },
].map((t) => (
<button
key={t.id}
onClick={() => setTab(t.id as 'file' | 'paste' | 'study')}
className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
tab === t.id
? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
: 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
}`}
>
{t.label}
</button>
))}
</div>
{/* Content */}
<div className="p-6">
{/* File Upload Tab */}
{tab === 'file' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Upload an <code className="bg-gray-100 px-1 rounded">optimization_config.json</code> file
from an existing study.
</p>
<input
ref={fileInputRef}
type="file"
accept=".json"
onChange={handleFileSelect}
className="hidden"
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={isLoading}
className="w-full py-8 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-colors flex flex-col items-center gap-2"
>
<span className="text-3xl">📁</span>
<span className="text-gray-600">
{isLoading ? 'Loading...' : 'Click to select file'}
</span>
</button>
</div>
)}
{/* Paste JSON Tab */}
{tab === 'paste' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Paste your optimization configuration JSON below.
</p>
<textarea
value={jsonText}
onChange={(e) => setJsonText(e.target.value)}
placeholder={`{
"design_variables": [...],
"objectives": [...],
"method": "TPE"
}`}
className="w-full h-48 px-3 py-2 border rounded-lg font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button
onClick={handlePasteImport}
disabled={!jsonText.trim()}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Import JSON
</button>
</div>
)}
{/* Load Study Tab */}
{tab === 'study' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Enter a study name to load its configuration.
</p>
<input
type="text"
value={studyPath}
onChange={(e) => setStudyPath(e.target.value)}
placeholder="e.g., bracket_mass_v1 or M1_Mirror/m1_mirror_flatback"
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button
onClick={handleStudyLoad}
disabled={!studyPath.trim() || isLoading}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isLoading ? 'Loading...' : 'Load Study Config'}
</button>
</div>
)}
{/* Error Display */}
{error && (
<div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-700">{error}</p>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-4 border-t border-gray-200 bg-gray-50 rounded-b-lg">
<p className="text-xs text-gray-500">
Imported configurations will replace the current canvas content.
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,224 @@
/**
* TemplateSelector - Choose from pre-built optimization templates
*
* Displays template cards with preview and one-click loading
*/
import { useState } from 'react';
import { templates, CanvasTemplate, instantiateTemplate, getTemplatesByCategory } from '../../../lib/canvas/templates';
import { useCanvasStore } from '../../../hooks/useCanvasStore';
interface TemplateSelectorProps {
isOpen: boolean;
onClose: () => void;
onSelect: (template: CanvasTemplate) => void;
}
export function TemplateSelector({ isOpen, onClose, onSelect }: TemplateSelectorProps) {
const [selectedCategory, setSelectedCategory] = useState<'all' | 'structural' | 'optical' | 'general'>('all');
const [hoveredTemplate, setHoveredTemplate] = useState<string | null>(null);
const { loadFromIntent, clear } = useCanvasStore();
if (!isOpen) return null;
const filteredTemplates = selectedCategory === 'all'
? templates
: getTemplatesByCategory(selectedCategory);
const handleSelect = (template: CanvasTemplate) => {
clear();
const intent = instantiateTemplate(template);
loadFromIntent(intent);
onSelect(template);
onClose();
};
const categories = [
{ id: 'all', label: 'All Templates', count: templates.length },
{ id: 'structural', label: 'Structural', count: getTemplatesByCategory('structural').length },
{ id: 'optical', label: 'Optical', count: getTemplatesByCategory('optical').length },
{ id: 'general', label: 'General', count: getTemplatesByCategory('general').length },
];
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div
className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
style={{ animation: 'fadeIn 0.2s ease-out' }}
>
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center bg-gradient-to-r from-blue-50 to-purple-50">
<div>
<h2 className="text-xl font-semibold text-gray-800">Choose a Template</h2>
<p className="text-sm text-gray-500 mt-0.5">Start with a pre-configured optimization workflow</p>
</div>
<button
onClick={onClose}
className="w-8 h-8 flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors"
>
&times;
</button>
</div>
{/* Category Filters */}
<div className="px-6 py-3 border-b border-gray-100 flex gap-2 bg-gray-50">
{categories.map((cat) => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id as typeof selectedCategory)}
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
selectedCategory === cat.id
? 'bg-blue-600 text-white shadow-sm'
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-200'
}`}
>
{cat.label}
<span className={`ml-1.5 ${selectedCategory === cat.id ? 'text-blue-200' : 'text-gray-400'}`}>
({cat.count})
</span>
</button>
))}
</div>
{/* Template Grid */}
<div className="flex-1 overflow-y-auto p-6">
<div className="grid grid-cols-2 gap-4">
{filteredTemplates.map((template) => (
<TemplateCard
key={template.id}
template={template}
isHovered={hoveredTemplate === template.id}
onHover={() => setHoveredTemplate(template.id)}
onLeave={() => setHoveredTemplate(null)}
onSelect={() => handleSelect(template)}
/>
))}
</div>
{filteredTemplates.length === 0 && (
<div className="text-center py-12">
<p className="text-gray-500">No templates in this category</p>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-3 border-t border-gray-200 bg-gray-50 flex justify-between items-center">
<p className="text-xs text-gray-500">
Templates provide a starting point - customize parameters after loading
</p>
<button
onClick={onClose}
className="px-4 py-2 text-gray-600 hover:text-gray-800 text-sm"
>
Cancel
</button>
</div>
</div>
<style>{`
@keyframes fadeIn {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
}
`}</style>
</div>
);
}
interface TemplateCardProps {
template: CanvasTemplate;
isHovered: boolean;
onHover: () => void;
onLeave: () => void;
onSelect: () => void;
}
function TemplateCard({ template, isHovered, onHover, onLeave, onSelect }: TemplateCardProps) {
const intent = template.intent;
const stats = {
designVars: intent.design_variables?.length || 0,
objectives: intent.objectives?.length || 0,
constraints: intent.constraints?.length || 0,
method: intent.optimization?.method || 'TPE',
hasSurrogate: intent.surrogate?.enabled || false,
};
const categoryColors = {
structural: 'bg-orange-100 text-orange-700',
optical: 'bg-purple-100 text-purple-700',
general: 'bg-blue-100 text-blue-700',
};
return (
<div
className={`border rounded-xl p-4 cursor-pointer transition-all duration-200 ${
isHovered
? 'border-blue-400 shadow-lg transform -translate-y-0.5 bg-blue-50/30'
: 'border-gray-200 hover:border-gray-300 bg-white'
}`}
onMouseEnter={onHover}
onMouseLeave={onLeave}
onClick={onSelect}
>
{/* Header */}
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
<span className="text-2xl">{template.icon}</span>
<div>
<h3 className="font-semibold text-gray-800">{template.name}</h3>
<span className={`text-xs px-2 py-0.5 rounded-full ${categoryColors[template.category]}`}>
{template.category}
</span>
</div>
</div>
{stats.hasSurrogate && (
<span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded-full">
Turbo
</span>
)}
</div>
{/* Description */}
<p className="text-sm text-gray-600 mb-4 line-clamp-2">{template.description}</p>
{/* Stats */}
<div className="flex gap-4 text-xs text-gray-500">
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-blue-400"></span>
<span>{stats.designVars} vars</span>
</div>
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-green-400"></span>
<span>{stats.objectives} obj</span>
</div>
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-orange-400"></span>
<span>{stats.constraints} con</span>
</div>
<div className="flex items-center gap-1">
<span className="font-medium text-gray-600">{stats.method}</span>
</div>
</div>
{/* Use Button (appears on hover) */}
<div
className={`mt-4 transition-all duration-200 overflow-hidden ${
isHovered ? 'max-h-10 opacity-100' : 'max-h-0 opacity-0'
}`}
>
<button
className="w-full py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
onClick={(e) => {
e.stopPropagation();
onSelect();
}}
>
Use This Template
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,5 @@
// Canvas Hooks
export { useCanvasStore } from './useCanvasStore';
export type { OptimizationConfig } from './useCanvasStore';
export { useCanvasChat } from './useCanvasChat';
export { useIntentParser } from './useIntentParser';

View File

@@ -22,6 +22,45 @@ interface CanvasState {
toIntent: () => OptimizationIntent;
clear: () => void;
loadFromIntent: (intent: OptimizationIntent) => void;
loadFromConfig: (config: OptimizationConfig) => void;
}
// Optimization config structure (from optimization_config.json)
export interface OptimizationConfig {
study_name?: string;
model?: {
path?: string;
type?: string;
};
solver?: {
type?: string;
solution?: number;
};
design_variables?: Array<{
name: string;
expression_name?: string;
lower: number;
upper: number;
type?: string;
}>;
objectives?: Array<{
name: string;
direction?: string;
weight?: number;
extractor?: string;
}>;
constraints?: Array<{
name: string;
type?: string;
value?: number;
extractor?: string;
}>;
method?: string;
max_trials?: number;
surrogate?: {
type?: string;
min_trials?: number;
} | null;
}
let nodeIdCounter = 0;
@@ -43,6 +82,14 @@ const getDefaultData = (type: NodeType): CanvasNodeData => {
}
};
// Layout constants for auto-arrangement
const LAYOUT = {
startX: 100,
startY: 100,
colWidth: 250,
rowHeight: 120,
};
export const useCanvasStore = create<CanvasState>((set, get) => ({
nodes: [],
edges: [],
@@ -119,7 +166,216 @@ export const useCanvasStore = create<CanvasState>((set, get) => ({
},
loadFromIntent: (intent) => {
// TODO: Implement reverse serialization
console.log('Loading intent:', intent);
// Clear existing
nodeIdCounter = 0;
const nodes: Node<CanvasNodeData>[] = [];
const edges: Edge[] = [];
let col = 0;
let row = 0;
// Helper to create positioned node
const createNode = (type: NodeType, data: Partial<CanvasNodeData>, colOffset = 0): string => {
const id = getNodeId();
nodes.push({
id,
type,
position: {
x: LAYOUT.startX + (col + colOffset) * LAYOUT.colWidth,
y: LAYOUT.startY + row * LAYOUT.rowHeight,
},
data: { ...getDefaultData(type), ...data, configured: true } as CanvasNodeData,
});
return id;
};
// Model node (column 0)
col = 0;
const modelId = createNode('model', {
label: 'Model',
filePath: intent.model?.path,
fileType: intent.model?.type as 'prt' | 'fem' | 'sim' | undefined,
});
// Solver node (column 1)
col = 1;
const solverId = createNode('solver', {
label: 'Solver',
solverType: intent.solver?.type as any,
});
edges.push({ id: `e_${modelId}_${solverId}`, source: modelId, target: solverId });
// Design variables (column 0, multiple rows)
col = 0;
row = 1;
const dvIds: string[] = [];
for (const dv of intent.design_variables || []) {
const dvId = createNode('designVar', {
label: dv.name,
expressionName: dv.name,
minValue: dv.min,
maxValue: dv.max,
unit: dv.unit,
});
dvIds.push(dvId);
edges.push({ id: `e_${dvId}_${modelId}`, source: dvId, target: modelId });
row++;
}
// Extractors (column 2)
col = 2;
row = 0;
const extractorMap: Record<string, string> = {};
for (const ext of intent.extractors || []) {
const extId = createNode('extractor', {
label: ext.name,
extractorId: ext.id,
extractorName: ext.name,
config: ext.config,
});
extractorMap[ext.id] = extId;
edges.push({ id: `e_${solverId}_${extId}`, source: solverId, target: extId });
row++;
}
// Objectives (column 3)
col = 3;
row = 0;
const objIds: string[] = [];
for (const obj of intent.objectives || []) {
const objId = createNode('objective', {
label: obj.name,
name: obj.name,
direction: obj.direction,
weight: obj.weight,
});
objIds.push(objId);
// Connect to extractor if specified
if (obj.extractor && extractorMap[obj.extractor]) {
edges.push({ id: `e_${extractorMap[obj.extractor]}_${objId}`, source: extractorMap[obj.extractor], target: objId });
}
row++;
}
// Constraints (column 3, after objectives)
const conIds: string[] = [];
for (const con of intent.constraints || []) {
const conId = createNode('constraint', {
label: con.name,
name: con.name,
operator: con.operator as any,
value: con.value,
});
conIds.push(conId);
if (con.extractor && extractorMap[con.extractor]) {
edges.push({ id: `e_${extractorMap[con.extractor]}_${conId}`, source: extractorMap[con.extractor], target: conId });
}
row++;
}
// Algorithm (column 4)
col = 4;
row = 0;
const algoId = createNode('algorithm', {
label: 'Algorithm',
method: intent.optimization?.method as any,
maxTrials: intent.optimization?.max_trials,
});
// Connect all objectives and constraints to algorithm
for (const objId of objIds) {
edges.push({ id: `e_${objId}_${algoId}`, source: objId, target: algoId });
}
for (const conId of conIds) {
edges.push({ id: `e_${conId}_${algoId}`, source: conId, target: algoId });
}
// Surrogate (column 5, optional)
if (intent.surrogate?.enabled) {
col = 5;
const surId = createNode('surrogate', {
label: 'Surrogate',
enabled: true,
modelType: intent.surrogate.type as any,
minTrials: intent.surrogate.min_trials,
});
edges.push({ id: `e_${algoId}_${surId}`, source: algoId, target: surId });
}
set({
nodes,
edges,
selectedNode: 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,
};
// Infer extractors from objectives and constraints
const extractorIds = new Set<string>();
for (const obj of intent.objectives) {
if (obj.extractor) extractorIds.add(obj.extractor);
}
for (const con of intent.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)',
};
intent.extractors = Array.from(extractorIds).map(id => ({
id,
name: extractorNames[id] || id,
}));
get().loadFromIntent(intent);
},
}));

View File

@@ -0,0 +1,172 @@
/**
* useIntentParser - Parse Claude messages for canvas updates
*
* Detects structured intents in chat messages and applies them to canvas
*/
import { useCallback } from 'react';
import { useCanvasStore, OptimizationConfig } from './useCanvasStore';
import { OptimizationIntent } from '../lib/canvas/intent';
import { Message } from '../components/chat/ChatMessage';
interface ParsedUpdate {
type: 'intent' | 'config' | 'suggestion' | 'none';
data?: OptimizationIntent | OptimizationConfig;
suggestions?: string[];
}
export function useIntentParser() {
const { loadFromIntent, loadFromConfig, updateNodeData, nodes } = useCanvasStore();
/**
* Parse a message for structured intent JSON
*/
const parseIntent = useCallback((content: string): ParsedUpdate => {
// Look for JSON blocks in the message
const jsonBlockRegex = /```(?:json)?\s*\n?([\s\S]*?)\n?```/g;
const matches = [...content.matchAll(jsonBlockRegex)];
for (const match of matches) {
try {
const parsed = JSON.parse(match[1]);
// Check if it's an OptimizationIntent
if (parsed.version && parsed.source === 'canvas') {
return { type: 'intent', data: parsed as OptimizationIntent };
}
// Check if it's an OptimizationConfig (has design_variables or objectives)
if (parsed.design_variables || parsed.objectives || parsed.model?.path) {
return { type: 'config', data: parsed as OptimizationConfig };
}
} catch {
// Not valid JSON, continue
}
}
// Look for inline JSON (without code blocks)
const inlineJsonRegex = /\{[\s\S]*?"(?:version|design_variables|objectives)"[\s\S]*?\}/g;
const inlineMatches = content.match(inlineJsonRegex);
if (inlineMatches) {
for (const jsonStr of inlineMatches) {
try {
const parsed = JSON.parse(jsonStr);
if (parsed.version && parsed.source === 'canvas') {
return { type: 'intent', data: parsed as OptimizationIntent };
}
if (parsed.design_variables || parsed.objectives) {
return { type: 'config', data: parsed as OptimizationConfig };
}
} catch {
// Not valid JSON
}
}
}
// Look for suggestions in the message
const suggestions = extractSuggestions(content);
if (suggestions.length > 0) {
return { type: 'suggestion', suggestions };
}
return { type: 'none' };
}, []);
/**
* Extract actionable suggestions from Claude's response
*/
const extractSuggestions = (content: string): string[] => {
const suggestions: string[] = [];
// Common suggestion patterns
const patterns = [
/suggest(?:ing)?\s+(?:to\s+)?(?:add|include|use)\s+([^.!?\n]+)/gi,
/recommend(?:ing)?\s+([^.!?\n]+)/gi,
/consider\s+(?:adding|using|including)\s+([^.!?\n]+)/gi,
/you\s+(?:should|could|might)\s+(?:add|include|use)\s+([^.!?\n]+)/gi,
];
for (const pattern of patterns) {
const matches = content.matchAll(pattern);
for (const match of matches) {
if (match[1]) {
suggestions.push(match[1].trim());
}
}
}
return suggestions;
};
/**
* Apply a parsed update to the canvas
*/
const applyUpdate = useCallback((update: ParsedUpdate): boolean => {
switch (update.type) {
case 'intent':
if (update.data && 'version' in update.data) {
loadFromIntent(update.data as OptimizationIntent);
return true;
}
break;
case 'config':
if (update.data && !('version' in update.data)) {
loadFromConfig(update.data as OptimizationConfig);
return true;
}
break;
case 'suggestion':
// Suggestions are returned but not auto-applied
return false;
}
return false;
}, [loadFromIntent, loadFromConfig]);
/**
* Process a message and optionally apply updates
*/
const processMessage = useCallback((message: Message, autoApply = false): ParsedUpdate => {
const update = parseIntent(message.content);
if (autoApply && (update.type === 'intent' || update.type === 'config')) {
applyUpdate(update);
}
return update;
}, [parseIntent, applyUpdate]);
/**
* Check if a message contains canvas-related content
*/
const hasCanvasContent = useCallback((content: string): boolean => {
const keywords = [
'design variable', 'objective', 'constraint', 'extractor',
'optimization', 'algorithm', 'surrogate', 'model', 'solver',
'canvas', 'workflow', 'node'
];
const lowerContent = content.toLowerCase();
return keywords.some(kw => lowerContent.includes(kw));
}, []);
/**
* Apply parameter updates to specific nodes
*/
const applyParameterUpdates = useCallback((updates: Record<string, Partial<unknown>>) => {
for (const [nodeId, data] of Object.entries(updates)) {
const node = nodes.find(n => n.id === nodeId);
if (node) {
updateNodeData(nodeId, data as Record<string, unknown>);
}
}
}, [nodes, updateNodeData]);
return {
parseIntent,
applyUpdate,
processMessage,
hasCanvasContent,
applyParameterUpdates,
extractSuggestions,
};
}

View File

@@ -0,0 +1,5 @@
// Canvas Library Exports
export * from './schema';
export * from './intent';
export * from './validation';
export * from './templates';

View File

@@ -0,0 +1,278 @@
/**
* Canvas Templates - Pre-built optimization workflow templates
*
* Each template provides a complete starting point for common optimization scenarios.
*/
import { OptimizationIntent } from './intent';
export interface CanvasTemplate {
id: string;
name: string;
description: string;
category: 'structural' | 'optical' | 'general';
icon: string;
intent: OptimizationIntent;
}
/**
* Template 1: Mass Minimization
* Single-objective optimization to minimize structural mass while maintaining stiffness
*/
const massMinimizationTemplate: CanvasTemplate = {
id: 'mass_minimization',
name: 'Mass Minimization',
description: 'Minimize structural mass while maintaining stiffness constraints. Ideal for brackets, housings, and weight-critical components.',
category: 'structural',
icon: '⚖️',
intent: {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: undefined,
type: 'prt',
},
solver: {
type: 'SOL101',
},
design_variables: [
{ name: 'wall_thickness', min: 1.0, max: 10.0, unit: 'mm' },
{ name: 'rib_height', min: 5.0, max: 25.0, unit: 'mm' },
{ name: 'fillet_radius', min: 1.0, max: 5.0, unit: 'mm' },
],
extractors: [
{ id: 'E4', name: 'BDF Mass', config: {} },
{ id: 'E1', name: 'Max Displacement', config: { node_set: 'ALL' } },
],
objectives: [
{ name: 'mass', direction: 'minimize', weight: 1.0, extractor: 'E4' },
],
constraints: [
{ name: 'max_displacement', operator: '<=', value: 0.5, extractor: 'E1' },
],
optimization: {
method: 'TPE',
max_trials: 100,
},
},
};
/**
* Template 2: Multi-Objective Pareto
* Trade-off between mass and stiffness using NSGA-II
*/
const multiObjectiveTemplate: CanvasTemplate = {
id: 'multi_objective',
name: 'Multi-Objective Pareto',
description: 'Explore trade-offs between competing objectives. Generates a Pareto front for informed decision-making.',
category: 'structural',
icon: '📊',
intent: {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: undefined,
type: 'prt',
},
solver: {
type: 'SOL101',
},
design_variables: [
{ name: 'thickness', min: 2.0, max: 15.0, unit: 'mm' },
{ name: 'width', min: 10.0, max: 50.0, unit: 'mm' },
{ name: 'height', min: 20.0, max: 80.0, unit: 'mm' },
],
extractors: [
{ id: 'E4', name: 'BDF Mass', config: {} },
{ id: 'E1', name: 'Max Displacement', config: { node_set: 'ALL' } },
{ id: 'E3', name: 'Max Stress', config: { element_set: 'ALL' } },
],
objectives: [
{ name: 'mass', direction: 'minimize', weight: 1.0, extractor: 'E4' },
{ name: 'displacement', direction: 'minimize', weight: 1.0, extractor: 'E1' },
],
constraints: [
{ name: 'max_stress', operator: '<=', value: 250.0, extractor: 'E3' },
],
optimization: {
method: 'NSGA-II',
max_trials: 200,
},
},
};
/**
* Template 3: Turbo Mode with Surrogate
* High-efficiency optimization using neural network surrogates
*/
const turboModeTemplate: CanvasTemplate = {
id: 'turbo_mode',
name: 'Turbo Mode',
description: 'Accelerated optimization using neural network surrogates. Run thousands of virtual trials with periodic FEA validation.',
category: 'general',
icon: '🚀',
intent: {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: undefined,
type: 'prt',
},
solver: {
type: 'SOL101',
},
design_variables: [
{ name: 'param_1', min: 0.0, max: 100.0 },
{ name: 'param_2', min: 0.0, max: 100.0 },
{ name: 'param_3', min: 0.0, max: 100.0 },
{ name: 'param_4', min: 0.0, max: 100.0 },
],
extractors: [
{ id: 'E1', name: 'Objective Extractor', config: {} },
],
objectives: [
{ name: 'objective', direction: 'minimize', weight: 1.0, extractor: 'E1' },
],
constraints: [],
optimization: {
method: 'TPE',
max_trials: 50,
},
surrogate: {
enabled: true,
type: 'MLP',
min_trials: 20,
},
},
};
/**
* Template 4: Mirror Zernike Optimization
* Optical surface optimization using Zernike polynomial decomposition
*/
const mirrorZernikeTemplate: CanvasTemplate = {
id: 'mirror_zernike',
name: 'Mirror Zernike',
description: 'Optimize optical mirror surface quality using Zernike wavefront error metrics. Specialized for precision optics.',
category: 'optical',
icon: '🔭',
intent: {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: undefined,
type: 'prt',
},
solver: {
type: 'SOL101',
},
design_variables: [
{ name: 'rib_thickness', min: 5.0, max: 30.0, unit: 'mm' },
{ name: 'back_thickness', min: 10.0, max: 50.0, unit: 'mm' },
{ name: 'cell_count', min: 6, max: 24 },
{ name: 'lightweighting_ratio', min: 0.3, max: 0.8 },
],
extractors: [
{ id: 'E8', name: 'Zernike WFE', config: { terms: [4, 5, 6, 7, 8, 9, 10, 11], method: 'op2' } },
{ id: 'E4', name: 'BDF Mass', config: {} },
],
objectives: [
{ name: 'wfe_rms', direction: 'minimize', weight: 0.7, extractor: 'E8' },
{ name: 'mass', direction: 'minimize', weight: 0.3, extractor: 'E4' },
],
constraints: [
{ name: 'max_mass', operator: '<=', value: 150.0, extractor: 'E4' },
],
optimization: {
method: 'TPE',
max_trials: 150,
},
surrogate: {
enabled: true,
type: 'GNN',
min_trials: 30,
},
},
};
/**
* Template 5: Frequency Optimization
* Maximize natural frequencies for dynamic performance
*/
const frequencyOptimizationTemplate: CanvasTemplate = {
id: 'frequency_optimization',
name: 'Frequency Optimization',
description: 'Maximize natural frequencies to avoid resonance. Essential for rotating machinery and vibration-sensitive equipment.',
category: 'structural',
icon: '📈',
intent: {
version: '1.0',
source: 'canvas',
timestamp: new Date().toISOString(),
model: {
path: undefined,
type: 'prt',
},
solver: {
type: 'SOL103',
},
design_variables: [
{ name: 'base_thickness', min: 5.0, max: 25.0, unit: 'mm' },
{ name: 'stiffener_height', min: 10.0, max: 40.0, unit: 'mm' },
{ name: 'stiffener_spacing', min: 20.0, max: 80.0, unit: 'mm' },
],
extractors: [
{ id: 'E2', name: 'First Frequency', config: { mode: 1 } },
{ id: 'E4', name: 'BDF Mass', config: {} },
],
objectives: [
{ name: 'frequency_1', direction: 'maximize', weight: 1.0, extractor: 'E2' },
],
constraints: [
{ name: 'max_mass', operator: '<=', value: 50.0, extractor: 'E4' },
],
optimization: {
method: 'TPE',
max_trials: 100,
},
},
};
/**
* All available templates
*/
export const templates: CanvasTemplate[] = [
massMinimizationTemplate,
multiObjectiveTemplate,
turboModeTemplate,
mirrorZernikeTemplate,
frequencyOptimizationTemplate,
];
/**
* Get template by ID
*/
export function getTemplate(id: string): CanvasTemplate | undefined {
return templates.find(t => t.id === id);
}
/**
* Get templates by category
*/
export function getTemplatesByCategory(category: CanvasTemplate['category']): CanvasTemplate[] {
return templates.filter(t => t.category === category);
}
/**
* Create a fresh copy of a template's intent with updated timestamp
*/
export function instantiateTemplate(template: CanvasTemplate): OptimizationIntent {
return {
...template.intent,
timestamp: new Date().toISOString(),
};
}

View File

@@ -1,19 +1,111 @@
import { useState } from '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 { 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 { nodes, clear } = useCanvasStore();
const handleTemplateSelect = (template: CanvasTemplate) => {
showNotification(`Loaded template: ${template.name}`);
};
const handleImport = (source: string) => {
showNotification(`Imported from ${source}`);
};
const handleClear = () => {
if (nodes.length === 0 || window.confirm('Clear all nodes from the canvas?')) {
clear();
showNotification('Canvas cleared');
}
};
const showNotification = (message: string) => {
setNotification(message);
setTimeout(() => setNotification(null), 3000);
};
return (
<div className="h-screen flex flex-col">
<header className="bg-white border-b border-gray-200 px-6 py-4">
<h1 className="text-xl font-bold text-gray-800">
Optimization Canvas
</h1>
<p className="text-sm text-gray-500">
Drag components from the palette to build your optimization workflow
</p>
{/* Header with actions */}
<header className="bg-white border-b border-gray-200 px-6 py-3 flex items-center justify-between">
<div>
<h1 className="text-xl font-bold text-gray-800">
Optimization Canvas
</h1>
<p className="text-sm text-gray-500">
Drag components from the palette to build your optimization workflow
</p>
</div>
{/* Action Buttons */}
<div className="flex items-center gap-2">
<button
onClick={() => setShowTemplates(true)}
className="px-4 py-2 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-lg hover:from-blue-600 hover:to-purple-600 transition-all shadow-sm flex items-center gap-2"
>
<span>📋</span>
Templates
</button>
<button
onClick={() => setShowImporter(true)}
className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
>
<span>📥</span>
Import
</button>
<button
onClick={handleClear}
className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
>
<span>🗑</span>
Clear
</button>
</div>
</header>
{/* Main Canvas */}
<main className="flex-1 overflow-hidden">
<AtomizerCanvas />
</main>
{/* Template Selector Modal */}
<TemplateSelector
isOpen={showTemplates}
onClose={() => setShowTemplates(false)}
onSelect={handleTemplateSelect}
/>
{/* Config Importer Modal */}
<ConfigImporter
isOpen={showImporter}
onClose={() => setShowImporter(false)}
onImport={handleImport}
/>
{/* Notification Toast */}
{notification && (
<div
className="fixed bottom-4 left-1/2 transform -translate-x-1/2 px-4 py-2 bg-gray-800 text-white rounded-lg shadow-lg z-50"
style={{ animation: 'slideUp 0.3s ease-out' }}
>
{notification}
</div>
)}
<style>{`
@keyframes slideUp {
from { opacity: 0; transform: translate(-50%, 20px); }
to { opacity: 1; transform: translate(-50%, 0); }
}
`}</style>
</div>
);
}