Skip to content

Latest commit

Β 

History

History
440 lines (374 loc) Β· 14.4 KB

File metadata and controls

440 lines (374 loc) Β· 14.4 KB

MorphUI Architecture

System Overview

MorphUI is a full-stack adaptive UI application that uses AI to dynamically transform its interface based on user behavior and mood.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     User Interaction Layer                   β”‚
β”‚                   (Clicks, Scrolls, Navigation)              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   React Frontend (Port 5173)                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Components:                                                  β”‚
β”‚  β€’ Dashboard - Main UI container                             β”‚
β”‚  β€’ FeatureCard - Individual feature modules                  β”‚
β”‚  β€’ AdaptationIndicator - Loading state                       β”‚
β”‚  β€’ DemoControls - Manual controls                            β”‚
β”‚                                                               β”‚
β”‚  State Management (Zustand):                                 β”‚
β”‚  β€’ Current theme, layout, features                           β”‚
β”‚  β€’ Mood analysis results                                     β”‚
β”‚  β€’ Adaptation state                                          β”‚
β”‚                                                               β”‚
β”‚  Theme Engine:                                               β”‚
β”‚  β€’ 5 themes (minimal-dark, minimal-light, vibrant,          β”‚
β”‚    gamified, productivity)                                   β”‚
β”‚  β€’ 3 spacing modes (compact, normal, spacious)              β”‚
β”‚  β€’ 3 animation levels (minimal, normal, playful)            β”‚
β”‚                                                               β”‚
β”‚  Behavior Tracking:                                          β”‚
β”‚  β€’ Click tracking with coordinates                           β”‚
β”‚  β€’ Scroll depth monitoring                                   β”‚
β”‚  β€’ Navigation pattern detection                              β”‚
β”‚  β€’ Feature usage analytics                                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚ REST API / WebSocket (Future)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 Node.js Backend (Port 3000)                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  API Routes:                                                  β”‚
β”‚  β€’ /api/analytics - Behavior tracking endpoints             β”‚
β”‚  β€’ /api/adaptation - UI adaptation endpoints                β”‚
β”‚                                                               β”‚
β”‚  Services:                                                    β”‚
β”‚  β€’ BehaviorAnalyzer - Session management & metrics          β”‚
β”‚  β€’ OllamaService - Local AI-powered analysis                β”‚
β”‚                                                               β”‚
β”‚  Behavior Analysis:                                          β”‚
β”‚  β€’ Click frequency calculation                               β”‚
β”‚  β€’ Error rate detection                                      β”‚
β”‚  β€’ Dwell time analysis                                       β”‚
β”‚  β€’ Navigation pattern recognition                            β”‚
β”‚  β€’ Feature engagement scoring                                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚ Local HTTP (localhost:11434)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Ollama Local AI                           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Capabilities:                                                β”‚
β”‚  β€’ Mood inference from behavioral metrics                    β”‚
β”‚  β€’ UI adaptation recommendations                             β”‚
β”‚  β€’ Reasoning explanation generation                          β”‚
β”‚  β€’ πŸ”’ Privacy-first: All processing on your machine         β”‚
β”‚                                                               β”‚
β”‚  Models Supported:                                           β”‚
β”‚  β€’ gemma3:270m (Default - ultra-compact, very fast)         β”‚
β”‚  β€’ gemma2:2b (Lightweight)                                  β”‚
β”‚  β€’ gemma2:9b (More accurate)                                β”‚
β”‚  β€’ llama3.2:3b (Alternative)                                β”‚
β”‚  β€’ phi3:mini (Compact)                                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Flow

1. User Interaction β†’ Tracking

User clicks button
  ↓
BehaviorTracking Hook captures event
  ↓
POST /api/analytics/interaction {
  sessionId: "session-123",
  interaction: {
    type: "click",
    target: "dashboard",
    coordinates: { x: 100, y: 200 },
    timestamp: 1234567890
  }
}
  ↓
Backend stores in session memory

2. Behavior Analysis β†’ Metrics

Frontend requests metrics
  ↓
GET /api/analytics/metrics/session-123
  ↓
Backend calculates:
  - avgClickFrequency: 8.5 clicks/min
  - errorRate: 0.05
  - avgDwellTime: 5.2 seconds
  - navigationPattern: "exploratory"
  ↓
Returns BehaviorMetrics object

3. AI Analysis β†’ Adaptation

Adaptation cycle triggered (every 30s or manual)
  ↓
POST /api/adaptation/recommend {
  sessionId: "session-123",
  currentState: {
    theme: "minimal-light",
    layout: "grid",
    features: [...]
  }
}
  ↓
Backend:
  1. Gets behavior metrics
  2. Calls Gemini AI for mood analysis
  3. Calls Gemini AI for UI recommendations
  ↓
Gemini analyzes:
  Mood: "relaxed" (confidence: 0.85)
  Recommendation: {
    theme: "vibrant",
    layout: "cards",
    features: [...],
    reasoning: "User is exploring comfortably"
  }
  ↓
Frontend applies adaptation
  ↓
UI morphs with smooth transitions

Component Architecture

Frontend Components

App.tsx (Root)
β”œβ”€β”€ ThemeProvider (styled-components)
β”‚   β”œβ”€β”€ GlobalStyles
β”‚   β”œβ”€β”€ Dashboard
β”‚   β”‚   β”œβ”€β”€ Header
β”‚   β”‚   β”œβ”€β”€ MoodBadge
β”‚   β”‚   β”œβ”€β”€ AdaptationInfo
β”‚   β”‚   └── FeaturesGrid
β”‚   β”‚       └── FeatureCard (x15)
β”‚   β”œβ”€β”€ AdaptationIndicator (Fixed position)
β”‚   └── DemoControls (Fixed position)
β”‚       β”œβ”€β”€ ToggleButton
β”‚       └── Panel
β”‚           β”œβ”€β”€ Mode Selection
β”‚           └── Action Buttons

Backend Services

index.ts (Express Server)
β”œβ”€β”€ Routes
β”‚   β”œβ”€β”€ /api/analytics
β”‚   β”‚   β”œβ”€β”€ POST /session
β”‚   β”‚   β”œβ”€β”€ POST /interaction
β”‚   β”‚   β”œβ”€β”€ POST /pageview
β”‚   β”‚   β”œβ”€β”€ GET /metrics/:sessionId
β”‚   β”‚   └── GET /session/:sessionId
β”‚   └── /api/adaptation
β”‚       β”œβ”€β”€ POST /recommend
β”‚       β”œβ”€β”€ POST /mood
β”‚       └── POST /feedback
└── Services
    β”œβ”€β”€ BehaviorAnalyzer
    β”‚   β”œβ”€β”€ Session Management
    β”‚   β”œβ”€β”€ Interaction Tracking
    β”‚   β”œβ”€β”€ Metrics Calculation
    β”‚   └── Cleanup Timer
    └── OllamaService
        β”œβ”€β”€ Mood Analysis
        β”œβ”€β”€ UI Adaptation
        └── Fallback Logic

State Management (Zustand)

AppStore {
  // UI Configuration
  theme: ThemeType
  layout: LayoutType
  visibleFeatures: string[]
  animations: 'minimal' | 'normal' | 'playful'
  spacing: 'compact' | 'normal' | 'spacious'
  complexity: 'simple' | 'moderate' | 'advanced'
  
  // AI State
  currentMood: MoodAnalysis | null
  adaptationReasoning: string
  isAdapting: boolean
  
  // Demo
  demoMode: 'auto' | 'stress' | 'focus' | 'explorer' | 'relax' | null
  
  // Actions
  applyAdaptation(adaptation, mood)
  setDemoMode(mode)
  setIsAdapting(isAdapting)
  resetToDefault()
}

Session Management

Session Lifecycle

  1. Creation: User visits β†’ sessionId generated β†’ Stored in sessionStorage
  2. Tracking: All interactions associated with sessionId
  3. Analysis: Metrics calculated on-demand from session data
  4. Expiration: Sessions auto-expire after 30 minutes of inactivity
  5. Cleanup: Expired sessions removed every 10 minutes

Session Data Structure

{
  sessionId: "session-1234567890-abc123",
  userId: "user-456" (optional),
  startTime: 1234567890000,
  lastActivity: 1234567890000,
  interactions: [
    { type: "click", timestamp: ..., target: "dashboard" },
    { type: "scroll", timestamp: ..., metadata: {...} }
  ],
  pageViews: ["/", "/analytics", "/settings"],
  featureUsage: {
    "dashboard": 12,
    "analytics": 5,
    "settings": 2
  }
}

AI Integration

Gemini Prompts

Mood Analysis Prompt

Analyze the following user behavior metrics and determine their current mood state.

Metrics:
- Average click frequency: 8.5 clicks/minute
- Error rate: 5.0%
- Average dwell time: 5.2 seconds
- Navigation pattern: exploratory
- Interaction speed: normal
- Scroll depth: 70%

Determine the user's mood from: stressed, focused, relaxed, exploratory, frustrated

Respond ONLY with a JSON object: {...}

UI Adaptation Prompt

Generate an optimal UI adaptation based on user behavior and mood.

Current UI State:
- Theme: minimal-light
- Layout: grid
- Visible Features: dashboard, analytics, calendar, tasks, settings

User Mood: relaxed (confidence: 0.85)

Behavior Metrics: {...}

Respond ONLY with a JSON object: {...}

Fallback Logic

If Gemini API fails:

  1. Rule-based mood detection:

    • High error rate + rapid clicks β†’ stressed
    • Low click frequency + long dwell time β†’ relaxed
    • Exploratory navigation + deep scrolling β†’ exploratory
  2. Predefined adaptations:

    • Each mood has a default UI configuration
    • Guaranteed consistent user experience

Theme System

Theme Structure

Theme {
  name: string
  colors: {
    primary, secondary, background, surface,
    text, textSecondary, border,
    success, warning, error, accent
  }
  spacing: { xs, sm, md, lg, xl }
  borderRadius: string
  shadows: { sm, md, lg }
  transitions: { fast, normal, slow }
}

Dynamic Theme Generation

getTheme(themeName, spacing, animations) β†’ Theme

// Example: Generate "vibrant" theme with "spacious" spacing and "playful" animations
getTheme('vibrant', 'spacious', 'playful') β†’ {
  name: 'Vibrant',
  colors: { ... }, // Vibrant color palette
  spacing: { xs: '12px', sm: '24px', ... }, // Spacious
  transitions: {
    fast: 'all 0.2s cubic-bezier(...)', // Playful
    normal: 'all 0.4s cubic-bezier(...)',
    slow: 'all 0.6s cubic-bezier(...)'
  }
}

Performance Considerations

Frontend

  • Debounced tracking: Scroll/hover events debounced to 300ms
  • Interaction limit: Only last 100 interactions stored per session
  • Animation optimization: Framer Motion for GPU-accelerated animations
  • Code splitting: Dynamic imports for large components (future)

Backend

  • In-memory sessions: Fast access, auto-cleanup
  • Rate limiting: 100 requests per 15 minutes per IP
  • Gemini API: Cached responses for identical queries (future)
  • Metrics calculation: On-demand, not stored

Security

API Security

  • CORS: Configured for specific frontend URL
  • Helmet: Security headers enabled
  • Rate Limiting: Prevents abuse
  • Input Validation: All endpoints validate inputs
  • No sensitive data: No passwords or PII stored

Environment Variables

  • API keys: Never committed to git
  • Separate configs: Dev vs. production keys
  • Secure transmission: HTTPS in production

Scalability

Current Limitations

  • In-memory sessions: Won't scale across multiple servers
  • No persistence: Sessions lost on server restart
  • Single server: Not load-balanced

Future Improvements

  • Redis: Distributed session storage
  • PostgreSQL: User profiles, adaptation history
  • Load balancing: Multiple backend instances
  • WebSocket: Real-time bidirectional communication
  • CDN: Static asset delivery

Testing Strategy

Unit Tests

  • Service logic (BehaviorAnalyzer, GeminiService)
  • Utility functions
  • State management

Integration Tests

  • API endpoints
  • Service interactions
  • Database operations (future)

E2E Tests

  • User flows
  • Adaptation cycles
  • Cross-browser compatibility

Performance Tests

  • Load testing (k6, Artillery)
  • Memory profiling
  • API response times

Deployment

Frontend (Vercel/Netlify)

cd packages/frontend
npm run build
# Deploy dist/ folder

Backend (Railway/Render/Heroku)

cd packages/backend
npm run build
# Deploy with Procfile or railway.json

Environment Setup

# Frontend
VITE_API_URL=https://api.morphui.com/api

# Backend
GEMINI_API_KEY=your_key_here
NODE_ENV=production
FRONTEND_URL=https://morphui.com

This architecture enables MorphUI to: βœ… Track user behavior in real-time
βœ… Analyze mood using AI
βœ… Adapt UI dynamically
βœ… Provide smooth, delightful transitions
βœ… Scale to production workloads