feat: Add Studio UI, intake system, and extractor improvements

Dashboard:
- Add Studio page with drag-drop model upload and Claude chat
- Add intake system for study creation workflow
- Improve session manager and context builder
- Add intake API routes and frontend components

Optimization Engine:
- Add CLI module for command-line operations
- Add intake module for study preprocessing
- Add validation module with gate checks
- Improve Zernike extractor documentation
- Update spec models with better validation
- Enhance solve_simulation robustness

Documentation:
- Add ATOMIZER_STUDIO.md planning doc
- Add ATOMIZER_UX_SYSTEM.md for UX patterns
- Update extractor library docs
- Add study-readme-generator skill

Tools:
- Add test scripts for extraction validation
- Add Zernike recentering test

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-27 12:02:30 -05:00
parent 3193831340
commit a26914bbe8
56 changed files with 14173 additions and 646 deletions

View File

@@ -0,0 +1,254 @@
/**
* StudioBuildDialog - Final dialog to name and build the study
*/
import React, { useState, useEffect } from 'react';
import { X, Loader2, FolderOpen, AlertCircle, CheckCircle, Sparkles, Play } from 'lucide-react';
import { intakeApi } from '../../api/intake';
interface StudioBuildDialogProps {
draftId: string;
onClose: () => void;
onBuildComplete: (finalPath: string, finalName: string) => void;
}
interface Topic {
name: string;
study_count: number;
}
export const StudioBuildDialog: React.FC<StudioBuildDialogProps> = ({
draftId,
onClose,
onBuildComplete,
}) => {
const [studyName, setStudyName] = useState('');
const [topic, setTopic] = useState('');
const [newTopic, setNewTopic] = useState('');
const [useNewTopic, setUseNewTopic] = useState(false);
const [topics, setTopics] = useState<Topic[]>([]);
const [isBuilding, setIsBuilding] = useState(false);
const [error, setError] = useState<string | null>(null);
const [validationErrors, setValidationErrors] = useState<string[]>([]);
// Load topics
useEffect(() => {
loadTopics();
}, []);
const loadTopics = async () => {
try {
const response = await intakeApi.listTopics();
setTopics(response.topics);
if (response.topics.length > 0) {
setTopic(response.topics[0].name);
}
} catch (err) {
console.error('Failed to load topics:', err);
}
};
// Validate study name
useEffect(() => {
const errors: string[] = [];
if (studyName.length > 0) {
if (studyName.length < 3) {
errors.push('Name must be at least 3 characters');
}
if (!/^[a-z0-9_]+$/.test(studyName)) {
errors.push('Use only lowercase letters, numbers, and underscores');
}
if (studyName.startsWith('draft_')) {
errors.push('Name cannot start with "draft_"');
}
}
setValidationErrors(errors);
}, [studyName]);
const handleBuild = async () => {
const finalTopic = useNewTopic ? newTopic : topic;
if (!studyName || !finalTopic) {
setError('Please provide both a study name and topic');
return;
}
if (validationErrors.length > 0) {
setError('Please fix validation errors');
return;
}
setIsBuilding(true);
setError(null);
try {
const response = await intakeApi.finalizeStudio(draftId, {
topic: finalTopic,
newName: studyName,
runBaseline: false,
});
onBuildComplete(response.final_path, response.final_name);
} catch (err) {
setError(err instanceof Error ? err.message : 'Build failed');
} finally {
setIsBuilding(false);
}
};
const isValid = studyName.length >= 3 &&
validationErrors.length === 0 &&
(topic || (useNewTopic && newTopic));
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-dark-850 border border-dark-700 rounded-xl shadow-xl w-full max-w-lg mx-4">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-dark-700">
<div className="flex items-center gap-2">
<Sparkles className="w-5 h-5 text-primary-400" />
<h2 className="text-lg font-semibold text-white">Build Study</h2>
</div>
<button
onClick={onClose}
className="p-1 hover:bg-dark-700 rounded text-dark-400 hover:text-white transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 space-y-6">
{/* Study Name */}
<div>
<label className="block text-sm font-medium text-dark-300 mb-2">
Study Name
</label>
<input
type="text"
value={studyName}
onChange={(e) => setStudyName(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'))}
placeholder="my_optimization_study"
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-white placeholder-dark-500 focus:outline-none focus:border-primary-400"
/>
{validationErrors.length > 0 && (
<div className="mt-2 space-y-1">
{validationErrors.map((err, i) => (
<p key={i} className="text-xs text-red-400 flex items-center gap-1">
<AlertCircle className="w-3 h-3" />
{err}
</p>
))}
</div>
)}
{studyName.length >= 3 && validationErrors.length === 0 && (
<p className="mt-2 text-xs text-green-400 flex items-center gap-1">
<CheckCircle className="w-3 h-3" />
Name is valid
</p>
)}
</div>
{/* Topic Selection */}
<div>
<label className="block text-sm font-medium text-dark-300 mb-2">
Topic Folder
</label>
{!useNewTopic && topics.length > 0 && (
<div className="space-y-2">
<select
value={topic}
onChange={(e) => setTopic(e.target.value)}
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-white focus:outline-none focus:border-primary-400"
>
{topics.map((t) => (
<option key={t.name} value={t.name}>
{t.name} ({t.study_count} studies)
</option>
))}
</select>
<button
onClick={() => setUseNewTopic(true)}
className="text-sm text-primary-400 hover:text-primary-300"
>
+ Create new topic
</button>
</div>
)}
{(useNewTopic || topics.length === 0) && (
<div className="space-y-2">
<input
type="text"
value={newTopic}
onChange={(e) => setNewTopic(e.target.value.replace(/[^A-Za-z0-9_]/g, '_'))}
placeholder="NewTopic"
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-white placeholder-dark-500 focus:outline-none focus:border-primary-400"
/>
{topics.length > 0 && (
<button
onClick={() => setUseNewTopic(false)}
className="text-sm text-dark-400 hover:text-white"
>
Use existing topic
</button>
)}
</div>
)}
</div>
{/* Preview */}
<div className="p-3 bg-dark-700/50 rounded-lg">
<p className="text-xs text-dark-400 mb-1">Study will be created at:</p>
<p className="text-sm text-white font-mono flex items-center gap-2">
<FolderOpen className="w-4 h-4 text-primary-400" />
studies/{useNewTopic ? newTopic || '...' : topic}/{studyName || '...'}
</p>
</div>
{/* Error */}
{error && (
<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400 text-sm flex items-center gap-2">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{error}
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 p-4 border-t border-dark-700">
<button
onClick={onClose}
disabled={isBuilding}
className="px-4 py-2 text-sm text-dark-300 hover:text-white hover:bg-dark-700 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={handleBuild}
disabled={!isValid || isBuilding}
className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-primary-500 text-white rounded-lg hover:bg-primary-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isBuilding ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Building...
</>
) : (
<>
<Play className="w-4 h-4" />
Build Study
</>
)}
</button>
</div>
</div>
</div>
);
};
export default StudioBuildDialog;

View File

@@ -0,0 +1,375 @@
/**
* StudioChat - Context-aware AI chat for Studio
*
* Uses the existing useChat hook to communicate with Claude via WebSocket.
* Injects model files and context documents into the conversation.
*/
import React, { useRef, useEffect, useState, useMemo } from 'react';
import { Send, Loader2, Sparkles, FileText, Wifi, WifiOff, Bot, User, File, AlertCircle } from 'lucide-react';
import { useChat } from '../../hooks/useChat';
import { useSpecStore, useSpec } from '../../hooks/useSpecStore';
import { MarkdownRenderer } from '../MarkdownRenderer';
import { ToolCallCard } from '../chat/ToolCallCard';
interface StudioChatProps {
draftId: string;
contextFiles: string[];
contextContent: string;
modelFiles: string[];
onSpecUpdated: () => void;
}
export const StudioChat: React.FC<StudioChatProps> = ({
draftId,
contextFiles,
contextContent,
modelFiles,
onSpecUpdated,
}) => {
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const [input, setInput] = useState('');
const [hasInjectedContext, setHasInjectedContext] = useState(false);
// Get spec store for canvas updates
const spec = useSpec();
const { reloadSpec, setSpecFromWebSocket } = useSpecStore();
// Build canvas state with full context for Claude
const canvasState = useMemo(() => ({
nodes: [],
edges: [],
studyName: draftId,
studyPath: `_inbox/${draftId}`,
// Include file info for Claude context
modelFiles,
contextFiles,
contextContent: contextContent.substring(0, 50000), // Limit context size
}), [draftId, modelFiles, contextFiles, contextContent]);
// Use the chat hook with WebSocket
// Power mode gives Claude write permissions to modify the spec
const {
messages,
isThinking,
error,
isConnected,
sendMessage,
updateCanvasState,
} = useChat({
studyId: draftId,
mode: 'power', // Power mode = --dangerously-skip-permissions = can write files
useWebSocket: true,
canvasState,
onError: (err) => console.error('[StudioChat] Error:', err),
onSpecUpdated: (newSpec) => {
// Claude modified the spec - update the store directly
console.log('[StudioChat] Spec updated by Claude');
setSpecFromWebSocket(newSpec, draftId);
onSpecUpdated();
},
onCanvasModification: (modification) => {
// Claude wants to modify canvas - reload the spec
console.log('[StudioChat] Canvas modification:', modification);
reloadSpec();
onSpecUpdated();
},
});
// Update canvas state when context changes
useEffect(() => {
updateCanvasState(canvasState);
}, [canvasState, updateCanvasState]);
// Scroll to bottom when messages change
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
// Auto-focus input
useEffect(() => {
inputRef.current?.focus();
}, []);
// Build context summary for display
const contextSummary = useMemo(() => {
const parts: string[] = [];
if (modelFiles.length > 0) {
parts.push(`${modelFiles.length} model file${modelFiles.length > 1 ? 's' : ''}`);
}
if (contextFiles.length > 0) {
parts.push(`${contextFiles.length} context doc${contextFiles.length > 1 ? 's' : ''}`);
}
if (contextContent) {
parts.push(`${contextContent.length.toLocaleString()} chars context`);
}
return parts.join(', ');
}, [modelFiles, contextFiles, contextContent]);
const handleSend = () => {
if (!input.trim() || isThinking) return;
let messageToSend = input.trim();
// On first message, inject full context so Claude has everything it needs
if (!hasInjectedContext && (modelFiles.length > 0 || contextContent)) {
const contextParts: string[] = [];
// Add model files info
if (modelFiles.length > 0) {
contextParts.push(`**Model Files Uploaded:**\n${modelFiles.map(f => `- ${f}`).join('\n')}`);
}
// Add context document content (full text)
if (contextContent) {
contextParts.push(`**Context Documents Content:**\n\`\`\`\n${contextContent.substring(0, 30000)}\n\`\`\``);
}
// Add current spec state
if (spec) {
const dvCount = spec.design_variables?.length || 0;
const objCount = spec.objectives?.length || 0;
const extCount = spec.extractors?.length || 0;
if (dvCount > 0 || objCount > 0 || extCount > 0) {
contextParts.push(`**Current Configuration:** ${dvCount} design variables, ${objCount} objectives, ${extCount} extractors`);
}
}
if (contextParts.length > 0) {
messageToSend = `${contextParts.join('\n\n')}\n\n---\n\n**User Request:** ${messageToSend}`;
}
setHasInjectedContext(true);
}
sendMessage(messageToSend);
setInput('');
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
// Welcome message for empty state
const showWelcome = messages.length === 0;
// Check if we have any context
const hasContext = modelFiles.length > 0 || contextContent.length > 0;
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="p-3 border-b border-dark-700 flex-shrink-0">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Sparkles className="w-5 h-5 text-primary-400" />
<span className="font-medium text-white">Studio Assistant</span>
</div>
<span className={`flex items-center gap-1 text-xs px-2 py-0.5 rounded ${
isConnected
? 'text-green-400 bg-green-400/10'
: 'text-red-400 bg-red-400/10'
}`}>
{isConnected ? <Wifi className="w-3 h-3" /> : <WifiOff className="w-3 h-3" />}
{isConnected ? 'Connected' : 'Disconnected'}
</span>
</div>
{/* Context indicator */}
{contextSummary && (
<div className="flex items-center gap-2 text-xs">
<div className="flex items-center gap-1 text-amber-400 bg-amber-400/10 px-2 py-1 rounded">
<FileText className="w-3 h-3" />
<span>{contextSummary}</span>
</div>
{hasContext && !hasInjectedContext && (
<span className="text-dark-500">Will be sent with first message</span>
)}
{hasInjectedContext && (
<span className="text-green-500">Context sent</span>
)}
</div>
)}
</div>
{/* Messages */}
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{/* Welcome message with context awareness */}
{showWelcome && (
<div className="flex gap-3">
<div className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center bg-primary-500/20 text-primary-400">
<Bot className="w-4 h-4" />
</div>
<div className="flex-1 bg-dark-700 rounded-lg px-4 py-3 text-sm text-dark-100">
<MarkdownRenderer content={hasContext
? `I can see you've uploaded files. Here's what I have access to:
${modelFiles.length > 0 ? `**Model Files:** ${modelFiles.join(', ')}` : ''}
${contextContent ? `\n**Context Document:** ${contextContent.substring(0, 200)}...` : ''}
Tell me what you want to optimize and I'll help you configure the study!`
: `Welcome to Atomizer Studio! I'm here to help you configure your optimization study.
**What I can do:**
- Read your uploaded context documents
- Help set up design variables, objectives, and constraints
- Create extractors for physics outputs
- Suggest optimization strategies
Upload your model files and any requirements documents, then tell me what you want to optimize!`} />
</div>
</div>
)}
{/* File context display (only if we have files but no messages yet) */}
{showWelcome && modelFiles.length > 0 && (
<div className="bg-dark-800/50 rounded-lg p-3 border border-dark-700">
<p className="text-xs text-dark-400 mb-2 font-medium">Loaded Files:</p>
<div className="flex flex-wrap gap-2">
{modelFiles.map((file, idx) => (
<span key={idx} className="flex items-center gap-1 text-xs bg-blue-500/10 text-blue-400 px-2 py-1 rounded">
<File className="w-3 h-3" />
{file}
</span>
))}
{contextFiles.map((file, idx) => (
<span key={idx} className="flex items-center gap-1 text-xs bg-amber-500/10 text-amber-400 px-2 py-1 rounded">
<FileText className="w-3 h-3" />
{file}
</span>
))}
</div>
</div>
)}
{/* Chat messages */}
{messages.map((msg) => {
const isAssistant = msg.role === 'assistant';
const isSystem = msg.role === 'system';
// System messages
if (isSystem) {
return (
<div key={msg.id} className="flex justify-center my-2">
<div className="px-3 py-1 bg-dark-700/50 rounded-full text-xs text-dark-400 border border-dark-600">
{msg.content}
</div>
</div>
);
}
return (
<div
key={msg.id}
className={`flex gap-3 ${isAssistant ? '' : 'flex-row-reverse'}`}
>
{/* Avatar */}
<div
className={`flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center ${
isAssistant
? 'bg-primary-500/20 text-primary-400'
: 'bg-dark-600 text-dark-300'
}`}
>
{isAssistant ? <Bot className="w-4 h-4" /> : <User className="w-4 h-4" />}
</div>
{/* Message content */}
<div
className={`flex-1 max-w-[85%] rounded-lg px-4 py-3 text-sm ${
isAssistant
? 'bg-dark-700 text-dark-100'
: 'bg-primary-500 text-white ml-auto'
}`}
>
{isAssistant ? (
<>
{msg.content && <MarkdownRenderer content={msg.content} />}
{msg.isStreaming && !msg.content && (
<span className="text-dark-400">Thinking...</span>
)}
{/* Tool calls */}
{msg.toolCalls && msg.toolCalls.length > 0 && (
<div className="mt-3 space-y-2">
{msg.toolCalls.map((tool, idx) => (
<ToolCallCard key={idx} toolCall={tool} />
))}
</div>
)}
</>
) : (
<span className="whitespace-pre-wrap">{msg.content}</span>
)}
</div>
</div>
);
})}
{/* Thinking indicator */}
{isThinking && messages.length > 0 && !messages[messages.length - 1]?.isStreaming && (
<div className="flex gap-3">
<div className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center bg-primary-500/20 text-primary-400">
<Bot className="w-4 h-4" />
</div>
<div className="bg-dark-700 rounded-lg px-4 py-3 flex items-center gap-2">
<Loader2 className="w-4 h-4 text-primary-400 animate-spin" />
<span className="text-sm text-dark-300">Thinking...</span>
</div>
</div>
)}
{/* Error display */}
{error && (
<div className="flex gap-3">
<div className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center bg-red-500/20 text-red-400">
<AlertCircle className="w-4 h-4" />
</div>
<div className="flex-1 px-4 py-3 bg-red-500/10 rounded-lg text-sm text-red-400 border border-red-500/30">
{error}
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Input */}
<div className="p-3 border-t border-dark-700 flex-shrink-0">
<div className="flex gap-2">
<textarea
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={isConnected ? "Ask about your optimization..." : "Connecting..."}
disabled={!isConnected}
rows={1}
className="flex-1 bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-sm text-white placeholder-dark-400 resize-none focus:outline-none focus:border-primary-400 disabled:opacity-50"
/>
<button
onClick={handleSend}
disabled={!input.trim() || isThinking || !isConnected}
className="p-2 bg-primary-500 text-white rounded-lg hover:bg-primary-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isThinking ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className="w-5 h-5" />
)}
</button>
</div>
{!isConnected && (
<p className="text-xs text-dark-500 mt-1">
Waiting for connection to Claude...
</p>
)}
</div>
</div>
);
};
export default StudioChat;

View File

@@ -0,0 +1,117 @@
/**
* StudioContextFiles - Context document upload and display
*/
import React, { useState, useRef } from 'react';
import { FileText, Upload, Trash2, Loader2 } from 'lucide-react';
import { intakeApi } from '../../api/intake';
interface StudioContextFilesProps {
draftId: string;
files: string[];
onUploadComplete: () => void;
}
export const StudioContextFiles: React.FC<StudioContextFilesProps> = ({
draftId,
files,
onUploadComplete,
}) => {
const [isUploading, setIsUploading] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const VALID_EXTENSIONS = ['.md', '.txt', '.pdf', '.json', '.csv', '.docx'];
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = Array.from(e.target.files || []);
if (selectedFiles.length === 0) return;
e.target.value = '';
setIsUploading(true);
try {
await intakeApi.uploadContextFiles(draftId, selectedFiles);
onUploadComplete();
} catch (err) {
console.error('Failed to upload context files:', err);
} finally {
setIsUploading(false);
}
};
const deleteFile = async (filename: string) => {
setDeleting(filename);
try {
await intakeApi.deleteContextFile(draftId, filename);
onUploadComplete();
} catch (err) {
console.error('Failed to delete context file:', err);
} finally {
setDeleting(null);
}
};
const getFileIcon = (_filename: string) => {
return <FileText className="w-3.5 h-3.5 text-amber-400" />;
};
return (
<div className="space-y-2">
{/* File List */}
{files.length > 0 && (
<div className="space-y-1">
{files.map((name) => (
<div
key={name}
className="flex items-center gap-2 px-2 py-1.5 rounded bg-dark-700/50 text-sm group"
>
{getFileIcon(name)}
<span className="text-dark-200 truncate flex-1">{name}</span>
<button
onClick={() => deleteFile(name)}
disabled={deleting === name}
className="p-1 opacity-0 group-hover:opacity-100 hover:bg-red-500/20 rounded text-red-400 transition-all"
>
{deleting === name ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<Trash2 className="w-3 h-3" />
)}
</button>
</div>
))}
</div>
)}
{/* Upload Button */}
<button
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg
border border-dashed border-dark-600 text-dark-400 text-sm
hover:border-primary-400/50 hover:text-primary-400 hover:bg-primary-400/5
disabled:opacity-50 transition-colors"
>
{isUploading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
{isUploading ? 'Uploading...' : 'Add context files'}
</button>
<input
ref={fileInputRef}
type="file"
multiple
accept={VALID_EXTENSIONS.join(',')}
onChange={handleFileSelect}
className="hidden"
/>
</div>
);
};
export default StudioContextFiles;

View File

@@ -0,0 +1,242 @@
/**
* StudioDropZone - Smart file drop zone for Studio
*
* Handles both model files (.sim, .prt, .fem) and context files (.pdf, .md, .txt)
*/
import React, { useState, useCallback, useRef } from 'react';
import { Upload, X, Loader2, AlertCircle, CheckCircle, File } from 'lucide-react';
import { intakeApi } from '../../api/intake';
interface StudioDropZoneProps {
draftId: string;
type: 'model' | 'context';
files: string[];
onUploadComplete: () => void;
}
interface FileStatus {
file: File;
status: 'pending' | 'uploading' | 'success' | 'error';
message?: string;
}
const MODEL_EXTENSIONS = ['.prt', '.sim', '.fem', '.afem'];
const CONTEXT_EXTENSIONS = ['.md', '.txt', '.pdf', '.json', '.csv', '.docx'];
export const StudioDropZone: React.FC<StudioDropZoneProps> = ({
draftId,
type,
files,
onUploadComplete,
}) => {
const [isDragging, setIsDragging] = useState(false);
const [pendingFiles, setPendingFiles] = useState<FileStatus[]>([]);
const [isUploading, setIsUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const validExtensions = type === 'model' ? MODEL_EXTENSIONS : CONTEXT_EXTENSIONS;
const validateFile = (file: File): { valid: boolean; reason?: string } => {
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
if (!validExtensions.includes(ext)) {
return { valid: false, reason: `Invalid type: ${ext}` };
}
if (file.size > 500 * 1024 * 1024) {
return { valid: false, reason: 'File too large (max 500MB)' };
}
return { valid: true };
};
const handleDragEnter = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
}, []);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
}, []);
const addFiles = useCallback((newFiles: File[]) => {
const validFiles: FileStatus[] = [];
for (const file of newFiles) {
if (pendingFiles.some(f => f.file.name === file.name)) {
continue;
}
const validation = validateFile(file);
validFiles.push({
file,
status: validation.valid ? 'pending' : 'error',
message: validation.reason,
});
}
setPendingFiles(prev => [...prev, ...validFiles]);
}, [pendingFiles, validExtensions]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
addFiles(Array.from(e.dataTransfer.files));
}, [addFiles]);
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
addFiles(Array.from(e.target.files || []));
e.target.value = '';
}, [addFiles]);
const removeFile = (index: number) => {
setPendingFiles(prev => prev.filter((_, i) => i !== index));
};
const uploadFiles = async () => {
const toUpload = pendingFiles.filter(f => f.status === 'pending');
if (toUpload.length === 0) return;
setIsUploading(true);
try {
const uploadFn = type === 'model'
? intakeApi.uploadFiles
: intakeApi.uploadContextFiles;
const response = await uploadFn(draftId, toUpload.map(f => f.file));
const results = new Map(
response.uploaded_files.map(f => [f.name, f.status === 'uploaded'])
);
setPendingFiles(prev => prev.map(f => {
if (f.status !== 'pending') return f;
const success = results.get(f.file.name);
return {
...f,
status: success ? 'success' : 'error',
message: success ? undefined : 'Upload failed',
};
}));
setTimeout(() => {
setPendingFiles(prev => prev.filter(f => f.status !== 'success'));
onUploadComplete();
}, 1000);
} catch (err) {
setPendingFiles(prev => prev.map(f =>
f.status === 'pending'
? { ...f, status: 'error', message: 'Upload failed' }
: f
));
} finally {
setIsUploading(false);
}
};
// Auto-upload when files are added
React.useEffect(() => {
const pending = pendingFiles.filter(f => f.status === 'pending');
if (pending.length > 0 && !isUploading) {
uploadFiles();
}
}, [pendingFiles, isUploading]);
return (
<div className="space-y-2">
{/* Drop Zone */}
<div
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
onClick={() => fileInputRef.current?.click()}
className={`
relative border-2 border-dashed rounded-lg p-4 cursor-pointer
transition-all duration-200 text-center
${isDragging
? 'border-primary-400 bg-primary-400/5'
: 'border-dark-600 hover:border-primary-400/50 hover:bg-white/5'
}
`}
>
<div className={`w-8 h-8 rounded-full flex items-center justify-center mx-auto mb-2
${isDragging ? 'bg-primary-400/20 text-primary-400' : 'bg-dark-700 text-dark-400'}`}>
<Upload className="w-4 h-4" />
</div>
<p className="text-sm text-dark-300">
{isDragging ? 'Drop files here' : 'Drop or click to add'}
</p>
<p className="text-xs text-dark-500 mt-1">
{validExtensions.join(', ')}
</p>
</div>
{/* Existing Files */}
{files.length > 0 && (
<div className="space-y-1">
{files.map((name, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-1.5 rounded bg-dark-700/50 text-sm"
>
<File className="w-3.5 h-3.5 text-dark-400" />
<span className="text-dark-200 truncate flex-1">{name}</span>
<CheckCircle className="w-3.5 h-3.5 text-green-400" />
</div>
))}
</div>
)}
{/* Pending Files */}
{pendingFiles.length > 0 && (
<div className="space-y-1">
{pendingFiles.map((f, i) => (
<div
key={i}
className={`flex items-center gap-2 px-2 py-1.5 rounded text-sm
${f.status === 'error' ? 'bg-red-500/10' :
f.status === 'success' ? 'bg-green-500/10' : 'bg-dark-700'}`}
>
{f.status === 'pending' && <Loader2 className="w-3.5 h-3.5 text-primary-400 animate-spin" />}
{f.status === 'uploading' && <Loader2 className="w-3.5 h-3.5 text-primary-400 animate-spin" />}
{f.status === 'success' && <CheckCircle className="w-3.5 h-3.5 text-green-400" />}
{f.status === 'error' && <AlertCircle className="w-3.5 h-3.5 text-red-400" />}
<span className={`truncate flex-1 ${f.status === 'error' ? 'text-red-400' : 'text-dark-200'}`}>
{f.file.name}
</span>
{f.message && (
<span className="text-xs text-red-400">({f.message})</span>
)}
{f.status === 'pending' && (
<button onClick={(e) => { e.stopPropagation(); removeFile(i); }} className="p-0.5 hover:bg-white/10 rounded">
<X className="w-3 h-3 text-dark-400" />
</button>
)}
</div>
))}
</div>
)}
<input
ref={fileInputRef}
type="file"
multiple
accept={validExtensions.join(',')}
onChange={handleFileSelect}
className="hidden"
/>
</div>
);
};
export default StudioDropZone;

View File

@@ -0,0 +1,172 @@
/**
* StudioParameterList - Display and add discovered parameters as design variables
*/
import React, { useState, useEffect } from 'react';
import { Plus, Check, SlidersHorizontal, Loader2 } from 'lucide-react';
import { intakeApi } from '../../api/intake';
interface Expression {
name: string;
value: number | null;
units: string | null;
is_candidate: boolean;
confidence: number;
}
interface StudioParameterListProps {
draftId: string;
onParameterAdded: () => void;
}
export const StudioParameterList: React.FC<StudioParameterListProps> = ({
draftId,
onParameterAdded,
}) => {
const [expressions, setExpressions] = useState<Expression[]>([]);
const [addedParams, setAddedParams] = useState<Set<string>>(new Set());
const [adding, setAdding] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
// Load expressions from spec introspection
useEffect(() => {
loadExpressions();
}, [draftId]);
const loadExpressions = async () => {
setLoading(true);
try {
const data = await intakeApi.getStudioDraft(draftId);
const introspection = (data.spec as any)?.model?.introspection;
if (introspection?.expressions) {
setExpressions(introspection.expressions);
// Check which are already added as DVs
const existingDVs = new Set<string>(
((data.spec as any)?.design_variables || []).map((dv: any) => dv.expression_name as string)
);
setAddedParams(existingDVs);
}
} catch (err) {
console.error('Failed to load expressions:', err);
} finally {
setLoading(false);
}
};
const addAsDesignVariable = async (expressionName: string) => {
setAdding(expressionName);
try {
await intakeApi.createDesignVariables(draftId, [expressionName]);
setAddedParams(prev => new Set([...prev, expressionName]));
onParameterAdded();
} catch (err) {
console.error('Failed to add design variable:', err);
} finally {
setAdding(null);
}
};
// Sort: candidates first, then by confidence
const sortedExpressions = [...expressions].sort((a, b) => {
if (a.is_candidate !== b.is_candidate) {
return b.is_candidate ? 1 : -1;
}
return (b.confidence || 0) - (a.confidence || 0);
});
// Show only candidates by default, with option to show all
const [showAll, setShowAll] = useState(false);
const displayExpressions = showAll
? sortedExpressions
: sortedExpressions.filter(e => e.is_candidate);
if (loading) {
return (
<div className="flex items-center justify-center py-4">
<Loader2 className="w-5 h-5 text-primary-400 animate-spin" />
</div>
);
}
if (expressions.length === 0) {
return (
<p className="text-xs text-dark-500 italic py-2">
No expressions found. Try running introspection.
</p>
);
}
const candidateCount = expressions.filter(e => e.is_candidate).length;
return (
<div className="space-y-2">
{/* Header with toggle */}
<div className="flex items-center justify-between text-xs text-dark-400">
<span>{candidateCount} candidates</span>
<button
onClick={() => setShowAll(!showAll)}
className="hover:text-primary-400 transition-colors"
>
{showAll ? 'Show candidates only' : `Show all (${expressions.length})`}
</button>
</div>
{/* Parameter List */}
<div className="space-y-1 max-h-48 overflow-y-auto">
{displayExpressions.map((expr) => {
const isAdded = addedParams.has(expr.name);
const isAdding = adding === expr.name;
return (
<div
key={expr.name}
className={`flex items-center gap-2 px-2 py-1.5 rounded text-sm
${isAdded ? 'bg-green-500/10' : 'bg-dark-700/50 hover:bg-dark-700'}
transition-colors`}
>
<SlidersHorizontal className="w-3.5 h-3.5 text-dark-400 flex-shrink-0" />
<div className="flex-1 min-w-0">
<span className={`block truncate ${isAdded ? 'text-green-400' : 'text-dark-200'}`}>
{expr.name}
</span>
{expr.value !== null && (
<span className="text-xs text-dark-500">
= {expr.value}{expr.units ? ` ${expr.units}` : ''}
</span>
)}
</div>
{isAdded ? (
<Check className="w-4 h-4 text-green-400 flex-shrink-0" />
) : (
<button
onClick={() => addAsDesignVariable(expr.name)}
disabled={isAdding}
className="p-1 hover:bg-primary-400/20 rounded text-primary-400 transition-colors disabled:opacity-50"
title="Add as design variable"
>
{isAdding ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<Plus className="w-3.5 h-3.5" />
)}
</button>
)}
</div>
);
})}
</div>
{displayExpressions.length === 0 && (
<p className="text-xs text-dark-500 italic py-2">
No candidate parameters found. Click "Show all" to see all expressions.
</p>
)}
</div>
);
};
export default StudioParameterList;

View File

@@ -0,0 +1,11 @@
/**
* Studio Components Index
*
* Export all Studio-related components.
*/
export { StudioDropZone } from './StudioDropZone';
export { StudioParameterList } from './StudioParameterList';
export { StudioContextFiles } from './StudioContextFiles';
export { StudioChat } from './StudioChat';
export { StudioBuildDialog } from './StudioBuildDialog';