From 0c83b1563675d9d9494a429dd6dcfa496a9ada88 Mon Sep 17 00:00:00 2001 From: SEB Fotografie - soeren Date: Tue, 11 Nov 2025 21:23:00 +0100 Subject: [PATCH] added prp --- prp/README.md | 296 +++++++ prp/api-specification.md | 522 ++++++++++++ prp/authentication-authorization.md | 552 +++++++++++++ prp/business-logic.md | 137 ++++ prp/configuration-settings.md | 636 +++++++++++++++ prp/data-models.md | 340 ++++++++ prp/deployment-requirements.md | 1164 +++++++++++++++++++++++++++ prp/frontend-components.md | 525 ++++++++++++ prp/plugin-architecture.md | 651 +++++++++++++++ 9 files changed, 4823 insertions(+) create mode 100644 prp/README.md create mode 100644 prp/api-specification.md create mode 100644 prp/authentication-authorization.md create mode 100644 prp/business-logic.md create mode 100644 prp/configuration-settings.md create mode 100644 prp/data-models.md create mode 100644 prp/deployment-requirements.md create mode 100644 prp/frontend-components.md create mode 100644 prp/plugin-architecture.md diff --git a/prp/README.md b/prp/README.md new file mode 100644 index 0000000..ef3197d --- /dev/null +++ b/prp/README.md @@ -0,0 +1,296 @@ +# Project Reconstruction Plan (PRP) Collection + +## Overview + +This comprehensive collection of PRP (Project Reconstruction Plan) files provides detailed specifications and documentation for recreating the AI StyleGallery application using any framework or technology stack. + +## Purpose + +These PRP files serve as a complete blueprint for: +- **Framework Migration**: Recreate the application in different frameworks (React, Angular, Django, etc.) +- **Technology Modernization**: Upgrade to newer versions or different tech stacks +- **Team Onboarding**: Help new developers understand the system architecture +- **System Documentation**: Maintain comprehensive documentation of business logic and implementation details + +## File Structure + +``` +prp/ +├── README.md # This overview file +├── business-logic.md # High-level business requirements and workflows +├── data-models.md # Complete data model specifications with relationships +├── api-specification.md # All API endpoints, parameters, and responses +├── frontend-components.md # Vue.js component specifications and interactions +├── plugin-architecture.md # AI provider plugin system details +├── authentication-authorization.md # User roles, permissions, and security +├── configuration-settings.md # Application settings and configuration structure +└── deployment-requirements.md # Dependencies, environment setup, and deployment notes +``` + +## PRP Files Guide + +### 1. Business Logic (`business-logic.md`) +**Read First** - Start here to understand what the application does + +**Contains**: +- High-level business requirements +- Core user workflows and journeys +- Business rules and constraints +- Success metrics and KPIs +- Future enhancement opportunities + +**Use For**: +- Understanding the application's purpose +- Planning framework migration strategy +- Identifying core features to implement + +### 2. Data Models (`data-models.md`) +**Read Second** - Essential for database design + +**Contains**: +- Complete entity relationship diagram +- Detailed model specifications with all attributes +- Foreign key relationships and constraints +- Data types and validation rules +- Business logic implementation details + +**Use For**: +- Database schema design +- ORM model creation +- Understanding data relationships +- Planning data migration strategies + +### 3. API Specification (`api-specification.md`) +**Read Third** - Critical for backend implementation + +**Contains**: +- Complete REST API endpoint documentation +- Request/response formats and examples +- Authentication and security requirements +- Error handling and status codes +- WebSocket integration details + +**Use For**: +- Backend API development +- Frontend integration planning +- API testing strategy +- Third-party integration planning + +### 4. Frontend Components (`frontend-components.md`) +**Framework-Specific** - Vue.js implementation details + +**Contains**: +- Component hierarchy and architecture +- State management patterns +- User interaction flows +- Responsive design specifications +- Accessibility requirements + +**Use For**: +- Vue.js specific implementation +- General frontend architecture planning +- Component-based framework migration +- UI/UX design reference + +### 5. Plugin Architecture (`plugin-architecture.md`) +**Technical Deep Dive** - Advanced backend patterns + +**Contains**: +- Strategy pattern implementation +- Plugin interface specifications +- AI provider integration details +- Error handling and logging +- Extension and customization points + +**Use For**: +- Implementing extensible AI provider systems +- Understanding plugin-based architecture +- Adding new AI service integrations +- Advanced backend development + +### 6. Authentication & Authorization (`authentication-authorization.md`) +**Security Critical** - Must implement carefully + +**Contains**: +- User role and permission system +- Laravel Sanctum API authentication +- Security measures and best practices +- Session management and protection +- Compliance and legal considerations + +**Use For**: +- Security implementation planning +- Authentication system design +- Permission and access control +- Security auditing and compliance + +### 7. Configuration & Settings (`configuration-settings.md`) +**Operational** - Runtime configuration management + +**Contains**: +- Settings management system +- Environment-based configuration +- Feature flags and dynamic settings +- Admin configuration interface +- Performance and monitoring settings + +**Use For**: +- Configuration management implementation +- Environment setup and deployment +- Feature flag system design +- Admin panel development + +### 8. Deployment Requirements (`deployment-requirements.md`) +**DevOps & Operations** - Production deployment guide + +**Contains**: +- System requirements and specifications +- Installation and setup procedures +- Web server configuration (Nginx/Apache) +- Security hardening and optimization +- Monitoring and troubleshooting guides + +**Use For**: +- Production environment setup +- DevOps and deployment automation +- Performance optimization +- Operational procedures and maintenance + +## How to Use These PRP Files + +### For Framework Migration + +1. **Start with Business Logic** - Understand core requirements +2. **Design Data Models** - Plan database schema +3. **Implement Authentication** - Set up security first +4. **Build API Layer** - Follow API specifications +5. **Create Frontend** - Use component specifications as guide +6. **Add Plugin System** - Implement extensible architecture +7. **Configure & Deploy** - Follow deployment requirements + +### For New Developer Onboarding + +1. **Read Business Logic** - Understand what the app does +2. **Study Data Models** - Learn the data structure +3. **Review API Specification** - Understand system interfaces +4. **Examine Frontend Components** - Learn UI interactions +5. **Set up Development Environment** - Follow deployment guide + +### For System Enhancement + +1. **Identify Enhancement Area** - Choose relevant PRP file +2. **Understand Current Implementation** - Study existing patterns +3. **Plan Changes** - Design improvements within existing architecture +4. **Implement & Test** - Follow established patterns and conventions + +## Key Architecture Patterns + +### Plugin-Based AI Integration +- **Strategy Pattern**: Runtime selection of AI providers +- **Interface Contract**: Consistent API across all providers +- **Error Handling**: Graceful degradation and retry logic +- **Logging**: Comprehensive audit trail for all operations + +### Component-Based Frontend +- **Single Page Application**: Vue.js with Inertia.js +- **State Management**: Composition API with reactive data +- **Real-time Updates**: WebSocket for live progress monitoring +- **Responsive Design**: Mobile-first approach with touch support + +### Role-Based Security +- **Two-Tier Authentication**: Session-based admin, token-based API +- **Granular Permissions**: Role-based access with ownership checks +- **Security Headers**: Comprehensive protection against common attacks +- **Audit Logging**: Complete trail of authentication and authorization events + +## Technology Stack Compatibility + +### Current Implementation +- **Backend**: Laravel 12.21.0 with PHP 8.3 +- **Frontend**: Vue.js 3.5.18 with Inertia.js 1.3.0 +- **Database**: SQLite with Eloquent ORM +- **Admin Panel**: Filament 3.3.34 +- **Styling**: Tailwind CSS 3.4.17 + +### Migration Opportunities +- **React/Angular**: Use API specification for backend integration +- **Django/FastAPI**: Implement data models and business logic +- **Next.js/Nuxt.js**: Full-stack framework migration +- **Spring Boot**: Java-based implementation +- **ASP.NET Core**: .NET implementation + +## Implementation Priorities + +### Phase 1: Core Foundation +1. **Database Schema** - Implement data models +2. **Authentication System** - User roles and security +3. **Basic API** - Core CRUD operations +4. **Simple Frontend** - Basic gallery view + +### Phase 2: Advanced Features +1. **AI Plugin System** - Extensible provider architecture +2. **Real-time Processing** - WebSocket integration +3. **Advanced UI** - Component-based interface +4. **Admin Panel** - Management interface + +### Phase 3: Production Readiness +1. **Performance Optimization** - Caching and scaling +2. **Security Hardening** - Production security measures +3. **Monitoring & Logging** - Operational visibility +4. **Deployment Automation** - CI/CD and DevOps + +## Quality Assurance + +### Testing Strategy +- **Unit Tests**: Individual component and function testing +- **Integration Tests**: API and component interaction testing +- **End-to-End Tests**: Complete user workflow testing +- **Performance Tests**: Load testing and optimization + +### Code Quality +- **Standards**: Follow PSR-12 for PHP, ESLint for JavaScript +- **Documentation**: Comprehensive code comments and API docs +- **Security**: Regular security audits and vulnerability scanning +- **Performance**: Monitoring and optimization based on metrics + +## Support and Maintenance + +### Documentation Updates +- Keep PRP files current with code changes +- Version control PRP files alongside code +- Regular review and updates for accuracy + +### Team Coordination +- Use PRP files for architecture decision records +- Reference PRP files in code reviews and planning +- Maintain consistency between PRP and implementation + +## Contributing to PRP Files + +### Update Process +1. **Identify Changes**: Document what needs updating +2. **Update PRP Files**: Modify relevant sections +3. **Review Changes**: Ensure accuracy and completeness +4. **Version Control**: Commit PRP changes with code changes + +### Quality Standards +- **Accuracy**: PRP must reflect actual implementation +- **Completeness**: Include all relevant details and examples +- **Clarity**: Use clear language and consistent formatting +- **Maintenance**: Regular updates to prevent drift + +## Success Metrics + +### Implementation Completeness +- **Feature Parity**: All documented features implemented +- **API Compatibility**: All endpoints match specifications +- **Performance**: Meets or exceeds documented benchmarks +- **Security**: Implements all security measures + +### Development Efficiency +- **Onboarding Time**: Reduced time for new developers +- **Bug Reduction**: Fewer architecture-related issues +- **Maintenance**: Easier troubleshooting and enhancements +- **Documentation**: Single source of truth for system knowledge + +This PRP collection provides a complete blueprint for understanding, maintaining, and recreating the AI StyleGallery application across different technologies and frameworks. \ No newline at end of file diff --git a/prp/api-specification.md b/prp/api-specification.md new file mode 100644 index 0000000..70574c7 --- /dev/null +++ b/prp/api-specification.md @@ -0,0 +1,522 @@ +# API Specification + +## Overview +RESTful API built with Laravel Sanctum for authentication. Provides endpoints for image management, style application, and AI processing integration. + +## Base URL +``` +/api +``` + +## Authentication +Laravel Sanctum token-based authentication using `Authorization: Bearer ` header. + +## Response Format +All responses use JSON format with consistent structure: + +### Success Response +```json +{ + "message": "Operation completed successfully", + "data": { ... } +} +``` + +### Error Response +```json +{ + "error": "Error description", + "message": "Detailed error message" +} +``` + +## Endpoints + +### 1. Image Management + +#### 1.1 Get Images +**Endpoint**: `GET /api/images` + +**Authentication**: Not required (filtered by visibility rules) + +**Description**: Retrieves paginated list of images with automatic filesystem synchronization + +**Query Parameters**: +- None + +**Response**: +```json +[ + { + "image_id": 1, + "path": "/storage/uploads/image.jpg", + "name": "image.jpg", + "is_temp": false, + "is_public": true, + "is_new": true + } +] +``` + +**Business Logic**: +- Synchronizes filesystem with database before returning results +- Filters images based on authentication status +- Adds `is_new` flag for recently uploaded images (within configurable timespan) +- Returns images in descending order by `updated_at` + +**Error Codes**: +- `500`: Internal server error during synchronization + +--- + +#### 1.2 Upload Image +**Endpoint**: `POST /api/images/upload` + +**Authentication**: Not required + +**Description**: Uploads new image file to the gallery + +**Request Body** (multipart/form-data): +```json +{ + "image": "file (JPEG, PNG, WebP, max 10MB)" +} +``` + +**Response**: +```json +{ + "message": "Image uploaded successfully", + "image_id": 1, + "path": "/storage/uploads/new-image.jpg" +} +``` + +**Validation Rules**: +- `image`: required, image file, mime types: jpeg,png,webp, max:10240KB + +**Business Logic**: +- Generates unique filename to prevent conflicts +- Stores in `public/storage/uploads/` directory +- Creates database record with `is_public = true` +- Returns full URL path for immediate use + +**Error Codes**: +- `422`: Validation failed (invalid file type/size) +- `500`: File storage error + +--- + +#### 1.3 Apply Style to Image +**Endpoint**: `POST /api/images/style-change` + +**Authentication**: Not required (same-origin check) + +**Description**: Initiates AI style transformation process + +**Headers**: +``` +Referer: https://yourdomain.com (same-origin validation) +``` + +**Request Body**: +```json +{ + "image_id": 1, + "style_id": 1 +} +``` + +**Response**: +```json +{ + "message": "Style change request sent", + "prompt_id": "comfyui-job-123", + "image_uuid": "550e8400-e29b-41d4-a716-446655440000", + "plugin": "comfyui" +} +``` + +**Validation Rules**: +- `image_id`: required, exists in `images` table +- `style_id`: nullable, exists in `styles` table + +**Business Logic**: +- Validates same-origin request for security +- Loads appropriate AI plugin based on style's API provider +- Updates image record with `comfyui_prompt_id` and `style_id` +- Returns tracking information for frontend progress monitoring + +**Error Codes**: +- `403`: Unauthorized origin +- `404`: Image or style not found +- `422`: Validation failed +- `500`: Plugin processing error + +--- + +#### 1.4 Fetch Styled Image Result +**Endpoint**: `GET /api/images/fetch-styled/{promptId}` + +**Authentication**: Not required + +**Description**: Retrieves result of completed AI style transformation + +**Path Parameters**: +- `promptId`: string (ComfyUI job identifier) + +**Response**: +```json +{ + "message": "Styled image fetched successfully", + "styled_image": { + "id": 2, + "path": "/storage/uploads/styled_image.png", + "is_temp": true + } +} +``` + +**Business Logic**: +- Finds image record by `comfyui_prompt_id` +- Loads appropriate AI plugin to fetch result +- Saves styled image to filesystem +- Creates new database record for styled image +- Links styled image to original via `original_image_id` + +**Error Codes**: +- `404`: Image not found or still processing +- `500`: Plugin fetch error or file save error + +--- + +#### 1.5 Keep Styled Image +**Endpoint**: `POST /api/images/keep` + +**Authentication**: Required (Sanctum) + +**Description**: Converts temporary styled image to permanent + +**Request Body**: +```json +{ + "image_id": 2 +} +``` + +**Response**: +```json +{ + "message": "Image kept successfully" +} +``` + +**Validation Rules**: +- `image_id`: required, exists in `images` table + +**Business Logic**: +- Verifies user owns the image +- Sets `is_temp = false` on image record +- Image becomes permanent part of user's gallery + +**Error Codes**: +- `401`: Unauthenticated +- `404`: Image not found +- `403`: User doesn't own image + +--- + +#### 1.6 Delete Image +**Endpoint**: `DELETE /api/images/{image}` + +**Authentication**: Required (Sanctum) + +**Description**: Permanently removes image and file + +**Path Parameters**: +- `image`: integer (image ID) + +**Response**: +```json +{ + "message": "Image deleted successfully" +} +``` + +**Business Logic**: +- Verifies user owns the image +- Deletes physical file from storage +- Removes database record +- Cascading: styled images deleted when original is deleted + +**Error Codes**: +- `401`: Unauthenticated +- `404`: Image not found +- `403`: User doesn't own image +- `500`: File deletion error + +--- + +#### 1.7 Get Image Status (Deprecated) +**Endpoint**: `GET /api/images/status` + +**Authentication**: Not required + +**Description**: Legacy endpoint for image processing status + +**Query Parameters**: +```json +{ + "image_id": 1, + "api_provider_name": "ComfyUI" +} +``` + +**Response**: +```json +{ + "status": "unknown" +} +``` + +**Note**: Currently returns static response, replaced by WebSocket progress + +--- + +### 2. Style Management + +#### 2.1 Get Available Styles +**Endpoint**: `GET /api/styles` + +**Authentication**: Not required + +**Description**: Retrieves all enabled styles for style selector + +**Response**: +```json +[ + { + "id": 1, + "title": "Oil Painting", + "description": "Classic oil painting style", + "preview_image": "/storage/style_previews/oil-painting.jpg", + "enabled": true + } +] +``` + +**Business Logic**: +- Returns only enabled styles +- Includes preview images for UI display +- Ordered by `sort_order` field + +**Error Codes**: +- `500`: Database query error + +--- + +### 3. AI Provider Management + +#### 3.1 Get ComfyUI URL +**Endpoint**: `GET /api/comfyui-url` + +**Authentication**: Not required + +**Description**: Returns WebSocket URL for real-time progress updates + +**Query Parameters** (optional): +```json +{ + "style_id": 1, + "image_uuid": "550e8400-e29b-41d4-a716-446655440000" +} +``` + +**Response**: +```json +{ + "comfyui_url": "https://your-comfyui-server.com" +} +``` + +**Business Logic**: +- Determines appropriate API provider based on style or image +- Falls back to first available ComfyUI provider if none specified +- Returns base URL for WebSocket connection + +**Error Codes**: +- `404`: No enabled ComfyUI provider found + +--- + +### 4. User Management + +#### 4.1 Get Authenticated User +**Endpoint**: `GET /api/user` + +**Authentication**: Required (Sanctum) + +**Description**: Returns current authenticated user information + +**Response**: +```json +{ + "id": 1, + "name": "John Doe", + "email": "john@example.com", + "role": "user", + "theme_preference": "light", + "locale": "en" +} +``` + +**Error Codes**: +- `401`: Unauthenticated + +--- + +### 5. Admin Management + +#### 5.1 Store Navigation State +**Endpoint**: `POST /api/admin/navigation-state` + +**Authentication**: Required (Sanctum) + +**Description**: Saves admin panel navigation preferences + +**Request Body**: +```json +{ + "state": "collapsed", + "active_tab": "dashboard" +} +``` + +**Response**: +```json +{ + "message": "Navigation state saved" +} +``` + +**Business Logic**: +- Stores UI state preferences for admin users +- Used by Filament admin panel for user experience + +--- + +## WebSocket Integration + +### ComfyUI Progress Updates + +**Connection**: +``` +WebSocket URL: ws://{comfyui-server-host}/ws +``` + +**Message Format**: +```json +{ + "type": "progress", + "data": { + "prompt_id": "job-123", + "value": 50, + "max": 100 + } +} +``` + +**Frontend Handling**: +- Connect to WebSocket after receiving `prompt_id` from style-change endpoint +- Monitor progress messages for matching `prompt_id` +- Update UI progress bar based on `value/max` percentage +- Fetch final result when progress reaches 100% + +## Error Handling + +### HTTP Status Codes +- `200`: Success +- `201`: Created +- `400`: Bad Request +- `401`: Unauthenticated +- `403`: Forbidden +- `404`: Not Found +- `422`: Validation Error +- `500`: Internal Server Error + +### Error Response Structure +```json +{ + "error": "Human readable error message", + "message": "Technical details for debugging", + "errors": { + "field_name": ["Specific field validation errors"] + } +} +``` + +## Rate Limiting + +### Current Implementation +- No explicit rate limiting configured +- External AI services may have their own limits +- Consider implementing for production deployment + +### Recommended Limits +- Image upload: 10 per minute per user +- Style change requests: 5 per minute per user +- API calls: 1000 per hour per user + +## Security Considerations + +### Authentication +- Laravel Sanctum for API authentication +- Bearer token in Authorization header +- CSRF protection for web routes + +### Input Validation +- All inputs validated using Laravel Form Requests +- File upload restrictions (type, size) +- SQL injection prevention via Eloquent ORM + +### Same-Origin Policy +- Style change endpoint validates request origin +- Prevents CSRF attacks from external sites + +### File Security +- Uploaded files stored outside web root +- File type validation prevents malicious uploads +- Secure file permissions on storage directories + +## Performance Considerations + +### Caching +- No explicit caching implemented +- Consider caching for frequently accessed data: + - Available styles list + - User permissions + - API provider configurations + +### Database Optimization +- Eager loading for relationships (styles → ai_models → api_providers) +- Consider indexes on frequently queried fields +- Automatic filesystem synchronization on image listing + +### File Storage +- Images stored on local filesystem +- Consider CDN integration for global distribution +- Automatic cleanup of temporary files + +## Future API Enhancements + +### Potential Endpoints +- `GET /api/images/{id}/history` - Processing history for image +- `POST /api/images/batch-style-change` - Apply style to multiple images +- `GET /api/styles/search?q=term` - Search styles by name/description +- `POST /api/users/preferences` - Update user preferences +- `GET /api/admin/stats` - Application statistics for admins + +### WebSocket Enhancements +- Real-time notifications for all users +- Live gallery updates when new images are processed +- Admin monitoring of processing queue status \ No newline at end of file diff --git a/prp/authentication-authorization.md b/prp/authentication-authorization.md new file mode 100644 index 0000000..ea3b8fb --- /dev/null +++ b/prp/authentication-authorization.md @@ -0,0 +1,552 @@ +# Authentication and Authorization Specification + +## Overview + +Comprehensive authentication and authorization system using Laravel Sanctum for API authentication and Filament for admin panel access control, with role-based permissions and security best practices. + +## Authentication Architecture + +### Laravel Sanctum Integration + +**Purpose**: Provides API authentication for SPA applications + +**Token Management**: +- **Token Storage**: Database storage with automatic expiration +- **Token Types**: Personal access tokens with configurable abilities +- **Security**: CSRF protection and secure token generation + +**Frontend Integration**: +```javascript +// Login process +axios.post('/login', credentials) + .then(response => { + // Store token securely + localStorage.setItem('api_token', response.data.token); + // Set default authorization header + axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`; + }); +``` + +### Session-Based Authentication + +**Purpose**: Traditional web session management for admin panel + +**Implementation**: +- Laravel Breeze scaffolding for basic auth +- Session cookies for state management +- CSRF protection for form submissions + +## User Model and Roles + +### User Model + +**Location**: `app/Models/User.php` + +**Key Attributes**: +```php +// Authentication +email: string (unique) // Primary login identifier +password: string (hashed) // Secure password hash +email_verified_at: timestamp // Email verification status + +// Authorization +role_id: bigint unsigned (nullable) // Foreign key to roles table + +// Two-Factor Authentication +two_factor_secret: text (nullable) // TOTP secret key +two_factor_recovery_codes: text (nullable) // Backup recovery codes +two_factor_confirmed_at: timestamp (nullable) // 2FA confirmation + +// Preferences +email_notifications_enabled: boolean (default: true) // Notification preferences +theme_preference: string (default: 'light') // UI theme +locale: string (default: 'en') // Language preference +``` + +### Role-Based Access Control + +**Role Model**: +```php +// Simple role system +id: bigint unsigned auto_increment primary key +name: varchar(255) unique // Role identifier ('admin', 'user') +created_at, updated_at: timestamps +``` + +**Predefined Roles**: +- **admin**: Full system access, user management, configuration +- **user**: Standard user access, personal gallery management + +**Role Assignment**: +```php +// Default role assignment (in migration) +$usersTable->foreignId('role_id')->constrained()->default(2); // Defaults to 'user' role + +// Role checking +$user->role->name === 'admin' +$user->role?->name === 'admin' // Safe null checking +``` + +## Authorization Mechanisms + +### API Authorization + +**Protected Routes**: +```php +// routes/api.php +Route::middleware('auth:sanctum')->group(function () { + Route::post('/api/images/keep', [ImageController::class, 'keepImage']); + Route::delete('/api/images/{image}', [ImageController::class, 'deleteImage']); + Route::get('/api/user', function (Request $request) { + return $request->user(); + }); +}); +``` + +**Middleware Stack**: +1. **auth:sanctum**: Validates bearer token +2. **Custom Logic**: Additional business rule validation + +### Admin Panel Authorization + +**Filament Integration**: +- Built-in authentication for `/admin` routes +- Session-based admin access +- Automatic logout on inactivity + +**Access Control**: +```php +// Filament panel configuration +->requirePasswordResetAfterLogin(false) +->passwordReset() +->emailVerification() +->twoFactorAuthentication() +``` + +## Security Measures + +### Password Security + +**Hashing Algorithm**: +- Laravel default: bcrypt with cost factor 12 +- Future migration path to Argon2 + +**Password Requirements**: +- Minimum 8 characters +- Mixed case letters +- Numbers and special characters +- Not in common password lists + +### Two-Factor Authentication + +**Implementation**: +- TOTP (Time-based One-Time Password) standard +- Google Authenticator, Authy compatibility +- Recovery codes for account recovery + +**Setup Flow**: +1. User enables 2FA in profile settings +2. QR code generated for authenticator app +3. User confirms setup with first TOTP code +4. Recovery codes generated and displayed once + +**Verification**: +```php +// Middleware for 2FA verification +if ($user->two_factor_secret && !$user->two_factor_confirmed_at) { + return redirect()->route('two-factor.challenge'); +} +``` + +### Session Security + +**Configuration**: +```php +// config/session.php +'secure' => env('SESSION_SECURE_COOKIE', true), // HTTPS only +'http_only' => true, // Prevent XSS access +'same_site' => 'lax', // CSRF protection +'expire_on_close' => false, // Persistent sessions +'lifetime' => 120, // 2 hour timeout +``` + +**Admin Session Management**: +- Shorter session lifetime for admin users +- Automatic logout on suspicious activity +- Session fixation protection + +## Permission System + +### Image Ownership + +**Business Rules**: +- Users can only modify their own images +- Temporary images are tied to processing session +- Public images visible to all authenticated users + +**Implementation**: +```php +// ImageController@deleteImage +public function deleteImage(Image $image) +{ + // Implicit authorization via route model binding + // User must own the image or be admin + $this->authorize('delete', $image); + // or explicit check + if ($image->user_id !== auth()->id() && !auth()->user()->isAdmin()) { + abort(403); + } +} +``` + +### Admin Permissions + +**Admin-Only Operations**: +- User management (create, edit, delete users) +- System configuration changes +- Plugin and API provider management +- Style and AI model configuration +- Application settings modification + +**Permission Checking**: +```php +// Policy-based authorization +class ImagePolicy +{ + public function delete(User $user, Image $image): bool + { + return $user->id === $image->user_id || $user->role->name === 'admin'; + } +} + +// Controller usage +$this->authorize('delete', $image); +``` + +## Security Headers and CSRF Protection + +### Security Headers + +**Content Security Policy**: +```php +// app/Http/Middleware/SetContentSecurityPolicy.php +$contentSecurityPolicy = [ + 'default-src' => ['self'], + 'script-src' => ['self', 'unsafe-inline', 'unsafe-eval'], + 'style-src' => ['self', 'unsafe-inline'], + 'img-src' => ['self', 'data:', 'https:'], + 'connect-src' => ['self', 'ws:', 'wss:'], +]; +``` + +**Other Security Headers**: +- `X-Frame-Options: SAMEORIGIN` - Prevent clickjacking +- `X-Content-Type-Options: nosniff` - Prevent MIME sniffing +- `Referrer-Policy: strict-origin-when-cross-origin` - Control referrer info +- `Permissions-Policy: camera=(), microphone=(), geolocation=()` - Disable unnecessary permissions + +### CSRF Protection + +**Laravel CSRF**: +- Automatic token generation for forms +- Middleware validation on state-changing requests +- Exception for API routes (handled by Sanctum) + +**Custom CSRF**: +```php +// Verify CSRF token manually if needed +if (!hash_equals($request->session()->token(), $request->input('_token'))) { + abort(419, 'CSRF token mismatch'); +} +``` + +## Authentication Flows + +### User Registration + +**Flow**: +1. User submits registration form +2. Validation (email format, password strength, uniqueness) +3. Account creation with default 'user' role +4. Email verification (if enabled) +5. Welcome email sent + +**Validation Rules**: +```php +'email' => 'required|email|unique:users|max:255', +'password' => 'required|min:8|confirmed', +'name' => 'required|string|max:255', +``` + +### User Login + +**Flow**: +1. User submits credentials +2. Rate limiting applied (5 attempts per minute) +3. Credentials verified against database +4. 2FA challenge if enabled +5. Session/token created +6. Redirect to appropriate interface + +**Rate Limiting**: +```php +// Throttle login attempts +RateLimiter::tooManyAttempts($key, 5) // 5 attempts +RateLimiter::hit($key, 60) // Lock for 60 seconds +``` + +### Password Reset + +**Secure Token Flow**: +1. User requests password reset +2. Secure token generated and emailed +3. Token validated on reset form +4. Password updated with new hash +5. Old tokens invalidated + +**Token Security**: +- Cryptographically secure random tokens +- Short expiration time (1 hour) +- Single-use tokens + +## Admin Authentication + +### Admin Panel Access + +**Route Protection**: +```php +// Admin routes protected by Filament middleware +Route::prefix('admin')->name('admin.')->middleware([ + 'auth:sanctum', // API authentication + // Filament middleware stack +])->group(function () { + // Admin routes +}); +``` + +**Role-Based Access**: +- Only users with 'admin' role can access admin panel +- Automatic redirect for unauthorized users +- Session management for admin activities + +### Admin User Management + +**User CRUD Operations**: +- Create new users with role assignment +- Edit user details and permissions +- Disable/enable user accounts +- Reset passwords securely + +**Bulk Operations**: +- Mass role assignment +- Account activation/deactivation +- Email notifications for status changes + +## API Security + +### Token Management + +**Token Creation**: +```php +// Create personal access token +$token = $user->createToken('api-token', ['read', 'write']); +$plainTextToken = $token->plainTextToken; +``` + +**Token Abilities**: +- `read`: View images and styles +- `write`: Upload images and apply styles +- `admin`: Full administrative access + +**Token Expiration**: +```php +// Create expiring token +$token = $user->createToken('temp-token', ['read'], now()->addHour()); +``` + +### API Rate Limiting + +**Current Implementation**: No explicit rate limiting (rely on external services) + +**Recommended Limits**: +```php +// Per-user rate limits +'api:images:upload' => '5,1', // 5 uploads per minute +'api:images:style-change' => '3,1', // 3 style changes per minute +'api:admin:*' => '60,1', // 60 admin actions per minute +``` + +## Security Monitoring + +### Audit Logging + +**Authentication Events**: +- Login attempts (success/failure) +- Password changes +- 2FA setup/removal +- Role changes +- Admin actions + +**Security Events**: +- Suspicious login attempts +- Multiple failed authentication attempts +- Admin privilege escalation +- API abuse detection + +### Intrusion Detection + +**Failed Login Monitoring**: +- Track failed attempts by IP/user +- Automatic account lockout after threshold +- Admin notification for repeated failures + +**Session Monitoring**: +- Concurrent session detection +- Session hijacking prevention +- Unusual activity flagging + +## Data Protection + +### Password Storage +- **Algorithm**: bcrypt with configurable cost +- **Salt**: Automatic per-password salt generation +- **Upgrade Path**: Automatic rehash on successful login + +### Sensitive Data +- **API Tokens**: Encrypted storage in database +- **2FA Secrets**: Encrypted TOTP secrets +- **Configuration**: Environment variables for sensitive settings + +### Data Backup Security +- Encrypted database backups +- Secure backup storage locations +- Access logging for backup operations + +## Compliance Considerations + +### GDPR Compliance + +**Data Handling**: +- User consent for data processing +- Right to data portability +- Right to be forgotten (account deletion) +- Data processing activity logs + +**Privacy Features**: +- Granular privacy settings +- Data export functionality +- Secure account deletion process + +### Security Standards + +**OWASP Compliance**: +- Protection against common web vulnerabilities +- Secure coding practices +- Regular security assessments + +**Industry Standards**: +- HTTPS enforcement +- Secure cookie handling +- Input validation and sanitization + +## Future Security Enhancements + +### Advanced Authentication + +**OAuth Integration**: +- Social login providers (Google, GitHub) +- Single sign-on capabilities +- Third-party application access + +**Biometric Authentication**: +- WebAuthn/FIDO2 support +- Hardware security key support +- Mobile authenticator integration + +### Advanced Authorization + +**Permission-Based Access**: +- Granular permissions beyond roles +- Resource-based permissions +- Dynamic permission assignment + +**Multi-Tenancy**: +- Organization-based access control +- Team-based permissions +- Resource isolation + +### Enhanced Security + +**Advanced Monitoring**: +- Real-time threat detection +- Automated security responses +- Security information and event management (SIEM) + +**Zero-Trust Architecture**: +- Continuous authentication +- Micro-segmentation +- Least privilege access + +## Deployment Security + +### Environment Security + +**Development**: +- Debug mode disabled +- Verbose error reporting off +- Test credentials and data + +**Production**: +- HTTPS enforcement +- Secure headers enabled +- Production credentials only + +### Infrastructure Security + +**Server Hardening**: +- Minimal attack surface +- Regular security updates +- Firewall configuration + +**Database Security**: +- Encrypted database connections +- Minimal privilege accounts +- Regular backup testing + +## Testing Security Features + +### Authentication Tests + +**Unit Tests**: +- Password hashing verification +- Token generation and validation +- Role assignment and checking + +**Integration Tests**: +- Complete login/logout flow +- API authentication middleware +- Admin panel access control + +**Security Tests**: +- SQL injection prevention +- XSS vulnerability testing +- CSRF protection validation + +## Troubleshooting Security + +### Common Issues + +**Token Expiration**: +- Automatic token refresh mechanisms +- Graceful handling of expired sessions +- User notification and re-authentication + +**Permission Errors**: +- Clear error messages for users +- Detailed logging for administrators +- Permission debugging tools + +**Session Issues**: +- Session fixation protection +- Secure session handling +- Cross-site request forgery prevention \ No newline at end of file diff --git a/prp/business-logic.md b/prp/business-logic.md new file mode 100644 index 0000000..4519922 --- /dev/null +++ b/prp/business-logic.md @@ -0,0 +1,137 @@ +# Business Logic Specification + +## Overview +AI StyleGallery is a web application that enables users to transform their uploaded images using various AI-generated artistic styles through integration with external AI services. + +## Core Business Requirements + +### Primary User Journey +1. **Image Upload**: Users can upload personal images to their gallery +2. **Style Selection**: Users can browse and select from available AI artistic styles +3. **AI Processing**: Selected images are sent to external AI services for style transformation +4. **Result Management**: Users can view styled results and choose to keep (make permanent) or discard them +5. **Gallery Management**: Users can view their collection of original and styled images + +### Key Business Rules +- **Image Privacy**: Images are private by default, users control visibility +- **Temporary Processing**: AI-styled images are initially temporary until user confirms +- **Style Availability**: Only enabled styles from active AI models are available to users +- **Provider Flexibility**: Support multiple AI service providers (ComfyUI, RunwareAI, etc.) +- **Real-time Progress**: Users receive real-time updates during AI processing + +## Core Business Workflows + +### 1. Image Style Transformation Workflow + +#### Process Flow +``` +User selects image → Opens context menu → Chooses "Change Style" → +Browses style selector → Selects style → Initiates AI processing → +Receives real-time progress updates → Views styled result → +Chooses to keep or discard the styled image +``` + +#### Technical Implementation +- Frontend captures user selection via Vue.js components +- Backend validates request and loads appropriate AI plugin +- Plugin handles communication with external AI service +- Real-time progress tracked via WebSocket (ComfyUI) or polling (other providers) +- Styled image saved to storage and database record created +- User notified of completion and can manage result + +#### Success Criteria +- Processing completes within reasonable time (typically 30-180 seconds) +- User receives clear progress feedback during processing +- Styled image maintains acceptable quality and resolution +- User can easily keep or discard results + +### 2. Gallery Management Workflow + +#### Image Synchronization +- Automatic sync between filesystem and database +- Missing files removed from database +- New files added to database with metadata +- Maintains data consistency across application restarts + +#### Visibility Rules +- **Public Images**: Visible to all users +- **Private Images**: Only visible to image owner +- **Temporary Images**: Visible to owner during processing/review period +- **Authenticated Users**: See all their own images +- **Unauthenticated Users**: See only public images and their temporary results + +### 3. Admin Management Workflow + +#### Content Management +- **Styles**: Create, edit, enable/disable artistic styles +- **AI Models**: Configure available AI models and their parameters +- **API Providers**: Set up connections to external AI services +- **Users**: Manage user accounts and assign roles +- **Settings**: Configure application-wide settings + +#### Quality Assurance +- Preview images for styles before publishing +- Test connections to AI services +- Monitor processing success rates +- Manage storage and cleanup old temporary files + +## Business Entities & Relationships + +### Primary Entities +- **Users**: Account holders with roles and preferences +- **Images**: Uploaded files with metadata and processing status +- **Styles**: AI artistic styles with prompts and parameters +- **AI Models**: Specific AI models (e.g., Stable Diffusion variants) +- **API Providers**: External AI services (ComfyUI, RunwareAI, etc.) + +### Key Relationships +- **User → Images**: One-to-many (users own multiple images) +- **Image → Style**: Many-to-one (multiple images can use same style) +- **Style → AI Model**: Many-to-one (multiple styles can use same model) +- **AI Model → API Provider**: Many-to-one (multiple models can use same provider) +- **Image → Original Image**: Self-referencing (styled images reference originals) + +## Business Constraints & Validation Rules + +### Data Validation +- **Image Files**: Must be valid image formats (JPEG, PNG, WebP), max 10MB +- **Style Prompts**: Required text describing desired artistic transformation +- **API URLs**: Must be valid, accessible endpoints +- **User Email**: Must be unique and valid format + +### Business Rules +- **Temporary Image Expiry**: Styled images expire if not kept within timeframe +- **Storage Limits**: Maximum storage per user or globally +- **API Rate Limits**: Respect external service limitations +- **Processing Queue**: Handle multiple simultaneous requests appropriately + +## Success Metrics + +### User Experience +- **Processing Speed**: Average time under 60 seconds for style transformation +- **Success Rate**: 95%+ successful transformations +- **User Retention**: Users return and process multiple images +- **Feature Adoption**: High usage of style transformation features + +### Technical Performance +- **System Uptime**: 99.5%+ availability +- **Response Times**: Gallery loads under 2 seconds +- **Error Rates**: Under 1% processing failures +- **Storage Efficiency**: Automatic cleanup of unused temporary files + +## Future Enhancement Opportunities + +### Potential Features +- **Batch Processing**: Apply styles to multiple images simultaneously +- **Style Chaining**: Apply multiple styles in sequence +- **Custom Styles**: User-created style presets +- **Social Features**: Share styled images with other users +- **Advanced Filters**: Search and filter gallery by style, date, etc. +- **Mobile Optimization**: Enhanced mobile experience +- **API Access**: Third-party integrations via API + +### Scalability Considerations +- **Multiple AI Providers**: Load balancing across providers +- **CDN Integration**: Faster image delivery globally +- **Database Optimization**: Handle large numbers of images efficiently +- **Caching Strategy**: Reduce redundant AI processing \ No newline at end of file diff --git a/prp/configuration-settings.md b/prp/configuration-settings.md new file mode 100644 index 0000000..0e4aa51 --- /dev/null +++ b/prp/configuration-settings.md @@ -0,0 +1,636 @@ +# Configuration and Settings Specification + +## Overview + +Comprehensive configuration management system using Laravel's settings with database storage, environment variables, and runtime configuration for flexible application behavior. + +## Configuration Architecture + +### Configuration Sources (Priority Order) + +1. **Runtime Settings** (Database) - User-configurable application behavior +2. **Environment Variables** (`.env`) - Sensitive and environment-specific settings +3. **Configuration Files** (`config/`) - Framework and package defaults +4. **Hardcoded Defaults** - Fallback values in code + +``` +┌─────────────────────────────────────────────────────────┐ +│ Runtime Settings (Database) │ +│ • User-configurable behavior │ +│ • Admin-managed settings │ +│ • Feature flags and toggles │ +└─────────────────────┬───────────────────────────────────┘ + │ Priority 1 (Highest) + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Environment Variables (.env) │ +│ • Sensitive credentials │ +│ • Environment-specific configuration │ +│ • Deployment-specific settings │ +└─────────────────────┬───────────────────────────────────┘ + │ Priority 2 + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Configuration Files (config/) │ +│ • Laravel framework settings │ +│ • Package configurations │ +│ • Default application behavior │ +└─────────────────────┬───────────────────────────────────┘ + │ Priority 3 + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Hardcoded Defaults │ +│ • Fallback values in code │ +│ • Emergency defaults │ +└─────────────────────────────────────────────────────────┘ +``` + +## Settings Model + +### Database Structure + +**Table**: `settings` + +**Schema**: +```sql +CREATE TABLE settings ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + key VARCHAR(255) UNIQUE NOT NULL, + value LONGTEXT NULL, + created_at TIMESTAMP NULL, + updated_at TIMESTAMP NULL +); +``` + +**Model**: `app/Models/Setting.php` + +**Key Features**: +- Unique constraint on `key` field +- `value` stored as LONGTEXT for flexibility (JSON, arrays, large strings) +- Automatic timestamps for audit trail + +### Setting Access Patterns + +**Simple Value Retrieval**: +```php +$value = Setting::where('key', 'app_name')->first()->value ?? 'Default Name'; +``` + +**Type-Safe Access**: +```php +// Boolean setting +$enabled = Setting::getBoolean('feature_enabled', false); + +// Integer setting +$maxImages = Setting::getInteger('max_images_per_user', 100); + +// JSON setting +$parameters = Setting::getJson('api_parameters', []); +``` + +## Configuration Categories + +### 1. Application Settings + +**Core Application Behavior**: + +```php +// Application Identity +'app_name' => 'AI StyleGallery' +'app_description' => 'Transform images with AI styles' +'app_url' => 'https://your-domain.com' + +// Gallery Behavior +'gallery_heading' => 'Meine Bildergalerie' +'default_style_id' => 1 +'new_image_timespan_minutes' => 60 +'image_refresh_interval' => 5 // seconds + +// Upload Configuration +'max_upload_size' => 10 // MB +'allowed_image_types' => 'jpeg,jpg,png,webp' +'auto_process_uploaded_images' => false + +// UI Configuration +'show_print_button' => true +'default_theme' => 'light' +'default_locale' => 'de' +``` + +### 2. AI Processing Settings + +**Processing Behavior**: +```php +// Timeout Configuration +'comfyui_timeout' => 180 // seconds +'runwareai_timeout' => 60 // seconds +'max_processing_time' => 300 // seconds + +// Retry Configuration +'max_retry_attempts' => 3 +'retry_delay' => 1000000 // microseconds + +// Queue Management +'max_concurrent_processes' => 3 +'process_queue_enabled' => true + +// Quality Settings +'default_output_quality' => 95 // JPEG quality +'enable_progressive_jpeg' => true +``` + +### 3. Storage Configuration + +**File Management**: +```php +// Storage Paths +'upload_path' => 'uploads/' +'style_preview_path' => 'style_previews/' +'temp_path' => 'temp/' + +// Cleanup Settings +'auto_cleanup_temp_files' => true +'temp_file_retention_hours' => 24 +'max_storage_per_user_gb' => 5 + +// CDN Configuration +'cdn_enabled' => false +'cdn_base_url' => 'https://cdn.your-domain.com' +``` + +### 4. Notification Settings + +**Communication Preferences**: +```php +// Email Settings +'email_notifications_enabled' => true +'admin_notification_email' => 'admin@your-domain.com' +'notification_from_email' => 'noreply@your-domain.com' + +// Processing Notifications +'notify_on_processing_start' => false +'notify_on_processing_complete' => true +'notify_on_processing_error' => true + +// Admin Alerts +'alert_on_high_error_rate' => true +'error_rate_threshold' => 10 // percentage +``` + +### 5. Security Settings + +**Security Configuration**: +```php +// Session Security +'session_lifetime' => 120 // minutes +'admin_session_lifetime' => 60 // minutes +'enable_session_fixation_protection' => true + +// Rate Limiting +'login_attempts_per_minute' => 5 +'api_rate_limit_per_hour' => 1000 + +// Content Security +'enable_csp' => true +'csp_report_only' => false +``` + +### 6. Performance Settings + +**Performance Optimization**: +```php +// Caching +'cache_enabled' => true +'cache_ttl' => 3600 // seconds +'style_cache_ttl' => 7200 // seconds + +// Image Optimization +'enable_lazy_loading' => true +'thumbnail_size' => 300 // pixels +'preview_quality' => 80 // JPEG quality + +// Database Optimization +'query_cache_enabled' => true +'eager_loading_enabled' => true +``` + +## Environment Configuration + +### Sensitive Configuration (`.env`) + +```bash +# Application +APP_NAME="AI StyleGallery" +APP_ENV=production +APP_KEY=base64:your-app-key-here +APP_URL=https://your-domain.com + +# Database +DB_CONNECTION=sqlite +DB_DATABASE=/path/to/database.sqlite + +# Mail Configuration +MAIL_MAILER=smtp +MAIL_HOST=smtp.your-provider.com +MAIL_PORT=587 +MAIL_USERNAME=your-email@domain.com +MAIL_PASSWORD=your-app-password +MAIL_ENCRYPTION=tls + +# Redis (for caching) +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +# Broadcasting (for real-time features) +BROADCAST_DRIVER=pusher +PUSHER_APP_ID=your-pusher-id +PUSHER_APP_KEY=your-pusher-key +PUSHER_APP_SECRET=your-pusher-secret +PUSHER_HOST=your-pusher-host +PUSHER_PORT=443 +PUSHER_SCHEME=https + +# AI Service Credentials +COMFYUI_API_URL=https://your-comfyui-server.com +COMFYUI_API_KEY=your-comfyui-key + +RUNWAREAI_API_URL=https://api.runwareai.com +RUNWAREAI_API_TOKEN=your-runwareai-token +``` + +## Configuration Files + +### Laravel Configuration (`config/`) + +#### `config/app.php` +```php +'locale' => env('APP_LOCALE', 'de'), +'timezone' => env('APP_TIMEZONE', 'Europe/Berlin'), +'key' => env('APP_KEY'), +'cipher' => 'AES-256-CBC', +``` + +#### `config/filesystems.php` +```php +'public' => [ + 'driver' => 'local', + 'root' => public_path('storage'), + 'url' => env('APP_URL').'/storage', + 'visibility' => 'public', +], +``` + +#### `config/filament.php` +```php +'brand' => [ + 'name' => env('APP_NAME', 'AI StyleGallery'), + 'logo' => '/images/logo.png', +], +'auth' => [ + 'guard' => 'web', + 'pages' => [ + 'login' => \App\Filament\Pages\Login::route('/login'), + ], +], +``` + +## Runtime Configuration Management + +### Setting Access Helpers + +**Location**: `app/Services/SettingsService.php` + +**Core Methods**: + +#### `get(string $key, $default = null)` +- Retrieves setting value with optional default +- Automatic type casting for common types + +#### `set(string $key, $value): void` +- Stores or updates setting value +- Handles type conversion and validation + +#### `getBoolean(string $key, bool $default = false): bool` +- Retrieves boolean setting with fallback + +#### `getInteger(string $key, int $default = 0): int` +- Retrieves integer setting with fallback + +#### `getJson(string $key, $default = []): array` +- Retrieves JSON setting as associative array + +**Usage Examples**: +```php +// Application settings +$appName = Settings::get('app_name', 'AI StyleGallery'); +$maxCopies = Settings::getInteger('max_print_copies', 10); +$features = Settings::getJson('enabled_features', []); + +// Feature flags +$printEnabled = Settings::getBoolean('show_print_button', true); +$notificationsEnabled = Settings::getBoolean('email_notifications_enabled', true); +``` + +### Configuration Caching + +**Cache Strategy**: +- Settings cached in Redis/memory for performance +- Automatic cache invalidation on setting changes +- Separate TTL for different setting categories + +**Implementation**: +```php +// Cache key pattern +'settings:' . $key => $value + +// Cache TTL by category +'application_settings' => 3600, // 1 hour +'ai_settings' => 1800, // 30 minutes +'security_settings' => 7200, // 2 hours +``` + +## Admin Configuration Interface + +### Filament Settings Management + +**Settings Resource**: `app/Filament/Resources/SettingResource.php` + +**Features**: +- **CRUD Interface**: Create, read, update, delete settings +- **Type Validation**: Ensure setting values match expected types +- **Bulk Operations**: Mass update related settings +- **Import/Export**: Backup and restore configuration +- **Validation**: Prevent invalid configuration values + +**Setting Types**: +- **Text**: Simple string values +- **Number**: Integer and float values +- **Boolean**: True/false toggles +- **JSON**: Complex configuration objects +- **Select**: Predefined option lists + +### Settings Categories + +**Organization**: +- **General**: Application name, description, URLs +- **Gallery**: Image handling, display options +- **AI Processing**: Provider settings, timeouts, quality +- **Storage**: File paths, cleanup, CDN settings +- **Notifications**: Email, alerts, communication +- **Security**: Authentication, rate limiting, privacy +- **Performance**: Caching, optimization, limits + +## Dynamic Configuration + +### Feature Flags + +**Implementation**: +```php +// Feature flag checking +if (Settings::getBoolean('enable_batch_processing', false)) { + // Enable batch processing features +} + +// Environment-specific features +if (app()->environment('production')) { + $features = Settings::getJson('production_features', []); +} else { + $features = Settings::getJson('development_features', []); +} +``` + +**Common Feature Flags**: +- `enable_printing`: Show/hide print functionality +- `enable_batch_processing`: Allow multiple image processing +- `enable_social_features`: User sharing capabilities +- `enable_advanced_styles`: Premium style options + +### Environment-Based Configuration + +**Automatic Configuration**: +```php +// Different settings per environment +$environment = app()->environment(); + +switch ($environment) { + case 'production': + $settings = Settings::getJson('production_overrides', []); + break; + case 'staging': + $settings = Settings::getJson('staging_overrides', []); + break; + default: + $settings = Settings::getJson('development_overrides', []); +} +``` + +## Configuration Validation + +### Setting Validation Rules + +**Validation Framework**: +```php +$rules = [ + 'app_name' => 'required|string|max:255', + 'max_upload_size' => 'required|integer|min:1|max:100', + 'allowed_image_types' => 'required|string', + 'comfyui_timeout' => 'required|integer|min:30|max:600', + 'cdn_enabled' => 'boolean', + 'api_parameters' => 'nullable|json', +]; +``` + +**Validation Implementation**: +```php +// Validate before saving +$validator = Validator::make($settings, $rules); +if ($validator->fails()) { + throw new ValidationException($validator->errors()); +} + +// Type conversion +$sanitizedValue = match($setting->type) { + 'boolean' => (bool) $value, + 'integer' => (int) $value, + 'json' => json_decode($value, true), + default => (string) $value, +}; +``` + +## Configuration Migration + +### Version Management + +**Configuration Versions**: +- Track configuration schema versions +- Automatic migration of configuration values +- Backup before major configuration changes + +**Migration Example**: +```php +// Configuration migration for new version +if ($currentVersion < 2.0) { + // Migrate old 'upload_size' to 'max_upload_size' + $oldValue = Settings::get('upload_size'); + if ($oldValue) { + Settings::set('max_upload_size', $oldValue * 1024 * 1024); // Convert MB to bytes + Settings::forget('upload_size'); + } +} +``` + +### Backup and Restore + +**Configuration Backup**: +```php +// Export all settings +$allSettings = Settings::all(); +$backup = [ + 'version' => config('app.version'), + 'timestamp' => now()->toISOString(), + 'settings' => $allSettings->pluck('value', 'key')->toArray(), +]; + +// Save to file +Storage::put('config-backup-' . date('Y-m-d-H-i-s') . '.json', json_encode($backup)); +``` + +## Monitoring and Analytics + +### Configuration Monitoring + +**Change Tracking**: +- Log all configuration changes +- Track who made changes and when +- Alert on critical configuration modifications + +**Performance Impact**: +- Monitor configuration load times +- Track cache hit/miss ratios +- Alert on configuration-related errors + +### Analytics Integration + +**Usage Analytics**: +```php +// Track feature usage +if (Settings::getBoolean('analytics_enabled', false)) { + Analytics::track('feature_used', [ + 'feature' => 'style_application', + 'style_id' => $style->id, + 'user_id' => auth()->id(), + ]); +} +``` + +## Security Considerations + +### Sensitive Configuration + +**Encryption**: +- Encrypt sensitive setting values in database +- Use Laravel's encryption helpers for sensitive data +- Separate encryption keys for different environments + +**Access Control**: +- Restrict sensitive settings to admin users only +- Audit trail for sensitive configuration changes +- Automatic masking in logs and exports + +### Configuration Injection Prevention + +**Input Sanitization**: +- Validate all configuration inputs +- Prevent code injection through configuration +- Escape special characters in configuration values + +## Deployment Configuration + +### Environment-Specific Settings + +**Deployment Pipeline**: +```php +// Production deployment +Settings::set('app_environment', 'production'); +Settings::set('cdn_enabled', true); +Settings::set('debug_mode', false); + +// Development deployment +Settings::set('app_environment', 'development'); +Settings::set('cdn_enabled', false); +Settings::set('debug_mode', true); +``` + +### Configuration Synchronization + +**Multi-Server Setup**: +- Synchronize configuration across web servers +- Handle configuration updates without downtime +- Validate configuration consistency + +## Troubleshooting Configuration + +### Common Issues + +**Configuration Not Loading**: +- Check database connectivity +- Verify settings table exists +- Validate setting key names + +**Performance Issues**: +- Monitor configuration cache hit rates +- Check for configuration-related database queries +- Optimize frequently accessed settings + +**Type Mismatches**: +- Ensure proper type casting in code +- Validate setting types in admin interface +- Handle legacy configuration gracefully + +### Debug Tools + +**Configuration Inspector**: +```php +// Development-only configuration debugging +if (app()->environment('local')) { + Route::get('/admin/config-debug', function () { + return [ + 'all_settings' => Settings::all(), + 'environment' => app()->environment(), + 'cached_settings' => Cache::get('settings:*'), + ]; + }); +} +``` + +## Future Configuration Enhancements + +### Advanced Features + +**Configuration Templates**: +- Predefined configuration sets for different use cases +- One-click configuration application +- Configuration comparison and diff tools + +**Dynamic Configuration**: +- Real-time configuration updates +- Hot-reloading of configuration changes +- A/B testing for configuration options + +**External Configuration**: +- Integration with external configuration management systems +- Cloud-based configuration storage +- Configuration sharing across projects + +### Configuration API + +**RESTful Configuration Management**: +- API endpoints for configuration management +- Version control for configuration changes +- Configuration validation via API + +**Webhook Integration**: +- Notify external systems of configuration changes +- Trigger deployments on configuration updates +- Integrate with monitoring and alerting systems \ No newline at end of file diff --git a/prp/data-models.md b/prp/data-models.md new file mode 100644 index 0000000..b9c89bc --- /dev/null +++ b/prp/data-models.md @@ -0,0 +1,340 @@ +# Data Models Specification + +## Entity Relationship Diagram + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ User │ +│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ Role │ │ Setting │ │ Image │ │ +│ │ • id │ │ • id │ │ • id │ │ +│ │ • name │ │ • key │ │ • uuid │ │ +│ │ • timestamps │ │ • value │ │ • path │ │ +│ └─────────────────┘ │ • timestamps │ │ • is_temp │ │ +│ │ 1 │ └─────────────────┘ │ • is_public │ │ +│ ▼ │ │ 1 │ • timestamps │ │ +│ ┌─────────────────┐ │ ▼ └─────────────────┘ │ +│ │ • id │ │ ┌─────────────────┐ │ +│ │ • name │ │ │ ApiProvider │ │ +│ │ • email │ │ │ • id │ │ +│ │ • password │ │ │ • name │ │ +│ │ • role_id │ │ │ • api_url │ │ +│ │ • timestamps │ │ │ • username │ │ +│ │ • 2FA fields │ │ │ • password │ │ +│ └─────────────────┘ │ │ • token │ │ +│ │ │ │ • plugin │ │ +│ ▼ │ │ • enabled │ │ +│ ┌─────────────────┐ │ │ • timestamps │ │ +│ │ Style │◄─┘ └─────────────────┘ │ +│ │ • id │ │ 1 │ +│ │ • title │ ▼ │ +│ │ • prompt │ ┌─────────────────┐ │ +│ │ • description │ │ AiModel │ │ +│ │ • preview_img │ │ • id │ │ +│ │ • parameters │ │ • name │ │ +│ │ • ai_model_id │ │ • model_id │ │ +│ │ • enabled │ │ • model_type │ │ +│ │ • sort_order │ │ • api_provider │ │ +│ │ • timestamps │ │ • parameters │ │ +│ └─────────────────┘ │ • enabled │ │ +│ │ │ • timestamps │ │ +│ ▼ │ └─────────────────┘ │ +│ ┌─────────────────┐ │ │ +│ │ Original │◄┘ │ +│ │ Image │ │ +│ └─────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Model Specifications + +### 1. User Model + +**Purpose**: Represents authenticated users of the application + +**Table**: `users` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +name: varchar(255) // User's display name +email: varchar(255) unique // Unique email address +password: varchar(255) // Hashed password +role_id: bigint unsigned nullable // Foreign key to roles table +email_notifications_enabled: tinyint(1) default(1) // Email notification preference +theme_preference: varchar(255) default('light') // UI theme preference +locale: varchar(255) default('en') // Language preference +two_factor_secret: text nullable // 2FA secret key +two_factor_recovery_codes: text nullable // 2FA backup codes +two_factor_confirmed_at: timestamp nullable // 2FA confirmation timestamp +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **BelongsTo**: Role (one user has one role) +- **HasMany**: Images (one user can have many images) + +**Business Rules**: +- Email must be unique across all users +- Password must be hashed using secure algorithm +- Role determines permissions and access levels +- 2FA fields are optional but provide enhanced security + +--- + +### 2. Role Model + +**Purpose**: Defines user roles for access control + +**Table**: `roles` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +name: varchar(255) unique // Role name (e.g., 'admin', 'user') +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **HasMany**: Users (one role can have many users) + +**Business Rules**: +- Role names must be unique +- Predefined roles: 'admin', 'user' +- Used by Filament for access control + +--- + +### 3. Image Model + +**Purpose**: Stores metadata for uploaded and AI-generated images + +**Table**: `images` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +uuid: char(36) unique nullable // Unique identifier for tracking +path: varchar(255) // File path relative to storage disk +original_image_id: bigint unsigned nullable // FK to original image (for styled images) +style_id: bigint unsigned nullable // FK to applied style +is_temp: tinyint(1) default(0) // True for temporary styled images +is_public: tinyint(1) default(1) // True for publicly visible images +comfyui_prompt_id: varchar(255) nullable // Tracking ID from ComfyUI +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **BelongsTo**: Style (many images can use one style) +- **BelongsTo**: Original Image (self-referencing, styled images reference originals) +- **HasMany**: Styled Images (self-referencing, original images have many styled versions) + +**Business Rules**: +- UUID is generated for tracking and external references +- Original images have `original_image_id` = null +- Styled images reference original via `original_image_id` +- Temporary images (`is_temp = true`) are pending user decision +- Public images (`is_public = true`) are visible to all users +- ComfyUI prompt ID tracks processing jobs + +--- + +### 4. Style Model + +**Purpose**: Defines AI artistic styles available for image transformation + +**Table**: `styles` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +title: varchar(255) // Display name of the style +prompt: longtext // AI prompt describing the style +description: longtext // Human-readable description +preview_image: varchar(255) // Path to style preview image +parameters: json nullable // Additional AI parameters (cast to array) +ai_model_id: bigint unsigned // FK to associated AI model +enabled: tinyint(1) default(1) // Whether style is active +sort_order: integer default(0) // Display order in UI +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **BelongsTo**: AiModel (many styles can use one AI model) +- **HasMany**: Images (one style can be applied to many images) + +**Business Rules**: +- Only enabled styles are available to users +- Preview images help users choose appropriate styles +- Parameters are JSON and merged with AI model parameters +- Sort order controls display sequence in style selector + +--- + +### 5. AiModel Model + +**Purpose**: Represents specific AI models available through providers + +**Table**: `ai_models` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +name: varchar(255) // Human-readable model name +model_id: varchar(255) // Identifier used by AI service +model_type: varchar(255) nullable // Type/category (e.g., 'Stable Diffusion') +parameters: json nullable // Default parameters (cast to array) +api_provider_id: bigint unsigned nullable // FK to primary API provider +enabled: tinyint(1) default(1) // Whether model is active +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **BelongsTo**: ApiProvider (many models can use one provider) +- **HasMany**: Styles (one model can have many styles) + +**Business Rules**: +- Model ID must match identifier expected by AI service +- Only enabled models are available for new styles +- Parameters provide defaults, merged with style parameters +- Primary API provider handles communication for this model + +--- + +### 6. ApiProvider Model + +**Purpose**: Configures connections to external AI services + +**Table**: `api_providers` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +name: varchar(255) // Provider name (e.g., 'ComfyUI Production') +api_url: varchar(255) // Base URL of AI service +username: varchar(255) nullable // Authentication username +password: varchar(255) nullable // Authentication password +token: varchar(255) nullable // API token/key +plugin: varchar(255) // Plugin identifier (e.g., 'comfyui', 'runwareai') +enabled: tinyint(1) default(1) // Whether provider is active +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: +- **HasMany**: AiModels (one provider can serve many models) +- **HasMany**: Styles (indirectly through AI models) + +**Business Rules**: +- Plugin field determines which adapter to use +- Only enabled providers are available for processing +- Authentication credentials are encrypted/stored securely +- API URL must be valid and accessible + +--- + +### 7. Setting Model + +**Purpose**: Stores application-wide configuration settings + +**Table**: `settings` + +**Attributes**: +```php +id: bigint unsigned auto_increment primary key +key: varchar(255) unique // Setting identifier +value: longtext nullable // Setting value (can be JSON) +created_at: timestamp nullable +updated_at: timestamp nullable +``` + +**Relationships**: None (standalone configuration storage) + +**Business Rules**: +- Keys must be unique across application +- Values can be simple strings or complex JSON +- Used for various configuration needs throughout app + +## Data Integrity Constraints + +### Foreign Key Relationships +- `users.role_id` → `roles.id` (nullable, defaults to user role) +- `images.original_image_id` → `images.id` (nullable, self-referencing) +- `images.style_id` → `styles.id` (nullable) +- `styles.ai_model_id` → `ai_models.id` (required) +- `ai_models.api_provider_id` → `api_providers.id` (nullable) + +### Unique Constraints +- `users.email` (unique) +- `roles.name` (unique) +- `images.uuid` (unique, nullable) +- `settings.key` (unique) + +### Check Constraints +- `images.is_temp` ∈ {0, 1} +- `images.is_public` ∈ {0, 1} +- `styles.enabled` ∈ {0, 1} +- `ai_models.enabled` ∈ {0, 1} +- `api_providers.enabled` ∈ {0, 1} + +## Data Types & Casting + +### Automatic Casting +- **Boolean Fields**: `enabled`, `is_temp`, `is_public` → boolean +- **JSON Fields**: `parameters` (in styles, ai_models) → array +- **Timestamps**: `created_at`, `updated_at` → datetime + +### File Paths +- All image paths are relative to storage disk +- Preview images stored in `storage/app/public/style_previews/` +- Uploaded images stored in `storage/app/public/uploads/` + +## Business Logic Implementation + +### Image Path Resolution +- **Storage Disk**: Uses 'public' disk configuration +- **URL Generation**: `asset('storage/' . $image->path)` +- **File Location**: `public_path('storage/' . $image->path)` + +### Parameter Merging +- **Style Parameters**: Override AI model parameters +- **Merge Strategy**: `array_replace_recursive($modelParams, $styleParams)` +- **Placeholder Replacement**: `__PROMPT__`, `__FILENAME__`, `__MODEL_ID__` + +### UUID Usage +- **Image Tracking**: Unique identifier for external references +- **Generation**: Laravel's `HasUuids` trait or manual generation +- **Uniqueness**: Enforced by unique database constraint + +## Data Access Patterns + +### Common Queries +- **User Images**: `$user->images()` - all images for a user +- **Public Images**: `Image::where('is_public', true)` +- **Active Styles**: `Style::where('enabled', true)->with('aiModel')` +- **Enabled Models**: `AiModel::where('enabled', true)->with('primaryApiProvider')` + +### Query Optimization +- **Eager Loading**: Styles load AI models and providers +- **Soft Deletes**: Not implemented (permanent deletion) +- **Indexing**: Consider indexes on frequently queried fields + +## Migration Strategy + +### Future Enhancements +- **Image Metadata**: EXIF data, dimensions, file size +- **Processing History**: Track all transformations applied to images +- **User Preferences**: Default styles, notification settings +- **Batch Operations**: Multiple image processing, bulk style application +- **Tagging System**: Categorize images with custom tags +- **Sharing Features**: Public galleries, social features + +### Schema Evolution +- **Version Control**: Each model change requires migration +- **Backward Compatibility**: Maintain existing data integrity +- **Testing**: Validate schema changes against business rules \ No newline at end of file diff --git a/prp/deployment-requirements.md b/prp/deployment-requirements.md new file mode 100644 index 0000000..acde1f1 --- /dev/null +++ b/prp/deployment-requirements.md @@ -0,0 +1,1164 @@ +# Deployment Requirements Specification + +## Overview + +Complete deployment guide for AI StyleGallery, including system requirements, dependency management, environment configuration, and operational procedures for production deployment. + +## System Requirements + +### Server Requirements + +#### Minimum Specifications +- **Operating System**: Linux (Ubuntu 20.04+, CentOS 8+, Debian 11+) +- **Web Server**: Apache 2.4+ or Nginx 1.20+ +- **Database**: SQLite 3.8+ (default) or MySQL 8.0+/PostgreSQL 13+ +- **PHP Version**: 8.3+ with extensions +- **Memory**: 2GB RAM minimum, 4GB recommended +- **Storage**: 10GB minimum, 50GB recommended +- **Network**: Stable internet connection for AI services + +#### Recommended Production Setup +- **Operating System**: Ubuntu 22.04 LTS +- **Web Server**: Nginx 1.24+ with PHP-FPM +- **Database**: PostgreSQL 15+ for production workloads +- **Redis**: 7.0+ for caching and sessions +- **SSL/TLS**: Let's Encrypt or commercial certificate + +### PHP Requirements + +#### Required Extensions +```bash +# Core extensions +php8.3-cli +php8.3-common +php8.3-fpm +php8.3-mysql # or php8.3-pgsql for PostgreSQL +php8.3-sqlite3 +php8.3-redis +php8.3-curl +php8.3-gd +php8.3-mbstring +php8.3-xml +php8.3-zip +php8.3-bcmath +php8.3-intl + +# Development extensions (recommended) +php8.3-xdebug # For development only +``` + +#### PHP Configuration (`php.ini`) +```ini +# Performance settings +memory_limit = 256M +max_execution_time = 300 +max_input_time = 300 +upload_max_filesize = 10M +post_max_size = 12M + +# Error handling +display_errors = Off +display_startup_errors = Off +error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT +log_errors = On +error_log = /var/log/php/error.log + +# Security +expose_php = Off +allow_url_fopen = Off +allow_url_include = Off + +# Session security +session.cookie_httponly = 1 +session.cookie_secure = 1 +session.use_strict_mode = 1 + +# OPcache (recommended for production) +opcache.enable = 1 +opcache.memory_consumption = 128 +opcache.max_accelerated_files = 10000 +opcache.validate_timestamps = 1 +``` + +## Dependency Management + +### PHP Dependencies (Composer) + +#### Production Dependencies +```json +{ + "require": { + "php": "^8.3", + "laravel/framework": "^12.0", + "laravel/tinker": "^2.10", + "filament/filament": "^3.3", + "laravel/sanctum": "^4.0", + "predis/predis": "^2.0", + "nesbot/carbon": "^3.0", + "ramsey/uuid": "^4.0", + "guzzlehttp/guzzle": "^7.0" + } +} +``` + +#### Development Dependencies +```json +{ + "require-dev": { + "phpunit/phpunit": "^12.0", + "laravel/pint": "^1.0", + "laravel/sail": "^1.0", + "spatie/laravel-ignition": "^2.0", + "fakerphp/faker": "^1.23", + "laravel/dusk": "^8.0" + } +} +``` + +### Node.js Dependencies (npm/yarn) + +#### Production Dependencies +```json +{ + "dependencies": { + "axios": "^1.11.0", + "vue": "^3.5.0", + "@inertiajs/vue3": "^1.3.0", + "tailwindcss": "^3.4.0", + "autoprefixer": "^10.4.0", + "postcss": "^8.5.0", + "@fortawesome/fontawesome-svg-core": "^7.0.0", + "@fortawesome/free-solid-svg-icons": "^7.0.0", + "@fortawesome/vue-fontawesome": "^3.1.0", + "vanilla-lazyload": "^19.1.0" + } +} +``` + +#### Development Dependencies +```json +{ + "devDependencies": { + "@vitejs/plugin-vue": "^5.2.0", + "laravel-vite-plugin": "^1.0.0", + "vite": "^5.4.0", + "@tailwindcss/forms": "^0.5.0", + "laravel-echo": "^2.1.0", + "pusher-js": "^8.4.0" + } +} +``` + +## Environment Configuration + +### Environment Variables (`.env`) + +#### Required Variables +```bash +# Application +APP_NAME="AI StyleGallery" +APP_ENV=production +APP_KEY=base64:your-generated-app-key +APP_DEBUG=false +APP_URL=https://your-domain.com + +# Database (SQLite default) +DB_CONNECTION=sqlite +DB_DATABASE=/path/to/storage/database.sqlite + +# Alternative Database (MySQL/PostgreSQL) +# DB_CONNECTION=mysql +# DB_HOST=127.0.0.1 +# DB_PORT=3306 +# DB_DATABASE=ai_stylegallery +# DB_USERNAME=your-db-user +# DB_PASSWORD=your-db-password + +# Redis (recommended for production) +REDIS_CLIENT=phpredis +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +# Mail Configuration +MAIL_MAILER=smtp +MAIL_HOST=smtp.your-provider.com +MAIL_PORT=587 +MAIL_USERNAME=your-email@domain.com +MAIL_PASSWORD=your-app-password +MAIL_ENCRYPTION=tls +MAIL_FROM_ADDRESS=noreply@your-domain.com +MAIL_FROM_NAME="${APP_NAME}" + +# Broadcasting (for real-time features) +BROADCAST_CONNECTION=pusher +PUSHER_APP_ID=your-pusher-id +PUSHER_APP_KEY=your-pusher-key +PUSHER_APP_SECRET=your-pusher-secret +PUSHER_HOST=api.pusherapp.com +PUSHER_PORT=443 +PUSHER_SCHEME=https +PUSHER_APP_CLUSTER=your-cluster + +# Queue (for background processing) +QUEUE_CONNECTION=database + +# Filesystem +FILESYSTEM_DISK=local + +# Sanctum (API authentication) +SANCTUM_STATEFUL_DOMAINS=your-domain.com +``` + +#### AI Provider Configuration +```bash +# ComfyUI Configuration +COMFYUI_API_URL=https://your-comfyui-server.com +COMFYUI_API_KEY=your-comfyui-api-key +COMFYUI_TIMEOUT=180 +COMFYUI_MAX_RETRIES=3 + +# RunwareAI Configuration +RUNWAREAI_API_URL=https://api.runwareai.com +RUNWAREAI_API_TOKEN=your-runwareai-token +RUNWAREAI_TIMEOUT=60 +RUNWAREAI_RATE_LIMIT_DELAY=1000 + +# Additional providers can be added here +``` + +## Installation and Setup + +### Automated Deployment Script + +#### Deploy Script (`deploy.sh`) +```bash +#!/bin/bash + +set -e # Exit on any error + +echo "🚀 Starting AI StyleGallery deployment..." + +# Variables +APP_DIR="/var/www/ai-stylegallery" +BACKUP_DIR="/var/backups/ai-stylegallery" +TIMESTAMP=$(date +%Y%m%d_%H%M%S) + +# Create backup +echo "📦 Creating backup..." +mkdir -p "$BACKUP_DIR" +tar -czf "$BACKUP_DIR/backup_$TIMESTAMP.tar.gz" -C "$(dirname "$APP_DIR")" "$(basename "$APP_DIR")" + +# Navigate to app directory +cd "$APP_DIR" + +# Backup current .env +cp .env ".env.backup.$TIMESTAMP" + +# Pull latest changes +echo "📥 Pulling latest changes..." +git pull origin main + +# Install PHP dependencies +echo "📦 Installing PHP dependencies..." +composer install --no-dev --optimize-autoloader + +# Install Node.js dependencies +echo "📦 Installing Node.js dependencies..." +npm ci + +# Build assets +echo "🔨 Building frontend assets..." +npm run build + +# Run database migrations +echo "🗄️ Running database migrations..." +php artisan migrate --force + +# Clear caches +echo "🧹 Clearing caches..." +php artisan config:clear +php artisan route:clear +php artisan view:clear +php artisan event:clear + +# Optimize application +echo "⚡ Optimizing application..." +php artisan optimize + +# Set proper permissions +echo "🔐 Setting permissions..." +chown -R www-data:www-data storage bootstrap/cache +chmod -R 755 storage bootstrap/cache +chmod -R 644 storage/logs/*.log + +# Restart web server +echo "🔄 Restarting web server..." +sudo systemctl reload nginx +sudo systemctl restart php8.3-fpm + +# Run health check +echo "🏥 Running health check..." +sleep 10 +curl -f https://your-domain.com/api/health || exit 1 + +echo "✅ Deployment completed successfully!" +echo "📋 Backup saved as: $BACKUP_DIR/backup_$TIMESTAMP.tar.gz" +``` + +### Manual Installation Steps + +#### 1. System Preparation +```bash +# Update system packages +sudo apt update && sudo apt upgrade -y + +# Install required software +sudo apt install -y nginx php8.3 php8.3-fpm php8.3-cli php8.3-common php8.3-mysql php8.3-sqlite3 php8.3-redis php8.3-curl php8.3-gd php8.3-mbstring php8.3-xml php8.3-zip php8.3-bcmath php8.3-intl + +# Install Composer +curl -sS https://getcomposer.org/installer | php +sudo mv composer.phar /usr/local/bin/composer + +# Install Node.js and npm +curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - +sudo apt install -y nodejs + +# Install Redis +sudo apt install -y redis-server + +# Start and enable Redis +sudo systemctl start redis-server +sudo systemctl enable redis-server +``` + +#### 2. Application Setup +```bash +# Create application directory +sudo mkdir -p /var/www/ai-stylegallery +sudo chown www-data:www-data /var/www/ai-stylegallery + +# Clone repository (or upload files) +git clone https://github.com/your-repo/ai-stylegallery.git /var/www/ai-stylegallery +cd /var/www/ai-stylegallery + +# Install PHP dependencies +composer install --no-dev + +# Install Node.js dependencies +npm install + +# Copy environment file +cp .env.example .env + +# Generate application key +php artisan key:generate + +# Configure database +touch database/database.sqlite +php artisan migrate + +# Build frontend assets +npm run build + +# Set permissions +sudo chown -R www-data:www-data storage bootstrap/cache +chmod -R 755 storage bootstrap/cache +``` + +#### 3. Web Server Configuration + +##### Nginx Configuration (`/etc/nginx/sites-available/ai-stylegallery`) +```nginx +server { + listen 80; + server_name your-domain.com; + root /var/www/ai-stylegallery/public; + + # Security headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # Handle static assets + location / { + try_files $uri $uri/ /index.php?$query_string; + } + + # PHP processing + location ~ \.php$ { + include snippets/fastcgi-php.conf; + fastcgi_pass unix:/var/run/php/php8.3-fpm.sock; + fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; + include fastcgi_params; + fastcgi_read_timeout 300; + } + + # Static assets caching + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + try_files $uri @proxy; + } + + # Deny access to sensitive files + location ~ /\.ht { + deny all; + } + + # API routes (optional, for better handling) + location /api/ { + try_files $uri $uri/ /index.php?$query_string; + } + + # Health check endpoint + location /health { + access_log off; + return 200 "healthy\n"; + add_header Content-Type text/plain; + } +} + +server { + listen 443 ssl http2; + server_name your-domain.com; + # SSL configuration... + # Same directives as above... +} +``` + +##### Apache Configuration (Alternative) +```apache + + ServerName your-domain.com + DocumentRoot /var/www/ai-stylegallery/public + + + Options -Indexes +FollowSymLinks + AllowOverride All + Require all granted + + + # Security headers + Header always set X-Frame-Options "SAMEORIGIN" + Header always set X-Content-Type-Options "nosniff" + Header always set X-XSS-Protection "1; mode=block" + Header always set Referrer-Policy "strict-origin-when-cross-origin" + + # Handle PHP files + + SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost" + + + # Health check + + Require all granted + Header set Content-Type "text/plain" + Header set Cache-Control "no-cache, no-store, must-revalidate" + + + ErrorLog ${APACHE_LOG_DIR}/ai-stylegallery_error.log + CustomLog ${APACHE_LOG_DIR}/ai-stylegallery_access.log combined + +``` + +## Operational Procedures + +### Database Management + +#### Backup Strategy +```bash +# Daily database backup +#!/bin/bash +BACKUP_DIR="/var/backups/ai-stylegallery" +mkdir -p "$BACKUP_DIR" + +# SQLite backup (default) +cp /var/www/ai-stylegallery/database/database.sqlite "$BACKUP_DIR/db_$(date +%Y%m%d_%H%M%S).sqlite" + +# MySQL backup (if using MySQL) +# mysqldump -h localhost -u username -p password ai_stylegallery > "$BACKUP_DIR/db_$(date +%Y%m%d_%H%M%S).sql" + +# Compress and cleanup old backups +find "$BACKUP_DIR" -name "db_*" -type f -mtime +7 -delete +``` + +#### Migration Management +```bash +# Run migrations +php artisan migrate + +# Rollback if needed +php artisan migrate:rollback + +# Check migration status +php artisan migrate:status + +# Seed database (for initial data) +php artisan db:seed +``` + +### File Storage Management + +#### Storage Structure +``` +/var/www/ai-stylegallery/ +├── storage/ +│ ├── app/ +│ │ ├── public/ +│ │ │ ├── uploads/ # User uploaded images +│ │ │ └── style_previews/ # AI style preview images +│ │ └── .gitignore +│ ├── framework/ +│ │ ├── cache/ +│ │ ├── sessions/ +│ │ └── views/ +│ ├── logs/ # Application logs +│ └── .gitignore +``` + +#### Storage Permissions +```bash +# Set proper ownership +sudo chown -R www-data:www-data /var/www/ai-stylegallery/storage + +# Set proper permissions +sudo chmod -R 755 /var/www/ai-stylegallery/storage +sudo chmod -R 644 /var/www/ai-stylegallery/storage/logs/*.log + +# Create symbolic link (if needed) +php artisan storage:link +``` + +### Log Management + +#### Log Configuration +```php +// config/logging.php +'channels' => [ + 'stack' => [ + 'driver' => 'stack', + 'channels' => ['single', 'daily'], + ], + 'single' => [ + 'driver' => 'single', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + ], + 'daily' => [ + 'driver' => 'daily', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'days' => 14, + ], +], +``` + +#### Log Rotation +```bash +# Logrotate configuration (/etc/logrotate.d/ai-stylegallery) +/var/www/ai-stylegallery/storage/logs/*.log { + daily + rotate 30 + compress + delaycompress + missingok + notifempty + create 644 www-data www-data + postrotate + systemctl reload nginx + endscript +} +``` + +### Monitoring and Health Checks + +#### Health Check Endpoint +```php +// routes/web.php +Route::get('/health', function () { + try { + // Database check + DB::connection()->getPdo(); + + // Storage check + Storage::disk('public')->exists('test'); + + // Cache check + Cache::store('redis')->put('health', 'ok', 10); + + return response()->json([ + 'status' => 'healthy', + 'timestamp' => now()->toISOString(), + 'version' => config('app.version'), + ]); + } catch (Exception $e) { + return response()->json([ + 'status' => 'unhealthy', + 'error' => $e->getMessage(), + 'timestamp' => now()->toISOString(), + ], 503); + } +}); +``` + +#### Monitoring Setup +```bash +# Install monitoring tools +sudo apt install -y htop iotop nethogs + +# Set up log monitoring +sudo apt install -y logwatch + +# Configure process monitoring +sudo apt install -y monit + +# Monit configuration for AI StyleGallery +# /etc/monit/conf.d/ai-stylegallery +check process php-fpm with pidfile /var/run/php/php8.3-fpm.pid + start program = "/etc/init.d/php8.3-fpm start" + stop program = "/etc/init.d/php8.3-fpm stop" + if cpu > 60% for 2 cycles then alert + if memory usage > 80% for 5 cycles then alert + +check process nginx with pidfile /var/run/nginx.pid + start program = "/etc/init.d/nginx start" + stop program = "/etc/init.d/nginx stop" + if cpu > 60% for 2 cycles then alert + if memory usage > 80% for 5 cycles then alert +``` + +## Security Hardening + +### Firewall Configuration +```bash +# UFW (Uncomplicated Firewall) +sudo ufw allow 'OpenSSH' +sudo ufw allow 'Nginx Full' +sudo ufw --force enable + +# Advanced firewall rules +sudo ufw allow from your-admin-ip to any port 22 +sudo ufw allow from your-office-ip-range to any port 80 +sudo ufw allow from your-office-ip-range to any port 443 +``` + +### SSL/TLS Setup +```bash +# Install Certbot for Let's Encrypt +sudo apt install -y certbot python3-certbot-nginx + +# Generate SSL certificate +sudo certbot --nginx -d your-domain.com -d www.your-domain.com + +# Auto-renewal (add to crontab) +sudo crontab -e +# Add: 0 12 * * * /usr/bin/certbot renew --quiet +``` + +### Security Updates +```bash +# Automated security updates +sudo apt install -y unattended-upgrades +sudo dpkg-reconfigure -plow unattended-upgrades + +# Manual security updates +sudo apt update && sudo apt upgrade -y +sudo apt autoremove -y +sudo apt autoclean +``` + +## Performance Optimization + +### PHP-FPM Optimization +```ini +# /etc/php/8.3/fpm/pool.d/www.conf +pm = dynamic +pm.max_children = 50 +pm.start_servers = 5 +pm.min_spare_servers = 5 +pm.max_spare_servers = 35 +pm.max_requests = 500 + +# Process manager settings +pm.process_idle_timeout = 10s +pm.max_requests = 1000 + +# Memory optimization +php_admin_value[memory_limit] = 256M +php_admin_flag[opcache.enable] = 1 +``` + +### MySQL Optimization (if using MySQL) +```ini +# /etc/mysql/mysql.conf.d/mysqld.cnf +[mysqld] +innodb_buffer_pool_size = 1G +innodb_log_file_size = 256M +innodb_flush_log_at_trx_commit = 2 +query_cache_size = 0 +query_cache_type = 0 +innodb_flush_method = O_DIRECT + +# Connection settings +max_connections = 100 +wait_timeout = 28800 +interactive_timeout = 28800 +``` + +### Nginx Optimization +```nginx +# Performance optimizations +worker_processes auto; +worker_rlimit_nofile 1024; + +events { + worker_connections 1024; + use epoll; + multi_accept on; +} + +http { + # Caching + proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_proxied expired no-cache no-store private must-revalidate auth; + gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; + + # Rate limiting + limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; + limit_req_zone $binary_remote_addr zone=upload:10m rate=2r/s; +} +``` + +## Troubleshooting + +### Common Issues + +#### Application Not Loading +```bash +# Check PHP-FPM status +sudo systemctl status php8.3-fpm + +# Check Nginx status +sudo systemctl status nginx + +# Check application logs +tail -f /var/www/ai-stylegallery/storage/logs/laravel.log + +# Test PHP processing +php -f /var/www/ai-stylegallery/public/index.php +``` + +#### Database Connection Issues +```bash +# Test database connection +php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database connected';" + +# Check database file permissions (SQLite) +ls -la /var/www/ai-stylegallery/database/database.sqlite + +# Check database configuration +php artisan config:cache +php artisan config:clear +``` + +#### File Upload Issues +```bash +# Check storage permissions +ls -la /var/www/ai-stylegallery/storage/app/public/ + +# Check PHP upload settings +php -i | grep upload + +# Test file upload +php -r "move_uploaded_file('/tmp/test.txt', '/var/www/ai-stylegallery/storage/app/public/uploads/test.txt');" +``` + +#### AI Service Connection Issues +```bash +# Test ComfyUI connection +curl -X GET "https://your-comfyui-server.com/queue" + +# Test RunwareAI connection +curl -X POST "https://api.runwareai.com" \ + -H "Authorization: Bearer your-token" \ + -H "Content-Type: application/json" \ + -d '{"taskType": "authentication", "apiKey": "your-token"}' + +# Check API provider configuration +php artisan tinker --execute="App\Models\ApiProvider::all()" +``` + +### Debug Mode + +#### Enable Debug Mode (Development Only) +```bash +# Edit .env file +APP_DEBUG=true +LOG_LEVEL=debug + +# Clear config cache +php artisan config:clear + +# Check detailed error logs +tail -f /var/www/ai-stylegallery/storage/logs/laravel.log +``` + +#### Performance Profiling +```bash +# Enable query logging +php artisan tinker --execute="DB::enableQueryLog();" + +# Profile application performance +php artisan tinker --execute="dump(app()->getLoadedProviders());" + +# Memory usage +php -r "echo 'Memory usage: ' . memory_get_peak_usage(true) / 1024 / 1024 . 'MB';" +``` + +## Backup and Recovery + +### Complete System Backup +```bash +#!/bin/bash +# Full system backup script + +BACKUP_DIR="/var/backups/ai-stylegallery" +APP_DIR="/var/www/ai-stylegallery" +TIMESTAMP=$(date +%Y%m%d_%H%M%S) + +# Create backup directory +mkdir -p "$BACKUP_DIR" + +# Backup application files +tar -czf "$BACKUP_DIR/app_$TIMESTAMP.tar.gz" -C "$(dirname "$APP_DIR")" "$(basename "$APP_DIR")" + +# Backup database +cp "$APP_DIR/database/database.sqlite" "$BACKUP_DIR/db_$TIMESTAMP.sqlite" + +# Backup Nginx configuration +cp /etc/nginx/sites-available/ai-stylegallery "$BACKUP_DIR/nginx_config_$TIMESTAMP" + +# Backup SSL certificates +cp -r /etc/letsencrypt/live/your-domain.com "$BACKUP_DIR/ssl_$TIMESTAMP" + +# Cleanup old backups (keep 7 days) +find "$BACKUP_DIR" -type f -mtime +7 -delete + +echo "Backup completed: $BACKUP_DIR/backup_$TIMESTAMP" +``` + +### Recovery Procedure +```bash +#!/bin/bash +# Recovery script + +BACKUP_DIR="/var/backups/ai-stylegallery" +APP_DIR="/var/www/ai-stylegallery" + +# Stop services +sudo systemctl stop nginx php8.3-fpm + +# Restore application files +LATEST_BACKUP=$(ls -t "$BACKUP_DIR/app_"*.tar.gz | head -1) +sudo tar -xzf "$LATEST_BACKUP" -C "$(dirname "$APP_DIR")" + +# Restore database +LATEST_DB=$(ls -t "$BACKUP_DIR/db_"*.sqlite | head -1) +cp "$LATEST_DB" "$APP_DIR/database/database.sqlite" + +# Restore Nginx configuration +LATEST_NGINX=$(ls -t "$BACKUP_DIR/nginx_config_"* | head -1) +sudo cp "$LATEST_NGINX" /etc/nginx/sites-available/ai-stylegallery + +# Set permissions +sudo chown -R www-data:www-data "$APP_DIR" +sudo chmod -R 755 "$APP_DIR/storage" "$APP_DIR/bootstrap/cache" + +# Start services +sudo systemctl start php8.3-fpm nginx + +# Test recovery +curl -f https://your-domain.com/health || exit 1 + +echo "Recovery completed successfully!" +``` + +## Scaling Considerations + +### Horizontal Scaling + +#### Load Balancer Setup +```nginx +# Load balancer configuration +upstream ai-stylegallery_backend { + server 192.168.1.10:80; + server 192.168.1.11:80; + server 192.168.1.12:80; + + # Health checks + keepalive 32; +} + +server { + listen 80; + server_name your-domain.com; + + location / { + proxy_pass http://ai-stylegallery_backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Health check + proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; + } +} +``` + +#### Shared Storage +```bash +# NFS shared storage for uploads +sudo apt install -y nfs-kernel-server +sudo mkdir -p /var/nfs/ai-stylegallery +sudo chown www-data:www-data /var/nfs/ai-stylegallery + +# Mount on web servers +sudo mount -t nfs storage-server:/var/nfs/ai-stylegallery /var/www/ai-stylegallery/storage/app/public +``` + +### Database Scaling + +#### Read Replicas +```bash +# MySQL read replica setup +CHANGE MASTER TO + MASTER_HOST='master-db-server', + MASTER_USER='replica_user', + MASTER_PASSWORD='replica_password', + MASTER_LOG_FILE='mysql-bin.000001', + MASTER_LOG_POS=107; +``` + +#### Redis Cluster +```bash +# Redis cluster setup for horizontal scaling +redis-cli --cluster create \ + 192.168.1.10:6379 \ + 192.168.1.11:6379 \ + 192.168.1.12:6379 \ + --cluster-replicas 0 +``` + +## Maintenance Procedures + +### Regular Maintenance Tasks + +#### Daily Tasks +- Monitor system resources (CPU, memory, disk) +- Check application logs for errors +- Verify AI service connectivity +- Test backup restoration + +#### Weekly Tasks +- Review and rotate application logs +- Check for security updates +- Monitor storage usage and cleanup +- Test full application functionality + +#### Monthly Tasks +- Full system backup and verification +- Security audit and penetration testing +- Performance analysis and optimization +- Dependency updates and testing + +### Emergency Procedures + +#### Service Outage Response +```bash +# Quick health check +curl -f https://your-domain.com/health + +# Check service status +sudo systemctl status nginx php8.3-fpm + +# View recent logs +sudo tail -f /var/log/nginx/error.log +sudo tail -f /var/www/ai-stylegallery/storage/logs/laravel.log + +# Restart services if needed +sudo systemctl restart nginx php8.3-fpm +``` + +#### Data Recovery +```bash +# From backup +cd /var/backups/ai-stylegallery +LATEST_BACKUP=$(ls -t *.tar.gz | head -1) +sudo tar -xzf "$LATEST_BACKUP" -C /var/www/ai-stylegallery --strip-components=1 + +# Restore database +LATEST_DB=$(ls -t db_*.sqlite | head -1) +cp "$LATEST_DB" /var/www/ai-stylegallery/database/database.sqlite +``` + +## Support and Documentation + +### Documentation Locations +- **API Documentation**: `/prp/api-specification.md` +- **Component Documentation**: `/prp/frontend-components.md` +- **Deployment Guide**: This document +- **User Manual**: Application help system + +### Support Contacts +- **Technical Support**: dev-team@your-domain.com +- **System Administrator**: admin@your-domain.com +- **Security Issues**: security@your-domain.com + +### Training Materials +- **Admin Training**: Filament admin panel usage +- **Developer Guide**: Contributing to the codebase +- **Operations Manual**: Day-to-day system management + +## Compliance and Legal + +### Data Protection +- **GDPR Compliance**: User data handling procedures +- **Data Retention**: Configurable data retention policies +- **Privacy Policy**: User data collection and usage transparency + +### Security Compliance +- **SSL/TLS**: HTTPS encryption for all communications +- **Data Encryption**: Sensitive data encryption at rest +- **Access Logging**: Comprehensive audit trails + +### Licensing +- **Application License**: Open source or commercial license +- **Third-party Libraries**: Compliance with library licenses +- **AI Service Terms**: Compliance with AI provider terms of service + +## Future Deployment Enhancements + +### Containerization (Docker) + +#### Dockerfile +```dockerfile +FROM php:8.3-fpm + +# Install system dependencies +RUN apt-get update && apt-get install -y \ + git curl libpng-dev libonig-dev libxml2-dev libzip-dev zip unzip \ + && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip + +# Install Composer +COPY --from=composer:latest /usr/bin/composer /usr/bin/composer + +# Copy application code +WORKDIR /var/www/ai-stylegallery +COPY . . + +# Install dependencies +RUN composer install --no-dev --optimize-autoloader + +# Set permissions +RUN chown -R www-data:www-data storage bootstrap/cache +``` + +#### Docker Compose +```yaml +version: '3.8' +services: + web: + build: . + ports: + - "80:80" + volumes: + - ./storage/app/public:/var/www/ai-stylegallery/storage/app/public + depends_on: + - redis + - db + + redis: + image: redis:7-alpine + + db: + image: postgres:15-alpine + environment: + POSTGRES_DB: ai_stylegallery + POSTGRES_USER: laravel + POSTGRES_PASSWORD: password +``` + +### CI/CD Pipeline + +#### GitHub Actions Workflow +```yaml +name: Deploy to Production +on: + push: + branches: [ main ] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + + - name: Install Dependencies + run: composer install --no-dev + + - name: Run Tests + run: php artisan test + + - name: Deploy to Server + uses: appleboy/ssh-action@master + with: + host: ${{ secrets.SERVER_HOST }} + username: ${{ secrets.SERVER_USER }} + key: ${{ secrets.SERVER_SSH_KEY }} + script: | + cd /var/www/ai-stylegallery + ./deploy.sh +``` + +### Monitoring and Alerting + +#### Prometheus Metrics +```php +// Prometheus metrics endpoint +Route::get('/metrics', function () { + $metrics = [ + 'app_requests_total' => \DB::table('access_logs')->count(), + 'app_users_total' => \App\Models\User::count(), + 'app_images_total' => \App\Models\Image::count(), + 'app_processing_time' => \Cache::get('avg_processing_time', 0), + ]; + + return response(implode("\n", array_map( + fn($key, $value) => "{$key} {$value}", + array_keys($metrics), + array_values($metrics) + )), 200, ['Content-Type' => 'text/plain']); +}); +``` + +#### Grafana Dashboard +- Application performance metrics +- AI service response times +- User activity and engagement +- System resource utilization +- Error rates and alerting + +This comprehensive deployment guide provides all necessary information for successfully deploying and maintaining the AI StyleGallery application in production environments. \ No newline at end of file diff --git a/prp/frontend-components.md b/prp/frontend-components.md new file mode 100644 index 0000000..2b3621c --- /dev/null +++ b/prp/frontend-components.md @@ -0,0 +1,525 @@ +# Frontend Components Specification + +## Architecture Overview + +Single Page Application built with Vue.js 3 and Inertia.js, providing a responsive image gallery interface with real-time AI processing capabilities. + +## Technology Stack + +- **Framework**: Vue.js 3.5.18 with Composition API +- **Routing**: Inertia.js 1.3.0 (Laravel backend integration) +- **Build Tool**: Vite 5.4.19 +- **Styling**: Tailwind CSS 3.4.17 +- **HTTP Client**: Axios 1.11.0 +- **State Management**: Vue 3 Composition API (ref, computed, reactive) +- **Real-time**: WebSocket for ComfyUI progress, polling for other providers + +## Component Hierarchy + +``` +App.vue (Root) +└── Home.vue (Main Gallery Page) + ├── GalleryGrid.vue (Image Grid Display) + ├── Navigation.vue (Pagination Controls) + ├── ImageContextMenu.vue (Image Actions Overlay) + │ └── StyleSelector.vue (Style Selection Interface) + ├── StyledImageDisplay.vue (Result Preview) + ├── LoadingSpinner.vue (Progress Indicator) + └── PrintQuantityModal.vue (Print Options) +``` + +## Component Specifications + +### 1. Home.vue (Main Gallery Page) + +**Purpose**: Primary interface displaying user's image gallery with pagination and overlay management + +**Location**: `resources/js/Pages/Home.vue` + +**Props**: +```typescript +interface Props { + galleryHeading: string // Page title + translations: object // Internationalization strings +} +``` + +**State Management**: +```typescript +const images = ref([]) // Gallery images array +const currentPage = ref(1) // Current pagination page +const currentOverlayComponent = ref(null) // Active overlay ('contextMenu', 'styleSelector', etc.) +const contextMenuPosition = ref({ x: 0, y: 0 }) // Context menu coordinates +const selectedImage = ref(null) // Currently selected image +const styledImage = ref(null) // Newly processed styled image +const processingProgress = ref(0) // AI processing progress (0-100) +const errorMessage = ref(null) // Error display state +const isLoading = ref(false) // Global loading state +const currentTheme = ref('light') // UI theme preference +``` + +**Key Methods**: + +#### `fetchImages()` +- **Purpose**: Retrieves and synchronizes gallery images +- **Implementation**: Axios GET to `/api/images` +- **Auto-refresh**: Polls every 5 seconds (configurable interval) +- **Error Handling**: Displays user-friendly error messages + +#### `applyStyle(style, imageId)` +- **Purpose**: Initiates AI style transformation process +- **Flow**: + 1. Sends style change request to backend + 2. Receives `prompt_id` and `plugin` type + 3. Establishes appropriate progress monitoring (WebSocket vs Polling) + 4. Updates UI with real-time progress + 5. Displays result when complete + +#### `showContextMenu(image, event)` +- **Purpose**: Displays context menu for selected image +- **Positioning**: Calculates optimal position based on click coordinates +- **Responsive**: Adapts to screen boundaries + +**UI Structure**: +- **Header**: Title and theme toggle +- **Gallery**: Grid layout with pagination +- **Overlays**: Conditional rendering based on `currentOverlayComponent` +- **Notifications**: Error messages with auto-dismiss + +**Styling**: +- **Layout**: Flexbox-based responsive design +- **Theme**: Light/dark mode support with CSS variables +- **Responsive**: Mobile-first approach with touch gestures + +--- + +### 2. GalleryGrid.vue + +**Purpose**: Displays images in responsive grid layout with interaction handling + +**Props**: +```typescript +interface Props { + images: Image[] // Array of image objects to display + translations: object // UI text translations +} +``` + +**Events**: +```typescript +interface Events { + imageTapped: [image: Image, event: MouseEvent] // Image selection +} +``` + +**Features**: +- **Responsive Grid**: Adaptive columns based on screen size +- **Lazy Loading**: Images load as they enter viewport +- **Touch Support**: Tap gestures for mobile devices +- **Accessibility**: Proper alt text and keyboard navigation + +**Image Object Structure**: +```typescript +interface Image { + image_id: number + path: string // URL to image file + name: string // Filename + is_temp: boolean // Temporary styled image flag + is_public: boolean // Visibility status + is_new: boolean // Recently uploaded flag +} +``` + +--- + +### 3. ImageContextMenu.vue + +**Purpose**: Contextual action menu displayed when user taps/clicks an image + +**Location**: `resources/js/Components/ImageContextMenu.vue` + +**Props**: +```typescript +interface Props { + position: { x: number, y: number } // Menu position coordinates + image: Image // Selected image object +} +``` + +**Events**: +```typescript +interface Events { + close: [] // Close menu + print: [image: Image] // Print image + changeStyle: [] // Open style selector + styleSelected: [style: Style, imageId: number] // Style applied +} +``` + +**Layout Structure**: +``` +┌─────────────────────────────────────────────────┐ +│ [X] Close [Image Preview] │ +│ │ +│ ┌─────────────────────────────────────────────┐ │ +│ │ ▲ │ │ +│ │ Image Preview │ │ +│ │ ▼ │ │ +│ │ (70% width) │ │ +│ └─────────────────────────────────────────────┘ │ +│ ┌─────────────────────────────────────────────┐ │ +│ │ [Print] [Change Style] [Close] │ │ +│ │ (30% width) │ │ +│ └─────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────┘ +``` + +**Features**: +- **Dynamic Positioning**: Calculates optimal position to stay within viewport +- **Backdrop Click**: Closes menu when clicking outside +- **Nested Components**: Embeds StyleSelector when needed +- **Responsive**: Adapts layout for different screen sizes + +**Styling**: +- **Overlay**: Semi-transparent backdrop with blur effect +- **Menu**: Elevated card with shadow and rounded corners +- **Responsive**: Touch-friendly button sizes on mobile + +--- + +### 4. StyleSelector.vue + +**Purpose**: Allows users to browse and select AI styles for image transformation + +**Props**: +```typescript +interface Props { + image_id: number // Target image for styling +} +``` + +**Events**: +```typescript +interface Events { + styleSelected: [style: Style, imageId: number] // Style chosen + back: [] // Return to context menu + close: [] // Close selector +} +``` + +**State Management**: +```typescript +const styles = ref([]) // Available styles array +// Lazy loading management +const observer = ref(null) // IntersectionObserver instance +``` + +**Key Methods**: + +#### `fetchStyles()` +- **Purpose**: Retrieves available styles from API +- **Implementation**: Axios GET to `/api/styles` +- **Filtering**: Only enabled styles returned +- **Lazy Loading**: Sets up IntersectionObserver for preview images + +#### `selectStyle(style)` +- **Purpose**: Confirms style selection and triggers processing +- **Implementation**: Emits `styleSelected` event with style and image ID + +**UI Structure**: +``` +┌─────────────────────────────────────────────────┐ +│ [<] Back Available Styles │ +├─────────────────────────────────────────────────┤ +│ ┌─────────────────────────────────────────────┐ │ +│ │ [Preview] Style Name [Description] │ │ +│ │ [Preview] Another Style [Description] │ │ +│ │ [Preview] Third Style [Description] │ │ +│ └─────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────┘ +``` + +**Features**: +- **Preview Images**: Thumbnail images for each style +- **Lazy Loading**: Images load when entering viewport +- **Back Navigation**: Return to previous context menu +- **Responsive**: Scrollable list on smaller screens + +**Style Object Structure**: +```typescript +interface Style { + id: number + title: string // Display name + description: string // Human-readable description + preview_image: string // Thumbnail image path + enabled: boolean // Availability status +} +``` + +--- + +### 5. LoadingSpinner.vue + +**Purpose**: Visual indicator for AI processing progress + +**Props**: +```typescript +interface Props { + progress: number // Progress percentage (0-100) +} +``` + +**Features**: +- **Progress Bar**: Visual representation of completion status +- **Animated**: Smooth progress updates +- **Responsive**: Adapts to different screen sizes +- **Accessible**: Screen reader compatible + +**Styling**: +- **Modern Design**: Gradient progress bar with smooth animations +- **Centered**: Overlay positioning for full-screen processes +- **Theme Aware**: Adapts to light/dark theme + +--- + +### 6. StyledImageDisplay.vue + +**Purpose**: Preview and management interface for completed AI-styled images + +**Props**: +```typescript +interface Props { + image: Image // Styled image object +} +``` + +**Events**: +```typescript +interface Events { + keep: [image: Image] // Keep styled image permanently + delete: [image: Image] // Discard styled image +} +``` + +**Features**: +- **Full Preview**: Large display of styled result +- **Action Buttons**: Keep/Discard options +- **Responsive**: Mobile-optimized layout +- **Loading State**: Handles image loading gracefully + +--- + +### 7. Navigation.vue + +**Purpose**: Pagination controls for gallery navigation + +**Props**: +```typescript +interface Props { + currentPage: number // Current active page + totalPages: number // Total available pages +} +``` + +**Events**: +```typescript +interface Events { + prevPage: [] // Navigate to previous page + nextPage: [] // Navigate to next page +} +``` + +**Features**: +- **Page Numbers**: Visual page indicators +- **Touch Gestures**: Swipe left/right for page navigation +- **Responsive**: Touch-friendly on mobile devices +- **Keyboard**: Arrow key navigation support + +--- + +### 8. PrintQuantityModal.vue + +**Purpose**: Print options interface for physical image printing + +**Props**: +```typescript +interface Props { + maxCopies: number // Maximum allowed copies +} +``` + +**Events**: +```typescript +interface Events { + close: [] // Close modal + printConfirmed: [quantity: number] // Print confirmed +} +``` + +**Features**: +- **Quantity Selection**: Number input for copy count +- **Validation**: Enforces maximum copy limits +- **Confirmation**: Clear confirmation before printing +- **Responsive**: Modal overlay with backdrop + +## Component Interactions + +### Image Selection Flow +``` +User taps image → GalleryGrid emits imageTapped → +Home.vue shows contextMenu at tap position → +ImageContextMenu displays with image preview and options +``` + +### Style Application Flow +``` +User selects "Change Style" → ImageContextMenu shows StyleSelector → +User browses and selects style → StyleSelector emits styleSelected → +Home.vue initiates AI processing with progress monitoring → +Real-time updates via WebSocket/Polling → Result displayed → +User can keep or discard styled image +``` + +### Progress Monitoring + +#### ComfyUI (WebSocket) +```typescript +// Establish WebSocket connection +const wsUrl = `ws://${comfyUiHost}/ws` +const ws = new WebSocket(wsUrl) + +// Monitor progress messages +ws.onmessage = (event) => { + const message = JSON.parse(event.data) + if (message.type === 'progress' && message.data.prompt_id === currentPromptId) { + processingProgress.value = (message.data.value / message.data.max) * 100 + } +} +``` + +#### Other Providers (Polling) +```typescript +// Poll for completion every 2 seconds +const pollForResult = () => { + axios.get(`/api/images/fetch-styled/${promptId}`) + .then(response => { + // Success - display result + styledImage.value = response.data.styled_image + currentOverlayComponent.value = 'styledImageDisplay' + }) + .catch(error => { + if (error.response?.status === 404) { + // Still processing - continue polling + setTimeout(pollForResult, 2000) + } else { + // Error - display message + showError(error.response?.data?.error) + } + }) +} +``` + +## State Management Patterns + +### Overlay Management +- Single active overlay at a time +- Stack-based navigation (context menu → style selector → back) +- Proper cleanup on component unmount + +### Error Handling +- Centralized error display with auto-dismiss +- User-friendly error messages +- Graceful degradation for failed operations + +### Theme Management +- Persistent theme preference in localStorage +- CSS variable-based theming +- System preference detection + +## Responsive Design + +### Breakpoints +- **Mobile**: < 768px (single column, touch-optimized) +- **Tablet**: 768px - 1024px (2-3 columns, hybrid interaction) +- **Desktop**: > 1024px (4+ columns, mouse-optimized) + +### Touch Interactions +- **Tap**: Image selection and button activation +- **Swipe**: Gallery navigation (left/right) +- **Long Press**: Context menu (mobile equivalent of right-click) +- **Pinch**: Zoom functionality (future enhancement) + +## Accessibility Features + +### ARIA Support +- Proper semantic HTML structure +- ARIA labels for interactive elements +- Screen reader announcements for dynamic content + +### Keyboard Navigation +- Tab order for all interactive elements +- Enter/Space for button activation +- Escape key for modal dismissal +- Arrow keys for gallery navigation + +### Visual Accessibility +- High contrast mode support +- Sufficient color contrast ratios +- Scalable text and UI elements +- Reduced motion preferences + +## Performance Optimizations + +### Image Loading +- **Lazy Loading**: IntersectionObserver for viewport detection +- **Progressive Loading**: Blur placeholder → low quality → high quality +- **Caching**: Browser cache for static assets +- **Compression**: Optimized image formats (WebP support) + +### Component Optimization +- **Conditional Rendering**: Only render active overlays +- **Event Delegation**: Efficient event handling for large galleries +- **Memoization**: Computed properties for expensive operations +- **Code Splitting**: Component-based lazy loading + +## Internationalization + +### Translation Structure +```typescript +interface Translations { + api: { + dark_mode: string + light_mode: string + close: string + print: string + change_style: string + } +} +``` + +### Implementation +- Laravel backend provides translations +- Vue components use translation keys +- Runtime language switching support + +## Future Enhancement Opportunities + +### Component Additions +- **ImageEditor.vue**: Basic image editing tools +- **BatchProcessor.vue**: Multi-image style application +- **GalleryFilters.vue**: Search and filter functionality +- **UserProfile.vue**: User settings and preferences +- **AdminDashboard.vue**: Administrative controls + +### Feature Enhancements +- **Drag & Drop**: Upload images via drag-and-drop +- **Keyboard Shortcuts**: Power user productivity features +- **Offline Support**: PWA capabilities for offline viewing +- **Social Features**: Share and discover styled images +- **Advanced Progress**: Detailed processing stage information + +### Technical Improvements +- **Virtual Scrolling**: Handle very large galleries efficiently +- **Service Workers**: Background processing and caching +- **WebAssembly**: Client-side image processing +- **Real-time Collaboration**: Multiple users styling same image \ No newline at end of file diff --git a/prp/plugin-architecture.md b/prp/plugin-architecture.md new file mode 100644 index 0000000..cc2892e --- /dev/null +++ b/prp/plugin-architecture.md @@ -0,0 +1,651 @@ +# Plugin Architecture Specification + +## Overview + +Extensible plugin system for integrating multiple AI service providers, enabling the application to work with different AI platforms (ComfyUI, RunwareAI, etc.) through a unified interface. + +## Architecture Pattern + +**Strategy Pattern Implementation** with plugin-based architecture allowing runtime selection of AI processing backends. + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ ImageController │ +│ • Orchestrates image processing workflow │ +│ • Loads appropriate plugin based on ApiProvider │ +└─────────────────────┬───────────────────────────────────────────┘ + │ + ┌─────────────▼─────────────────────────────────────────────┐ + │ PluginLoader │ + │ • Discovers and instantiates plugins │ + │ • Maps plugin identifiers to implementations │ + └─────────────┬───────────────────────────────────────────┘ + │ + ┌─────────────▼─────────────────────────────────────────────┐ + │ ApiPluginInterface │ + │ • Defines contract for all AI plugins │ + │ • Ensures consistent behavior across providers │ + └─────┬─────────────────┬──────────────────────────────────┘ + │ │ + ┌─────▼──────┐ ┌──────▼──────┐ + │ ComfyUi │ │ RunwareAi │ + │ Plugin │ │ Plugin │ + └────────────┘ └─────────────┘ +``` + +## Core Interfaces + +### ApiPluginInterface + +**Purpose**: Defines the contract that all AI provider plugins must implement + +**Location**: `app/Api/Plugins/ApiPluginInterface.php` + +**Methods**: + +#### Core Plugin Information +```php +/** + * Returns unique plugin identifier + */ +public function getIdentifier(): string + +/** + * Returns human-readable plugin name + */ +public function getName(): string + +/** + * Checks if plugin is enabled and ready for use + */ +public function isEnabled(): bool + +/** + * Enables the plugin + */ +public function enable(): bool + +/** + * Disables the plugin + */ +public function disable(): bool +``` + +#### Image Processing +```php +/** + * Main method for processing image style changes + * @param Image $image Original image to transform + * @param Style $style Style to apply + * @return array Processing result with tracking information + */ +public function processImageStyleChange(Image $image, Style $style): array +``` + +#### Progress & Status +```php +/** + * Gets current processing status for image + * @param string $imageUUID Image identifier + * @return array Status information + */ +public function getStatus(string $imageUUID): array + +/** + * Gets processing progress for image + * @param string $imageUUID Image identifier + * @return array Progress information (0-100 percentage) + */ +public function getProgress(string $imageUUID): array +``` + +#### Result Retrieval +```php +/** + * Retrieves final styled image data + * @param string $promptId Provider-specific job identifier + * @return string Base64 encoded image data + */ +public function getStyledImage(string $promptId): string +``` + +#### Provider-Specific Features +```php +/** + * Tests connection to AI service + * @param array $data Connection parameters + * @return bool Connection success + */ +public function testConnection(array $data): bool + +/** + * Searches for available AI models + * @param string $searchTerm Search query + * @return array Available models + */ +public function searchModels(string $searchTerm): array +``` + +## Plugin Implementations + +### 1. ComfyUI Plugin + +**Plugin Identifier**: `comfyui` + +**Purpose**: Integration with ComfyUI web-based AI image generation platform + +**Configuration Requirements**: +```php +// ApiProvider configuration +[ + 'name' => 'ComfyUI Production', + 'api_url' => 'https://your-comfyui-server.com', + 'plugin' => 'comfyui', + 'enabled' => true +] +``` + +#### Key Features + +**Workflow-Based Processing**: +- Uses JSON workflow definitions for complex AI pipelines +- Supports custom node-based processing graphs +- Parameter injection via placeholder replacement + +**WebSocket Progress Updates**: +- Real-time progress monitoring via WebSocket connection +- Detailed progress information (current step, completion percentage) +- Live preview of intermediate results + +**Placeholder System**: +```json +{ + "prompt": "__PROMPT__", + "filename": "__FILENAME__", + "model_id": "__MODEL_ID__" +} +``` +- `__PROMPT__`: Style prompt text +- `__FILENAME__`: Uploaded image filename +- `__MODEL_ID__`: AI model identifier + +#### Processing Flow + +1. **Image Upload** + ```php + POST {api_url}/upload/image + Body: multipart/form-data with image file + Response: {"name": "uploaded_filename.png"} + ``` + +2. **Workflow Construction** + ```php + // Merge model and style parameters + $mergedParams = array_replace_recursive($modelParams, $styleParams) + + // Replace placeholders + $workflow = str_replace('__PROMPT__', $prompt, $workflow) + $workflow = str_replace('__FILENAME__', $filename, $workflow) + $workflow = str_replace('__MODEL_ID__', $modelId, $workflow) + ``` + +3. **Prompt Queueing** + ```php + POST {api_url}/prompt + Body: {"prompt": $workflow} + Response: {"prompt_id": "unique-job-id"} + ``` + +4. **Progress Monitoring** + ```php + // WebSocket connection + ws://{server}/ws + + // Progress messages + { + "type": "progress", + "data": { + "prompt_id": "job-id", + "value": 50, + "max": 100 + } + } + ``` + +5. **Result Retrieval** + ```php + GET {api_url}/history/{prompt_id} + + // Extract image URL + $imageUrl = "/view?filename={$filename}&subfolder={$subfolder}&type=output" + + // Download final image + GET {api_url}{$imageUrl} + ``` + +#### Error Handling +- **Connection Failures**: Retry logic with exponential backoff +- **Invalid Workflows**: JSON validation before submission +- **Processing Timeouts**: Configurable timeout limits +- **WebSocket Disconnections**: Automatic reconnection attempts + +--- + +### 2. RunwareAI Plugin + +**Plugin Identifier**: `runwareai` + +**Purpose**: Integration with RunwareAI REST API for image style transformation + +**Configuration Requirements**: +```php +// ApiProvider configuration +[ + 'name' => 'RunwareAI Production', + 'api_url' => 'https://api.runwareai.com', + 'token' => 'your-api-token', + 'plugin' => 'runwareai', + 'enabled' => true +] +``` + +#### Key Features + +**Direct API Integration**: +- RESTful API communication +- Bearer token authentication +- Synchronous processing with immediate results + +**Model Search Capability**: +- Search available AI models by name/type +- Filter by model categories (base, checkpoint, etc.) +- Real-time model availability checking + +**Seed Image Processing**: +- Upload original image as "seed" +- Apply style transformation using seed as base +- Return styled result directly + +#### Processing Flow + +1. **Image Upload** + ```php + POST {api_url} + Headers: Authorization: Bearer {token} + Body: { + "taskType": "imageUpload", + "taskUUID": "unique-id", + "image": "data:image/png;base64,{base64_data}" + } + Response: { + "data": [{ + "imageUUID": "uploaded-image-uuid" + }] + } + ``` + +2. **Style Transformation** + ```php + POST {api_url} + Headers: Authorization: Bearer {token} + Body: { + "taskType": "imageInference", + "taskUUID": "unique-id", + "positivePrompt": "style prompt text", + "seedImage": "uploaded-image-uuid", + "model": "model-id", + "outputType": "base64Data" + } + Response: { + "data": [{ + "imageBase64Data": "base64-encoded-result" + }] + } + ``` + +3. **Model Search** (Optional) + ```php + POST {api_url} + Headers: Authorization: Bearer {token} + Body: { + "taskType": "modelSearch", + "search": "search-term", + "type": "base", + "category": "checkpoint", + "limit": 100 + } + Response: { + "data": [{ + "results": [{ + "name": "Model Name", + "air": "model-id", + "type": "model-type" + }] + }] + } + ``` + +#### Error Handling +- **Authentication Failures**: Clear error messages for token issues +- **Rate Limiting**: Respect API rate limits with proper delays +- **Invalid Parameters**: Validation of all request parameters +- **Network Issues**: Timeout handling with retry logic + +## Plugin Loading Mechanism + +### PluginLoader Class + +**Purpose**: Discovers, loads, and manages AI provider plugins + +**Location**: `app/Api/Plugins/PluginLoader.php` + +**Key Methods**: + +#### `getPlugin(string $pluginIdentifier, ApiProvider $apiProvider): ApiPluginInterface` +- **Purpose**: Returns instantiated plugin for given identifier +- **Implementation**: Dynamic class loading based on plugin identifier +- **Error Handling**: Throws exception for unknown plugins + +#### `getAvailablePlugins(): array` +- **Purpose**: Returns list of all available plugin identifiers +- **Implementation**: Scans plugin directory for implementations + +**Plugin Discovery**: +```php +// Maps plugin identifiers to class names +$pluginMap = [ + 'comfyui' => ComfyUi::class, + 'runwareai' => RunwareAi::class, +] + +// Dynamic instantiation +$pluginClass = $pluginMap[$identifier] ?? null; +if ($pluginClass) { + return new $pluginClass($apiProvider); +} +``` + +## Parameter Merging Strategy + +### Deep Merge Algorithm + +**Purpose**: Combines AI model parameters with style-specific overrides + +**Implementation**: +```php +$modelParams = $style->aiModel->parameters ?? []; +$styleParams = $style->parameters ?? []; +$mergedParams = array_replace_recursive($modelParams, $styleParams); +``` + +**Example**: +```php +// Model parameters (base configuration) +$modelParams = [ + "workflow" => [ + "nodes" => [ + "1" => ["class_type" => "KSampler"], + "2" => ["class_type" => "SaveImage"] + ] + ] +]; + +// Style parameters (overrides and additions) +$styleParams = [ + "workflow" => [ + "nodes" => [ + "1" => [ + "inputs" => ["seed" => 12345], + "class_type" => "KSamplerAdvanced" // Override + ], + "3" => ["class_type" => "PreviewImage"] // Addition + ] + ] +]; + +// Result: Deep merged configuration +$mergedParams = [ + "workflow" => [ + "nodes" => [ + "1" => [ + "class_type" => "KSamplerAdvanced", // Overridden + "inputs" => ["seed" => 12345] // Added + ], + "2" => ["class_type" => "SaveImage"], // Preserved + "3" => ["class_type" => "PreviewImage"] // Added + ] + ] +] +``` + +## Logging Integration + +### LoggablePlugin Trait + +**Purpose**: Provides consistent logging across all plugins + +**Location**: `app/Api/Plugins/LoggablePlugin.php` + +**Features**: +- **Structured Logging**: Consistent log format across plugins +- **Log Levels**: Debug, Info, Warning, Error +- **Context Information**: Plugin name, operation details +- **Performance Tracking**: Execution time monitoring + +**Usage**: +```php +class ComfyUi implements ApiPluginInterface +{ + use LoggablePlugin; + + public function processImageStyleChange(Image $image, Style $style): array + { + $this->logInfo('Starting ComfyUI style change process', [ + 'image_id' => $image->id, + 'style_id' => $style->id + ]); + + // Processing logic... + + $this->logInfo('ComfyUI style change completed successfully', [ + 'prompt_id' => $result['prompt_id'] + ]); + + return $result; + } +} +``` + +## Error Handling Strategy + +### Plugin-Specific Errors + +**ComfyUI Errors**: +- **Workflow Validation**: Invalid JSON structure in workflow +- **Node Connection**: Missing or invalid node connections +- **Resource Limits**: GPU memory or processing queue full +- **Network Timeout**: Server unreachable or slow response + +**RunwareAI Errors**: +- **Authentication**: Invalid or expired API token +- **Rate Limiting**: Too many requests per minute/hour +- **Model Availability**: Requested model not available +- **Image Processing**: Invalid image format or corrupted data + +### Error Recovery + +**Retry Logic**: +```php +$maxRetries = 3; +$retryDelay = 1000000; // 1 second in microseconds + +for ($attempt = 1; $attempt <= $maxRetries; $attempt++) { + try { + return $this->processImageStyleChange($image, $style); + } catch (RetryableException $e) { + if ($attempt === $maxRetries) { + throw new MaxRetriesExceededException('Processing failed after ' . $maxRetries . ' attempts'); + } + usleep($retryDelay * $attempt); // Exponential backoff + } +} +``` + +**Circuit Breaker Pattern**: +- Track failure rates per provider +- Temporarily disable failing providers +- Automatic recovery testing + +## Testing Strategy + +### Unit Tests +- **Plugin Interface**: Verify all plugins implement required methods +- **Parameter Merging**: Test deep merge algorithm with various inputs +- **Error Handling**: Verify proper exception throwing and recovery + +### Integration Tests +- **End-to-End Processing**: Test complete workflow with mock AI services +- **Provider Switching**: Verify seamless transition between providers +- **Error Scenarios**: Test behavior with network failures and invalid responses + +### Mock Services +- **ComfyUI Mock**: Simulated WebSocket and HTTP responses +- **RunwareAI Mock**: Mock API responses for all endpoints +- **Network Simulation**: Latency and failure injection + +## Future Plugin Development + +### Adding New Providers + +1. **Implement Interface**: + ```php + class NewProvider implements ApiPluginInterface + { + use LoggablePlugin; + + public function getIdentifier(): string { return 'newprovider'; } + public function getName(): string { return 'New AI Provider'; } + // ... implement all required methods + } + ``` + +2. **Register Plugin**: + ```php + // In PluginLoader + $pluginMap['newprovider'] = NewProvider::class; + ``` + +3. **Add Configuration**: + - Create ApiProvider record with appropriate settings + - Configure authentication and endpoint details + +### Plugin Enhancement Opportunities + +**Batch Processing Plugin**: +- Process multiple images simultaneously +- Queue management and progress aggregation +- Resource optimization across multiple requests + +**Local Processing Plugin**: +- Integration with local AI models (Stable Diffusion WebUI) +- Reduced latency for development/testing +- Offline processing capabilities + +**Cloud Provider Plugins**: +- **AWS Bedrock**: Amazon's AI service integration +- **Google Vertex AI**: Google's ML platform +- **Azure Cognitive Services**: Microsoft AI services +- **Replicate**: Cloud-based model hosting + +**Specialized Processing**: +- **Upscaling Plugin**: Dedicated image enhancement +- **Style Transfer Plugin**: Specialized style application +- **Inpainting Plugin**: Content-aware image editing + +## Configuration Management + +### Provider-Specific Settings + +**ComfyUI Settings**: +```php +// Via ApiProvider parameters (JSON) +{ + "timeout": 180, + "retry_attempts": 3, + "websocket_enabled": true, + "workflow_path": "/custom/workflows" +} +``` + +**RunwareAI Settings**: +```php +{ + "request_timeout": 60, + "rate_limit_delay": 1000, + "model_cache_ttl": 3600, + "supported_formats": ["png", "jpg", "webp"] +} +``` + +### Environment-Based Configuration + +**Development**: +- Local ComfyUI instance +- Mock API responses for testing +- Verbose logging enabled + +**Production**: +- Multiple load-balanced providers +- Failover between providers +- Performance monitoring and alerting + +## Performance Considerations + +### Resource Management +- **Connection Pooling**: Reuse HTTP connections where possible +- **Timeout Configuration**: Appropriate timeouts for different operations +- **Memory Management**: Clean up large image data after processing + +### Scalability +- **Concurrent Processing**: Handle multiple simultaneous requests +- **Queue Management**: Prevent resource exhaustion +- **Load Balancing**: Distribute requests across multiple provider instances + +### Monitoring +- **Performance Metrics**: Processing time, success rates, error frequencies +- **Resource Usage**: Memory, CPU, network utilization +- **Business Metrics**: User satisfaction, feature adoption + +## Security Considerations + +### Credential Management +- **Encrypted Storage**: API tokens encrypted in database +- **Environment Variables**: Sensitive configuration in env files +- **Access Control**: Restrict plugin configuration to admin users + +### Input Validation +- **Image Validation**: Verify uploaded image integrity +- **Parameter Sanitization**: Clean and validate all AI parameters +- **Output Verification**: Ensure generated images are safe for display + +### Network Security +- **HTTPS Enforcement**: All external API calls over TLS +- **Certificate Validation**: Verify AI service certificates +- **Request Signing**: Authenticate requests where required + +## Deployment Considerations + +### Plugin Distribution +- **Composer Packages**: Each plugin as separate package +- **Auto-Discovery**: Automatic plugin registration +- **Version Management**: Plugin compatibility checking + +### Environment Setup +- **Development**: Easy plugin development and testing +- **Staging**: Pre-production validation of new plugins +- **Production**: Zero-downtime plugin updates + +### Backup and Recovery +- **Configuration Backup**: Plugin settings and credentials +- **State Preservation**: In-progress processing state +- **Failover**: Automatic switching to backup providers \ No newline at end of file