You are an AI assistant tasked with generating a fully functional, multi-page Next.js MVP application based on the concept of training AI models on retro hardware simulations. The application, 'Retro AI Trainer', aims to provide a unique platform for users to understand the foundational principles of AI by simulating training processes on historical minicomputers.
PROJECT OVERVIEW:
The 'Retro AI Trainer' is a SaaS platform that bridges the gap between historical computing and modern AI. It allows users to train simplified AI models, specifically focusing on Transformer architectures, within simulated environments of 1970s minicomputers using assembly language. The core value proposition is to offer an educational and experimental tool that demystifies AI training by illustrating the process on resource-constrained systems, highlighting the ingenuity required and the fundamental building blocks of modern AI. The application will simulate the training of a basic Transformer model (single-layer, single-head) to perform tasks like digit sequence reversal on a PDP-11-like environment. Users will be able to visualize the training progress, compare different parameters, and understand the computational challenges of early AI.
TECH STACK:
- **Framework**: Next.js (App Router)
- **Language**: TypeScript
- **Styling**: Tailwind CSS
- **ORM**: Drizzle ORM with PostgreSQL (or SQLite for simpler MVP setup)
- **UI Components**: shadcn/ui
- **State Management**: React Context API / Zustand (for global state)
- **Authentication**: NextAuth.js (for user management)
- **Simulation Engine**: A custom-built simulation layer in Node.js/TypeScript to mimic the PDP-11 environment and assembly execution. (Note: This is the most complex part and might initially use simplified logic or a pre-compiled assembly executor).
- **Charting**: Chart.js or similar for visualizing training metrics.
- **Database**: PostgreSQL (preferred) or SQLite.
DATABASE SCHEMA:
1. **users** Table:
* `id` (UUID, Primary Key)
* `name` (String)
* `email` (String, Unique)
* `emailVerified` (Timestamp, Nullable)
* `image` (String, Nullable)
* `createdAt` (Timestamp)
* `updatedAt` (Timestamp)
2. **accounts** Table (for NextAuth.js):
* `id` (BigInt, Primary Key)
* `userId` (UUID, Foreign Key to users.id)
* `type` (String)
* `provider` (String)
* `providerAccountId` (String)
* `refresh_token` (Text, Nullable)
* `access_token` (Text, Nullable)
* `expires_at` (BigInt, Nullable)
* `token_type` (String, Nullable)
* `scope` (String, Nullable)
* `id_token` (Text, Nullable)
* `session_state` (String, Nullable)
3. **sessions** Table (for NextAuth.js):
* `id` (BigInt, Primary Key)
* `sessionToken` (String, Unique)
* `userId` (UUID, Foreign Key to users.id)
* `expires` (Timestamp)
4. **verificationTokens** Table (for NextAuth.js):
* `identifier` (String)
* `token` (String)
* `expires` (Timestamp)
5. **simulations** Table:
* `id` (UUID, Primary Key)
* `userId` (UUID, Foreign Key to users.id)
* `modelType` (String, e.g., 'Transformer-v1')
* `task` (String, e.g., 'SequenceReversal')
* `parameters` (JSON, e.g., {'heads': 1, 'layers': 1, 'embeddingSize': 64, 'epochs': 50})
* `status` (String, e.g., 'Pending', 'Running', 'Completed', 'Failed')
* `simulationLog` (Text, Nullable)
* `createdAt` (Timestamp)
* `updatedAt` (Timestamp)
6. **trainingMetrics** Table:
* `id` (UUID, Primary Key)
* `simulationId` (UUID, Foreign Key to simulations.id)
* `epoch` (Integer)
* `loss` (Float)
* `accuracy` (Float, Nullable)
* `timestamp` (Timestamp)
CORE FEATURES & USER FLOW:
1. **User Authentication**:
* **Flow**: User lands on the homepage. Clicks 'Sign Up' or 'Log In'. Redirected to Auth page (using NextAuth.js). Options: Email/Password, Google OAuth.
* **Details**: Securely handles user registration and login. Upon successful login, redirects to the Dashboard.
* **Edge Case**: Incorrect credentials, OAuth errors, email verification flow.
2. **Dashboard**:
* **Flow**: After login, user sees their dashboard. Displays a list of past simulations, their status, and key metrics summary. A prominent button 'Start New Simulation' is visible.
* **Details**: Provides an overview of user activity. Links to view/manage individual simulations.
* **Edge Case**: No previous simulations found (empty state).
3. **New Simulation Setup**:
* **Flow**: User clicks 'Start New Simulation' on the Dashboard. Presented with a form to configure the simulation:
* Select Model Architecture (MVP: 'Transformer-v1')
* Select Task (MVP: 'Sequence Reversal')
* Configure Parameters: Number of epochs, embedding size, learning rate (simplified for MVP).
* (Future: Dataset selection)
* **Details**: User inputs are validated. Upon submission, a new entry is created in the `simulations` table with 'Pending' status.
* **Edge Case**: Invalid parameter inputs, missing selections.
4. **Simulation Execution & Monitoring**:
* **Flow**: The backend picks up 'Pending' simulations. The simulation engine starts processing. User can navigate to the 'Simulation Details' page for the running simulation.
* **Details**: The 'Simulation Details' page shows real-time progress: current epoch, simulated time, loss/accuracy (fetched periodically via API). A visualizer (e.g., Chart.js) displays the training curve.
* **Backend**: The simulation engine executes the assembly code (or its logic) step-by-step, calculates metrics, and stores them in `trainingMetrics`. Updates `simulations.status`.
* **Edge Cases**: Simulation errors (backend logs to `simulationLog`), timeouts, resource limits reached.
5. **Simulation Results & Analysis**:
* **Flow**: Once a simulation completes ('Completed' status), the 'Simulation Details' page displays the final metrics, performance graphs, and potentially a summary log.
* **Details**: Users can review the effectiveness of their chosen parameters. Option to 'Save' or 'Share' (future) simulation results.
* **Edge Case**: Failed simulation, incomplete data.
API & DATA FETCHING (using Next.js App Router conventions):
- **Authentication API**: Handled by NextAuth.js (`/auth/[...nextauth]/route.ts`).
- **Simulation API Routes**: (e.g., `app/api/simulations/route.ts`, `app/api/simulations/[id]/route.ts`)
- `POST /api/simulations`: Create a new simulation. Request body: `{ modelType, task, parameters }`. Response: `{ simulationId }`.
- `GET /api/simulations`: Get list of user's simulations. Response: `[{ id, modelType, task, status, createdAt }]`.
- `GET /api/simulations/[id]`: Get details of a specific simulation. Response: `{ ...simulationDetails, metrics: [...] }`.
- `PUT /api/simulations/[id]/cancel`: (Optional) Allow users to cancel running simulations.
- **Data Fetching in Components**: Utilize Server Components for initial data loading (e.g., Dashboard, Simulation List) and Client Components with `fetch` or libraries like SWR/React Query for real-time updates (e.g., simulation monitoring) or form submissions.
- **Real-time Updates**: For monitoring, implement polling or Server-Sent Events (SSE) to fetch metrics updates.
COMPONENT BREAKDOWN (Next.js App Router):
- **`app/layout.tsx`**: Root layout (HTML, Head, Body, global providers, Tailwind CSS setup).
- **`app/page.tsx`**: Landing Page (Introduction, Features, Call to Action).
- **`app/(auth)/login/page.tsx`**: Login Page.
- **`app/(auth)/signup/page.tsx`**: Sign Up Page.
- **`app/dashboard/page.tsx`**: (Protected Route) User Dashboard. Lists past simulations. Fetches data using Server Component. Contains 'Start New Simulation' button.
- **`app/dashboard/loading.tsx`**: Loading UI for Dashboard.
- **`app/dashboard/error.tsx`**: Error UI for Dashboard.
- **`app/simulations/new/page.tsx`**: (Protected Route) Form page for creating a new simulation. Includes configuration options.
- **`app/simulations/[id]/page.tsx`**: (Protected Route) Simulation Detail Page. Displays status, real-time metrics (using Client Component and polling/SSE), charts, logs, and final results.
- **`app/simulations/[id]/loading.tsx`**: Loading UI for Simulation Detail.
- **`app/components/ui/`**: Reusable UI components from shadcn/ui (Button, Card, Input, Label, Select, Progress, Alert, etc.).
- **`app/components/dashboard/`**: Dashboard-specific components (e.g., `SimulationList`, `SimulationListItem`).
- **`app/components/simulation/`**: Simulation-specific components (e.g., `ParameterForm`, `MetricsChart`, `StatusDisplay`).
- **`app/components/layout/`**: Layout components (e.g., `Navbar`, `Footer`, `Sidebar` if needed).
- **`lib/`**: Utility functions, database connection (Drizzle ORM setup), simulation engine logic, auth helpers.
- **`app/api/simulations/route.ts`**: API route for simulation CRUD operations.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style**: "Retro-Futuristic Minimalist". Combines the clean, functional aesthetic of modern minimalist design with subtle nods to 70s/80s computing aesthetics (e.g., monospace fonts, limited color palettes, functional layouts).
- **Color Palette**: Primary: Dark Charcoal (`#1E1E1E`). Secondary: Muted Teal (`#4FD1C5`). Accent: Vintage Orange (`#F56565`). Tertiary: Light Grey (`#A0AEC0`). White/Off-white (`#FFFFFF`) for text.
- **Typography**: Main: Inter (`sans-serif`). Code/Monospace display: 'Fira Code' or 'Source Code Pro' (`monospace`).
- **Layout**: Clean, card-based layouts for dashboards and lists. Full-width visualizations. Responsive design using Tailwind CSS's mobile-first approach.
- **Micro-interactions**: Subtle hover effects on buttons and cards. Smooth transitions between pages and states. Loading spinners/skeletons.
- **Responsive Rules**: Mobile-first. Utilize Tailwind's `sm:`, `md:`, `lg:` prefixes for breakpoint-specific styling. Ensure readability and usability across all screen sizes.
SAMPLE/MOCK DATA:
1. **User (John Doe)**:
`{ id: '...', name: 'John Doe', email: 'john.doe@example.com', image: 'url_to_avatar.jpg' }`
2. **Simulation (Running)**:
`{ id: 'sim_123', userId: '...', modelType: 'Transformer-v1', task: 'SequenceReversal', status: 'Running', createdAt: '2023-10-27T10:00:00Z', epochs: 25, totalEpochs: 50 }`
3. **Simulation (Completed)**:
`{ id: 'sim_456', userId: '...', modelType: 'Transformer-v1', task: 'SequenceReversal', status: 'Completed', createdAt: '2023-10-27T09:00:00Z', epochs: 50, totalEpochs: 50 }`
4. **Training Metrics (for sim_456)**:
`[{ epoch: 1, loss: 1.5, accuracy: 0.1, timestamp: '...' }, { epoch: 2, loss: 1.3, accuracy: 0.15, timestamp: '...' }, ..., { epoch: 50, loss: 0.05, accuracy: 0.98, timestamp: '...' }]`
5. **Simulation (Pending)**:
`{ id: 'sim_789', userId: '...', modelType: 'Transformer-v1', task: 'SequenceReversal', status: 'Pending', createdAt: '2023-10-27T11:00:00Z' }`
6. **Simulation Setup Parameters (Example JSON)**:
`{ modelType: 'Transformer-v1', task: 'SequenceReversal', parameters: { epochs: 100, embeddingSize: 64, learningRate: 0.001 } }`
7. **Empty Dashboard State**:
`[]` (representing no simulations found).
ANIMATIONS:
- **Page Transitions**: Use Next.js's built-in support or libraries like `Framer Motion` for smooth fade/slide transitions between pages.
- **Hover Effects**: Subtle scale-up or background color changes on interactive elements (buttons, cards, links).
- **Loading States**: Skeleton loaders for content areas, spinners for data fetching or simulation processes.
- **Chart Animations**: Animate chart drawing and updates for a more dynamic feel.
- **State Changes**: Fade-in/out or slide effects when data updates or statuses change.
EDGE CASES:
- **Authentication**: Handle expired sessions, invalid tokens, OAuth provider errors gracefully. Implement password reset flow.
- **Empty States**: Display informative messages and clear calls to action when lists are empty (e.g., Dashboard with no simulations).
- **Simulation Failures**: Catch backend errors during simulation. Log detailed error messages in `simulations.simulationLog`. Display a user-friendly error message on the UI, possibly with a link to the detailed log.
- **Validation**: Implement robust frontend and backend validation for all user inputs, especially simulation parameters.
- **Resource Limits**: If simulating on a shared backend, implement limits on simulation time or complexity per user tier to prevent abuse.
- **Network Errors**: Handle API request failures gracefully, showing appropriate messages to the user.
TURKISH TRANSLATIONS (Key UI Elements):
- Sign Up: Kayıt Ol
- Log In: Giriş Yap
- Dashboard: Kontrol Paneli
- Start New Simulation: Yeni Simülasyon Başlat
- Simulation Settings: Simülasyon Ayarları
- Model: Model
- Task: Görev
- Parameters: Parametreler
- Epochs: Epok Sayısı
- Run Simulation: Simülasyonu Çalıştır
- Simulation Status: Simülasyon Durumu
- Running: Çalışıyor
- Completed: Tamamlandı
- Failed: Hata Oluştu
- Pending: Bekliyor
- Training Loss: Eğitim Kaybı
- Accuracy: Doğruluk
- Epoch: Epok
- View Details: Detayları Gör
- Simulation Results: Simülasyon Sonuçları
- Configuration: Yapılandırma
- History: Geçmiş
- Settings: Ayarlar
- Welcome: Hoş Geldiniz
- Your Simulations: Simülasyonlarınız
- No simulations yet: Henüz simülasyonunuz yok.
- Create one now: Hemen bir tane oluşturun.