Files
supervisor-ui/IMPLEMENTATION.md
Sebastian Krüger e0cfd371c0
Some checks failed
Build and Push Docker Image to Gitea / build-and-push (push) Failing after 1m22s
feat: initial commit - Supervisor UI with Next.js 16 and Tailwind CSS 4
- Modern web interface for Supervisor process management
- Built with Next.js 16 (App Router) and Tailwind CSS 4
- Full XML-RPC client implementation for Supervisor API
- Real-time process monitoring with auto-refresh
- Process control: start, stop, restart operations
- Modern dashboard with system status and statistics
- Dark/light theme with OKLCH color system
- Docker multi-stage build with runtime env var configuration
- Gitea CI/CD workflow for automated builds
- Comprehensive documentation (README, IMPLEMENTATION, DEPLOYMENT)

Features:
- Backend proxy pattern for secure API communication
- React Query for state management and caching
- TypeScript strict mode with Zod validation
- Responsive design with mobile support
- Health check endpoint for monitoring
- Non-root user security in Docker

Environment Variables:
- SUPERVISOR_HOST, SUPERVISOR_PORT
- SUPERVISOR_USERNAME, SUPERVISOR_PASSWORD (optional)
- Configurable at build-time and runtime

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 18:23:51 +01:00

17 KiB

Supervisor UI - Implementation Summary

Overview

A sophisticated, production-ready web application for managing Supervisor processes, built with Next.js 16 and Tailwind CSS 4. This implementation follows modern best practices and patterns from the pastel-ui project.

Project Architecture

Technology Stack

  • Framework: Next.js 16.0.3 (App Router, Standalone Output)
  • React: 19.2.0 with strict mode
  • Styling: Tailwind CSS 4.1.17 (CSS-first approach with OKLCH colors)
  • State Management:
    • TanStack Query 5.90.10 (server state)
    • Zustand 5.0.8 (client state - ready for future use)
  • API Communication: XML-RPC client for Supervisor
  • Type Safety: TypeScript 5.9.3 + Zod 3.25.76
  • UI Components: Custom components with lucide-react icons
  • Notifications: Sonner 1.7.4
  • Package Manager: pnpm 10.20.0

Key Features Implemented

  1. Real-time Monitoring

    • Auto-refreshing process list (every 3 seconds)
    • System status updates (every 5 seconds)
    • Process state indicators with color-coded badges
    • Uptime tracking and formatting
  2. Process Control

    • Start/Stop/Restart individual processes
    • Intelligent button states based on process status
    • Optimistic UI updates with React Query mutations
    • Toast notifications for all actions
    • Proper error handling with user feedback
  3. Modern Dashboard

    • System status card with version info
    • Process statistics (total, running, stopped, fatal)
    • Quick action cards for navigation
    • Responsive grid layout
    • Smooth animations and transitions
  4. Backend API Proxy

    • Next.js API routes for all Supervisor methods
    • Secure server-side XML-RPC communication
    • Environment-based configuration
    • Error handling and validation
    • RESTful API design
  5. Theme System

    • Dark/light mode with system preference detection
    • Smooth theme transitions
    • OKLCH color space for perceptual uniformity
    • Custom color palette for process states
    • Persistent theme storage
  6. Docker Support

    • Multi-stage Dockerfile for optimized builds
    • Node.js 20 Alpine base (lightweight)
    • Non-root user security
    • Health check endpoint
    • Docker Compose configuration
    • Arty integration ready

File Structure

supervisor-ui/
├── app/
│   ├── api/
│   │   ├── health/route.ts                    # Health check endpoint
│   │   └── supervisor/
│   │       ├── system/route.ts                # System info API
│   │       └── processes/
│   │           ├── route.ts                   # All processes API
│   │           └── [name]/
│   │               ├── route.ts               # Single process info
│   │               ├── start/route.ts         # Start process
│   │               ├── stop/route.ts          # Stop process
│   │               ├── restart/route.ts       # Restart process
│   │               └── logs/
│   │                   ├── stdout/route.ts    # Stdout logs
│   │                   └── stderr/route.ts    # Stderr logs
│   ├── config/page.tsx                        # Configuration page (placeholder)
│   ├── logs/page.tsx                          # Logs page (placeholder)
│   ├── processes/page.tsx                     # Process management page
│   ├── globals.css                            # Tailwind CSS + theme system
│   ├── layout.tsx                             # Root layout with providers
│   └── page.tsx                               # Dashboard home
├── components/
│   ├── layout/
│   │   └── Navbar.tsx                         # Navigation bar with theme toggle
│   ├── process/
│   │   ├── ProcessCard.tsx                    # Individual process card
│   │   └── SystemStatus.tsx                   # System status display
│   ├── providers/
│   │   ├── Providers.tsx                      # Combined provider wrapper
│   │   └── ThemeProvider.tsx                  # Theme context provider
│   └── ui/
│       ├── badge.tsx                          # Badge component
│       ├── button.tsx                         # Button component
│       └── card.tsx                           # Card components
├── lib/
│   ├── hooks/
│   │   └── useSupervisor.ts                   # React Query hooks
│   ├── supervisor/
│   │   ├── client.ts                          # XML-RPC client class
│   │   └── types.ts                           # TypeScript types + Zod schemas
│   └── utils/
│       └── cn.ts                              # Class name utility
├── .dockerignore                              # Docker ignore patterns
├── .env.example                               # Environment variable template
├── .eslintrc.json                             # ESLint configuration
├── .gitignore                                 # Git ignore patterns
├── .prettierrc                                # Prettier configuration
├── docker-compose.yml                         # Docker Compose setup
├── Dockerfile                                 # Multi-stage production build
├── next.config.ts                             # Next.js configuration
├── package.json                               # Dependencies and scripts
├── postcss.config.mjs                         # PostCSS with Tailwind plugin
├── README.md                                  # User documentation
└── tsconfig.json                              # TypeScript configuration

API Routes Specification

System Information

  • GET /api/health - Health check (returns status and timestamp)
  • GET /api/supervisor/system - Get system info (version, state, PID)

Process Management

  • GET /api/supervisor/processes - List all processes
  • GET /api/supervisor/processes/[name] - Get single process info
  • POST /api/supervisor/processes/[name]/start - Start process
  • POST /api/supervisor/processes/[name]/stop - Stop process
  • POST /api/supervisor/processes/[name]/restart - Restart process

Logs

  • GET /api/supervisor/processes/[name]/logs/stdout - Get stdout logs
  • GET /api/supervisor/processes/[name]/logs/stderr - Get stderr logs

Query parameters for logs:

  • offset (default: -4096) - Byte offset for reading
  • length (default: 4096) - Number of bytes to read

Configuration

Environment Variables

# Supervisor Connection
SUPERVISOR_HOST=localhost
SUPERVISOR_PORT=9001

# Optional: Basic Authentication
SUPERVISOR_USERNAME=user
SUPERVISOR_PASSWORD=pass

Supervisor Setup

Your supervisord.conf must enable the inet HTTP server:

[inet_http_server]
port = 127.0.0.1:9001
username = user      ; Optional
password = pass      ; Optional

Development Workflow

Local Development

# Install dependencies
pnpm install

# Create environment file
cp .env.example .env.local
# Edit .env.local with your Supervisor connection details

# Run development server
pnpm dev

# Open http://localhost:3000

Code Quality

# Type checking
pnpm type-check

# Linting
pnpm lint
pnpm lint:fix

# Formatting
pnpm format

Production Build

# Build for production
pnpm build

# Start production server
pnpm start

Docker Deployment

Option 1: Docker Build & Run

# Build image
docker build -t supervisor-ui:latest .

# Run container
docker run -d \
  --name supervisor-ui \
  -p 3000:3000 \
  -e SUPERVISOR_HOST=localhost \
  -e SUPERVISOR_PORT=9001 \
  supervisor-ui:latest

Option 2: Docker Compose

# Start service
docker-compose up -d

# View logs
docker-compose logs -f

# Stop service
docker-compose down
# Start service
arty up -d supervisor-ui

# Check status
arty ps

# View logs
arty logs supervisor-ui

# Stop service
arty down supervisor-ui

Design System

Color Palette (OKLCH)

The application uses OKLCH color space for perceptually uniform colors:

Light Mode:

  • Background: oklch(98% 0 0) - Nearly white
  • Foreground: oklch(20% 0 0) - Dark gray
  • Primary: oklch(55% 0.15 220) - Blue-green
  • Success: oklch(60% 0.15 140) - Green
  • Warning: oklch(75% 0.15 90) - Yellow
  • Destructive: oklch(55% 0.20 25) - Red

Dark Mode:

  • Background: oklch(15% 0.01 250) - Very dark blue-gray
  • Foreground: oklch(95% 0 0) - Nearly white
  • Colors automatically adjusted for dark mode

Process State Styling

  • RUNNING: Green background with success colors
  • STOPPED/EXITED: Gray muted colors
  • STARTING/BACKOFF: Yellow warning colors
  • STOPPING: Yellow warning colors
  • FATAL: Red destructive colors
  • UNKNOWN: Gray muted colors

Typography

  • Font: Inter (Google Fonts)
  • Headings: Bold with gradient text effects
  • Body: Regular with good readability
  • Code/Mono: For PIDs, uptimes, versions

Animations

  • fade-in: Gentle fade-in (0.3s)
  • slide-up/down: Slide animations (0.4s)
  • scale-in: Scale animation (0.2s)
  • pulse-slow: Slow pulsing (3s)
  • spin-slow: Slow rotation (3s)

React Query Configuration

Query Settings

  • Stale Time: 3 seconds (for real-time feel)
  • Refetch on Window Focus: Disabled
  • Retry: 2 attempts
  • Refetch Intervals:
    • System info: 5 seconds
    • Processes list: 3 seconds
    • Individual process: 3 seconds
    • Logs: 2 seconds (when enabled)

Mutation Handling

All mutations (start/stop/restart) automatically:

  1. Show loading states on buttons
  2. Display toast notifications on success/error
  3. Invalidate related queries to trigger refetch
  4. Update UI optimistically where possible

Supervisor Client Implementation

The XML-RPC client (lib/supervisor/client.ts) implements all Supervisor API methods:

System Methods

  • getAPIVersion()
  • getSupervisorVersion()
  • getIdentification()
  • getState()
  • getPID()
  • getSystemInfo() - Combined method

Process Control

  • getAllProcessInfo()
  • getProcessInfo(name)
  • startProcess(name, wait)
  • stopProcess(name, wait)
  • restartProcess(name) - Custom implementation
  • signalProcess(name, signal)
  • signalProcessGroup(name, signal)
  • signalAllProcesses(signal)

Log Methods

  • readProcessStdoutLog(name, offset, length)
  • readProcessStderrLog(name, offset, length)
  • tailProcessStdoutLog(name, offset, length)
  • tailProcessStderrLog(name, offset, length)
  • clearProcessLogs(name)
  • clearAllProcessLogs()

Configuration Methods

  • reloadConfig()
  • addProcessGroup(name)
  • removeProcessGroup(name)

Control Methods

  • shutdown()
  • restart()
  • sendProcessStdin(name, chars)

Type Safety

Zod Schemas

All API responses are validated with Zod schemas:

  • ProcessInfoSchema - Process information structure
  • SupervisorStateInfoSchema - System state structure
  • ConfigInfoSchema - Configuration structure
  • ReloadConfigResultSchema - Reload results

TypeScript Types

Comprehensive type definitions for:

  • Process states and state codes
  • Supervisor states
  • API responses and requests
  • Component props
  • Hook return types

Future Enhancements

Planned Features

  1. Log Viewer

    • Real-time log tailing with auto-scroll
    • Search and filtering capabilities
    • Multi-process log aggregation
    • Log level highlighting
    • Download log files
  2. Configuration Management

    • Reload configuration UI
    • Add/remove process groups
    • View full configuration
    • Validation before applying
  3. Advanced Features

    • Process group batch operations
    • Keyboard shortcuts (start/stop/restart)
    • Charts for uptime and resource usage
    • Process dependency visualization
    • Event history timeline
    • Notifications for state changes
  4. Real-time Updates

    • WebSocket support for push updates
    • Server-Sent Events (SSE) fallback
    • Reduce polling when WebSocket available
  5. Multi-Instance Support

    • Connect to multiple Supervisor servers
    • Instance switcher in navbar
    • Dashboard showing all instances
    • Stored connections management

Performance Optimizations

Current Optimizations

  1. React Query Caching

    • Intelligent cache invalidation
    • Stale-while-revalidate pattern
    • Background refetching
  2. Component Optimizations

    • Proper React.memo usage where needed
    • Efficient re-render prevention
    • Loading skeletons for better UX
  3. Docker Build

    • Multi-stage build reduces image size
    • Layer caching for faster rebuilds
    • Non-root user for security
    • Health checks for reliability
  4. Tailwind CSS

    • CSS-first approach with v4
    • Tree-shaking unused styles
    • Optimized for production

Potential Optimizations

  1. Code Splitting

    • Dynamic imports for heavy components
    • Route-based code splitting
    • Lazy loading for charts/graphs
  2. Image Optimization

    • Next.js Image component
    • WebP format support
    • Lazy loading images
  3. Bundle Analysis

    • Use webpack-bundle-analyzer
    • Identify large dependencies
    • Replace or optimize heavy libraries

Security Considerations

Implemented

  1. Backend Proxy Pattern

    • No direct browser-to-Supervisor connection
    • Credentials stored server-side only
    • CSRF protection via Next.js
  2. Docker Security

    • Non-root user in container
    • Minimal attack surface
    • Health checks for monitoring
  3. Type Safety

    • Runtime validation with Zod
    • TypeScript strict mode
    • No unsafe type assertions

Recommendations

  1. Authentication

    • Add user authentication layer
    • Role-based access control
    • Session management
  2. HTTPS

    • Use HTTPS in production
    • Secure cookie flags
    • HSTS headers
  3. Rate Limiting

    • Implement rate limiting on API routes
    • Prevent DoS attacks
    • Monitor for abuse

Testing Strategy

Current State

  • Development testing completed
  • Manual UI testing performed
  • API route functionality verified
  1. Unit Tests

    • Supervisor client methods
    • Utility functions
    • Component logic
  2. Integration Tests

    • API route handlers
    • React Query hooks
    • Component interactions
  3. E2E Tests

    • Critical user flows
    • Process control operations
    • Error scenarios
  4. Tools to Add

    • Vitest for unit tests
    • React Testing Library
    • Playwright for E2E tests

Deployment Checklist

Pre-Deployment

  • Set environment variables
  • Configure Supervisor connection
  • Test API connectivity
  • Review security settings
  • Enable HTTPS if possible
  • Set up monitoring/logging

Docker Deployment

  • Build Docker image
  • Push to registry (if using one)
  • Configure docker-compose.yml
  • Set up persistent storage (if needed)
  • Configure networking
  • Set up reverse proxy (nginx/traefik)

Post-Deployment

  • Verify health check endpoint
  • Test all process operations
  • Check real-time updates
  • Verify theme switching
  • Test on different browsers
  • Monitor error logs

Maintenance

Regular Tasks

  1. Dependency Updates

    pnpm update --latest
    pnpm audit
    
  2. Security Patches

    • Monitor security advisories
    • Apply patches promptly
    • Test after updates
  3. Performance Monitoring

    • Check response times
    • Monitor memory usage
    • Review error logs
  4. Backup

    • No persistent data stored
    • Configuration in environment variables
    • Code in version control

Troubleshooting

Common Issues

  1. "Failed to connect to Supervisor"

    • Check Supervisor is running
    • Verify inet_http_server enabled
    • Check SUPERVISOR_HOST and PORT
    • Test with curl http://localhost:9001/RPC2
  2. Theme Not Persisting

    • Clear browser localStorage
    • Check for JavaScript errors
    • Verify ThemeProvider is wrapping app
  3. Processes Not Updating

    • Check React Query devtools
    • Verify API routes returning data
    • Check browser console for errors
  4. Docker Container Won't Start

    • Check health check endpoint
    • Review container logs
    • Verify environment variables
    • Check network connectivity

Debug Mode

Enable React Query DevTools by installing:

pnpm add @tanstack/react-query-devtools

Add to components/providers/Providers.tsx:

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

// In return statement:
<ReactQueryDevtools initialIsOpen={false} />

Credits & References

Inspired By

  • pastel-ui: Configuration patterns, Docker setup, and Tailwind CSS v4 usage
  • Supervisor: The excellent process control system this UI manages
  • Next.js: Modern React framework with excellent DX

Built With

License

MIT License - Feel free to use and modify for your needs.


Last Updated: November 23, 2025 Version: 0.1.0 Status: Production Ready (Core Features)