Skip to content

Latest commit

 

History

History
499 lines (413 loc) · 12.8 KB

File metadata and controls

499 lines (413 loc) · 12.8 KB

Vibe Platform API Overview

🎯 Platform Purpose

Vibe Platform is a dynamic container management system that enables on-demand creation and management of isolated React application environments. Each container provides a fully functional development environment with file management, real-time updates, and isolated execution.

🏗️ System Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Frontend UI   │────│   Orchestrator  │────│   Docker Engine │
│   (Port 3000)   │    │   (Port 4000)   │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │                       │                       │
    ┌─────────┐           ┌─────────┐           ┌─────────┐
    │ Traefik │           │ Network │           │ Storage │
    │ (Port 80)│           │Network  │           │Volumes │
    └─────────┘           └─────────┘           └─────────┘

Core Components

  1. Orchestrator - Central API managing container lifecycle
  2. React Base Image - Pre-configured Vite + React + TypeScript environment
  3. Traefik - Reverse proxy for routing and load balancing
  4. Docker Network - Isolated communication between services

🚀 Key Features

Container Management

  • Dynamic Creation: Instantly provision isolated React development environments
  • Resource Allocation: Configurable memory and CPU limits per container
  • Health Monitoring: Real-time health checks with automatic recovery
  • Lifecycle Control: Start, stop, and remove containers on demand

File Management

  • Live Sync: Real-time file updates without container restart
  • Flexible File Access: Backend accepts any file operations
  • Frontend Restrictions: AI access limitations enforced on frontend side
  • Auto-Generated System Files: All configuration files automatically copied from React base template
  • File Operations: Create, read, update files via REST API
  • Automated Configuration: ES module compatibility and dependency management

Development Environment

  • Vite Build System: Fast development server with HMR
  • TypeScript Support: Full TypeScript configuration
  • Tailwind CSS: Utility-first CSS framework
  • ESLint Ready: Code quality and linting tools

📡 API Reference

Base URL: http://localhost:4000

🏥 Health & Monitoring

Get System Health

GET /health

Response:

{
  "status": "ok",
  "uptime": 3600,
  "memory": {
    "rss": "64MB",
    "heapUsed": "32MB", 
    "heapTotal": "48MB"
  },
  "docker": {
    "version": "24.0.0",
    "containers": 5,
    "containersRunning": 3
  },
  "vibeContainers": {
    "total": 3,
    "healthy": 2,
    "unhealthy": 1
  }
}

📦 Container Management

List All Containers

GET /containers

Response:

[
  {
    "id": "vibe-project-12345678",
    "image": "vibe-react-base:latest",
    "state": "running",
    "port": 3001
  }
]

Create New Container

POST /containers
Content-Type: application/json

Request Body (Frontend-Validated):

{
  "projectId": "my-project",
  "files": {
    "src/App.tsx": "export default function App() { return <div>Hello World</div>; }",
    "src/components/Button.tsx": "export const Button = () => <button>Click me</button>;",
    "package.json": "{ \"name\": \"my-app\", \"dependencies\": { \"react\": \"^18.0.0\", \"axios\": \"^1.0.0\" } }"
  }
}

Response:

{
  "projectId": "my-project",
  "containerId": "vibe-my-project-abc12345",
  "port": 3001,
  "url": "http://localhost:3001",
  "status": "running",
  "createdAt": "2024-01-15T10:30:00.000Z",
  "systemFiles": ["vite.config.ts", "tsconfig.json", "tailwind.config.cjs", "postcss.config.cjs", "eslint.config.js", "index.html"]
}

Delete Container

DELETE /containers/:containerId

Response:

{
  "success": true,
  "message": "Container vibe-my-project-abc12345 removed"
}

Stop Container

POST /containers/:containerId/stop

Start Container

POST /containers/:containerId/start

📁 File Management

List Files in Container

GET /containers/:containerId/files

Response:

{
  "containerId": "vibe-my-project-abc12345",
  "fileCount": 12,
  "files": [
    "src/App.tsx",
    "src/main.tsx",
    "package.json",
    "vite.config.ts",
    "tailwind.config.cjs"
  ]
}

Get File Content

GET /containers/:containerId/file/:filePath

Response:

{
  "filepath": "src/App.tsx",
  "content": "export default function App() {\n  return <div>Hello World</div>;\n}"
}

Update Files

PUT /containers/:containerId/files
Content-Type: application/json

Request Body (Frontend-Validated):

{
  "files": {
    "src/App.tsx": "export default function App() { return <div>Updated Content</div>; }",
    "src/components/Button.tsx": "export const Button = () => <button>Click me</button>;",
    "package.json": "{ \"name\": \"my-app\", \"dependencies\": { \"react\": \"^18.0.0\", \"axios\": \"^1.2.0\" } }"
  }
}

Response:

{
  "success": true,
  "message": "Files updated"
}

Update Files

PUT /containers/:containerId/files
Content-Type: application/json

Request Body:

{
  "files": {
    "src/App.tsx": "export default function App() { return <div>Updated Content</div>; }",
    "src/components/Button.tsx": "export const Button = () => <button>Click me</button>;"
  }
}

Response:

{
  "success": true,
  "message": "Files updated"
}

📋 Container Logs

Get Container Logs

GET /containers/:containerId/logs

Response:

{
  "logs": "  VITE v5.1.0  ready in 323 ms\n\n  ➜  Local:   http://localhost:3000/\n  ➜  Network: http://172.18.0.3:3000/"
}

🎛️ Configuration Options

Environment Variables

# Server Configuration
PORT=4000                          # Orchestrator port

# Container Port Allocation
PORT_RANGE_START=3001              # Dynamic container port range start
PORT_RANGE_END=3999                # Dynamic container port range end

# Resource Limits
CONTAINER_MEMORY_MB=512            # Memory limit per container (MB)
CONTAINER_CPU_SHARES=256           # CPU shares per container

# Health Checks
HEALTH_CHECK_INTERVAL_MS=30000      # Health check interval (ms)
STARTUP_TIMEOUT_MS=60000           # Container startup timeout (ms)

# Network Configuration
NETWORK_NAME=vibe-network           # Docker network name
HOST_IP=localhost                   # Host IP for container URLs

Container Resource Limits

  • Memory: 512MB (configurable)
  • CPU: 256 shares (configurable)
  • Port Range: 3001-3999 (auto-allocation)
  • Health Check: 30-second intervals
  • Startup Timeout: 60 seconds

🔄 Workflows

1. Create New Development Environment

// 1. Create container with initial files
const response = await fetch('/containers', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    projectId: 'my-project',
    files: {
      'src/App.tsx': 'export default function App() { return <div>My App</div>; }',
      'package.json': JSON.stringify({
        name: 'my-app',
        dependencies: { react: '^18.0.0', 'react-dom': '^18.0.0' }
      })
    }
  })
});

// 2. Get container URL
const { url } = await response.json();

// 3. Navigate to new environment
window.open(url, '_blank');

2. Live Code Updates

// Real-time file synchronization
const updateFile = async (containerId, filePath, content) => {
  await fetch(`/containers/${containerId}/files`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      files: { [filePath]: content }
    })
  });
};

3. Monitor Container Status

const checkHealth = async () => {
  const response = await fetch('/health');
  const { vibeContainers } = await response.json();
  return vibeContainers;
};

🤖 AI Access Guidelines (Frontend-Managed)

Recommended Frontend Restrictions

The frontend should enforce these AI limitations:

Allowed AI Operations

  • Create/Modify files within src/ directory
  • Update package.json for dependency management
  • Read any file content (for context)

Prohibited AI Operations

  • Modify system configuration files (vite.config.ts, tsconfig.json, etc.)
  • Create files outside src/ directory (except package.json)
  • Access Docker files, build scripts, or system templates

Frontend Validation Example

// Recommended frontend validation before sending to API
const validateAIFiles = (files) => {
  const validFiles = {};
  const allowedPaths = ['src/', 'package.json'];
  
  for (const [filepath, content] of Object.entries(files)) {
    const isValidPath = allowedPaths.some(allowed => 
      filepath === allowed || filepath.startsWith(allowed)
    );
    
    if (isValidPath) {
      validFiles[filepath] = content;
    } else {
      console.warn(`Restricted path blocked: ${filepath}`);
    }
  }
  
  return validFiles;
};

Backend Behavior

The orchestrator backend:

  • No file path restrictions - accepts all file operations
  • No validation filtering - relies on frontend enforcement
  • Full file access - can create/modify any file in container

🛠️ Development Tools Integration

Supported File Types

  • TypeScript: .ts, .tsx with full type checking
  • JavaScript: .js, .jsx for compatibility
  • Styles: .css, .scss, .module.css
  • Assets: Images, fonts, and static files
  • Config: JSON, YAML configuration files

Package Management

  • NPM: Automatic package installation
  • Dependencies: Real-time dependency resolution
  • Scripts: Support for npm scripts execution

Build Tools

  • Vite: Fast development server and production builds
  • PostCSS: CSS processing and optimization
  • Tailwind CSS: Utility-first styling framework

🔒 Security Considerations

Network Isolation

  • Containers run in isolated Docker network
  • No external network access by default
  • Port binding controlled through API

Resource Protection

  • Memory limits prevent resource exhaustion
  • CPU shares ensure fair resource distribution
  • File system isolation via container boundaries

Access Control

  • Docker socket access limited to orchestrator
  • Container cleanup prevents resource leaks
  • Health monitoring detects anomalies

📊 Monitoring & Analytics

System Metrics

  • Memory usage tracking
  • CPU utilization monitoring
  • Container health status
  • Network connectivity checks

Performance Monitoring

  • Container startup time
  • File operation latency
  • Resource consumption trends
  • Error rate tracking

🚦 Service Status

Required Services

  • Docker Engine: Container runtime
  • Docker Network: vibe-network must exist
  • Base Image: vibe-react-base:latest must be built

Health Endpoints

  • GET /health - System health overview
  • GET /containers - Container status listing
  • Container health checks via Docker API

🎯 Use Cases

Development Environments

  • Isolated feature development
  • Code review environments
  • Testing and validation
  • Live coding demonstrations

Educational Purposes

  • Programming tutorials
  • Coding workshops
  • Student assignments
  • Interactive learning

Rapid Prototyping

  • Quick idea validation
  • Component testing
  • API integration testing
  • UI/UX experimentation

📱 Frontend Integration Guide

Authentication (Future Enhancement)

// Placeholder for authentication
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer <token>'
};

Error Handling

const handleApiError = (response) => {
  if (!response.ok) {
    throw new Error(`API Error: ${response.status} - ${response.statusText}`);
  }
  return response.json();
};

WebSocket Support (Future Enhancement)

// Placeholder for real-time updates
const ws = new WebSocket('ws://localhost:4000/ws');
ws.onmessage = (event) => {
  const { type, data } = JSON.parse(event.data);
  // Handle real-time container updates
};

Last Updated: January 2024
Platform Version: 1.1.0 - AI Restricted Access

📋 Important Update: AI access is now restricted to src/ directory and package.json only. See AI_CONSTRAINTS.md for detailed documentation.