ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add support for template file creation and bind mounts
Juan Denis5fe76cd81147
diff --git a/.gitignore b/.gitignoreindex 26976e3c..d11e7ddf 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,5 @@ nul.env/frontend/dist*.tmp+.planning_old+.mcp.json\ No newline at end of filediff --git a/.planning/PROJECT.md b/.planning/PROJECT.mddeleted file mode 100644index ce22907b..00000000--- a/.planning/PROJECT.md+++ /dev/null@@ -1,87 +0,0 @@-# ServerKit Enhancement Project--## Current State--**Version**: v1.1 (Milestone 2 Complete)-**Active**: Milestone 3 - Visual Workflow Builder (v1.2)-**Last Updated**: 2026-01-19--ServerKit is a modern, self-hosted server management panel (Flask backend + React frontend) with multi-environment WordPress support and community features.--### What's Shipped--**v1.1 (Milestone 2)**:-- **Multi-Environment App Linking** - Link prod/dev WordPress instances with shared databases-- **WordPress External DB Template** - Connect WordPress to external MySQL with custom table prefixes-- **Environment Switching UI** - Badges, filters, linked apps navigation-- **GitHub Integration** - Repository links, version update checks, star prompt--**v1.0 (Milestone 1)**:-- Docker/Domain Infrastructure, Private URLs, Historical Metrics-- Templates & Applications UI polish, FileManager disk usage--### Tech Stack-- **Backend**: Python 3.11+, Flask 3.0, SQLAlchemy, Flask-SocketIO, psutil-- **Frontend**: React 18, Vite, Recharts, Lucide React, LESS-- **Infrastructure**: Docker, Nginx, Let's Encrypt--## Next Milestone Goals--**Milestone 3: Visual Workflow Builder (v1.2)**--Create a visual, flow-based interface for orchestrating infrastructure:-- **Canvas Foundation** - React Flow with pan/zoom, node rendering-- **Resource Nodes** - Visual blocks for Docker apps, databases, domains-- **Configuration Panels** - Side panels adapting existing forms-- **Connection Logic** - Validate and visualize relationships-- **Save/Load** - Persist workflows, import existing infrastructure-- **Deploy** - Execute workflows to create/update resources-------<details>-<summary>Original Project Goals (v1.0)</summary>--### Priority 1: Fix Critical Infrastructure-- [x] Debug and fix Docker container port exposure to host-- [x] Fix domain-to-application routing via Nginx-- [x] Ensure WordPress, PHP, Flask templates deploy and route correctly--### Priority 2: Add Private URL Feature-- [x] Generate unique private URLs for apps (e.g., `/p/abc123`)-- [x] Allow custom private slugs-- [x] Apps accessible without public indexing--### Priority 3: UI/UX Polish-- [x] Improve Applications list and management pages-- [x] Fix Templates page icons and update filtering-- [x] Enhance FileManager disk usage visualization-- [x] Add historical metrics graphs to Dashboard (CPU, Memory, Disk over time)--### Critical Issues Identified (Resolved)-1. ~~Docker port/domain mapping not working~~ Fixed with debug infrastructure-2. ~~Template icons URLs broken~~ Fixed with Lucide fallbacks-3. ~~No historical metrics~~ Added with MetricsHistoryService--</details>-------## Key Files--- Docker Service: `backend/app/services/docker_service.py`-- Nginx Service: `backend/app/services/nginx_service.py`-- Template Service: `backend/app/services/template_service.py`-- Private URL Service: `backend/app/services/private_url_service.py`-- Metrics History Service: `backend/app/services/metrics_history_service.py`-- File Service: `backend/app/services/file_service.py`-- Dashboard: `frontend/src/pages/Dashboard.jsx`-- Templates Page: `frontend/src/pages/Templates.jsx`-- Applications Page: `frontend/src/pages/Applications.jsx`-- FileManager: `frontend/src/pages/FileManager.jsx`--## Quick Links--- [Milestone 1 Archive](./milestones/v1.0-ROADMAP.md)-- [Current Roadmap](./ROADMAP.md)-- [Project State](./STATE.md)diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.mddeleted file mode 100644index aa597c54..00000000--- a/.planning/ROADMAP.md+++ /dev/null@@ -1,209 +0,0 @@-# ServerKit Enhancement Roadmap-------## Completed Milestones--### [Milestone 1: Infrastructure Fixes, Private URLs & UI Polish](./milestones/v1.0-ROADMAP.md) (v1.0)-Completed 2026-01-19 | 9 phases | 109 commits | +14,667/-2,836 lines--### [Milestone 2: Multi-Environment WordPress & Community Features](./milestones/v1.1-ROADMAP.md) (v1.1)-Completed 2026-01-19 | 5 phases | Multi-environment app linking, shared DB support, GitHub integration--### [Milestone 3: Visual Workflow Builder](./milestones/v1.2-ROADMAP.md) (v1.2)-Completed 2026-01-19 | 6 phases | React Flow canvas, node types, deploy from workflow-------## Current Milestone--> **Milestone 4**: Container Logs & Monitoring-> **Version**: v1.3-> **Started**: 2026-01-19-> **Status**: In Progress--**Goal**: Add comprehensive container logging and monitoring capabilities - real-time log streaming, search/filtering, per-app resource graphs, and configurable alert rules with notifications.-------## Phase Overview--| Phase | Name | Status | Goal |-|-------|------|--------|------|-| 22 | Container Logs API | **completed** | Backend API to fetch/stream Docker container logs |-| 23 | Log Viewer UI | pending | Real-time log display with auto-scroll, ANSI color support |-| 24 | Log Search & Filtering | pending | Search within logs, filter by level/time, export |-| 25 | Per-App Resource Collection | pending | Collect per-container CPU/memory/network stats via Docker API |-| 26 | App Resource Graphs | pending | Per-app resource usage charts in application detail view |-| 27 | Alert Rules Engine | pending | Define thresholds, evaluate metrics, trigger alerts |-| 28 | Alert Notifications | pending | Send alerts via email, Discord, Telegram webhooks |-------## Phase 22: Container Logs API (Completed)-**Goal**: Create backend API to fetch and stream Docker container logs--**Key Tasks**:-- Add Docker logs service to fetch container logs-- Create GET /apps/{id}/logs endpoint with tail/since parameters-- Add WebSocket endpoint for real-time log streaming-- Handle log rotation and buffer limits-- Support multiple output formats (raw, JSON)--**Success Criteria**:-- [x] Can fetch last N lines of container logs-- [x] Can stream logs in real-time via WebSocket-- [x] Logs include timestamps-- [x] Handles containers that aren't running-------## Phase 23: Log Viewer UI-**Goal**: Create real-time log viewer component in application detail page--**Key Tasks**:-- Create LogViewer component with terminal-style display-- Implement auto-scroll with pause on user scroll-- Add ANSI color code parsing for colored output-- Connect to WebSocket for live streaming-- Add play/pause, clear, and download buttons--**Success Criteria**:-- [ ] Logs display in real-time-- [ ] Colors render correctly (ANSI codes)-- [ ] Auto-scroll works with manual override-- [ ] Can pause/resume streaming-------## Phase 24: Log Search & Filtering-**Goal**: Add search and filtering capabilities to log viewer--**Key Tasks**:-- Add search input with highlight matches-- Filter by log level (INFO, WARN, ERROR, DEBUG)-- Filter by time range (last hour, today, custom)-- Add regex search option-- Export filtered logs to file--**Success Criteria**:-- [ ] Can search within logs-- [ ] Search matches highlighted-- [ ] Level filtering works-- [ ] Can export logs-------## Phase 25: Per-App Resource Collection-**Goal**: Collect and store per-container resource metrics--**Key Tasks**:-- Use Docker stats API to get container metrics-- Create ContainerMetrics model for storage-- Add background collection job (every 30s)-- Store CPU %, memory usage, network I/O per container-- Create API endpoint GET /apps/{id}/metrics/history--**Success Criteria**:-- [ ] Per-container metrics collected-- [ ] Historical data stored (7 days retention)-- [ ] API returns time-series data-- [ ] Collection doesn't impact performance-------## Phase 26: App Resource Graphs-**Goal**: Display per-app resource usage charts in application detail--**Key Tasks**:-- Create AppMetricsGraph component using Recharts-- Add to application detail page (new Metrics tab or Overview)-- Show CPU, memory, network charts-- Add time range selector (1h, 6h, 24h, 7d)-- Show current vs average stats--**Success Criteria**:-- [ ] CPU/memory graphs display correctly-- [ ] Time range selection works-- [ ] Charts update with new data-- [ ] Mobile responsive-------## Phase 27: Alert Rules Engine-**Goal**: Create system for defining and evaluating alert rules--**Key Tasks**:-- Create AlertRule model (metric, operator, threshold, duration)-- Create AlertHistory model for triggered alerts-- Add alert evaluation service (runs with metrics collection)-- Create CRUD API for alert rules-- Support app-specific and system-wide rules--**Success Criteria**:-- [ ] Can create/edit/delete alert rules-- [ ] Rules evaluate against metrics-- [ ] Alerts trigger when thresholds exceeded-- [ ] Alert history tracked-------## Phase 28: Alert Notifications-**Goal**: Send alert notifications through multiple channels--**Key Tasks**:-- Integrate with existing notification preferences-- Send email alerts (if configured)-- Send Discord webhook alerts-- Send Telegram bot alerts-- Add alert cooldown to prevent spam-- Create notification templates--**Success Criteria**:-- [ ] Email notifications work-- [ ] Discord webhooks work-- [ ] Telegram notifications work-- [ ] Cooldown prevents duplicate alerts-------## Dependencies--```-Phase 22 (Logs API) ──────► Phase 23 (Log Viewer)- │- ▼-Phase 23 ─────────────────► Phase 24 (Search/Filter)--Phase 25 (Metrics Collection) ──► Phase 26 (Graphs)- │- ▼-Phase 26 ─────────────────────► Phase 27 (Alert Rules)- │- ▼-Phase 27 ─────────────────────► Phase 28 (Notifications)-```-------## Technical Notes--- Docker SDK for Python: `docker.containers.get(id).logs()`-- Docker stats API: `docker.containers.get(id).stats(stream=True)`-- WebSocket: Use existing Flask-SocketIO setup-- Charts: Recharts (already installed)-- Notifications: Extend existing NotificationService-------## Estimated Complexity--| Phase | Complexity | Files Changed |-|-------|------------|---------------|-| 22 | Medium | 4-6 (service, API, socket) |-| 23 | Medium | 3-5 (component, styles) |-| 24 | Medium | 2-4 (component updates) |-| 25 | High | 5-7 (model, service, API, job) |-| 26 | Medium | 3-5 (component, styles) |-| 27 | High | 5-7 (models, service, API) |-| 28 | Medium | 3-5 (service updates) |diff --git a/.planning/STATE.md b/.planning/STATE.mddeleted file mode 100644index 0bd739f4..00000000--- a/.planning/STATE.md+++ /dev/null@@ -1,91 +0,0 @@-# ServerKit Enhancement - State--## Current Status-- **Milestone**: 4 - Container Logs & Monitoring-- **Current Phase**: 23 - Log Viewer UI-- **Phase Status**: Planning Complete-- **Last Updated**: 2026-01-19--## Phase Progress--| Phase | Status | Started | Completed |-|-------|--------|---------|-----------|-| 22 | completed | 2026-01-19 | 2026-01-19 |-| 23 | pending | - | - |-| 24 | pending | - | - |-| 25 | pending | - | - |-| 26 | pending | - | - |-| 27 | pending | - | - |-| 28 | pending | - | - |--## Milestone 4 Overview-Container Logs & Monitoring (v1.3)--**Goal**: Add comprehensive container logging and monitoring capabilities - real-time log streaming, search/filtering, per-app resource graphs, and configurable alert rules with notifications.--**Key Features**:-- Real-time container log streaming via WebSocket-- Log search with filtering by level, time, regex-- Per-app CPU/memory/network metrics collection-- Resource usage graphs in application detail-- Configurable alert rules with thresholds-- Multi-channel notifications (email, Discord, Telegram)--## Phase Descriptions--### Phase 22: Container Logs API-Backend API to fetch and stream Docker container logs--### Phase 23: Log Viewer UI-Real-time log display with auto-scroll, ANSI color support--### Phase 24: Log Search & Filtering-Search within logs, filter by level/time, export--### Phase 25: Per-App Resource Collection-Collect per-container CPU/memory/network stats via Docker API--### Phase 26: App Resource Graphs-Per-app resource usage charts in application detail view--### Phase 27: Alert Rules Engine-Define thresholds, evaluate metrics, trigger alerts--### Phase 28: Alert Notifications-Send alerts via email, Discord, Telegram webhooks--## Previous Milestone Summary--### Milestone 3 (v1.2) - Completed 2026-01-19-Visual Workflow Builder:-- Phase 16: Workflow Canvas Foundation-- Phase 17: Resource Node Types-- Phase 18: Node Configuration Panels-- Phase 19: Connection Logic-- Phase 20: Workflow Save/Load-- Phase 21: Deploy from Workflow--### Milestone 2 (v1.1) - Completed 2026-01-19-Multi-Environment WordPress & Community Features:-- Phase 11-15: WordPress external DB, app linking, environment UI, GitHub links--### Milestone 1 (v1.0) - Completed 2026-01-19-Infrastructure Fixes, Private URLs & UI Polish:-- Phases 1-10: Docker/domain debugging, templates, UI polish--## Blockers-None currently identified.--## Notes-- Using subprocess for Docker CLI commands (not Docker SDK)-- WebSocket infrastructure extended with container log streaming-- Recharts already installed for graphs-- Existing NotificationService will be extended for alerts--## Session Log-- 2026-01-19: Phase 22 completed - Container Logs API (3 commits)--## Quick Links-- [ROADMAP.md](./ROADMAP.md)-- [PROJECT.md](./PROJECT.md)-- [Milestone 3 Archive](./milestones/v1.2-ROADMAP.md)diff --git a/.planning/milestones/v1.0-ROADMAP.md b/.planning/milestones/v1.0-ROADMAP.mddeleted file mode 100644index 3646705d..00000000--- a/.planning/milestones/v1.0-ROADMAP.md+++ /dev/null@@ -1,253 +0,0 @@-# Milestone 1: Infrastructure Fixes, Private URLs & UI Polish--> **Version**: 1.0-> **Completed**: 2026-01-19-> **Commits**: 109-> **Files Changed**: 94 (+14,667 / -2,836)-------## Key Accomplishments--1. **Docker/Domain Debugging Infrastructure** - Port accessibility checks, Nginx diagnostics, routing debug APIs and diagnostic UI for troubleshooting deployment issues-2. **Critical Bug Fixes** - Fixed NDJSON parsing in compose_ps (affecting container detection) and CLI .env loading for production environments-3. **Private URL System** - Secure shareable URLs with custom slugs, Nginx routing integration, frontend management component-4. **Dashboard Historical Metrics** - Time-series graphs using Recharts with background collection, auto-aggregation (minute/hour/day), and configurable retention-5. **Templates Page Polish** - Lucide icon fallbacks for 60+ templates, URL filter persistence, featured badges, enhanced cards and modal-6. **Applications UI Polish** - Grid/list toggle, bulk actions with confirmation modal, sorting options, enhanced status indicators with animations-7. **FileManager Disk Usage** - Multi-mount disk widget, directory size analysis, file type breakdown with PieChart, collapsible sidebar-------## Phase Details--### Phase 1: Docker & Domain Debugging-**Goal**: Fix port mapping and domain routing for Docker apps-**Status**: Completed--#### Deliverables-- `DockerService.check_port_accessible()` - Test port availability-- `DockerService.get_container_port_bindings()` - Get port mappings-- `DockerService.get_container_network_info()` - Full network settings-- `NginxService.get_site_config()` - Config content and status-- `NginxService.diagnose_site()` - Full diagnostic with recommendations-- Debug API endpoints: `/api/v1/domains/debug/diagnose/{app_id}`, `/api/v1/domains/debug/test-routing/{app_id}`-- `RoutingDiagnosticsCard` component in Application detail page-- `scripts/test-routing.sh` for manual server testing--#### Commits-- `5182d23` feat: Add port accessibility and container network diagnostics-- `f14af71` feat: Add Nginx config diagnostics and routing checks-- `cb809ee` feat: Add routing diagnostic API endpoints-- `1a2c390` fix: Validate port configuration on domain creation-- `5ac5a85` feat: Verify port accessibility after template installation-- `47acb09` feat: Add port accessibility to app status endpoint-- `9a072fb` feat: Add routing diagnostics UI to application detail-- `eeec611` chore: Add routing test script-------### Phase 2: WordPress Template Testing-**Goal**: Deploy and verify WordPress works end-to-end-**Status**: Completed--#### Findings-- WordPress template deploys and works correctly-- Domain routing through Nginx functions properly-- Found and fixed 2 critical bugs--#### Bug Fixes-1. **NDJSON Parsing** (`docker_service.py:compose_ps`) - `docker compose ps --format json` outputs NDJSON, not JSON array-2. **CLI .env Loading** (`cli.py`) - CLI commands failed to load .env from production paths--#### Commits-- `3f9884c` fix: Parse NDJSON output from docker compose ps-- `4ba0afe` fix: Load .env file in CLI before app initialization-------### Phase 3: PHP App Template Testing-**Goal**: Deploy and verify PHP/Laravel apps work correctly-**Status**: Completed--PHP testing completed - all Docker Compose output formats now handled.--#### Commits-- `4d9ad82` fix(3): handle all docker compose ps output formats-------### Phase 4: Flask/Python Template Testing-**Goal**: Deploy and verify Python apps route correctly-**Status**: Skipped (covered by Phase 1 debugging infrastructure)-------### Phase 5: Private URL System-**Goal**: Add private URL generation and custom slugs-**Status**: Completed--#### Deliverables-- Database fields: `private_slug`, `private_url_enabled`-- `PrivateURLService` for secure slug generation and validation-- API endpoints for enable/disable/update/regenerate-- Nginx config generation for `/p/{slug}` routing-- `PrivateURLSection` frontend component-- Private URL indicator in applications list--#### Commits-- `d40f82e` feat: Add private URL fields to Application model-- `5b0af3b` feat: Add PrivateURLService for slug generation-- `85cb72c` feat: Add private URL API endpoints-- `9a16753` feat: Add Nginx private URL configuration-- `48534dc` feat: Register private URLs API blueprint-- `f090f2b` feat: Add PrivateURLSection frontend component-- `17babbc` feat: Integrate PrivateURLSection into app detail-- `2bb90cb` feat: Add private URL indicator to applications list-------### Phase 6: Dashboard Historical Metrics-**Goal**: Add CPU/Memory/Disk graphs over time-**Status**: Completed--#### Deliverables-- `MetricsHistory` model with minute/hour/day aggregation levels-- `MetricsHistoryService` with background collection every 60 seconds-- Auto-aggregation and cleanup per retention policy (24h minute, 7d hourly, 30d daily)-- REST API endpoints: `/api/v1/metrics/history`, `/api/v1/metrics/stats`, collection control-- `MetricsGraph` component using Recharts LineChart-- Period selector (1h, 6h, 24h, 7d, 30d)--#### Commits-- `8a54630` feat(phase6): add MetricsHistory model-- `d6f0ee9` feat(phase6): add MetricsHistoryService-- `189dead` Add metrics API endpoints and auto-start collection-- `131757f` Add MetricsGraph component-- `900ac73` Integrate MetricsGraph into Dashboard-- `acbf79a` Add styles for MetricsGraph component-- `453697a` docs: Complete Phase 6-------### Phase 7: Templates Page Polish-**Goal**: Fix icons, update URLs, improve filtering-**Status**: Completed--#### Deliverables-- Lucide icon mappings for 60+ templates as fallbacks-- Icon error handling with graceful fallback-- URL param persistence for category, search, and sort filters-- Active filter chips with remove buttons and "Clear All"-- Featured badge for 10 curated templates-- Enhanced cards with version styling and link indicators-- Improved modal with requirements section and icons--#### Commits-- `342b660` feat(7): Polish templates page with icons, filters, and sorting-- `a11962d` docs(7): Complete Templates Page Polish phase-------### Phase 8: Applications UI Polish-**Goal**: Improve app list and management pages-**Status**: Completed--#### Deliverables-- Lucide icons replacing all inline SVGs-- Sorting options (name A-Z/Z-A, status, type, newest)-- Grid/list view toggle with localStorage persistence-- Bulk selection with checkboxes and action bar-- `ConfirmModal` component for destructive actions-- Enhanced status badges with animated pulse for running apps-- Search filter with URL param persistence-- Improved app cards with port, domain count, container info--#### Commits-- `9cdaf73` feat(8): Polish applications UI with icons, sorting, grid view, and bulk actions-- `b8e083c` docs(8): Add Phase 8 summary-------### Phase 9: FileManager Disk Usage UI-**Goal**: Better visualization for disk usage-**Status**: Completed--#### Deliverables-- Backend: `get_all_disk_mounts()`, `analyze_directory_sizes()`, `get_file_type_breakdown()`-- Multi-mount disk usage widget with color-coded progress bars-- Directory analysis panel with horizontal bar charts-- File type breakdown with Recharts PieChart (8 categories)-- Largest files list with navigation-- Collapsible sidebar with localStorage persistence-- Lucide icons replacing all emoji file icons-- Responsive layout with mobile sidebar slide-in--#### Commits-- `4c7f551` feat(9): Add backend directory analysis and disk mount endpoints-- `135f053` feat(9): Add FileManager disk usage visualization and analysis-- `5fd7f0e` docs(9): Add Phase 9 summary-------### Phase 10: Integration Testing-**Goal**: End-to-end testing of all features-**Status**: Skipped-------## Files Changed Summary--### Backend-- `backend/app/services/docker_service.py` - Port/network diagnostics-- `backend/app/services/nginx_service.py` - Config diagnostics, private URLs-- `backend/app/services/file_service.py` - Disk analysis methods-- `backend/app/services/private_url_service.py` - New service-- `backend/app/services/metrics_history_service.py` - New service-- `backend/app/models/application.py` - Private URL fields-- `backend/app/models/metrics_history.py` - New model-- `backend/app/api/domains.py` - Debug endpoints, validation-- `backend/app/api/apps.py` - Port status-- `backend/app/api/private_urls.py` - New blueprint-- `backend/app/api/metrics.py` - New blueprint-- `backend/app/api/files.py` - Analysis endpoints-- `backend/cli.py` - .env loading fix--### Frontend-- `frontend/src/pages/Dashboard.jsx` - Metrics graph integration-- `frontend/src/pages/Templates.jsx` - Complete rewrite-- `frontend/src/pages/Applications.jsx` - Complete rewrite-- `frontend/src/pages/FileManager.jsx` - Complete rewrite-- `frontend/src/pages/ApplicationDetail.jsx` - Diagnostics, private URL-- `frontend/src/components/MetricsGraph.jsx` - New component-- `frontend/src/components/PrivateURLSection.jsx` - New component-- `frontend/src/services/api.js` - All new API methods-- `frontend/src/styles/pages/_templates.less` - Extended-- `frontend/src/styles/pages/_applications.less` - Extended-- `frontend/src/styles/pages/_file-manager.less` - Extended-- `frontend/src/styles/components/_metrics-graph.less` - New-- `frontend/src/styles/components/_private-url.less` - New--### Scripts-- `scripts/test-routing.sh` - New diagnostic script-------## Technical Decisions--1. **Single Nginx config for private URLs** - All private URL routes in one config file, regenerated on change-2. **SQLite for metrics storage** - MetricsHistory model with auto-aggregation rather than time-series DB-3. **Recharts for visualization** - Consistent with existing project dependencies-4. **Lucide React icons** - Consistent icon library across all UI pages-5. **localStorage for UI state** - View modes, sidebar state persisted locally-6. **URL params for filters** - Shareable/bookmarkable filter states-------## Notes--- All UI pages now polished: Dashboard, Templates, Applications, FileManager-- Private URLs work for any Docker app with a configured port-- Metrics collection starts automatically on backend startup-- Directory analysis has depth limits to prevent performance issues-- All styling uses existing LESS variables for consistencydiff --git a/.planning/phases/01-docker-domain-debugging/SUMMARY.md b/.planning/phases/01-docker-domain-debugging/SUMMARY.mddeleted file mode 100644index 701b6992..00000000--- a/.planning/phases/01-docker-domain-debugging/SUMMARY.md+++ /dev/null@@ -1,101 +0,0 @@-# Phase 1: Docker & Domain Debugging - Summary--## Completion Status-**Completed**: 2026-01-19-**All 8 tasks completed successfully**--## What Was Built--### Backend Changes--#### 1. DockerService Diagnostics (`docker_service.py`)-- `check_port_accessible(port, host)` - Test if a port has something listening-- `get_container_port_bindings(container_name)` - Get port mappings for a container-- `get_container_network_info(container_name)` - Get full network settings including IPs--#### 2. NginxService Diagnostics (`nginx_service.py`)-- `get_site_config(name)` - Get config content, enabled status, parsed info-- `diagnose_site(name, port)` - Full diagnostic with health check and recommendations-- `check_site_routing(name, domain, port)` - Test the complete routing chain--#### 3. Debug API Endpoints (`domains.py`)-- `GET /api/v1/domains/debug/diagnose/{app_id}` - Comprehensive diagnostic report-- `POST /api/v1/domains/debug/test-routing/{app_id}` - Active routing tests--#### 4. Domain Creation Validation (`domains.py`)-- Docker apps now require a port before adding domains-- Port accessibility check with warning if not reachable-- Actionable error messages with hints--#### 5. Template Installation Verification (`template_service.py`)-- Wait for containers to start after docker compose up-- Check if configured port is accessible-- Include port status in installation response--#### 6. App Status Enhancement (`apps.py`)-- `GET /api/v1/apps/{id}/status` now includes:- - `port`: The configured port number- - `port_accessible`: Boolean indicating if port is reachable--### Frontend Changes--#### 7. Application Detail Page (`ApplicationDetail.jsx`)-- Port accessibility status shown in overview info-- New `RoutingDiagnosticsCard` component for Docker apps:- - Health summary (all checks passed / issues detected)- - Nginx config status (exists, enabled, running, syntax)- - Docker status (port accessible, containers found)- - Issues list with specific problems- - Recommendations list with fixes- - Expandable Nginx config preview--#### 8. Test Script (`scripts/test-routing.sh`)-- Comprehensive shell script for manual testing-- Tests: port, nginx config, syntax, service, backend, domain routing, docker status-- Colored output with pass/fail indicators-- Actionable hints for failures--## Commits--| Hash | Type | Description |-|------|------|-------------|-| `5182d23` | feat | Add port accessibility and container network diagnostics |-| `f14af71` | feat | Add Nginx config diagnostics and routing checks |-| `cb809ee` | feat | Add routing diagnostic API endpoints |-| `1a2c390` | fix | Validate port configuration on domain creation |-| `5ac5a85` | feat | Verify port accessibility after template installation |-| `47acb09` | feat | Add port accessibility to app status endpoint |-| `9a072fb` | feat | Add routing diagnostics UI to application detail |-| `eeec611` | chore | Add routing test script |--## Testing Checklist--To verify the implementation:--1. [ ] Deploy a Docker template (e.g., nginx, whoami)-2. [ ] Verify Application record has correct port in database-3. [ ] Check port is accessible: `curl http://127.0.0.1:{port}`-4. [ ] Add domain to the application via API/UI-5. [ ] Verify warning appears if port not accessible-6. [ ] Verify Nginx config created in `/etc/nginx/sites-available/`-7. [ ] Verify symlink in `/etc/nginx/sites-enabled/`-8. [ ] Call `/api/v1/domains/debug/diagnose/{app_id}` and check response-9. [ ] View app in UI, click "Run Diagnostics" button-10. [ ] Verify all health checks display correctly-11. [ ] Run `scripts/test-routing.sh {app_name} {port}` on server--## Known Limitations--1. Port check uses TCP connection - may show false positive if port bound but app not responding to HTTP-2. 3-second wait after container start may not be enough for slow-starting apps-3. Nginx config check requires file system access (admin only)-4. Test script requires bash and common Linux tools (nc, curl)--## Next Steps--With diagnostics in place, proceed to:-- **Phase 2**: Test WordPress template deployment-- **Phase 3**: Test PHP app template deployment-- **Phase 4**: Test Flask/Python template deployment--The diagnostic tools will help identify any remaining issues during template testing.diff --git a/.planning/phases/01-docker-domain-debugging/phase-1-PLAN.md b/.planning/phases/01-docker-domain-debugging/phase-1-PLAN.mddeleted file mode 100644index c856e420..00000000--- a/.planning/phases/01-docker-domain-debugging/phase-1-PLAN.md+++ /dev/null@@ -1,434 +0,0 @@-# Phase 1: Docker & Domain Debugging - Execution Plan--## Objective-Fix the critical issue where Docker apps are not accessible via connected domains. Traffic should flow: **Browser → Domain → Nginx → localhost:{port} → Docker Container**--## Problem Analysis--After reviewing the codebase, I identified the following potential issues:--### Issue 1: Port Mapping in Docker Compose-**Location**: `template_service.py:377-508` (install_template method)--The template service:-1. Generates `docker-compose.yml` from template-2. Stores port in Application model from variables (`PORT`, `HTTP_PORT`, `WEB_PORT`)-3. Runs `docker compose up`--**Problem**: The port stored in the Application model is the **host port** (good), but we need to verify the docker-compose.yml actually maps `host:container` correctly.--### Issue 2: Nginx Config Generation-**Location**: `nginx_service.py:115-138` (DOCKER_SITE_TEMPLATE)--```nginx-location / {- proxy_pass http://127.0.0.1:{port};- ...-}-```--**Current flow**:-1. User creates domain via `POST /api/v1/domains`-2. `domains.py:106-124` calls `NginxService.create_site()` for Docker apps-3. Creates config in `/etc/nginx/sites-available/{app_name}`-4. Enables site (symlink to `sites-enabled`)-5. Reloads Nginx--**Potential Issues**:-- Config might fail silently-- Port from Application model might be None or wrong-- Symlink might not be created-- Nginx reload might fail--### Issue 3: Missing Diagnostic Information-There's no way to:-- Check if a port is accessible on localhost-- View the generated Nginx config-- Test the proxy connection-- See container port bindings in the UI-------## Execution Context--### Files to Modify-```-backend/app/services/nginx_service.py # Add diagnostic methods-backend/app/services/docker_service.py # Add port inspection-backend/app/api/domains.py # Add debug endpoints-backend/app/api/apps.py # Enhance status with port info-frontend/src/pages/ApplicationDetail.jsx # Add diagnostic UI-```--### Dependencies-- Python: socket, subprocess (already available)-- Frontend: Existing API service-------## Tasks--### Task 1: Add Port Accessibility Check-**File**: `backend/app/services/docker_service.py`--Add method to check if a port is accessible:--```python-@staticmethod-def check_port_accessible(port: int, host: str = '127.0.0.1') -> Dict:- """Check if a port is accessible (something is listening)."""- import socket- try:- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- sock.settimeout(2)- result = sock.connect_ex((host, port))- sock.close()- return {- 'accessible': result == 0,- 'port': port,- 'host': host- }- except Exception as e:- return {'accessible': False, 'error': str(e)}--@staticmethod-def get_container_port_bindings(container_name: str) -> Dict:- """Get port bindings for a container."""- try:- result = subprocess.run(- ['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', container_name],- capture_output=True, text=True- )- if result.returncode == 0:- ports = json.loads(result.stdout.strip())- return {'success': True, 'ports': ports}- return {'success': False, 'error': result.stderr}- except Exception as e:- return {'success': False, 'error': str(e)}-```--**Verification**: Unit test with a known running container-------### Task 2: Add Nginx Config Diagnostics-**File**: `backend/app/services/nginx_service.py`--Add methods to diagnose Nginx configuration:--```python-@classmethod-def get_site_config(cls, name: str) -> Dict:- """Get the content of a site configuration file."""- config_path = os.path.join(cls.SITES_AVAILABLE, name)- if not os.path.exists(config_path):- return {'exists': False, 'error': 'Config file not found'}-- try:- with open(config_path, 'r') as f:- content = f.read()-- enabled_path = os.path.join(cls.SITES_ENABLED, name)- is_enabled = os.path.exists(enabled_path) or os.path.islink(enabled_path)-- return {- 'exists': True,- 'enabled': is_enabled,- 'content': content,- 'path': config_path- }- except Exception as e:- return {'exists': True, 'error': str(e)}--@classmethod-def diagnose_site(cls, name: str, port: int = None) -> Dict:- """Full diagnostic for a site configuration."""- diagnosis = {- 'config': cls.get_site_config(name),- 'nginx_running': cls.get_status().get('running', False),- 'config_valid': cls.test_config()- }-- if port:- from app.services.docker_service import DockerService- diagnosis['port_accessible'] = DockerService.check_port_accessible(port)-- return diagnosis-```--**Verification**: Test with an existing app-------### Task 3: Add Debug API Endpoints-**File**: `backend/app/api/domains.py`--Add diagnostic endpoints:--```python-@domains_bp.route('/debug/diagnose/<int:app_id>', methods=['GET'])-@jwt_required()-@admin_required-def diagnose_app_routing(app_id):- """Diagnose routing issues for an application."""- app = Application.query.get(app_id)- if not app:- return jsonify({'error': 'Application not found'}), 404-- diagnosis = {- 'app': {- 'id': app.id,- 'name': app.name,- 'type': app.app_type,- 'port': app.port,- 'root_path': app.root_path,- 'status': app.status- },- 'domains': [],- 'nginx': None,- 'docker': None- }-- # Get domains- domains = Domain.query.filter_by(application_id=app_id).all()- diagnosis['domains'] = [d.to_dict() for d in domains]-- # Nginx diagnosis- diagnosis['nginx'] = NginxService.diagnose_site(app.name, app.port)-- # Docker diagnosis (if docker app)- if app.app_type == 'docker':- from app.services.docker_service import DockerService-- # Check port accessibility- if app.port:- diagnosis['docker'] = {- 'port_check': DockerService.check_port_accessible(app.port),- }-- # Get container info- if app.root_path:- containers = DockerService.compose_ps(app.root_path)- diagnosis['docker']['containers'] = containers-- # Get port bindings for each container- for container in containers:- if container.get('Name'):- bindings = DockerService.get_container_port_bindings(container['Name'])- container['port_bindings'] = bindings-- return jsonify(diagnosis), 200-```--**Verification**: Call endpoint and verify all data is returned-------### Task 4: Fix Domain Creation to Validate Port-**File**: `backend/app/api/domains.py`--Enhance domain creation to validate the port is accessible before creating Nginx config:--```python-# In create_domain(), after getting the app:-if app.app_type == 'docker':- if not app.port:- return jsonify({- 'error': 'Docker app must have a port configured before adding domains',- 'hint': 'Update the application with a valid port number'- }), 400-- # Check if port is accessible- from app.services.docker_service import DockerService- port_check = DockerService.check_port_accessible(app.port)-- # Add warning if port not accessible (but still allow creation)- port_warning = None- if not port_check.get('accessible'):- port_warning = f"Warning: Port {app.port} is not currently accessible. Make sure the container is running."-```--Then include `port_warning` in the response.--**Verification**: Create domain for stopped app, verify warning appears-------### Task 5: Add Container Port Discovery-**File**: `backend/app/services/template_service.py`--After starting containers, verify the actual port mapping:--```python-# In install_template(), after compose_up succeeds (around line 458):--# Verify container is actually running and port is mapped-import time-time.sleep(2) # Give container time to start--if app_port:- from app.services.docker_service import DockerService- port_check = DockerService.check_port_accessible(app_port)- if not port_check.get('accessible'):- # Log warning but don't fail - container might need more startup time- print(f"Warning: Port {app_port} not accessible immediately after start")-```--**Verification**: Install a template and check logs-------### Task 6: Enhance App Status API with Port Info-**File**: `backend/app/api/apps.py`--Modify `get_app_status` to include port accessibility:--```python-# In get_app_status(), add after getting containers:--# Add port check-port_status = None-if app.port:- port_status = DockerService.check_port_accessible(app.port)--return jsonify({- 'status': actual_status,- 'containers': containers,- 'running': running_count,- 'total': total_count,- 'port': app.port,- 'port_accessible': port_status.get('accessible') if port_status else None-}), 200-```--**Verification**: Call `/api/v1/apps/{id}/status` and verify port_accessible field-------### Task 7: Add Frontend Diagnostic Display-**File**: `frontend/src/pages/ApplicationDetail.jsx`--Add a diagnostic section that shows:-- Port configuration and accessibility-- Nginx config status (exists, enabled)-- Container port bindings-- "Test Connection" button--```jsx-// Add new component or section:-<div className="diagnostic-section">- <h3>Routing Diagnostics</h3>-- <div className="diagnostic-item">- <label>Port:</label>- <span>{app.port || 'Not configured'}</span>- {portAccessible !== null && (- <span className={portAccessible ? 'status-ok' : 'status-error'}>- {portAccessible ? '✓ Accessible' : '✗ Not accessible'}- </span>- )}- </div>-- <div className="diagnostic-item">- <label>Nginx Config:</label>- <span className={nginxStatus?.exists ? 'status-ok' : 'status-error'}>- {nginxStatus?.exists ? 'Created' : 'Missing'}- </span>- {nginxStatus?.enabled && <span className="badge">Enabled</span>}- </div>-- <button onClick={runDiagnostics}>Run Full Diagnostics</button>-</div>-```--**Verification**: View app detail page and verify diagnostics display-------### Task 8: Create Test Script-**File**: `scripts/test-routing.sh` (new file)--Create a script to test the full routing chain:--```bash-#!/bin/bash-# Test Docker app routing--APP_NAME=$1-PORT=$2-DOMAIN=$3--echo "=== Testing routing for $APP_NAME ==="--echo "1. Checking if port $PORT is accessible on localhost..."-nc -z 127.0.0.1 $PORT && echo " ✓ Port accessible" || echo " ✗ Port NOT accessible"--echo "2. Checking Nginx config..."-[ -f /etc/nginx/sites-available/$APP_NAME ] && echo " ✓ Config exists" || echo " ✗ Config missing"-[ -L /etc/nginx/sites-enabled/$APP_NAME ] && echo " ✓ Config enabled" || echo " ✗ Config NOT enabled"--echo "3. Testing Nginx config syntax..."-sudo nginx -t 2>&1 | grep -q "successful" && echo " ✓ Config valid" || echo " ✗ Config INVALID"--echo "4. Testing HTTP request to localhost:$PORT..."-curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$PORT/ | grep -q "200\|301\|302" && echo " ✓ Container responds" || echo " ✗ Container NOT responding"--if [ -n "$DOMAIN" ]; then- echo "5. Testing HTTP request via domain $DOMAIN..."- curl -s -o /dev/null -w "%{http_code}" -H "Host: $DOMAIN" http://127.0.0.1/ | grep -q "200\|301\|302" && echo " ✓ Domain routing works" || echo " ✗ Domain routing FAILED"-fi--echo "=== Done ==="-```--**Verification**: Run script with a test app-------## Verification--### Integration Test Checklist-After all tasks complete:--1. [ ] Deploy a Docker template (e.g., nginx, whoami)-2. [ ] Verify Application record has correct port-3. [ ] Check port is accessible: `curl http://127.0.0.1:{port}`-4. [ ] Add domain to the application-5. [ ] Verify Nginx config created in `/etc/nginx/sites-available/`-6. [ ] Verify symlink in `/etc/nginx/sites-enabled/`-7. [ ] Test domain access: `curl -H "Host: yourdomain.com" http://127.0.0.1/`-8. [ ] Check diagnostic endpoint returns all data-9. [ ] Verify frontend shows diagnostic info--### Expected Results-- Port accessibility shows green checkmark when container is running-- Nginx config status shows "Created" and "Enabled"-- Domain resolves to the correct container-- Diagnostic endpoint provides actionable information-------## Success Criteria-- [ ] Docker containers expose ports to localhost correctly-- [ ] Nginx configs are created and enabled automatically-- [ ] Domains route traffic to Docker containers-- [ ] Diagnostic info visible in UI-- [ ] Debug endpoint provides full routing diagnosis-- [ ] Clear error messages when something is misconfigured-------## Rollback Plan-All changes are additive (new methods, new endpoints). No breaking changes to existing functionality. If issues arise:-1. Revert the specific file changes-2. Existing functionality remains unchanged-------## Output-After execution:-- New diagnostic methods in DockerService and NginxService-- New `/api/v1/domains/debug/diagnose/{app_id}` endpoint-- Enhanced app status with port information-- Frontend diagnostic section in ApplicationDetail-- Test script for manual verificationdiff --git a/.planning/phases/02-wordpress-testing/SUMMARY.md b/.planning/phases/02-wordpress-testing/SUMMARY.mddeleted file mode 100644index fb17a8c5..00000000--- a/.planning/phases/02-wordpress-testing/SUMMARY.md+++ /dev/null@@ -1,112 +0,0 @@-# Phase 2: WordPress Template Testing - Summary--## Completion Status-**Completed**: 2026-01-19-**Result**: WordPress deployment works; 2 bugs found and fixed--## Test Results--### What Works Correctly-- Template listing and fetching-- Template installation with docker-compose-- Port allocation and accessibility-- Nginx reverse proxy configuration-- Domain management-- WordPress container runs properly-- Domain routing through Nginx works-- `curl http://test-wordpress.local/` returns WordPress--### Verification Checklist--| Check | Result |-|-------|--------|-| WordPress template loads from API | PASS |-| Template installs without errors | PASS |-| Both containers (wordpress, db) running | PASS |-| Port is accessible on localhost | PASS |-| Domain created without errors | PASS |-| Nginx config exists and is enabled | PASS |-| Direct port access returns HTTP response | PASS |-| Domain routing works via Nginx | PASS |-| WordPress installation wizard loads | PASS |--## Bugs Found and Fixed--### Bug 1: Container Detection Fails (Critical)-**Location**: `docker_service.py:539-551` (`compose_ps` method)--**Root Cause**: `docker compose ps --format json` outputs NDJSON (one JSON object per line), not a JSON array. The code did:-```python-return json.loads(result.stdout) # Fails on NDJSON-```-This threw `JSONDecodeError`, which was caught and returned `[]`.--**Fix**: Parse each line separately:-```python-containers = []-for line in result.stdout.strip().split('\n'):- if line.strip():- containers.append(json.loads(line))-return containers-```--**Commit**: `3f9884c`--### Bug 2: CLI Database Path Issue-**Location**: `cli.py`--**Root Cause**: CLI commands (like `list-users`, `reset-password`) failed with "unable to open database file" because they didn't load the `.env` file from `/opt/serverkit/.env`. The code used the default path `sqlite:////app/instance/serverkit.db` instead of the configured path.--**Fix**: Load `.env` file before `create_app()` is called:-```python-from dotenv import load_dotenv-# Check multiple locations: ./env, ../env, /opt/serverkit/.env-```--**Commit**: `4ba0afe`--### Bug 3: Database Status Not Updated (Consequence of Bug 1)-**Location**: `apps.py:313-325`--**Root Cause**: When `compose_ps` returned empty `[]` (due to Bug 1), the status endpoint saw `total_count == 0` and set `actual_status = 'stopped'`, then updated the database.--**Fix**: Bug 1 fix resolves this. Now `compose_ps` correctly returns container list.--**Note**: The `container_id` field is intentionally not populated for Docker Compose apps because they have multiple containers with auto-generated names.--## Commits--| Hash | Type | Description |-|------|------|-------------|-| `3f9884c` | fix | Parse NDJSON output from docker compose ps |-| `4ba0afe` | fix | Load .env file in CLI before app initialization |--## Success Criteria--- [x] WordPress container starts successfully-- [x] Database connection works-- [x] Domain routes to WordPress-- [x] Installation wizard accessible--## Impact of Fixes--The Bug 1 fix is **critical** because it affects:-1. App status endpoint (`/api/v1/apps/{id}/status`)-2. Routing diagnostics (`/api/v1/domains/debug/diagnose/{app_id}`)-3. Any code using `DockerService.compose_ps()`--The Bug 2 fix enables CLI commands to work in production environments.--## Recommendations--1. **Test on server**: Re-run the diagnostics endpoint after deploying these fixes-2. **Verify status**: Check that app status now shows 'running' correctly-3. **CLI test**: Run `python cli.py --debug list-users` to verify .env loading--## Next Steps--With WordPress working:-- **Phase 3**: PHP App Template Testing-- **Phase 4**: Flask/Python Template Testing--Both should benefit from the Bug 1 fix.diff --git a/.planning/phases/02-wordpress-testing/phase-2-PLAN.md b/.planning/phases/02-wordpress-testing/phase-2-PLAN.mddeleted file mode 100644index b5ed60ae..00000000--- a/.planning/phases/02-wordpress-testing/phase-2-PLAN.md+++ /dev/null@@ -1,316 +0,0 @@-# Phase 2: WordPress Template Testing - Execution Plan--## Objective-Deploy a WordPress template and verify end-to-end functionality: container startup, database connectivity, Nginx routing, and domain access. Use Phase 1 diagnostic tools to identify and fix any issues.--## Context--### WordPress Template Location-- **Template file**: `backend/templates/wordpress.yaml`-- **Version**: WordPress 6.4 with MySQL 8.0-- **Services**: WordPress (Apache+PHP) + MySQL database-- **Default port**: 8080--### Template Structure-```yaml-compose:- services:- wordpress:- image: wordpress:6.4-apache- ports: "${HTTP_PORT}:80"- volumes: wordpress_html:/var/www/html- db:- image: mysql:8.0- volumes: wordpress_db:/var/lib/mysql-```--### Available Diagnostic Tools (from Phase 1)-- `GET /api/v1/domains/debug/diagnose/{app_id}` - Full routing diagnosis-- `GET /api/v1/apps/{id}/status` - Port accessibility check-- UI: Application Detail → Routing Diagnostics card-- CLI: `scripts/test-routing.sh`-------## Prerequisites--Before testing, ensure:-1. Docker is installed and running-2. ServerKit backend is running-3. User is authenticated with admin role-4. `/var/serverkit/apps/` directory exists with write permissions-5. `/etc/serverkit/` directory exists for template config-------## Tasks--### Task 1: Verify Template Exists and Is Valid-**Type**: Verification (no code changes expected)--1. Check that `backend/templates/wordpress.yaml` exists-2. Verify template structure matches schema-3. Confirm template is in `backend/templates/index.json`-4. Test template fetch via API: `GET /api/v1/templates/wordpress`--**Expected Result**: Template loads without errors--**If Issues Found**:-- Fix YAML syntax errors-- Add missing required fields-- Update index.json if template missing-------### Task 2: Install WordPress Template-**Type**: Testing--1. Call template installation API:- ```- POST /api/v1/templates/wordpress/install- {- "name": "test-wordpress",- "variables": {- "HTTP_PORT": "8085"- }- }- ```--2. Monitor installation:- - Check for errors in response- - Verify `port_accessible` field in response- - Note the `app_id` returned--3. Verify files created:- - `/var/serverkit/apps/test-wordpress/docker-compose.yml`- - `/var/serverkit/apps/test-wordpress/.env`- - `/var/serverkit/apps/test-wordpress/.serverkit-template.json`--**Expected Result**: Installation completes, returns app_id, port_accessible = true--**If Issues Found**:-- Check Docker logs: `docker compose logs` in app directory-- Verify MySQL container starts (slow startup)-- Check port conflicts with `_find_available_port()`-------### Task 3: Verify Container Status-**Type**: Testing--1. Check Docker containers running:- ```bash- docker ps --filter "name=test-wordpress"- ```--2. Verify both services are up:- - `test-wordpress-wordpress-1` (or similar name)- - `test-wordpress-db-1`--3. Check container health:- ```bash- docker compose -f /var/serverkit/apps/test-wordpress/docker-compose.yml ps- ```--4. Call app status API:- ```- GET /api/v1/apps/{app_id}/status- ```- - Expect: `status: running`, `port_accessible: true`--**Expected Result**: Both containers running, port accessible--**If Issues Found**:-- MySQL may need 30-60 seconds to initialize-- Check logs: `docker compose logs db`-- WordPress may fail if DB not ready - check `docker compose logs wordpress`-------### Task 4: Verify Database Connectivity-**Type**: Testing--1. Check MySQL container accepts connections:- ```bash- docker exec test-wordpress-db-1 mysql -u wordpress -p${WP_DB_PASSWORD} -e "SHOW DATABASES;"- ```--2. Verify WordPress database exists:- ```bash- docker exec test-wordpress-db-1 mysql -u wordpress -p${WP_DB_PASSWORD} -e "USE wordpress; SHOW TABLES;"- ```--3. Check WordPress can connect to DB:- - Access WordPress container- - Check wp-config.php has correct credentials- - Or simply verify WordPress loads (Task 5)--**Expected Result**: Database accessible, credentials work--**If Issues Found**:-- Check environment variables in `.env` file-- Verify MySQL finished initializing-- Check Docker network connectivity between containers-------### Task 5: Add Domain and Test Nginx Routing-**Type**: Testing + Potential fixes--1. Create domain for the app:- ```- POST /api/v1/domains- {- "name": "test-wordpress.local",- "application_id": {app_id},- "is_primary": true- }- ```--2. Check for warnings in response (port not accessible, etc.)--3. Run Phase 1 diagnostics:- ```- GET /api/v1/domains/debug/diagnose/{app_id}- ```--4. Verify Nginx config created:- - Check `/etc/nginx/sites-available/test-wordpress`- - Check symlink in `/etc/nginx/sites-enabled/`- - Verify config has correct port--5. Test direct port access:- ```bash- curl -I http://127.0.0.1:8085/- ```- - Should return 302 redirect to WordPress setup--6. Test domain routing (add to /etc/hosts first):- ```bash- echo "127.0.0.1 test-wordpress.local" | sudo tee -a /etc/hosts- curl -I http://test-wordpress.local/- ```--**Expected Result**:-- Nginx config created and enabled-- Direct port access returns HTTP response-- Domain routing works--**If Issues Found**:-- Use Phase 1 diagnostics to identify specific failure-- Check Nginx logs: `/var/log/nginx/test-wordpress.error.log`-- Verify Nginx service is running-- Check port matches between Nginx config and container-------### Task 6: Access WordPress Installation Wizard-**Type**: Testing--1. Open browser to `http://test-wordpress.local/` or `http://127.0.0.1:8085/`--2. Verify WordPress installation page loads:- - Should show language selection- - Then show "Welcome" setup page- - Should ask for site title, admin user, password--3. Complete WordPress installation:- - Site Title: "Test WordPress"- - Username: admin- - Password: (generate strong password)- - Email: [email protected]--4. Verify WordPress dashboard loads after installation--**Expected Result**: WordPress fully functional, can create posts--**If Issues Found**:-- Check browser console for errors-- Verify database connectivity (Task 4)-- Check file permissions in WordPress volume-------### Task 7: Document Results and Issues-**Type**: Documentation--1. Create test results document with:- - Installation outcome (success/failure)- - Container status- - Database connectivity- - Nginx routing status- - WordPress accessibility- - Any errors encountered- - Fixes applied--2. If issues found, categorize:- - **Template issues**: Fix in `wordpress.yaml`- - **Service issues**: Fix in `template_service.py`- - **Nginx issues**: Fix in `nginx_service.py`- - **Docker issues**: Document workaround--3. Update template if changes needed--**Expected Result**: Clear documentation of test results-------## Verification Checklist--After completing all tasks:--- [ ] WordPress template loads from API-- [ ] Template installs without errors-- [ ] Both containers (wordpress, db) running-- [ ] Port is accessible on localhost-- [ ] Domain created without errors-- [ ] Nginx config exists and is enabled-- [ ] Direct port access returns HTTP response-- [ ] Domain routing works via Nginx-- [ ] WordPress installation wizard loads-- [ ] WordPress installation completes-- [ ] WordPress dashboard accessible-- [ ] Can create and view a blog post-------## Success Criteria--- [ ] WordPress container starts successfully-- [ ] Database connection works-- [ ] Domain routes to WordPress-- [ ] Installation wizard accessible-------## Cleanup (After Testing)--To remove test installation:-```bash-# Stop and remove containers-docker compose -f /var/serverkit/apps/test-wordpress/docker-compose.yml down -v--# Remove app directory-rm -rf /var/serverkit/apps/test-wordpress--# Remove from database-DELETE FROM applications WHERE name = 'test-wordpress';--# Remove Nginx config-sudo rm /etc/nginx/sites-enabled/test-wordpress-sudo rm /etc/nginx/sites-available/test-wordpress-sudo nginx -s reload--# Remove hosts entry-sudo sed -i '/test-wordpress.local/d' /etc/hosts-```-------## Output--After execution:-- Verified WordPress template works end-to-end-- Documentation of any issues found-- Fixes applied if needed-- Ready to proceed to Phase 3 (PHP testing)diff --git a/.planning/phases/03-php-testing/phase-3-PLAN.md b/.planning/phases/03-php-testing/phase-3-PLAN.mddeleted file mode 100644index 50198e15..00000000--- a/.planning/phases/03-php-testing/phase-3-PLAN.md+++ /dev/null@@ -1,280 +0,0 @@-# Phase 3: PHP App Template Testing - Execution Plan--## Objective-Deploy a PHP application template and verify end-to-end functionality: container startup, PHP execution, Nginx routing, and domain access. Verify the Bug 1 fix from Phase 2 works correctly.--## Context--### PHP Template Location-- **Template file**: `backend/templates/php-app.yaml`-- **Version**: PHP 8.3 with Apache-- **Default port**: 8100-- **Image**: `php:8.3-apache`--### Template Structure-```yaml-compose:- services:- app:- image: php:${PHP_VERSION:-8.3}-apache- ports: "${HTTP_PORT}:80"- volumes: html:/var/www/html-```--### Key Differences from WordPress-- Single container (no database)-- Apache built-in (not Nginx + PHP-FPM)-- Volume for custom PHP code-- Simpler deployment--### Available Diagnostic Tools (from Phase 1)-- `GET /api/v1/domains/debug/diagnose/{app_id}` - Full routing diagnosis-- `GET /api/v1/apps/{id}/status` - Port accessibility check-- Phase 2 bug fixes: NDJSON parsing should now work correctly-------## Prerequisites--Before testing:-1. Phase 2 bug fixes deployed (`3f9884c` - NDJSON parsing)-2. Docker installed and running-3. ServerKit backend running-4. Admin API access-------## Tasks--### Task 1: Verify Template Exists and Is Valid-**Type**: Verification--1. Check that `backend/templates/php-app.yaml` exists-2. Verify template structure matches schema-3. Confirm template is in `backend/templates/index.json`-4. Test template fetch via API: `GET /api/v1/templates/php-app`--**Expected Result**: Template loads without errors-------### Task 2: Install PHP App Template-**Type**: Testing--1. Call template installation API:- ```- POST /api/v1/templates/php-app/install- {- "name": "test-php",- "variables": {- "HTTP_PORT": "8100",- "PHP_VERSION": "8.3"- }- }- ```--2. Monitor installation:- - Check for errors in response- - Verify `port_accessible` field in response- - Note the `app_id` returned--3. Verify files created:- - `/var/serverkit/apps/test-php/docker-compose.yml`- - `/var/serverkit/apps/test-php/.env`--**Expected Result**: Installation completes, returns app_id-------### Task 3: Verify Container Status (Bug Fix Validation)-**Type**: Testing + Bug Fix Validation--This task validates the Phase 2 Bug 1 fix (NDJSON parsing).--1. Check Docker container running:- ```bash- docker ps --filter "name=test-php"- ```--2. Call app status API:- ```- GET /api/v1/apps/{app_id}/status- ```- - **Critical**: Verify `containers` array is NOT empty (Bug 1 fix)- - Expect: `status: running`, `port_accessible: true`--3. Verify status in database matches actual container state--**Expected Result**: Status endpoint correctly shows running container--**If Bug Not Fixed**:-- containers array is empty-- status shows 'stopped' despite container running-- Need to verify NDJSON fix was deployed-------### Task 4: Create Test PHP File-**Type**: Testing--1. Create a simple PHP info file in the container:- ```bash- docker exec test-php bash -c 'echo "<?php phpinfo(); ?>" > /var/www/html/index.php'- ```--2. Test direct port access:- ```bash- curl http://127.0.0.1:8100/- ```- - Should return PHP info page HTML--3. Verify PHP version:- ```bash- docker exec test-php php -v- ```- - Should show PHP 8.3.x--**Expected Result**: PHP executes correctly, phpinfo() displays-------### Task 5: Add Domain and Test Nginx Routing-**Type**: Testing--1. Create domain for the app:- ```- POST /api/v1/domains- {- "name": "test-php.local",- "application_id": {app_id},- "is_primary": true- }- ```--2. Run diagnostics:- ```- GET /api/v1/domains/debug/diagnose/{app_id}- ```- - Verify `health.overall` is true- - Verify `docker.containers` is NOT empty--3. Verify Nginx config:- ```bash- cat /etc/nginx/sites-available/test-php- ```- - Should proxy to port 8100--4. Test domain routing:- ```bash- echo "127.0.0.1 test-php.local" | sudo tee -a /etc/hosts- curl http://test-php.local/- ```--**Expected Result**: Domain routes to PHP app, phpinfo() displays-------### Task 6: Test PHP Functionality-**Type**: Testing--1. Create test PHP script:- ```bash- docker exec test-php bash -c 'cat > /var/www/html/test.php << EOF- <?php- header("Content-Type: application/json");- echo json_encode([- "status" => "ok",- "php_version" => PHP_VERSION,- "server" => \$_SERVER["SERVER_SOFTWARE"],- "document_root" => \$_SERVER["DOCUMENT_ROOT"],- "extensions" => get_loaded_extensions()- ]);- EOF'- ```--2. Test via curl:- ```bash- curl http://test-php.local/test.php- ```- - Should return JSON with PHP info--3. Verify common extensions are available:- - json, mbstring, curl should be loaded--**Expected Result**: PHP scripts execute, JSON returned-------### Task 7: Document Results-**Type**: Documentation--1. Create test results document with:- - Installation outcome- - Container detection (Bug 1 validation)- - PHP execution- - Nginx routing- - Any issues found--2. Compare to WordPress results:- - Both should now work with Bug 1 fix- - Note any PHP-specific issues--**Expected Result**: Clear documentation of test results-------## Verification Checklist--After completing all tasks:--- [ ] PHP template loads from API-- [ ] Template installs without errors-- [ ] Container is detected correctly (Bug 1 validation)-- [ ] Port is accessible on localhost-- [ ] PHP executes in container-- [ ] Domain created without errors-- [ ] Nginx config exists and is enabled-- [ ] Domain routing works via Nginx-- [ ] PHP scripts return expected output-- [ ] Diagnostics show correct health status-------## Success Criteria--- [ ] PHP apps execute correctly via Nginx-- [ ] Static assets served properly-- [ ] Container detection works (Bug 1 fix validated)-------## Cleanup (After Testing)--```bash-# Stop and remove container-docker compose -f /var/serverkit/apps/test-php/docker-compose.yml down -v--# Remove app directory-rm -rf /var/serverkit/apps/test-php--# Remove from database-DELETE FROM applications WHERE name = 'test-php';--# Remove Nginx config-sudo rm /etc/nginx/sites-enabled/test-php-sudo rm /etc/nginx/sites-available/test-php-sudo nginx -s reload--# Remove hosts entry-sudo sed -i '/test-php.local/d' /etc/hosts-```-------## Output--After execution:-- Verified PHP template works end-to-end-- Validated Bug 1 fix from Phase 2-- Documentation of any issues found-- Ready to proceed to Phase 4 (Flask/Python testing)diff --git a/.planning/phases/05-private-urls/SUMMARY.md b/.planning/phases/05-private-urls/SUMMARY.mddeleted file mode 100644index a321fff4..00000000--- a/.planning/phases/05-private-urls/SUMMARY.md+++ /dev/null@@ -1,131 +0,0 @@-# Phase 5: Private URL System - Summary--## Completion Status-**Completed**: 2026-01-19-**Result**: Private URL system fully implemented--## What Was Built--### Backend--1. **Database Schema** (`backend/app/models/application.py`)- - Added `private_slug` field (unique, indexed)- - Added `private_url_enabled` boolean field- - Updated `to_dict()` to include new fields--2. **Private URL Service** (`backend/app/services/private_url_service.py`)- - Cryptographically secure slug generation (12 chars default)- - Slug validation (length, format, reserved words)- - Uniqueness checking with database queries- - Reserved slugs: api, admin, static, assets, health, status--3. **API Endpoints** (`backend/app/api/private_urls.py`)- - `POST /api/v1/apps/{id}/private-url` - Enable with optional custom slug- - `GET /api/v1/apps/{id}/private-url` - Get current status- - `PUT /api/v1/apps/{id}/private-url` - Update slug- - `DELETE /api/v1/apps/{id}/private-url` - Disable- - `POST /api/v1/apps/{id}/private-url/regenerate` - Generate new random slug- - `GET /api/v1/apps/p/{slug}` - Public resolver (no auth required)--4. **Nginx Integration** (`backend/app/services/nginx_service.py`)- - Template for private URL location blocks- - `regenerate_all_private_urls()` - Full config regeneration- - Auto-enables site config and reloads Nginx- - Handles both with and without trailing slash--### Frontend--5. **Private URL Component** (`frontend/src/components/PrivateURLSection.jsx`)- - Enable/disable toggle with custom slug input- - Copy to clipboard functionality- - Regenerate random slug button- - Edit slug with validation feedback- - Clean UI with proper styling--6. **API Methods** (`frontend/src/services/api.js`)- - `enablePrivateUrl(appId, slug)`- - `getPrivateUrl(appId)`- - `updatePrivateUrl(appId, slug)`- - `disablePrivateUrl(appId)`- - `regeneratePrivateUrl(appId)`--7. **Styles** (`frontend/src/styles/components/_private-url.less`)- - Section styling matching existing design- - Input group with `/p/` prefix- - Success state for enabled URLs- - Indicator styling for app list--8. **Integration**- - `ApplicationDetail.jsx` - PrivateURLSection in OverviewTab for Docker apps- - `Applications.jsx` - Private URL indicator badge in app list--## Commits--| Hash | Type | Description |-|------|------|-------------|-| `d40f82e` | feat | Add private URL fields to Application model |-| `5b0af3b` | feat | Add PrivateURLService for slug generation |-| `85cb72c` | feat | Add private URL API endpoints |-| `9a16753` | feat | Add Nginx private URL configuration |-| `48534dc` | feat | Register private URLs API blueprint |-| `f090f2b` | feat | Add PrivateURLSection frontend component |-| `17babbc` | feat | Integrate PrivateURLSection into app detail |-| `2bb90cb` | feat | Add private URL indicator to applications list |--## Verification Checklist--- [x] Database fields added (`private_slug`, `private_url_enabled`)-- [x] API endpoints respond correctly-- [x] Slug validation works (length, format, uniqueness, reserved)-- [x] Nginx config generation implemented-- [x] Frontend component renders correctly-- [x] Copy to clipboard works-- [x] Regenerate creates new slug-- [x] Custom slug can be set-- [x] Disable removes slug-- [x] Application list shows indicator--## Success Criteria--- [x] Private URLs can be generated for any Docker app-- [x] Custom slugs work with validation-- [x] Private URL routes to correct container via Nginx-- [x] UI allows easy management and copying--## Technical Decisions--1. **Single config file approach**: All private URLs in one Nginx config file (`serverkit-private-urls`), regenerated on any change. Simpler than per-app files.--2. **Slug format**: Lowercase alphanumeric + hyphens, 3-50 chars, can't start/end with hyphen or have consecutive hyphens.--3. **Port requirement**: Only Docker apps with a configured port can have private URLs.--4. **Auth model**: Enabling/managing requires authentication. Accessing the private URL itself requires no auth (by design - shareable).--## Testing Notes--To test the feature:--1. **Enable private URL**:- ```bash- curl -X POST http://localhost:5000/api/v1/apps/{id}/private-url \- -H "Authorization: Bearer $TOKEN" \- -H "Content-Type: application/json" \- -d '{"slug": "my-custom-slug"}'- ```--2. **Access private URL** (after Nginx config deployed):- ```bash- curl http://server.example.com/p/my-custom-slug/- ```--3. **Resolve slug**:- ```bash- curl http://localhost:5000/api/v1/apps/p/my-custom-slug- ```--## Next Steps--- Phase 6: Dashboard Historical Metrics-- Phase 7: Templates Page Polish-- Phase 8: Applications UI Polishdiff --git a/.planning/phases/05-private-urls/phase-5-PLAN.md b/.planning/phases/05-private-urls/phase-5-PLAN.mddeleted file mode 100644index 3c26fab7..00000000--- a/.planning/phases/05-private-urls/phase-5-PLAN.md+++ /dev/null@@ -1,804 +0,0 @@-# Phase 5: Private URL System - Execution Plan--## Objective-Allow applications to have private, shareable URLs that are not publicly indexed. Users can generate random slugs or set custom slugs for private access.--## Context--### Current Application Model-From `backend/app/models/application.py`:-```python-class Application(db.Model):- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(100), nullable=False)- app_type = db.Column(db.String(50), nullable=False)- status = db.Column(db.String(20), default='stopped')- port = db.Column(db.Integer, nullable=True)- root_path = db.Column(db.String(500), nullable=True)- # ... other fields-```--### Nginx Integration-The `NginxService` already handles reverse proxy configuration for Docker apps using the `DOCKER_SITE_TEMPLATE`. Private URLs will need a separate routing mechanism.--### API Pattern-- Routes use Flask Blueprint pattern-- JWT authentication via `@jwt_required()`-- Admin check via `admin_required` decorator or inline check-- Standard JSON responses with `{'error': ...}` or `{'success': ..., 'data': ...}`-------## Prerequisites--Before implementation:-1. Database migration system in place (Flask-Migrate)-2. Understanding of existing Nginx config generation-------## Tasks--### Task 1: Database Schema Updates-**Type**: Backend - Database--Add new fields to the Application model:--1. Open `backend/app/models/application.py`-2. Add fields:- ```python- # Private URL feature- private_slug = db.Column(db.String(50), unique=True, nullable=True, index=True)- private_url_enabled = db.Column(db.Boolean, default=False)- ```--3. Update `to_dict()` method to include new fields:- ```python- 'private_slug': self.private_slug,- 'private_url_enabled': self.private_url_enabled,- ```--4. Create migration:- ```bash- flask db migrate -m "Add private URL fields to Application"- flask db upgrade- ```--**Expected Result**: Application model has private URL fields-------### Task 2: Create Private URL Service-**Type**: Backend - Service--Create `backend/app/services/private_url_service.py`:--```python-import secrets-import string-import re-from typing import Optional, Tuple--class PrivateURLService:- """Service for managing private URLs for applications."""-- # Slug configuration- SLUG_ALPHABET = string.ascii_lowercase + string.digits- DEFAULT_SLUG_LENGTH = 12- MIN_SLUG_LENGTH = 3- MAX_SLUG_LENGTH = 50-- # Reserved slugs (system paths)- RESERVED_SLUGS = {'api', 'admin', 'static', 'assets', 'health', 'status'}-- @classmethod- def generate_slug(cls, length: int = None) -> str:- """Generate a cryptographically secure random slug."""- length = length or cls.DEFAULT_SLUG_LENGTH- return ''.join(secrets.choice(cls.SLUG_ALPHABET) for _ in range(length))-- @classmethod- def validate_slug(cls, slug: str) -> Tuple[bool, Optional[str]]:- """Validate a custom slug.-- Returns:- Tuple of (is_valid, error_message)- """- if not slug:- return False, "Slug cannot be empty"-- if len(slug) < cls.MIN_SLUG_LENGTH:- return False, f"Slug must be at least {cls.MIN_SLUG_LENGTH} characters"-- if len(slug) > cls.MAX_SLUG_LENGTH:- return False, f"Slug cannot exceed {cls.MAX_SLUG_LENGTH} characters"-- # Only alphanumeric and hyphens allowed- if not re.match(r'^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$', slug):- return False, "Slug must contain only lowercase letters, numbers, and hyphens (cannot start or end with hyphen)"-- # No consecutive hyphens- if '--' in slug:- return False, "Slug cannot contain consecutive hyphens"-- # Check reserved- if slug.lower() in cls.RESERVED_SLUGS:- return False, f"Slug '{slug}' is reserved"-- return True, None-- @classmethod- def is_slug_available(cls, slug: str, exclude_app_id: int = None) -> bool:- """Check if a slug is available (not used by another app)."""- from app.models import Application-- query = Application.query.filter_by(private_slug=slug)- if exclude_app_id:- query = query.filter(Application.id != exclude_app_id)-- return query.first() is None-- @classmethod- def generate_unique_slug(cls, max_attempts: int = 10) -> Optional[str]:- """Generate a unique slug that doesn't exist in the database."""- for _ in range(max_attempts):- slug = cls.generate_slug()- if cls.is_slug_available(slug):- return slug- return None-```--**Expected Result**: Service class for slug generation and validation-------### Task 3: Create Private URL API Endpoints-**Type**: Backend - API--Create `backend/app/api/private_urls.py`:--```python-from flask import Blueprint, request, jsonify-from flask_jwt_extended import jwt_required, get_jwt_identity-from app import db-from app.models import Application, User-from app.services.private_url_service import PrivateURLService-from app.services.nginx_service import NginxService--private_urls_bp = Blueprint('private_urls', __name__)---@private_urls_bp.route('/<int:app_id>/private-url', methods=['POST'])-@jwt_required()-def enable_private_url(app_id):- """Enable private URL for an application and generate/set slug."""- current_user_id = get_jwt_identity()- user = User.query.get(current_user_id)- app = Application.query.get(app_id)-- if not app:- return jsonify({'error': 'Application not found'}), 404-- if user.role != 'admin' and app.user_id != current_user_id:- return jsonify({'error': 'Access denied'}), 403-- data = request.get_json() or {}- custom_slug = data.get('slug')-- if custom_slug:- # Validate custom slug- is_valid, error = PrivateURLService.validate_slug(custom_slug)- if not is_valid:- return jsonify({'error': error}), 400-- if not PrivateURLService.is_slug_available(custom_slug, exclude_app_id=app_id):- return jsonify({'error': 'Slug is already in use'}), 409-- slug = custom_slug- else:- # Generate unique slug- slug = PrivateURLService.generate_unique_slug()- if not slug:- return jsonify({'error': 'Could not generate unique slug'}), 500-- app.private_slug = slug- app.private_url_enabled = True- db.session.commit()-- # Update Nginx config if app has port- nginx_result = None- if app.port:- nginx_result = NginxService.update_private_url_config(app)-- return jsonify({- 'message': 'Private URL enabled',- 'private_slug': slug,- 'private_url': f'/p/{slug}',- 'nginx_updated': nginx_result.get('success') if nginx_result else None- }), 200---@private_urls_bp.route('/<int:app_id>/private-url', methods=['PUT'])-@jwt_required()-def update_private_url(app_id):- """Update the private URL slug for an application."""- current_user_id = get_jwt_identity()- user = User.query.get(current_user_id)- app = Application.query.get(app_id)-- if not app:- return jsonify({'error': 'Application not found'}), 404-- if user.role != 'admin' and app.user_id != current_user_id:- return jsonify({'error': 'Access denied'}), 403-- if not app.private_url_enabled:- return jsonify({'error': 'Private URL is not enabled for this app'}), 400-- data = request.get_json()- if not data or 'slug' not in data:- return jsonify({'error': 'Slug is required'}), 400-- new_slug = data['slug']-- # Validate- is_valid, error = PrivateURLService.validate_slug(new_slug)- if not is_valid:- return jsonify({'error': error}), 400-- if not PrivateURLService.is_slug_available(new_slug, exclude_app_id=app_id):- return jsonify({'error': 'Slug is already in use'}), 409-- old_slug = app.private_slug- app.private_slug = new_slug- db.session.commit()-- # Update Nginx config- nginx_result = None- if app.port:- nginx_result = NginxService.update_private_url_config(app, old_slug=old_slug)-- return jsonify({- 'message': 'Private URL updated',- 'private_slug': new_slug,- 'private_url': f'/p/{new_slug}',- 'nginx_updated': nginx_result.get('success') if nginx_result else None- }), 200---@private_urls_bp.route('/<int:app_id>/private-url', methods=['DELETE'])-@jwt_required()-def disable_private_url(app_id):- """Disable private URL for an application."""- current_user_id = get_jwt_identity()- user = User.query.get(current_user_id)- app = Application.query.get(app_id)-- if not app:- return jsonify({'error': 'Application not found'}), 404-- if user.role != 'admin' and app.user_id != current_user_id:- return jsonify({'error': 'Access denied'}), 403-- old_slug = app.private_slug- app.private_slug = None- app.private_url_enabled = False- db.session.commit()-- # Remove Nginx config for private URL- nginx_result = None- if old_slug:- nginx_result = NginxService.remove_private_url_config(old_slug)-- return jsonify({- 'message': 'Private URL disabled',- 'nginx_updated': nginx_result.get('success') if nginx_result else None- }), 200---@private_urls_bp.route('/<int:app_id>/private-url/regenerate', methods=['POST'])-@jwt_required()-def regenerate_private_url(app_id):- """Generate a new random slug for an application."""- current_user_id = get_jwt_identity()- user = User.query.get(current_user_id)- app = Application.query.get(app_id)-- if not app:- return jsonify({'error': 'Application not found'}), 404-- if user.role != 'admin' and app.user_id != current_user_id:- return jsonify({'error': 'Access denied'}), 403-- if not app.private_url_enabled:- return jsonify({'error': 'Private URL is not enabled for this app'}), 400-- old_slug = app.private_slug- new_slug = PrivateURLService.generate_unique_slug()-- if not new_slug:- return jsonify({'error': 'Could not generate unique slug'}), 500-- app.private_slug = new_slug- db.session.commit()-- # Update Nginx config- nginx_result = None- if app.port:- nginx_result = NginxService.update_private_url_config(app, old_slug=old_slug)-- return jsonify({- 'message': 'Private URL regenerated',- 'private_slug': new_slug,- 'private_url': f'/p/{new_slug}',- 'nginx_updated': nginx_result.get('success') if nginx_result else None- }), 200-```--**Expected Result**: API endpoints for managing private URLs-------### Task 4: Create Public Resolver Endpoint-**Type**: Backend - API--Add a public endpoint to resolve private URLs. This does NOT require authentication.--Add to `backend/app/api/private_urls.py`:--```python-@private_urls_bp.route('/p/<slug>', methods=['GET'])-def resolve_private_url(slug):- """Resolve a private URL slug to app info (public endpoint).-- This endpoint is for API consumers that need to look up which app- a private URL points to. The actual proxying is handled by Nginx.- """- app = Application.query.filter_by(- private_slug=slug,- private_url_enabled=True- ).first()-- if not app:- return jsonify({'error': 'Not found'}), 404-- return jsonify({- 'app_id': app.id,- 'app_name': app.name,- 'port': app.port,- 'status': app.status- }), 200-```--**Expected Result**: Public endpoint for slug resolution-------### Task 5: Nginx Integration for Private URLs-**Type**: Backend - Service--Update `backend/app/services/nginx_service.py` to handle private URL routing.--1. Add new template for private URL routing:--```python-PRIVATE_URL_LOCATION_TEMPLATE = '''- # Private URL: /p/{slug}- location /p/{slug}/ {{- proxy_pass http://127.0.0.1:{port}/;- proxy_http_version 1.1;- proxy_set_header Upgrade $http_upgrade;- proxy_set_header Connection 'upgrade';- 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;- proxy_set_header X-Private-URL {slug};- proxy_cache_bypass $http_upgrade;- proxy_read_timeout 86400;- }}-'''--PRIVATE_URL_MAIN_CONFIG = '''# ServerKit Private URL Routes-# This file is auto-generated. Do not edit manually.--server {{- listen 80;- listen [::]:80;- server_name _;-- # Private URL routes-{locations}-- # Fallback for unknown slugs- location /p/ {{- return 404;- }}-}}-'''-```--2. Add methods:--```python-@classmethod-def update_private_url_config(cls, app, old_slug: str = None) -> Dict:- """Update Nginx config for a private URL."""- # Implementation to regenerate private-urls config file- pass--@classmethod-def remove_private_url_config(cls, slug: str) -> Dict:- """Remove a private URL from Nginx config."""- pass--@classmethod-def regenerate_all_private_urls(cls) -> Dict:- """Regenerate the entire private URLs config from database."""- from app.models import Application-- apps = Application.query.filter(- Application.private_url_enabled == True,- Application.private_slug.isnot(None),- Application.port.isnot(None)- ).all()-- locations = []- for app in apps:- location = cls.PRIVATE_URL_LOCATION_TEMPLATE.format(- slug=app.private_slug,- port=app.port- )- locations.append(location)-- config = cls.PRIVATE_URL_MAIN_CONFIG.format(- locations='\n'.join(locations)- )-- # Write to /etc/nginx/sites-available/serverkit-private-urls- # Enable and reload- pass-```--**Expected Result**: Nginx generates configs for `/p/{slug}` routes-------### Task 6: Register API Blueprint-**Type**: Backend - Configuration--1. Update `backend/app/api/__init__.py` to import and register the new blueprint:--```python-from app.api.private_urls import private_urls_bp--def register_blueprints(app):- # ... existing blueprints ...- app.register_blueprint(private_urls_bp, url_prefix='/api/v1/apps')-```--Note: The `/p/<slug>` public endpoint will be at `/api/v1/apps/p/<slug>` OR we can register it separately at the root.--Alternative: Register public resolver at root level:-```python-# In app/__init__.py or main blueprint[email protected]('/p/<slug>')-def private_url_redirect(slug):- # This is handled by Nginx in production, but for dev/testing- pass-```--**Expected Result**: API routes accessible-------### Task 7: Frontend - Private URL Section Component-**Type**: Frontend--Create `frontend/src/components/PrivateURLSection.jsx`:--```jsx-import React, { useState } from 'react';-import { Card, Button, Input, Switch, message, Tooltip, Space, Alert } from 'antd';-import { CopyOutlined, ReloadOutlined, LinkOutlined } from '@ant-design/icons';-import api from '../api';--const PrivateURLSection = ({ app, onUpdate }) => {- const [loading, setLoading] = useState(false);- const [customSlug, setCustomSlug] = useState('');- const [editMode, setEditMode] = useState(false);-- const baseUrl = window.location.origin;- const privateUrl = app.private_slug ? `${baseUrl}/p/${app.private_slug}` : null;-- const handleEnable = async () => {- setLoading(true);- try {- const response = await api.post(`/apps/${app.id}/private-url`, {- slug: customSlug || undefined- });- message.success('Private URL enabled');- onUpdate();- setCustomSlug('');- } catch (error) {- message.error(error.response?.data?.error || 'Failed to enable private URL');- } finally {- setLoading(false);- }- };-- const handleDisable = async () => {- setLoading(true);- try {- await api.delete(`/apps/${app.id}/private-url`);- message.success('Private URL disabled');- onUpdate();- } catch (error) {- message.error(error.response?.data?.error || 'Failed to disable private URL');- } finally {- setLoading(false);- }- };-- const handleRegenerate = async () => {- setLoading(true);- try {- await api.post(`/apps/${app.id}/private-url/regenerate`);- message.success('Private URL regenerated');- onUpdate();- } catch (error) {- message.error(error.response?.data?.error || 'Failed to regenerate');- } finally {- setLoading(false);- }- };-- const handleUpdateSlug = async () => {- if (!customSlug) return;- setLoading(true);- try {- await api.put(`/apps/${app.id}/private-url`, { slug: customSlug });- message.success('Slug updated');- onUpdate();- setEditMode(false);- setCustomSlug('');- } catch (error) {- message.error(error.response?.data?.error || 'Failed to update slug');- } finally {- setLoading(false);- }- };-- const copyToClipboard = () => {- navigator.clipboard.writeText(privateUrl);- message.success('URL copied to clipboard');- };-- return (- <Card title="Private URL" size="small">- {!app.private_url_enabled ? (- <div>- <p>Enable a private, shareable URL for this application.</p>- <Space direction="vertical" style={{ width: '100%' }}>- <Input- placeholder="Custom slug (optional)"- value={customSlug}- onChange={(e) => setCustomSlug(e.target.value.toLowerCase())}- addonBefore="/p/"- />- <Button- type="primary"- onClick={handleEnable}- loading={loading}- icon={<LinkOutlined />}- >- Enable Private URL- </Button>- </Space>- </div>- ) : (- <div>- <Alert- message="Private URL Active"- description={- <div>- <code>{privateUrl}</code>- <Space style={{ marginTop: 8 }}>- <Tooltip title="Copy URL">- <Button icon={<CopyOutlined />} size="small" onClick={copyToClipboard} />- </Tooltip>- <Tooltip title="Regenerate">- <Button icon={<ReloadOutlined />} size="small" onClick={handleRegenerate} loading={loading} />- </Tooltip>- </Space>- </div>- }- type="success"- showIcon- />-- {editMode ? (- <Space style={{ marginTop: 16 }}>- <Input- placeholder="New slug"- value={customSlug}- onChange={(e) => setCustomSlug(e.target.value.toLowerCase())}- addonBefore="/p/"- />- <Button type="primary" size="small" onClick={handleUpdateSlug} loading={loading}>- Save- </Button>- <Button size="small" onClick={() => setEditMode(false)}>- Cancel- </Button>- </Space>- ) : (- <Button- type="link"- size="small"- onClick={() => setEditMode(true)}- style={{ marginTop: 8, padding: 0 }}- >- Change slug- </Button>- )}-- <div style={{ marginTop: 16 }}>- <Button danger onClick={handleDisable} loading={loading}>- Disable Private URL- </Button>- </div>- </div>- )}- </Card>- );-};--export default PrivateURLSection;-```--**Expected Result**: Reusable component for private URL management-------### Task 8: Integrate into Application Detail Page-**Type**: Frontend--Update `frontend/src/pages/ApplicationDetail.jsx`:--1. Import the component:-```jsx-import PrivateURLSection from '../components/PrivateURLSection';-```--2. Add to the page layout (in the details/settings section):-```jsx-{app.app_type === 'docker' && app.port && (- <PrivateURLSection app={app} onUpdate={fetchApp} />-)}-```--**Expected Result**: Private URL section visible on Docker app detail pages-------### Task 9: Update Applications List-**Type**: Frontend--Update `frontend/src/pages/ApplicationsList.jsx` (or equivalent):--1. Add private URL indicator to app cards/rows:-```jsx-{app.private_url_enabled && (- <Tooltip title={`Private URL: /p/${app.private_slug}`}>- <LinkOutlined style={{ color: '#52c41a' }} />- </Tooltip>-)}-```--2. Add quick copy action for private URL in actions menu--**Expected Result**: Visual indicator for apps with private URLs-------### Task 10: Test End-to-End-**Type**: Testing--1. **Database migration test**:- - Run migration- - Verify fields exist in database--2. **API tests**:- - Enable private URL (auto-generated slug)- - Enable private URL (custom slug)- - Update slug- - Regenerate slug- - Disable private URL- - Test validation (invalid slugs, duplicates)--3. **Nginx tests**:- - Verify config file generated- - Test `/p/{slug}` routes to correct port- - Test Nginx reload works--4. **Frontend tests**:- - Enable/disable toggle works- - Copy button works- - Slug editing works- - Error messages display correctly--**Expected Result**: All features working end-to-end-------## Verification Checklist--After completing all tasks:--- [ ] Database migration applied successfully-- [ ] `private_slug` and `private_url_enabled` fields exist-- [ ] API endpoints respond correctly-- [ ] Slug validation works (length, format, uniqueness)-- [ ] Nginx config generates for private URLs-- [ ] `/p/{slug}` routes to correct app port-- [ ] Frontend component renders correctly-- [ ] Copy to clipboard works-- [ ] Regenerate creates new slug-- [ ] Custom slug can be set-- [ ] Disable removes slug and config-- [ ] Application list shows indicator-------## Success Criteria--- [ ] Private URLs can be generated for any Docker app-- [ ] Custom slugs work with validation-- [ ] Private URL routes to correct container via Nginx-- [ ] UI allows easy management and copying-------## Implementation Notes--### Nginx Architecture Decision--Two approaches for `/p/{slug}` routing:--**Option A: Single config file with all routes (Recommended)**-- One file: `/etc/nginx/sites-available/serverkit-private-urls`-- Regenerate entire file when any private URL changes-- Pros: Simple, single point of configuration-- Cons: Full regeneration on any change--**Option B: Separate config per app**-- Individual files per slug-- Pros: Granular updates-- Cons: More complex management--**Recommendation**: Option A for simplicity. Private URL changes are infrequent.--### Port Requirement--Private URLs only work for apps with a configured `port` field. This is enforced in:-1. API (returns error if no port)-2. Frontend (only shows section if port exists)--### Security Considerations--- Slugs are public but unguessable (12 chars = 36^12 combinations)-- No authentication on `/p/{slug}` access (by design - shareable)-- Users can regenerate slugs if compromised-------## Output--After execution:-- Database schema updated with private URL fields-- New service for slug generation-- API endpoints for private URL management-- Nginx integration for `/p/{slug}` routing-- Frontend UI for managing private URLs-- Ready for Phase 6 (Dashboard Historical Metrics)diff --git a/.planning/phases/06-dashboard-historical-metrics/SUMMARY.md b/.planning/phases/06-dashboard-historical-metrics/SUMMARY.mddeleted file mode 100644index ec57b6aa..00000000--- a/.planning/phases/06-dashboard-historical-metrics/SUMMARY.md+++ /dev/null@@ -1,89 +0,0 @@-# Phase 6: Dashboard Historical Metrics - Summary--## Overview-Added time-series graphs to the dashboard showing CPU, Memory, and Disk usage trends over configurable time periods with automatic data collection and aggregation.--## Completed-- [x] Task 1: Create MetricsHistory Model-- [x] Task 2: Create Metrics History Service-- [x] Task 3: Add Background Metrics Collection-- [x] Task 4: Create Historical Metrics API-- [x] Task 5: Create MetricsGraph Component-- [x] Task 6: Create useMetricsHistory Hook (integrated in component)-- [x] Task 7: Add Graphs to Dashboard-- [x] Task 8: Add Styles for Metrics Graphs-- [x] Task 9: Initialize Collection on App Start--## Implementation Details--### Backend-- **MetricsHistory Model** (`backend/app/models/metrics_history.py`)- - Stores CPU, Memory, Disk metrics at three aggregation levels: minute, hour, day- - Composite index on (level, timestamp) for efficient queries- - Retention: 24h minute data, 7 days hourly, 30 days daily--- **MetricsHistoryService** (`backend/app/services/metrics_history_service.py`)- - Background thread collects metrics every 60 seconds- - Auto-aggregates minute→hour (every hour) and hour→day (daily)- - Auto-cleanup of expired data per retention policy- - Period configurations: 1h, 6h, 24h use minute level; 7d uses hour; 30d uses day--- **Metrics API** (`backend/app/api/metrics.py`)- - `GET /api/v1/metrics/history?period=1h` - Get historical data- - `GET /api/v1/metrics/stats` - Get storage statistics- - `POST /api/v1/metrics/collection/start|stop` - Control collection- - `POST /api/v1/metrics/aggregate` - Trigger manual aggregation--### Frontend-- **MetricsGraph Component** (`frontend/src/components/MetricsGraph.jsx`)- - Recharts-based LineChart with CPU, Memory, Disk lines- - Period selector (1h, 6h, 24h, 7d, 30d)- - Summary row with averages- - Compact mode for smaller displays- - Custom tooltip with data details--- **Styles** (`frontend/src/styles/components/_metrics-graph.less`)- - Card layout matching design system- - Loading, error, empty states- - Responsive breakpoints for mobile--## API Response Format-```json-{- "period": "1h",- "level": "minute",- "points": 60,- "data": [- {- "timestamp": "2026-01-19T10:00:00",- "cpu": { "percent": 45.2, "min": null, "max": null },- "memory": { "percent": 62.1, "used_gb": 8.5, "total_gb": 16.0 },- "disk": { "percent": 35.0, "used_gb": 200, "total_gb": 500 },- "load": { "1m": 1.2, "5m": 1.1, "15m": 0.9 }- }- ],- "summary": {- "cpu_avg": 42.5,- "memory_avg": 61.8,- "disk_avg": 35.0- }-}-```--## Files Changed-- `backend/app/models/metrics_history.py` (new)-- `backend/app/models/__init__.py` (export added)-- `backend/app/services/metrics_history_service.py` (new)-- `backend/app/api/metrics.py` (new)-- `backend/app/__init__.py` (blueprint + auto-start)-- `frontend/src/components/MetricsGraph.jsx` (new)-- `frontend/src/services/api.js` (API methods)-- `frontend/src/pages/Dashboard.jsx` (integration)-- `frontend/src/styles/components/_metrics-graph.less` (new)-- `frontend/src/styles/main.less` (import)--## Notes-- Collection starts automatically on app startup-- Windows compatibility: load averages will be null (not available on Windows)-- Database migration runs automatically (SQLAlchemy create_all)-- Charts update on period change; no auto-refresh (uses cached data)diff --git a/.planning/phases/06-dashboard-metrics/phase-6-PLAN.md b/.planning/phases/06-dashboard-metrics/phase-6-PLAN.mddeleted file mode 100644index 7c04b1e9..00000000--- a/.planning/phases/06-dashboard-metrics/phase-6-PLAN.md+++ /dev/null@@ -1,384 +0,0 @@-# Phase 6: Dashboard Historical Metrics - Execution Plan--## Objective-Add time-series graphs for CPU, Memory, and Disk usage on the Dashboard. Store metrics historically and allow querying by time period (1h, 6h, 24h, 7d, 30d).--## Context--### Current Implementation-- **Monitoring Service** (`backend/app/services/monitoring_service.py`): Uses `psutil` to get current metrics-- **WebSocket Metrics**: `useMetrics` hook subscribes to real-time metrics via WebSocket-- **Dashboard**: Displays current metrics in cards with progress bars-- **Frontend**: Already has `recharts` v2.12.3 installed--### Key Findings-- `MonitoringService.get_current_metrics()` returns CPU, memory, disk, load average-- Dashboard already uses WebSocket for real-time updates-- SQLite is used for all app data - can add MetricsHistory model-- Need to balance storage size with query performance--### Storage Decision-**Use SQLite** with automatic data aggregation:-- Keep 24h of minute-level data (~1440 rows/day)-- Aggregate to hourly for 7-day view (~168 rows)-- Aggregate to daily for 30-day view (~30 rows)-- Total: ~1640 rows maximum - very manageable-------## Prerequisites--1. Backend running with SQLAlchemy-2. Frontend with recharts installed-3. Existing monitoring service working-------## Tasks--### Task 1: Create MetricsHistory Model-**Type**: Backend - Database--Create `backend/app/models/metrics_history.py`:--```python-from datetime import datetime-from app import db--class MetricsHistory(db.Model):- """Historical metrics storage with automatic aggregation levels."""- __tablename__ = 'metrics_history'-- id = db.Column(db.Integer, primary_key=True)- timestamp = db.Column(db.DateTime, nullable=False, index=True)-- # Aggregation level: 'minute', 'hour', 'day'- level = db.Column(db.String(10), nullable=False, default='minute', index=True)-- # CPU metrics- cpu_percent = db.Column(db.Float, nullable=False)- cpu_percent_min = db.Column(db.Float, nullable=True) # For aggregated records- cpu_percent_max = db.Column(db.Float, nullable=True)-- # Memory metrics- memory_percent = db.Column(db.Float, nullable=False)- memory_used_bytes = db.Column(db.BigInteger, nullable=False)- memory_total_bytes = db.Column(db.BigInteger, nullable=False)-- # Disk metrics (root partition)- disk_percent = db.Column(db.Float, nullable=False)- disk_used_bytes = db.Column(db.BigInteger, nullable=False)- disk_total_bytes = db.Column(db.BigInteger, nullable=False)-- # Load average (Unix only)- load_1m = db.Column(db.Float, nullable=True)- load_5m = db.Column(db.Float, nullable=True)- load_15m = db.Column(db.Float, nullable=True)-- # Sample count (for aggregated records)- sample_count = db.Column(db.Integer, default=1)-- def to_dict(self):- return {- 'timestamp': self.timestamp.isoformat(),- 'level': self.level,- 'cpu': {- 'percent': self.cpu_percent,- 'min': self.cpu_percent_min,- 'max': self.cpu_percent_max- },- 'memory': {- 'percent': self.memory_percent,- 'used_bytes': self.memory_used_bytes,- 'total_bytes': self.memory_total_bytes- },- 'disk': {- 'percent': self.disk_percent,- 'used_bytes': self.disk_used_bytes,- 'total_bytes': self.disk_total_bytes- },- 'load': {- '1m': self.load_1m,- '5m': self.load_5m,- '15m': self.load_15m- }- }-```--Update `backend/app/models/__init__.py` to export the new model.--**Expected Result**: MetricsHistory table created on app start-------### Task 2: Create Metrics History Service-**Type**: Backend - Service--Create `backend/app/services/metrics_history_service.py`:--Key methods:-1. `record_metrics()` - Store current metrics snapshot-2. `get_history(period)` - Query historical data by time period-3. `aggregate_old_data()` - Aggregate minute data to hour/day-4. `cleanup_old_data()` - Remove data older than retention period--Retention policy:-- Minute-level: 24 hours-- Hour-level: 7 days-- Day-level: 30 days--Collection approach:-- Background thread or use existing monitoring thread-- Record every 60 seconds-- Run aggregation every hour (via cron or thread)--**Expected Result**: Service that records and retrieves historical metrics-------### Task 3: Add Background Metrics Collection-**Type**: Backend - Service--Modify `backend/app/services/monitoring_service.py` or create a separate background task:--1. Start collection thread on app startup-2. Record metrics every 60 seconds-3. Run hourly aggregation-4. Run daily cleanup--Options:-- Add to existing monitoring thread-- Use Flask-APScheduler (if installed)-- Use simple threading.Timer--Recommendation: Extend existing MonitoringService with history recording.--**Expected Result**: Metrics automatically recorded every minute-------### Task 4: Create Historical Metrics API-**Type**: Backend - API--Create `backend/app/api/metrics.py`:--```python-@metrics_bp.route('/history', methods=['GET'])-@jwt_required()-def get_metrics_history():- """Get historical metrics data.-- Query params:- period: 1h, 6h, 24h, 7d, 30d (default: 1h)- metric: cpu, memory, disk, all (default: all)-- Returns:- JSON with time-series data points- """-```--Response format:-```json-{- "period": "24h",- "points": 60,- "data": [- {- "timestamp": "2026-01-19T10:00:00",- "cpu": {"percent": 45.2, "min": 30.1, "max": 78.5},- "memory": {"percent": 62.1, "used_gb": 7.8, "total_gb": 16.0},- "disk": {"percent": 45.0, "used_gb": 234.5, "total_gb": 512.0}- }- ],- "summary": {- "cpu_avg": 42.3,- "memory_avg": 61.5,- "disk_avg": 44.8- }-}-```--Register blueprint in `backend/app/__init__.py`.--**Expected Result**: API endpoint returns historical metrics-------### Task 5: Create MetricsGraph Component-**Type**: Frontend - Component--Create `frontend/src/components/MetricsGraph.jsx`:--Features:-- Uses Recharts (already installed)-- Responsive container-- Time period selector (1h, 6h, 24h, 7d, 30d)-- Line/Area chart for CPU, Memory, Disk-- Hover tooltips with exact values-- Color coding for thresholds-- Loading state--Props:-```jsx-<MetricsGraph- data={timeSeriesData}- metric="cpu|memory|disk"- period="1h|6h|24h|7d|30d"- onPeriodChange={handler}- showMin={boolean}- showMax={boolean}-/>-```--**Expected Result**: Reusable chart component for metrics-------### Task 6: Create useMetricsHistory Hook-**Type**: Frontend - Hook--Create `frontend/src/hooks/useMetricsHistory.js`:--```javascript-export function useMetricsHistory(period = '1h') {- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(null);-- // Fetch on mount and period change- // Return { data, loading, error, refresh }-}-```--Add API method to `frontend/src/services/api.js`:-```javascript-async getMetricsHistory(period = '1h') {- return this.request(`/metrics/history?period=${period}`);-}-```--**Expected Result**: Hook for fetching historical metrics-------### Task 7: Add Graphs to Dashboard-**Type**: Frontend - Integration--Update `frontend/src/pages/Dashboard.jsx`:--1. Import MetricsGraph component-2. Add state for historical data period-3. Add period selector tabs/buttons-4. Render CPU, Memory, Disk graphs below current stats-5. Handle loading and error states--Layout:-```-[Status Bar]-[Current Stats Cards - CPU | Memory | Disk | Network]-[Period Selector: 1h | 6h | 24h | 7d | 30d]-[Graphs Section]- - CPU History Graph- - Memory History Graph- - Disk History Graph-[Services & Apps Columns]-```--**Expected Result**: Dashboard shows historical graphs-------### Task 8: Add Styles for Metrics Graphs-**Type**: Frontend - Styles--Create `frontend/src/styles/components/_metrics-graph.less`:--Styles for:-- Graph container with proper sizing-- Period selector tabs-- Recharts customization (tooltip, legend)-- Responsive behavior-- Loading/error states-- Color variables for metrics--Import in `main.less`.--**Expected Result**: Polished graph UI-------### Task 9: Initialize Collection on App Start-**Type**: Backend - Startup--Ensure metrics collection starts automatically:--1. Check if collection should auto-start (config option)-2. Start background thread in `create_app()` or via `before_first_request`-3. Handle graceful shutdown-4. Log collection status--**Expected Result**: Metrics collection starts with server-------## Verification Checklist--After completing all tasks:--- [ ] MetricsHistory model exists and table created-- [ ] Metrics recorded every 60 seconds-- [ ] API returns historical data for all periods-- [ ] Aggregation reduces minute data to hour/day-- [ ] Old data cleaned up per retention policy-- [ ] Dashboard displays CPU/Memory/Disk graphs-- [ ] Period selector switches time range-- [ ] Tooltips show exact values on hover-- [ ] Graphs responsive on different screen sizes-- [ ] No performance issues with 30-day view-------## Success Criteria--- [ ] Metrics stored persistently-- [ ] Historical data queryable by time period-- [ ] Graphs display correctly with interactions-- [ ] Dashboard remains performant-------## Implementation Notes--### Data Points Per Period-| Period | Level | Expected Points |-|--------|-------|-----------------|-| 1h | minute | 60 |-| 6h | minute | 360 |-| 24h | minute | 1440 |-| 7d | hour | 168 |-| 30d | day | 30 |--### Chart Library-Recharts is already installed. Key components to use:-- `<ResponsiveContainer>` for responsive sizing-- `<LineChart>` or `<AreaChart>` for time series-- `<Tooltip>` for hover info-- `<XAxis>`, `<YAxis>` for axes-- `<Legend>` for metric labels--### Performance Considerations-- Use SQLite indexes on timestamp and level-- Lazy load graphs (only fetch when visible)-- Consider WebSocket for live updates to latest point-- Cache API responses briefly (30 seconds)-------## Output--After execution:-- MetricsHistory model in database-- Background collection running-- Historical metrics API available-- Dashboard with interactive graphs-- Ready for Phase 7 (Templates Page Polish)diff --git a/.planning/phases/07-templates-page-polish/PLAN.md b/.planning/phases/07-templates-page-polish/PLAN.mddeleted file mode 100644index 347ac0e1..00000000--- a/.planning/phases/07-templates-page-polish/PLAN.md+++ /dev/null@@ -1,196 +0,0 @@-# Phase 7: Templates Page Polish--## Objective-Fix broken icons, improve filtering UX, and enhance template cards with better information display.--## Context--### Current State-- Templates page exists at `frontend/src/pages/Templates.jsx`-- Templates are stored as YAML files in `backend/templates/`-- Each template has an `icon` field with external URLs (may be broken)-- Category filtering exists but lacks clear filter state indication-- No URL param persistence for filters-- Template detail modal shows basic info--### Key Files-- `frontend/src/pages/Templates.jsx` - Main page component-- `frontend/src/styles/pages/_templates.less` - Styles-- `backend/templates/*.yaml` - Individual template files-- `backend/templates/index.json` - Template index-- `backend/app/services/template_service.py` - Template service-- `backend/app/api/templates.py` - API endpoints--### Dependencies-- Lucide icons already available in project-- No new packages needed-------## Tasks--### Task 1: Add Lucide Icon Mappings for Templates-**Goal**: Create icon mapping using Lucide icons as fallback when external icons fail--**Files to modify**:-- `frontend/src/pages/Templates.jsx`--**Implementation**:-1. Create `getTemplateIcon(templateId)` function that maps template IDs to Lucide icons-2. Map each template to an appropriate icon (e.g., wordpress → Globe, grafana → BarChart3, etc.)-3. Update template card to try img first, fall back to Lucide icon on error-4. Add `onError` handler to img tags that switches to fallback--**Verification**: Template cards show icons even when external URLs fail-------### Task 2: Add Icon Error Handling with State-**Goal**: Handle icon load failures gracefully with visual fallback--**Files to modify**:-- `frontend/src/pages/Templates.jsx`--**Implementation**:-1. Add state to track which template icons have failed loading-2. Create `handleIconError(templateId)` that adds ID to failed set-3. When icon fails, render Lucide icon instead of broken img-4. Apply same logic to modal large icon--**Verification**: No broken image placeholders visible-------### Task 3: Add URL Param Persistence for Filters-**Goal**: Persist category and search filters in URL for shareable links--**Files to modify**:-- `frontend/src/pages/Templates.jsx`--**Implementation**:-1. Import `useSearchParams` from react-router-dom-2. Initialize `selectedCategory` and `searchQuery` from URL params-3. Update URL when filters change using `setSearchParams`-4. Handle browser back/forward navigation--**Verification**:-- Filtering updates URL (e.g., `/templates?category=monitoring&search=uptime`)-- Refreshing page preserves filter state-- Browser back button works-------### Task 4: Add Active Filter Chips with Clear Button-**Goal**: Show active filters as removable chips with "Clear All" option--**Files to modify**:-- `frontend/src/pages/Templates.jsx`-- `frontend/src/styles/pages/_templates.less`--**Implementation**:-1. Add filter chips section below search/category filters-2. Show chip for active category with X button to remove-3. Show chip for search term (if any) with X button-4. Add "Clear All" button when any filter is active-5. Style chips to match design system--**Verification**: Active filters visible and removable via chips-------### Task 5: Enhance Template Cards with Additional Info-**Goal**: Add version badge styling and improve card layout--**Files to modify**:-- `frontend/src/pages/Templates.jsx`-- `frontend/src/styles/pages/_templates.less`--**Implementation**:-1. Make version badge more prominent with colored background-2. Add website/docs link indicator if available (small icon)-3. Add "Popular" or "Featured" indicator for select templates (hardcoded list initially)-4. Improve category badge styling--**Verification**: Cards show enhanced info clearly-------### Task 6: Improve Template Detail Modal-**Goal**: Enhance modal with better organization and system requirements--**Files to modify**:-- `frontend/src/pages/Templates.jsx`-- `frontend/src/styles/pages/_templates.less`--**Implementation**:-1. Add "Requirements" section showing memory/storage needs-2. Show Docker Compose preview (collapsible code block)-3. Improve section headers with icons-4. Add copy button for Docker Compose-5. Better organize variable list (group by type: required vs optional)--**Verification**: Modal provides comprehensive template info-------### Task 7: Add Search Icon to Search Input-**Goal**: Add visual search icon inside the search input--**Files to modify**:-- `frontend/src/pages/Templates.jsx`-- `frontend/src/styles/pages/_templates.less`--**Implementation**:-1. Import Search icon from lucide-react-2. Wrap search input in container with positioned icon-3. Add left padding to input for icon space-4. Style icon appropriately--**Verification**: Search input has icon-------### Task 8: Add Results Count and Sort Options-**Goal**: Show template count and add sort dropdown--**Files to modify**:-- `frontend/src/pages/Templates.jsx`-- `frontend/src/styles/pages/_templates.less`--**Implementation**:-1. Add results header showing "X templates" count-2. Add sort dropdown (Name A-Z, Name Z-A, Version, Category)-3. Implement sorting logic-4. Persist sort preference in URL params--**Verification**: Count visible, sorting works correctly-------## Verification--After completing all tasks:-1. All template icons load (fallback works)-2. Filtering is intuitive with visible chips-3. URL reflects current filter state-4. Template cards show useful information-5. Detail modal provides comprehensive info-6. Search has visual icon-7. Results can be sorted-8. Page remains performant-------## Success Criteria-- [ ] All icons load correctly (with fallbacks)-- [ ] Filtering is intuitive and persistent-- [ ] Template cards show useful info at a glance-- [ ] Details modal provides complete information-- [ ] Search and sort enhance discoverability-------## Output-- Modified `frontend/src/pages/Templates.jsx`-- Modified `frontend/src/styles/pages/_templates.less`-- Phase 7 SUMMARY.md on completiondiff --git a/.planning/phases/07-templates-page-polish/SUMMARY.md b/.planning/phases/07-templates-page-polish/SUMMARY.mddeleted file mode 100644index e23a6575..00000000--- a/.planning/phases/07-templates-page-polish/SUMMARY.md+++ /dev/null@@ -1,78 +0,0 @@-# Phase 7: Templates Page Polish - Summary--## Overview-Comprehensive UI polish for the templates page including icon fallbacks, improved filtering with URL persistence, enhanced template cards, and better modal organization.--## Completed-- [x] Task 1: Add Lucide Icon Mappings for Templates-- [x] Task 2: Add Icon Error Handling with State-- [x] Task 3: Add URL Param Persistence for Filters-- [x] Task 4: Add Active Filter Chips with Clear Button-- [x] Task 5: Enhance Template Cards with Additional Info-- [x] Task 6: Improve Template Detail Modal-- [x] Task 7: Add Search Icon to Search Input-- [x] Task 8: Add Results Count and Sort Options--## Implementation Details--### Icon Fallback System-- Created `TEMPLATE_ICONS` mapping for 60+ templates to appropriate Lucide icons-- Icons grouped by category: monitoring, CMS, DevOps, storage, collaboration, media, etc.-- `failedIcons` state tracks which external icons failed to load-- `renderIcon()` function tries external image first, falls back to Lucide on error-- Same fallback logic applies to both card icons and modal large icons--### URL Filter Persistence-- Uses `useSearchParams` from react-router-dom-- Filter state stored in URL: `?category=monitoring&search=uptime&sort=featured`-- `updateFilters()` helper manages URL param updates-- Browser back/forward navigation works correctly-- Filters persist on page refresh--### Active Filter Chips-- Shows removable chips when category or search is active-- Each chip has X button to remove that specific filter-- "Clear All" button appears when any filter is active-- Styled with accent color to stand out--### Enhanced Template Cards-- Featured badge (gold gradient) for curated templates-- 10 featured templates: wordpress, nextcloud, grafana, portainer, uptime-kuma, gitea, vaultwarden, jellyfin, ghost, n8n-- Version badge with accent color styling-- Link indicators (ExternalLink, BookOpen icons) when website/docs available-- Improved category badge styling--### Improved Detail Modal-- Section headers with icons (Tag, Cpu, Settings, Server, Container)-- Requirements section showing memory/storage needs-- Variables sorted by required first, with badges:- - Required: accent color badge- - Auto: green "Auto" badge for auto-generated values-- Variables with `hidden: true` filtered out-- Docker Compose section with copy button placeholder--### Search Improvements-- Search icon inside input field-- Clear button (X) appears when search has value-- Proper padding for icon placement--### Results & Sorting-- Results count header: "X templates"-- Sort dropdown with options:- - Name (A-Z) - default- - Name (Z-A)- - Featured First-- Sort preference persisted in URL--## Files Changed-- `frontend/src/pages/Templates.jsx` - Complete rewrite with new features-- `frontend/src/styles/pages/_templates.less` - Extended with new styles--## Commits-- `342b660` - feat(7): Polish templates page with icons, filters, and sorting--## Notes-- All 60+ templates have Lucide icon mappings-- Featured templates list is hardcoded but can easily be made dynamic-- Sort by version was considered but version formats are inconsistent (e.g., "6.4", "231128", "2024-01")-- Mobile responsive styles includeddiff --git a/.planning/phases/08-applications-ui-polish/PLAN.md b/.planning/phases/08-applications-ui-polish/PLAN.mddeleted file mode 100644index 185e34ef..00000000--- a/.planning/phases/08-applications-ui-polish/PLAN.md+++ /dev/null@@ -1,215 +0,0 @@-# Phase 8: Applications UI Polish--## Objective-Improve the applications list and management pages with better status visibility, quick actions, sorting, and bulk operations.--## Context--### Current State-- Applications list at `frontend/src/pages/Applications.jsx`- - Shows app name, type, domains, status badge- - Has start/stop/restart actions inline- - CreateAppModal for new apps- - Private URL indicator already added (Phase 5)-- Application detail at `frontend/src/pages/ApplicationDetail.jsx`- - Tab-based navigation (overview, logs, deploy, domains, etc.)- - Environment variables component- - Routing diagnostics-- Styles in `frontend/src/styles/pages/_applications.less`--### Key Files-- `frontend/src/pages/Applications.jsx` - List page-- `frontend/src/pages/ApplicationDetail.jsx` - Detail page-- `frontend/src/styles/pages/_applications.less` - Styles-- `frontend/src/services/api.js` - API methods--### What Works Well-- Basic app list with status badges-- Quick actions (start/stop/restart)-- Domain links-- Tab organization in detail--### What Needs Improvement-- No sorting options-- No bulk selection/actions-- No view mode toggle (grid/list)-- Status colors could be more prominent-- No confirmation for destructive actions-- Action buttons lack icons-------## Tasks--### Task 1: Add Lucide Icons and Improve Action Buttons-**Goal**: Replace inline SVGs with Lucide icons, add icons to action buttons--**Files to modify**:-- `frontend/src/pages/Applications.jsx`--**Implementation**:-1. Import Lucide icons: `Play, Square, RotateCcw, Settings, Plus, Package, Grid, List`-2. Replace inline SVGs with Lucide components-3. Add icons to Start/Stop/Restart/Manage buttons-4. Improve "New Application" button with Plus icon--**Verification**: All buttons have consistent icons-------### Task 2: Add Sorting Options to Applications List-**Goal**: Allow sorting apps by name, status, type, or creation date--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Add sort state: `sortBy` (name-asc, name-desc, status, type, created)-2. Add sort dropdown in header area-3. Implement `sortApps()` function-4. Sort by running first for status sort-5. Style dropdown to match design system--**Verification**: Sorting changes list order correctly-------### Task 3: Add Grid/List View Toggle-**Goal**: Allow users to switch between compact list and card grid views--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Add `viewMode` state: 'list' | 'grid'-2. Add toggle buttons (Grid/List icons)-3. Create card-style layout for grid view-4. Keep existing row layout for list view-5. Persist preference in localStorage--**Verification**: Toggle switches between views, preference persists-------### Task 4: Add Bulk Selection and Actions-**Goal**: Allow selecting multiple apps for bulk start/stop/restart/delete--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Add `selectedApps` state (Set of app IDs)-2. Add checkbox to each app row/card-3. Add "Select All" checkbox in header-4. Show bulk action bar when apps selected-5. Implement bulk start/stop/restart handlers-6. Add confirmation modal for bulk delete-7. Style selected state and action bar--**Verification**: Can select multiple apps and perform bulk actions-------### Task 5: Add Confirmation Modal Component-**Goal**: Create reusable confirmation dialog for destructive actions--**Files to modify**:-- `frontend/src/pages/Applications.jsx` (inline component)-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Create `ConfirmModal` component with:- - Title, message, confirmText, cancelText props- - Danger variant for destructive actions- - Loading state for async confirm-2. Use for bulk delete confirmation-3. Use for individual app delete-4. Style with warning colors for danger variant--**Verification**: Destructive actions require confirmation-------### Task 6: Improve Status Indicators-**Goal**: Make app status more visually prominent--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Larger status badges with background color-2. Animated pulse for "running" status-3. Add port info to status area (e.g., "Running on :8080")-4. Show "Starting..." or "Stopping..." during transitions-5. Error status with tooltip showing error message--**Verification**: Status clearly visible, transitions shown-------### Task 7: Add Search Filter to Applications List-**Goal**: Allow filtering apps by name--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Add search input to header-2. Filter apps by name (case-insensitive)-3. Show "No apps match" message when filtered empty-4. Add Search icon and clear button (like Templates page)--**Verification**: Search filters list correctly-------### Task 8: Improve App Cards with More Info-**Goal**: Show more useful info in app cards/rows--**Files to modify**:-- `frontend/src/pages/Applications.jsx`-- `frontend/src/styles/pages/_applications.less`--**Implementation**:-1. Show main port in status area-2. Show domain count badge if multiple domains-3. Show "Last deployed" timestamp if available-4. Show container count for Docker apps-5. Improve type badge styling (like template version badges)--**Verification**: Cards show relevant info at a glance-------## Verification--After completing all tasks:-1. Apps list has sorting dropdown and search-2. Grid/list toggle works and persists-3. Bulk selection and actions work-4. Destructive actions have confirmation-5. Status indicators are prominent and clear-6. App cards show useful info-7. All buttons have icons-8. Page remains performant with many apps-------## Success Criteria-- [ ] App status visible at a glance-- [ ] Quick actions work reliably with icons-- [ ] Sorting and filtering work correctly-- [ ] Bulk actions functional with confirmation-- [ ] Grid/list toggle works-------## Output-- Modified `frontend/src/pages/Applications.jsx`-- Modified `frontend/src/styles/pages/_applications.less`-- Phase 8 SUMMARY.md on completiondiff --git a/.planning/phases/08-applications-ui-polish/SUMMARY.md b/.planning/phases/08-applications-ui-polish/SUMMARY.mddeleted file mode 100644index a75e4eff..00000000--- a/.planning/phases/08-applications-ui-polish/SUMMARY.md+++ /dev/null@@ -1,92 +0,0 @@-# Phase 8: Applications UI Polish - Summary--## Overview-Comprehensive UI polish for the applications list page including Lucide icons, sorting, grid/list toggle, bulk selection and actions, improved status indicators, search filter, and enhanced app cards.--## Completed-- [x] Task 1: Add Lucide Icons and Improve Action Buttons-- [x] Task 2: Add Sorting Options to Applications List-- [x] Task 3: Add Grid/List View Toggle-- [x] Task 4: Add Bulk Selection and Actions-- [x] Task 5: Add Confirmation Modal Component-- [x] Task 6: Improve Status Indicators-- [x] Task 7: Add Search Filter to Applications List-- [x] Task 8: Improve App Cards with More Info--## Implementation Details--### Lucide Icons-- Replaced all inline SVGs with Lucide React icons-- Icons used: Plus, Package, Grid, List, Play, Square, RotateCcw, Settings, Search, X, ChevronDown, Check, Trash2, AlertTriangle, Link2, Globe, Container, Clock-- Docker apps show Container icon instead of letter-- Modal close button uses X icon--### Sorting Options-- Dropdown with 5 sort options:- - Name (A-Z) - default- - Name (Z-A)- - Status (running first, then stopped, then error)- - Type (alphabetical)- - Newest First (by created_at)-- Sort preference persisted in URL params-- Uses `useMemo` for efficient re-sorting--### Grid/List View Toggle-- Toggle buttons in toolbar (List/Grid icons)-- List view: Row-based with inline actions-- Grid view: Card-based with hover effects-- View mode persisted in localStorage (`serverkit-apps-view-mode`)--### Bulk Selection and Actions-- Custom checkbox component with styled appearance-- "Select All" checkbox in list header-- Bulk action bar appears when apps selected-- Actions: Start, Stop, Restart, Delete-- Delete requires confirmation modal-- Clear selection button--### Confirmation Modal-- Reusable `ConfirmModal` component-- Props: title, message, confirmText, danger, onConfirm, onCancel, loading-- Danger variant shows warning icon and red button-- Loading state disables buttons during async operations--### Status Indicators-- Enhanced `status-badge-enhanced` class with larger badges-- Animated pulse effect for running status-- Status colors:- - Running: green with pulse animation- - Stopped: gray- - Error: red- - Warning: yellow with pulse-- Transition states show "Starting...", "Stopping...", etc.--### Search Filter-- Search input in toolbar with Search icon-- Clear button (X) when search has value-- Filters by app name and app type-- Case-insensitive matching-- URL param persistence-- "No matching applications" empty state--### Enhanced App Cards-- Type badge with accent color styling-- Port display (e.g., `:8080`)-- Domain count with Globe icon-- Private URL indicator with Link2 icon-- Container count for Docker apps-- Grid cards are clickable to navigate to detail page--## Files Changed-- `frontend/src/pages/Applications.jsx` - Complete rewrite with new features-- `frontend/src/styles/pages/_applications.less` - Extended with new styles--## Commits-- `9cdaf73` - feat(8): Polish applications UI with icons, sorting, grid view, and bulk actions--## Notes-- All 8 tasks implemented in single comprehensive update-- Responsive design with mobile adjustments-- Button text hidden on mobile, icons only-- Grid view cards have hover lift effect-- Checkboxes use custom styled appearance matching design systemdiff --git a/.planning/phases/09-filemanager-disk-usage/PLAN.md b/.planning/phases/09-filemanager-disk-usage/PLAN.mddeleted file mode 100644index 694b39ea..00000000--- a/.planning/phases/09-filemanager-disk-usage/PLAN.md+++ /dev/null@@ -1,244 +0,0 @@-# Phase 9: FileManager Disk Usage UI--## Objective-Improve disk usage visualization in the FileManager with enhanced widgets, directory size analysis, storage breakdown charts, and better UI organization.--## Context--### Current State-- FileManager at `frontend/src/pages/FileManager.jsx` (635 lines)- - Basic disk usage bar showing used/total/percent- - Color coding for warning (>75%) and critical (>90%)- - `loadDiskUsage()` calls `api.getDiskUsage(currentPath)`-- Backend `FileService.get_disk_usage()` uses `shutil.disk_usage(path)`- - Returns total, used, free, percent, and human-readable versions-- Styles in `frontend/src/styles/pages/_file-manager.less`-- Recharts already used in project (MetricsGraph component)--### Key Files-- `frontend/src/pages/FileManager.jsx` - Main page-- `frontend/src/styles/pages/_file-manager.less` - Styles-- `frontend/src/services/api.js` - API methods-- `backend/app/api/files.py` - Files API-- `backend/app/services/file_service.py` - File service--### What Works Well-- Basic disk usage display-- File browsing and management-- Color-coded progress bar--### What Needs Improvement-- No multi-mount point support-- No directory size analysis-- No file type breakdown-- Disk widget takes up horizontal space-- No visualization beyond simple bar-------## Tasks--### Task 1: Add Backend Directory Size Analysis Endpoint-**Goal**: Create endpoint to analyze directory sizes--**Files to modify**:-- `backend/app/services/file_service.py`-- `backend/app/api/files.py`--**Implementation**:-1. Add `analyze_directory_sizes(path)` method to FileService:- - Use `os.scandir()` to iterate directory- - Calculate sizes recursively for subdirectories (with depth limit)- - Return array of `{name, path, size, size_human, is_dir}`- - Sort by size descending- - Limit to top 20 entries-2. Add `/files/analyze` endpoint:- - Accept `path` parameter- - Optional `depth` param (default 1)- - Return subdirectory sizes and large files-3. Add `get_all_disk_mounts()` method:- - Use `psutil.disk_partitions()`- - Return array of mount points with usage stats--**Verification**: API returns directory sizes correctly-------### Task 2: Add Multi-Mount Disk Usage Widget-**Goal**: Show disk usage for all mount points with visual bars--**Files to modify**:-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`-- `frontend/src/services/api.js`--**Implementation**:-1. Add `getAllDiskUsage()` API method-2. Replace single disk bar with multi-mount widget:- - Each mount shows: device, mountpoint, progress bar, used/total- - Color coding: green (<70%), yellow (70-90%), red (>=90%)-3. Make widget collapsible (collapsed by default)-4. Add refresh button with last updated timestamp-5. Style as card in sidebar area--**Verification**: All mounts display with correct percentages and colors-------### Task 3: Create Directory Analysis Panel-**Goal**: Add "Analyze" button to show directory sizes--**Files to modify**:-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Add "Analyze" button to toolbar-2. Create `analyzeDirectory()` function that calls new endpoint-3. Add `directoryAnalysis` state to store results-4. Create analysis panel showing:- - Bar chart of subdirectory sizes (horizontal bars)- - Each bar shows: name, size, percentage of parent- - Click bar to navigate to that directory-5. Show loading state during analysis-6. Add close button to dismiss panel--**Verification**: Analysis shows accurate directory sizes-------### Task 4: Add Storage Type Breakdown-**Goal**: Show pie chart of space used by file type--**Files to modify**:-- `backend/app/services/file_service.py`-- `backend/app/api/files.py`-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Add `get_file_type_breakdown(path)` backend method:- - Walk directory tree (with depth limit for performance)- - Categorize files: images, videos, documents, code, archives, other- - Calculate total size per category- - Return category name, size, count, color-2. Add `/files/type-breakdown` endpoint-3. Add frontend API method-4. Create pie chart component using Recharts PieChart-5. Show legend with category names and sizes-6. Display in analysis panel alongside directory sizes--**Verification**: Pie chart shows accurate file type distribution-------### Task 5: Add Largest Files List-**Goal**: Show top 10 largest files in current directory--**Files to modify**:-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Extend directory analysis to include largest files-2. Create "Largest Files" section in analysis panel:- - Show file name, size, path- - Truncate long paths- - Click to select file in file list-3. Add toggle between "By Directory" and "By File" views-4. Style list with consistent spacing--**Verification**: Shows correct largest files, navigation works-------### Task 6: Reorganize Layout with Collapsible Sidebar-**Goal**: Move disk/analysis widgets to collapsible sidebar panel--**Files to modify**:-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Create sidebar layout structure:- - Main content (file list + preview)- - Right sidebar (disk usage, analysis)-2. Add toggle button to show/hide sidebar-3. Sidebar sections:- - Disk Usage (collapsible)- - Directory Analysis (when active)- - File Type Breakdown (when active)-4. Save sidebar state to localStorage-5. Responsive: sidebar becomes bottom sheet on mobile--**Verification**: Layout works at all screen sizes-------### Task 7: Add Lucide Icons Throughout-**Goal**: Replace emoji icons with Lucide React icons--**Files to modify**:-- `frontend/src/pages/FileManager.jsx`-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Import Lucide icons: Folder, File, FileCode, FileImage, etc.-2. Replace emoji-based file icons with Lucide components-3. Replace `<span className="icon">` with Lucide icons-4. Add icons to analysis panel sections-5. Ensure consistent icon sizing--**Verification**: All icons render correctly-------### Task 8: Polish and Responsive Adjustments-**Goal**: Ensure everything works well on all screen sizes--**Files to modify**:-- `frontend/src/styles/pages/_file-manager.less`--**Implementation**:-1. Add responsive breakpoints for:- - Sidebar visibility (<1200px: bottom sheet)- - File list columns (<768px: hide some columns)- - Analysis charts (<640px: stack vertically)-2. Add smooth transitions for sidebar toggle-3. Ensure touch-friendly tap targets-4. Test and fix any layout issues--**Verification**: Works on mobile, tablet, and desktop-------## Verification--After completing all tasks:-1. All mount points show with color-coded progress bars-2. "Analyze" button shows directory sizes and type breakdown-3. Charts render correctly with Recharts-4. Largest files list navigates correctly-5. Sidebar collapses and expands smoothly-6. Layout responsive at all sizes-7. Build succeeds with no errors-------## Success Criteria-- [ ] Multi-mount disk usage visible-- [ ] Directory analysis functional-- [ ] Pie chart shows file type breakdown-- [ ] Largest files list works-- [ ] Sidebar layout responsive-- [ ] All icons are Lucide components-------## Output-- Modified `frontend/src/pages/FileManager.jsx`-- Modified `frontend/src/styles/pages/_file-manager.less`-- Modified `frontend/src/services/api.js`-- Modified `backend/app/services/file_service.py`-- Modified `backend/app/api/files.py`-- Phase 9 SUMMARY.md on completiondiff --git a/.planning/phases/09-filemanager-disk-usage/SUMMARY.md b/.planning/phases/09-filemanager-disk-usage/SUMMARY.mddeleted file mode 100644index f25708b1..00000000--- a/.planning/phases/09-filemanager-disk-usage/SUMMARY.md+++ /dev/null@@ -1,82 +0,0 @@-# Phase 9: FileManager Disk Usage UI - Summary--## Overview-Comprehensive enhancement of the FileManager page with disk usage visualization, directory analysis, file type breakdown charts, and improved layout with collapsible sidebar.--## Completed-- [x] Task 1: Add Backend Directory Size Analysis Endpoint-- [x] Task 2: Add Multi-Mount Disk Usage Widget-- [x] Task 3: Create Directory Analysis Panel-- [x] Task 4: Add Storage Type Breakdown-- [x] Task 5: Add Largest Files List-- [x] Task 6: Reorganize Layout with Collapsible Sidebar-- [x] Task 7: Add Lucide Icons Throughout-- [x] Task 8: Polish and Responsive Adjustments--## Implementation Details--### Backend Enhancements-- **`get_all_disk_mounts()`**: Uses `psutil.disk_partitions()` to list all mount points with usage stats-- **`analyze_directory_sizes(path, depth, limit)`**: Recursively calculates subdirectory sizes with depth limit-- **`get_file_type_breakdown(path, max_depth)`**: Categorizes files into 8 types (images, videos, audio, documents, code, archives, data, other)-- New API endpoints: `/files/disk-mounts`, `/files/analyze`, `/files/type-breakdown`--### Multi-Mount Disk Widget-- Shows all mount points with device, mountpoint, and usage-- Color-coded progress bars: green (<70%), yellow (70-90%), red (>=90%)-- Collapsible section with state persisted in localStorage-- Refresh button with last updated timestamp--### Directory Analysis Panel-- "Analyze" button in toolbar triggers analysis-- Dual-view toggle: Directories vs Files-- Horizontal bar charts showing relative sizes-- Click directory bar to navigate into it-- Click file to select in file list--### File Type Breakdown-- Recharts PieChart with donut style-- 8 file categories with distinct colors-- Legend showing category name and size-- Displayed when analysis is active--### Largest Files List-- Top 10 largest files in current directory-- Shows filename and size-- Click to select file in main list--### Sidebar Layout-- Right sidebar with 320px width-- Toggle button in toolbar-- Contains: Disk Usage, Directory Analysis, File Types-- Mobile: slides in from right as overlay-- State persisted in localStorage--### Lucide Icons-- Replaced all emoji-based file icons with Lucide components-- Icon types: Folder, File, FileCode, FileImage, FileVideo, FileAudio, FileArchive, Database, Terminal, FileText-- Color-coded by file type-- All toolbar buttons now use Lucide icons--### Responsive Design-- Sidebar becomes slide-in panel on <1024px-- File list columns hide progressively on smaller screens-- Touch-friendly tap targets-- Smooth transitions--## Files Changed-- `backend/app/services/file_service.py` - Added analysis methods-- `backend/app/api/files.py` - Added analysis endpoints-- `frontend/src/services/api.js` - Added API methods-- `frontend/src/pages/FileManager.jsx` - Complete rewrite with sidebar and analysis-- `frontend/src/styles/pages/_file-manager.less` - Extended with new styles--## Commits-- `4c7f551` - feat(9): Add backend directory analysis and disk mount endpoints-- `135f053` - feat(9): Add FileManager disk usage visualization and analysis--## Notes-- Directory analysis has depth limits to prevent performance issues on large directories-- File type breakdown walks up to 3 levels deep by default-- PieChart uses Recharts library already present in project-- Sidebar state persisted separately from disk collapsed statediff --git a/.planning/phases/11-shared-database-wordpress-template/SUMMARY.md b/.planning/phases/11-shared-database-wordpress-template/SUMMARY.mddeleted file mode 100644index 882ccca7..00000000--- a/.planning/phases/11-shared-database-wordpress-template/SUMMARY.md+++ /dev/null@@ -1,51 +0,0 @@-# Phase 11: Shared Database WordPress Template — Summary--## Outcome-**Completed** — Created a new WordPress template supporting external MySQL databases, enabling dev/prod environments to share the same database with different table prefixes.--## What Was Built--### 1. WordPress External DB Template-- **File**: `backend/templates/wordpress-external-db.yaml`-- New template variant allowing WordPress to connect to external MySQL databases-- Configurable variables: DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, TABLE_PREFIX-- Uses WordPress `WORDPRESS_TABLE_PREFIX` for multi-instance isolation on same database--### 2. Template Registration-- **File**: `backend/templates/index.json`-- Added `wordpress-external-db` entry with categories: cms, blog, website, development--### 3. Database Connection Validation-- **File**: `backend/app/services/template_service.py`-- Added `validate_mysql_connection()` method with:- - Socket-level port connectivity check- - Full MySQL authentication test (when pymysql available)- - Graceful fallback to port-only check if pymysql not installed-- Integrated validation into `install_template()` for wordpress-external-db--### 4. API Endpoint-- **File**: `backend/app/api/templates.py`-- Added `POST /templates/test-db-connection` endpoint-- Validates host, port, user, password, database parameters-- Returns success/failure with detailed error messages--### 5. Frontend API Method-- **File**: `frontend/src/services/api.js`-- Added `testDatabaseConnection(config)` method for frontend to call validation endpoint--## Key Decisions-- **Separate template**: Created new template file rather than adding conditional logic to existing wordpress.yaml for clarity and maintainability-- **Optional pymysql**: Made MySQL library optional - uses socket check as fallback if not installed-- **Table prefix pattern**: Recommended convention: `wp_` for prod, `wp_dev_` for dev environments--## Files Changed-- `backend/templates/wordpress-external-db.yaml` (new)-- `backend/templates/index.json` (modified)-- `backend/app/services/template_service.py` (modified)-- `backend/app/api/templates.py` (modified)-- `frontend/src/services/api.js` (modified)--## Testing Notes-- Template appears in template browser under categories: cms, blog, website, development-- Database connection test validates before installation attempt-- Table prefix isolation allows multiple WordPress instances on same databasediff --git a/.planning/phases/11-shared-db-wordpress-template/PLAN.md b/.planning/phases/11-shared-db-wordpress-template/PLAN.mddeleted file mode 100644index ddaea26b..00000000--- a/.planning/phases/11-shared-db-wordpress-template/PLAN.md+++ /dev/null@@ -1,302 +0,0 @@-# Phase 11: Shared Database WordPress Template--## Objective-Create a WordPress template variant that connects to an external database instead of bundling its own MySQL container. This enables prod/dev environment sharing via a single database with different table prefixes.--## Execution Context--### Key Files-- `backend/templates/wordpress.yaml` - Existing WordPress template (reference)-- `backend/templates/index.json` - Template registry-- `backend/app/services/template_service.py` - Template installation logic-- `backend/app/api/templates.py` - Template API endpoints--### Current WordPress Template-The existing `wordpress.yaml` template:-- Bundles MySQL 8.0 container-- Uses hardcoded `WORDPRESS_DB_HOST=db` (internal service)-- Creates `wordpress_db` volume for database storage-- Variables: `HTTP_PORT`, `DB_PASSWORD`, `WP_DB_PASSWORD`--### WordPress Environment Variables-WordPress official Docker image supports:-- `WORDPRESS_DB_HOST` - Database host (can be `host:port`)-- `WORDPRESS_DB_USER` - Database username-- `WORDPRESS_DB_PASSWORD` - Database password-- `WORDPRESS_DB_NAME` - Database name-- `WORDPRESS_TABLE_PREFIX` - Table prefix (default: `wp_`)-------## Tasks--### Task 1: Create WordPress External DB Template-**File**: `backend/templates/wordpress-external-db.yaml`--Create a new template for WordPress with external database support:--```yaml-id: wordpress-external-db-name: WordPress (External Database)-version: "6.4"-description: WordPress CMS connecting to an existing external MySQL database-icon: https://s.w.org/style/images/about/WordPress-logotype-wmark.png-website: https://wordpress.org-documentation: https://wordpress.org/documentation/-categories:- - cms- - blog- - website- - development--variables:- - name: HTTP_PORT- description: HTTP port for WordPress- type: port- default: "8080"- - name: DB_HOST- description: External database host (e.g., 192.168.1.100 or db.example.com)- type: string- required: true- - name: DB_PORT- description: External database port- type: string- default: "3306"- - name: DB_NAME- description: Database name- type: string- default: "wordpress"- required: true- - name: DB_USER- description: Database username- type: string- default: "wordpress"- required: true- - name: DB_PASSWORD- description: Database password- type: password- required: true- - name: TABLE_PREFIX- description: WordPress table prefix (use different prefix for dev vs prod)- type: string- default: "wp_"--ports:- - port: 8080- protocol: tcp- description: Web interface--volumes:- - name: html- path: /var/www/html- description: WordPress files--compose:- services:- wordpress:- image: wordpress:${VERSION:-6.4-apache}- container_name: ${APP_NAME}- restart: unless-stopped- environment:- - WORDPRESS_DB_HOST=${DB_HOST}:${DB_PORT}- - WORDPRESS_DB_USER=${DB_USER}- - WORDPRESS_DB_PASSWORD=${DB_PASSWORD}- - WORDPRESS_DB_NAME=${DB_NAME}- - WORDPRESS_TABLE_PREFIX=${TABLE_PREFIX}- volumes:- - wordpress_html:/var/www/html- ports:- - "${HTTP_PORT}:80"-- volumes:- wordpress_html:-```--Key differences from standard WordPress template:-- No `db` service-- No `wordpress_db` volume-- No `depends_on: db`-- External DB connection variables (host, port, name, user, password)-- `TABLE_PREFIX` variable for multi-instance support--### Task 2: Register Template in Index-**File**: `backend/templates/index.json`--Add the new template entry to the templates array:--```json-{- "id": "wordpress-external-db",- "name": "WordPress (External Database)",- "version": "6.4",- "description": "WordPress CMS with external MySQL database support for dev/prod environments",- "categories": ["cms", "blog", "website", "development"]-}-```--Place it after the standard WordPress entry.--### Task 3: Add Database Connection Validation-**File**: `backend/app/services/template_service.py`--Add a method to validate MySQL connection before installation:--```python-@classmethod-def validate_mysql_connection(cls, host: str, port: int, user: str,- password: str, database: str) -> Dict:- """Validate MySQL database connection.-- Returns:- Dict with 'success' and optional 'error' message- """- import socket-- try:- # First check if host:port is reachable- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- sock.settimeout(5)- result = sock.connect_ex((host, int(port)))- sock.close()-- if result != 0:- return {- 'success': False,- 'error': f'Cannot connect to {host}:{port} - host unreachable'- }-- # Try MySQL connection if pymysql available- try:- import pymysql- conn = pymysql.connect(- host=host,- port=int(port),- user=user,- password=password,- database=database,- connect_timeout=5- )- conn.close()- return {'success': True}- except ImportError:- # pymysql not available, just check port was reachable- return {'success': True, 'warning': 'MySQL library not available, only port check performed'}- except Exception as e:- return {- 'success': False,- 'error': f'Database connection failed: {str(e)}'- }-- except Exception as e:- return {- 'success': False,- 'error': f'Connection check failed: {str(e)}'- }-```--Integrate into `install_template()` method for external-db templates:--```python-# In install_template(), after variable processing:-if template_id == 'wordpress-external-db':- db_check = cls.validate_mysql_connection(- host=variables.get('DB_HOST'),- port=variables.get('DB_PORT', '3306'),- user=variables.get('DB_USER'),- password=variables.get('DB_PASSWORD'),- database=variables.get('DB_NAME')- )- if not db_check.get('success'):- return {- 'success': False,- 'error': f"Database connection failed: {db_check.get('error')}"- }-```--### Task 4: Add API Endpoint for DB Connection Test-**File**: `backend/app/api/templates.py`--Add an endpoint to test database connections before installation:--```python-@templates_bp.route('/test-db-connection', methods=['POST'])-@jwt_required()-def test_db_connection():- """Test database connection before template installation."""- data = request.get_json()-- required = ['host', 'user', 'password', 'database']- for field in required:- if field not in data:- return jsonify({'error': f'Missing required field: {field}'}), 400-- result = TemplateService.validate_mysql_connection(- host=data.get('host'),- port=data.get('port', 3306),- user=data.get('user'),- password=data.get('password'),- database=data.get('database')- )-- if result.get('success'):- return jsonify({'success': True, 'message': 'Connection successful'}), 200- else:- return jsonify({- 'success': False,- 'error': result.get('error')- }), 400-```--### Task 5: Add Frontend API Method-**File**: `frontend/src/services/api.js`--Add method to test database connections:--```javascript-async testDatabaseConnection(config) {- return this.request('/templates/test-db-connection', {- method: 'POST',- body: config- });-}-```-------## Verification--After implementation:-1. [ ] New template `wordpress-external-db` appears in template list-2. [ ] Template has correct variables: HTTP_PORT, DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, TABLE_PREFIX-3. [ ] Installing with invalid DB credentials shows clear error-4. [ ] Installing with valid external DB succeeds-5. [ ] WordPress container starts without bundled MySQL-6. [ ] WordPress connects to external database-7. [ ] Table prefix is applied correctly-8. [ ] Build passes without errors-------## Success Criteria-- [ ] WordPress template can connect to external MySQL-- [ ] Connection errors shown clearly during install-- [ ] Table prefix configurable-------## Output-- Created: `backend/templates/wordpress-external-db.yaml`-- Modified: `backend/templates/index.json`-- Modified: `backend/app/services/template_service.py`-- Modified: `backend/app/api/templates.py`-- Modified: `frontend/src/services/api.js`-- Created: `.planning/phases/11-shared-db-wordpress-template/SUMMARY.md`-------## Notes-- The external DB template is separate from the standard WordPress template for clarity-- Users can install standard WordPress first (with bundled DB), then install WordPress-External-DB pointing to the same database with a different table prefix for dev-- pymysql is optional - if not installed, only port connectivity is checked-- Table prefix must end with underscore (WordPress requirement)-- Phase 12 will add the UI for linking apps and auto-configuring shared databasesdiff --git a/.planning/phases/12-multi-environment-app-linking/PLAN.md b/.planning/phases/12-multi-environment-app-linking/PLAN.mddeleted file mode 100644index abe78bb0..00000000--- a/.planning/phases/12-multi-environment-app-linking/PLAN.md+++ /dev/null@@ -1,185 +0,0 @@-# Phase 12: Multi-Environment App Linking — PLAN--## Objective-Add database schema and API support for linking applications as prod/dev pairs that share database resources.--## Execution Context--**Key Files:**-- `backend/app/models/application.py` — Application model (add new fields)-- `backend/app/api/apps.py` — Apps API endpoints (add linking endpoints)-- `backend/app/models/__init__.py` — Model exports-- `backend/app/services/template_service.py` — Template service (credential propagation)-- `frontend/src/services/api.js` — Frontend API methods--**Patterns to Follow:**-- SQLAlchemy model with `db.create_all()` (no Alembic migrations)-- Blueprint pattern for API routes with `@jwt_required()` decorator-- `to_dict()` serialization method on models-- `admin_required` decorator from templates.py for admin-only operations--## Context--**Phase 11 Created:**-- `wordpress-external-db.yaml` template with configurable DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, TABLE_PREFIX-- Database connection validation via `validate_mysql_connection()`--**This Phase Enables:**-- Linking a dev WordPress to a prod WordPress-- Auto-propagating database credentials when linking-- Auto-configuring table prefixes to avoid collision (wp_ for prod, wp_dev_ for dev)--## Tasks--### Task 1: Add Environment Fields to Application Model-**File:** `backend/app/models/application.py`--Add new columns to Application model:-```python-# Environment linking-environment_type = db.Column(db.String(20), default='standalone') # 'production', 'development', 'staging', 'standalone'-linked_app_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=True)-shared_config = db.Column(db.Text, nullable=True) # JSON string for shared resources-```--Add self-referential relationship:-```python-linked_app = db.relationship('Application', remote_side=[id], backref='linked_apps')-```--Update `to_dict()` to include new fields.--**Verification:** Check model imports and `db.create_all()` creates the new columns.-------### Task 2: Create App Linking API Endpoints-**File:** `backend/app/api/apps.py`--Add new endpoints:--1. **POST /apps/{id}/link** — Link two apps as prod/dev pair- - Request: `{ "target_app_id": int, "as_environment": "development" | "production" | "staging" }`- - Validates both apps exist and belong to same user (or admin)- - Validates apps are same type (e.g., both docker/wordpress)- - Sets environment_type on both apps- - Links apps bidirectionally- - Returns updated app info--2. **GET /apps/{id}/linked** — Get linked apps- - Returns all apps linked to this app- - Includes environment type and shared config--3. **DELETE /apps/{id}/link** — Unlink apps- - Removes link from both apps- - Resets environment_type to 'standalone'--4. **PUT /apps/{id}/environment** — Update environment type only- - Request: `{ "environment_type": "production" | "development" | "staging" | "standalone" }`- - For apps not linked, just sets the type--**Verification:** Test endpoints with curl or frontend.-------### Task 3: Add Database Credential Propagation-**File:** `backend/app/services/template_service.py`--Add method to propagate database credentials when linking:-```python-@classmethod-def propagate_db_credentials(cls, source_app_id: int, target_app_id: int, target_prefix: str = None) -> Dict:- """Propagate database credentials from source app to target app.-- Reads source app's .env file for DB credentials, updates target app's- .env with same credentials but different table prefix.- """-```--Logic:-1. Get source app's root_path-2. Read source app's `.env` or `docker-compose.yml` for DB_HOST, DB_NAME, DB_USER, DB_PASSWORD-3. Get target app's root_path-4. Update target app's env with same credentials but different TABLE_PREFIX-5. Store shared config in shared_config field as JSON--**Verification:** After linking, target app should have source app's DB credentials.-------### Task 4: Add Frontend API Methods-**File:** `frontend/src/services/api.js`--Add methods:-```javascript-async linkApp(appId, targetAppId, asEnvironment) {- return this.request(`/apps/${appId}/link`, {- method: 'POST',- body: { target_app_id: targetAppId, as_environment: asEnvironment }- });-}--async getLinkedApps(appId) {- return this.request(`/apps/${appId}/linked`);-}--async unlinkApp(appId) {- return this.request(`/apps/${appId}/link`, {- method: 'DELETE'- });-}--async updateAppEnvironment(appId, environmentType) {- return this.request(`/apps/${appId}/environment`, {- method: 'PUT',- body: { environment_type: environmentType }- });-}-```--**Verification:** Methods callable from browser console.-------### Task 5: Update App List Response to Include Environment Info-**File:** `backend/app/api/apps.py`--Modify `get_apps()` and `get_app()` to include:-- `environment_type` in response-- `linked_apps` summary (id, name, environment_type)-- `has_linked_apps` boolean--**Verification:** GET /apps returns environment info.-------## Verification--```bash-# Test model changes (will happen on app startup)-cd backend && python -c "from app import db, create_app; app = create_app(); app.app_context().push(); db.create_all()"--# Test API endpoints (after implementation)-# Link apps-curl -X POST http://localhost:5000/api/v1/apps/1/link \- -H "Authorization: Bearer <token>" \- -H "Content-Type: application/json" \- -d '{"target_app_id": 2, "as_environment": "development"}'--# Get linked apps-curl http://localhost:5000/api/v1/apps/1/linked \- -H "Authorization: Bearer <token>"-```--## Success Criteria-- [ ] Application model has environment_type, linked_app_id, shared_config fields-- [ ] Apps can be linked via API-- [ ] Linked apps visible in GET /apps response-- [ ] Database credentials propagate when linking WordPress apps-- [ ] Frontend API methods added--## Output-- Modified: `backend/app/models/application.py`-- Modified: `backend/app/api/apps.py`-- Modified: `backend/app/services/template_service.py`-- Modified: `frontend/src/services/api.js`diff --git a/.planning/phases/12-multi-environment-app-linking/SUMMARY.md b/.planning/phases/12-multi-environment-app-linking/SUMMARY.mddeleted file mode 100644index 52c2a9d1..00000000--- a/.planning/phases/12-multi-environment-app-linking/SUMMARY.md+++ /dev/null@@ -1,84 +0,0 @@-# Phase 12: Multi-Environment App Linking — Summary--## Outcome-**Completed** — Apps can now be linked as prod/dev pairs with shared database credentials automatically propagated.--## What Was Built--### 1. Application Model Updates-**File:** `backend/app/models/application.py`-- Added `environment_type` column (production/development/staging/standalone)-- Added `linked_app_id` for bidirectional app linking-- Added `shared_config` JSON field for storing shared resource info-- Added `linked_app` self-referential relationship-- Updated `to_dict()` with optional `include_linked` parameter--### 2. App Linking API Endpoints-**File:** `backend/app/api/apps.py`-- `POST /apps/{id}/link` — Link two apps as prod/dev pair-- `GET /apps/{id}/linked` — Get all linked apps-- `DELETE /apps/{id}/link` — Unlink apps-- `PUT /apps/{id}/environment` — Update environment type only-- Updated `GET /apps` with environment filtering and `include_linked` param-- Updated `GET /apps/{id}` to include linked app info by default--### 3. Database Credential Propagation-**File:** `backend/app/services/template_service.py`-- Added `propagate_db_credentials()` method-- Reads source app's `.env` for DB credentials (DB_HOST, DB_NAME, etc.)-- Updates target app's `.env` with same credentials but different table prefix-- Auto-assigns table prefixes (wp_ for prod, wp_dev_ for dev)-- Optionally updates docker-compose.yml environment variables--### 4. Frontend API Methods-**File:** `frontend/src/services/api.js`-- `linkApp(appId, targetAppId, asEnvironment, options)` — Link apps with optional credential propagation-- `getLinkedApps(appId)` — Get linked apps-- `unlinkApp(appId)` — Unlink apps-- `updateAppEnvironment(appId, environmentType)` — Set environment type--## Commits-1. `34bee0e` — feat(12): Add environment linking fields to Application model-2. `3e4ba70` — feat(12): Add app linking API endpoints-3. `7485771` — feat(12): Add database credential propagation for linked apps-4. `46f6f3a` — feat(12): Add frontend API methods for app linking-5. `65d1fbe` — feat(12): Update app list response to include environment info and filtering--## API Reference--### Link Apps-```bash-POST /apps/{id}/link-{- "target_app_id": 2,- "as_environment": "development",- "propagate_credentials": true,- "table_prefix": "wp_dev_"-}-```--### Get Linked Apps-```bash-GET /apps/{id}/linked-```--### Filter by Environment-```bash-GET /apps?environment=production-GET /apps?include_linked=true-```--## Key Decisions-- **Bidirectional linking**: Both apps store reference to each other-- **Auto table prefix**: Prevents collision when sharing database (wp_ vs wp_dev_)-- **Optional credential propagation**: Can be disabled via `propagate_credentials: false`-- **Environment types**: production, development, staging, standalone (default)--## Files Changed-- `backend/app/models/application.py`-- `backend/app/api/apps.py`-- `backend/app/services/template_service.py`-- `frontend/src/services/api.js`--## Next Steps-Phase 13 will add the UI for managing linked apps and environment switching.diff --git a/.planning/phases/13-environment-switching-ui/PLAN.md b/.planning/phases/13-environment-switching-ui/PLAN.mddeleted file mode 100644index 04557e1e..00000000--- a/.planning/phases/13-environment-switching-ui/PLAN.md+++ /dev/null@@ -1,151 +0,0 @@-# Phase 13: Environment Switching UI — PLAN--## Objective-Add UI components for managing environment types, linking apps as prod/dev pairs, and syncing themes between WordPress environments.--## Execution Context--**Key Files:**-- `frontend/src/pages/Applications.jsx` — App list (add environment badges)-- `frontend/src/pages/ApplicationDetail.jsx` — App detail (add linked apps section)-- `frontend/src/components/LinkedAppsSection.jsx` — New component for linked apps-- `frontend/src/components/LinkAppModal.jsx` — New modal for linking apps-- `frontend/src/styles/components/_badges.less` — Environment badge styles-- `frontend/src/styles/components/_linked-apps.less` — Linked apps section styles--**API Methods Available (from Phase 12):**-- `api.linkApp(appId, targetAppId, asEnvironment, options)`-- `api.getLinkedApps(appId)`-- `api.unlinkApp(appId)`-- `api.updateAppEnvironment(appId, environmentType)`--**Patterns to Follow:**-- Functional components with hooks-- Lucide icons (already imported in Applications.jsx)-- Status badge pattern from _badges.less-- Card-based UI for sections-- Modal pattern from CreateAppModal--## Tasks--### Task 1: Add Environment Badge to App List-**Files:** `frontend/src/pages/Applications.jsx`, `frontend/src/styles/components/_badges.less`--Add environment badge next to status badge in both list and grid views:-- Show badge only when `environment_type !== 'standalone'`-- Colors: green=production, blue=development, yellow=staging-- Badge text: "PROD", "DEV", "STAGING"-- Add linked icon indicator if `has_linked_app` is true--Update `AppRow` and `AppCard` components to display environment info.--**Verification:** Apps with environment types show colored badges.-------### Task 2: Add Environment Filter to Apps Toolbar-**File:** `frontend/src/pages/Applications.jsx`--Add environment filter dropdown in toolbar:-- Options: All, Production, Development, Staging, Standalone-- Uses URL params like existing search/sort-- Calls `api.getApps()` with `?environment=` filter--**Verification:** Filter dropdown filters apps by environment type.-------### Task 3: Create LinkedAppsSection Component-**Files:** `frontend/src/components/LinkedAppsSection.jsx`, `frontend/src/styles/components/_linked-apps.less`--New component showing linked apps in Overview tab:-```jsx-<LinkedAppsSection- app={app}- linkedApps={linkedApps}- onLink={() => setShowLinkModal(true)}- onUnlink={handleUnlink}- onNavigate={(appId) => navigate(`/apps/${appId}`)}-/>-```--Features:-- Shows current environment type with colored badge-- Lists linked apps with their status-- "Link App" button to open modal-- "Unlink" button with confirmation-- Quick navigation to linked app--**Verification:** Component renders in Overview tab with linked app info.-------### Task 4: Create LinkAppModal Component-**File:** `frontend/src/components/LinkAppModal.jsx`--Modal for linking an app to another:-- Dropdown to select target app (filtered to same type, not already linked)-- Environment type selection (This app will be: Development / Production / Staging)-- Table prefix input for WordPress apps (optional, auto-generated default)-- Checkbox: "Propagate database credentials" (default: true)-- Shows preview of what will happen-- Calls `api.linkApp()` on submit--**Verification:** Modal opens, shows compatible apps, links successfully.-------### Task 5: Integrate Linked Apps Section into ApplicationDetail-**File:** `frontend/src/pages/ApplicationDetail.jsx`--Add LinkedAppsSection to Overview tab:-- Load linked apps on mount using `api.getLinkedApps(id)`-- Add state for `linkedApps`, `showLinkModal`-- Handle unlink with confirmation dialog-- Refresh after link/unlink operations--Update header to show environment badge next to status badge.--**Verification:** Overview tab shows linked apps section with functional link/unlink.-------### Task 6: Add Environment Settings to Settings Tab-**File:** `frontend/src/pages/ApplicationDetail.jsx`--Add environment configuration section in SettingsTab:-- Current environment type display-- Dropdown to change environment type (standalone apps only)-- Warning when changing linked app environment-- "Unlink from [app name]" button for linked apps--**Verification:** Can change environment type for standalone apps.-------## Verification--```javascript-// In browser console, verify:-// 1. Apps with environment_type show badges-// 2. Filter dropdown works-// 3. Linked apps section appears in Overview-// 4. Link modal shows compatible apps-// 5. Link/unlink operations work-```--## Success Criteria-- [ ] Environment badges visible in app list (list and grid views)-- [ ] Environment filter dropdown in toolbar-- [ ] Linked apps section in Overview tab-- [ ] Link app modal with target selection-- [ ] Unlink functionality with confirmation-- [ ] Environment type editable in Settings tab--## Output-- Modified: `frontend/src/pages/Applications.jsx`-- Modified: `frontend/src/pages/ApplicationDetail.jsx`-- Created: `frontend/src/components/LinkedAppsSection.jsx`-- Created: `frontend/src/components/LinkAppModal.jsx`-- Modified: `frontend/src/styles/components/_badges.less`-- Created: `frontend/src/styles/components/_linked-apps.less`diff --git a/.planning/phases/13-environment-switching-ui/SUMMARY.md b/.planning/phases/13-environment-switching-ui/SUMMARY.mddeleted file mode 100644index 64d5d8a6..00000000--- a/.planning/phases/13-environment-switching-ui/SUMMARY.md+++ /dev/null@@ -1,118 +0,0 @@-# Phase 13: Environment Switching UI - Summary--## Overview-Implemented the frontend UI for managing multi-environment app linking, including environment badges, linked apps section, link app modal, and environment settings.--## Completed: 2026-01-19--## What Was Built--### 1. Environment Badges in App List-**File**: `frontend/src/pages/Applications.jsx`--- Added `EnvironmentBadge` helper component showing PROD/DEV/STAGING badges-- Color coding: green (production), blue (development), yellow (staging)-- Shows linked icon when app is linked to another-- Added environment filter dropdown to toolbar-- Filter state persisted via URL params (`?envFilter=production`)-- Added 'environment' as sort option--### 2. LinkedAppsSection Component-**File**: `frontend/src/components/LinkedAppsSection.jsx`--- Displays current environment type with colored badge-- Shows linked apps list with:- - App name and environment type- - Running status badge- - Port number- - Quick navigation button- - Unlink button-- Shows shared database info when credentials propagated-- Empty state messaging for standalone/unlinked apps--### 3. LinkAppModal Component-**File**: `frontend/src/components/LinkAppModal.jsx`--- Modal for linking apps together-- Filters compatible apps (same type, not already linked, standalone)-- Environment selection (dev/prod/staging) via radio buttons-- Visual preview diagram showing link relationship-- Docker-specific options:- - Propagate database credentials checkbox- - Table prefix configuration-- Loading and empty states--### 4. Linked Apps Integration in ApplicationDetail-**File**: `frontend/src/pages/ApplicationDetail.jsx`--- Added environment badge to app header-- Integrated LinkedAppsSection in OverviewTab-- Added LinkAppModal with show/hide state-- Added handlers for link, unlink, and navigate actions-- Loads linked apps data on mount and after link/unlink--### 5. Environment Settings in Settings Tab-**File**: `frontend/src/pages/ApplicationDetail.jsx`--- Environment Configuration section in SettingsTab-- Current environment type display-- Dropdown to change environment (standalone apps only)-- Disabled state with badge for linked apps-- Unlink Application button for linked apps-- Warning styling for linked app section--### 6. Styles-**Files**:-- `frontend/src/styles/components/_linked-apps.less` (new)-- `frontend/src/styles/components/_badges.less` (modified)-- `frontend/src/styles/pages/_settings.less` (modified)-- `frontend/src/styles/main.less` (modified)--Styles include:-- `.env-badge` variants for production/development/staging-- `.linked-apps-section` with header, list, items-- `.linked-app-item` with info, icon, details, actions-- `.link-app-modal` with form, preview diagram-- `.env-radio-group` and `.env-radio-option`-- `.settings-row`, `.settings-label`, `.settings-control`-- `.status-badge-sm` for compact status display--## Files Changed--| File | Change Type |-|------|-------------|-| `frontend/src/pages/Applications.jsx` | Modified |-| `frontend/src/pages/ApplicationDetail.jsx` | Modified |-| `frontend/src/components/LinkedAppsSection.jsx` | Created |-| `frontend/src/components/LinkAppModal.jsx` | Created |-| `frontend/src/styles/components/_badges.less` | Modified |-| `frontend/src/styles/components/_linked-apps.less` | Created |-| `frontend/src/styles/pages/_settings.less` | Modified |-| `frontend/src/styles/main.less` | Modified |--## Commits--1. `f2fc1c4` - Add environment badges to application list-2. `60ba896` - Add environment filter dropdown to apps toolbar-3. `92df579` - Create LinkedAppsSection component for app detail-4. `d61628e` - Create LinkAppModal component for linking apps-5. `9dbcfea` - Integrate linked apps section into ApplicationDetail-6. `99bc859` - Add environment settings to Settings tab--## API Methods Used (from Phase 12)-- `api.getLinkedApps(appId)` - Get linked apps-- `api.linkApp(appId, targetId, environment, options)` - Link apps-- `api.unlinkApp(appId)` - Unlink apps-- `api.updateAppEnvironment(appId, environmentType)` - Change environment--## Success Criteria--- [x] Environment type visible in UI (badges in list and detail)-- [x] Easy navigation between linked apps (LinkedAppsSection with buttons)-- [ ] Theme sync works for WordPress apps (deferred - Phase 15)--## Notes--- Theme sync feature deferred to Phase 15 (testing phase)-- All environment management now accessible through both Overview and Settings tabs-- Filter dropdown integrates with existing URL param pattern used for other filtersdiff --git a/.planning/phases/14-github-community-links/PLAN.md b/.planning/phases/14-github-community-links/PLAN.mddeleted file mode 100644index 0a8a8879..00000000--- a/.planning/phases/14-github-community-links/PLAN.md+++ /dev/null@@ -1,148 +0,0 @@-# Phase 14: GitHub & Community Links--## Objective-Add GitHub repository link and community resources throughout the application UI, including version checking for updates.--## Execution Context--### Key Files-- `frontend/src/pages/Settings.jsx` - AboutSection component (lines 1649-1754)-- `frontend/src/components/Sidebar.jsx` - Navigation sidebar-- `frontend/src/styles/pages/_settings.less` - About section styles-- `frontend/src/styles/layout/_sidebar.less` - Sidebar styles-- `frontend/src/services/api.js` - API service-- `backend/app/api/system.py` - Version endpoint--### Existing State-- **AboutSection already exists** in Settings.jsx with:- - Version display (fetched from `/api/v1/system/version`)- - GitHub link pointing to `https://github.com/serverkit` (needs update to correct URL)- - Documentation link (placeholder `#`)- - Support link (placeholder `#`)-- **Sidebar** has user profile at bottom but no external links-- **Lucide icons** already used throughout frontend--### Repository URLs-- Main: `https://github.com/jhd3197/ServerKit`-- Issues: `https://github.com/jhd3197/ServerKit/issues`-- Discussions: `https://github.com/jhd3197/ServerKit/discussions`-- Releases: `https://github.com/jhd3197/ServerKit/releases`-- Wiki/Docs: `https://github.com/jhd3197/ServerKit/wiki` (or README)-------## Tasks--### Task 1: Update About Section Links-**File**: `frontend/src/pages/Settings.jsx`--Update the existing AboutSection component:--1. **Fix GitHub URL** (line 1722)- - Change from `https://github.com/serverkit` to `https://github.com/jhd3197/ServerKit`--2. **Add functional links**- - Documentation → `https://github.com/jhd3197/ServerKit#readme`- - Support → `https://github.com/jhd3197/ServerKit/issues`--3. **Add additional community links**- - GitHub Discussions: `https://github.com/jhd3197/ServerKit/discussions`- - Report Bug: `https://github.com/jhd3197/ServerKit/issues/new`- - Star on GitHub badge/prompt--4. **Replace inline SVGs with Lucide icons**- - Import: `Github, FileText, HelpCircle, MessageSquare, Bug, Star`- - Replace existing SVG icons with Lucide components--### Task 2: Add Version Update Check-**Files**: `backend/app/api/system.py`, `frontend/src/pages/Settings.jsx`, `frontend/src/services/api.js`--1. **Backend: Add GitHub releases check endpoint**- ```python- @system_bp.route('/check-update', methods=['GET'])- def check_update():- # Fetch latest release from GitHub API- # Compare with current version- # Return: current_version, latest_version, update_available, release_url- ```--2. **Frontend API: Add checkUpdate method**- ```javascript- async checkUpdate() {- return this.request('/system/check-update');- }- ```--3. **Frontend UI: Show update notification in AboutSection**- - Display "Update available: v1.x.x" with link to release- - Badge/indicator when update available- - "You're up to date" message when current--### Task 3: Add GitHub Link to Sidebar-**Files**: `frontend/src/components/Sidebar.jsx`, `frontend/src/styles/layout/_sidebar.less`--1. **Add GitHub icon link between nav and user profile**- - Small GitHub icon with hover effect- - Links to repository- - Tooltip: "View on GitHub"--2. **Styling**- - Match existing sidebar aesthetic- - Subtle but visible- - Hover state with accent color--### Task 4: Add Star Prompt for New Users-**Files**: `frontend/src/pages/Settings.jsx`, `frontend/src/styles/pages/_settings.less`--1. **Add "Star on GitHub" card**- - Shows in About section- - GitHub star icon with count (if API allows)- - Dismissible (localStorage to remember)- - Friendly CTA: "If you find ServerKit useful, consider starring the repo!"--2. **Styling**- - Accent-colored border or background- - Star icon prominent- - Dismiss button (X)-------## Verification--After implementation:-1. [ ] GitHub link in About section opens correct repository-2. [ ] Documentation link opens README-3. [ ] Support/Issues link opens GitHub Issues-4. [ ] Discussions link opens GitHub Discussions-5. [ ] Sidebar GitHub icon visible and functional-6. [ ] Update check shows current version status-7. [ ] Star prompt displays for new users-8. [ ] Star prompt can be dismissed-9. [ ] All icons are Lucide (no inline SVGs in changed code)-10. [ ] Build passes without errors-------## Success Criteria-- [ ] GitHub link visible in main UI (sidebar)-- [ ] Documentation accessible from Settings-- [ ] Version check shows update availability-- [ ] Community links functional (Issues, Discussions)-------## Output-- Modified: `frontend/src/pages/Settings.jsx`-- Modified: `frontend/src/components/Sidebar.jsx`-- Modified: `frontend/src/styles/pages/_settings.less`-- Modified: `frontend/src/styles/layout/_sidebar.less`-- Modified: `frontend/src/services/api.js`-- Modified: `backend/app/api/system.py`-- Created: `.planning/phases/14-github-community-links/SUMMARY.md`-------## Notes-- GitHub API rate limits: 60 requests/hour for unauthenticated. Cache update check result.-- Star count requires GitHub API call - consider if worth the complexity-- Keep changes minimal and focused per CLAUDE.md guidelinesdiff --git a/.planning/phases/14-github-community-links/SUMMARY.md b/.planning/phases/14-github-community-links/SUMMARY.mddeleted file mode 100644index cbe282e1..00000000--- a/.planning/phases/14-github-community-links/SUMMARY.md+++ /dev/null@@ -1,81 +0,0 @@-# Phase 14: GitHub & Community Links - Summary--## Overview-Added GitHub repository links and community resources throughout the application UI, including version update checking via the GitHub releases API.--## Completed-- [x] Task 1: Update About Section Links-- [x] Task 2: Add Version Update Check-- [x] Task 3: Add GitHub Link to Sidebar-- [x] Task 4: Add Star Prompt for New Users--## Implementation Details--### About Section Links (Task 1)-- Fixed GitHub URL from `github.com/serverkit` to `github.com/jhd3197/ServerKit`-- Added Documentation link to README-- Added Support & Issues link to GitHub Issues-- Added Discussions link-- Added Report a Bug link-- Replaced all inline SVGs with Lucide icons (Github, FileText, HelpCircle, MessageSquare, Bug, Check, Layers)--### Version Update Check (Task 2)-**Backend** (`backend/app/api/system.py`):-- Added `/system/check-update` endpoint-- Fetches latest release from GitHub API (`api.github.com/repos/jhd3197/ServerKit/releases/latest`)-- Compares versions using semver-like comparison-- Returns: `current_version`, `latest_version`, `update_available`, `release_url`-- 1-hour cache to respect GitHub API rate limits (60 req/hour unauthenticated)--**Frontend**:-- Added `checkUpdate()` API method-- "Check for Updates" button in About section-- Shows update notification with release link when available-- Shows "You're up to date!" when current-- Loading spinner while checking--### Sidebar GitHub Link (Task 3)-- Added GitHub icon link between nav container and user profile-- Uses Lucide `Github` icon-- Links to `github.com/jhd3197/ServerKit`-- Hover effect matches sidebar aesthetic--### Star Prompt (Task 4)-- Dismissible "Star on GitHub" card in About section-- Shows for new users by default-- Remembers dismissal in localStorage (`serverkit-star-prompt-dismissed`)-- Accent-colored gradient design with gold star icon-- Links to repository-- Mobile responsive with stacked layout on small screens--## Files Changed-- `frontend/src/pages/Settings.jsx` - Added Lucide imports, updated AboutSection-- `frontend/src/components/Sidebar.jsx` - Added GitHub link-- `frontend/src/styles/pages/_settings.less` - Added update check and star prompt styles-- `frontend/src/styles/layout/_sidebar.less` - Added sidebar github link styles-- `frontend/src/services/api.js` - Added checkUpdate() method-- `backend/app/api/system.py` - Added check-update endpoint with caching--## Commits-- `78bfb6a` - feat(14): Update About section with correct GitHub links-- `4f5da49` - feat(14): Add version update check via GitHub releases API-- `2d32aad` - feat(14): Add GitHub link to sidebar-- `a20d4ab` - feat(14): Add Star on GitHub prompt for new users--## Verification-- [x] GitHub link in About section opens correct repository-- [x] Documentation link opens README-- [x] Support/Issues link opens GitHub Issues-- [x] Discussions link opens GitHub Discussions-- [x] Sidebar GitHub icon visible and functional-- [x] Update check shows current version status-- [x] Star prompt displays for new users-- [x] Star prompt can be dismissed (persisted in localStorage)-- [x] All icons are Lucide (no inline SVGs in changed code)-- [x] Build passes without errors--## Notes-- GitHub API rate limit: 60 requests/hour for unauthenticated requests-- Update check results cached for 1 hour on backend-- Star prompt uses localStorage key `serverkit-star-prompt-dismissed`-- All new icons use Lucide React components for consistencydiff --git a/.planning/phases/15-wordpress-dev-workflow-testing/15-1-PLAN.md b/.planning/phases/15-wordpress-dev-workflow-testing/15-1-PLAN.mddeleted file mode 100644index e6faf1db..00000000--- a/.planning/phases/15-wordpress-dev-workflow-testing/15-1-PLAN.md+++ /dev/null@@ -1,107 +0,0 @@-# Phase 15: WordPress Dev Workflow Testing--## Objective-Validate the complete multi-environment WordPress workflow end-to-end and create user documentation for the feature.--## Execution Context-- **Phase**: 15 of Milestone 2-- **Type**: Testing & Documentation (no code changes expected)-- **Dependencies**: Phases 11-14 completed-- **Estimated Scope**: Small (documentation only - no code)--## Context--### What Was Built (Phases 11-14)-1. **Phase 11**: WordPress External DB template (`wordpress-external-db.yaml`) allowing WordPress to connect to external MySQL-2. **Phase 12**: App linking API (`POST/GET/DELETE /apps/{id}/link`) with database credential propagation-3. **Phase 13**: UI for environment badges, linked apps section, link modal, and environment settings-4. **Phase 14**: GitHub links and community resources--### Key Components to Test-- Template: `backend/templates/wordpress-external-db.yaml`-- API: `POST /apps/{id}/link`, `GET /apps/{id}/linked`, `DELETE /apps/{id}/link`-- Frontend: LinkAppModal, LinkedAppsSection, environment badges-- DB propagation: `propagate_db_credentials()` in template_service.py--## Tasks--### Task 1: Create Test Plan Document-**Goal**: Document the complete test workflow with expected outcomes--Create `.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md` with:-- Prerequisites (MySQL server, ServerKit running)-- Step-by-step test procedure-- Expected outcomes for each step-- Rollback procedures--### Task 2: Create Multi-Environment User Guide-**Goal**: Create user documentation for the multi-environment feature--Create `docs/MULTI_ENVIRONMENT.md` with:-- Feature overview (what prod/dev linking is)-- Use case: WordPress theme development workflow-- Step-by-step setup guide:- 1. Create production WordPress (standard template)- 2. Create development WordPress (external-db template)- 3. Link apps via UI- 4. Verify database sharing-- Limitations and gotchas-- FAQ section--### Task 3: Update Main Documentation-**Goal**: Reference the new feature in existing docs--Update `docs/README.md`:-- Add section about multi-environment support-- Link to MULTI_ENVIRONMENT.md guide--### Task 4: Create SUMMARY.md-**Goal**: Document phase completion--Create `.planning/phases/15-wordpress-dev-workflow-testing/SUMMARY.md`:-- What was tested/documented-- Documentation files created-- Any issues discovered-- Milestone 2 completion status--### Task 5: Complete Milestone 2-**Goal**: Finalize milestone and prepare for release--- Update STATE.md marking Phase 15 and Milestone 2 complete-- Update ROADMAP.md with completion status-- Git commit all changes--## Verification--After completing all tasks:-- [ ] TEST-PLAN.md exists with complete workflow-- [ ] docs/MULTI_ENVIRONMENT.md exists with setup guide-- [ ] docs/README.md references multi-environment feature-- [ ] SUMMARY.md documents phase completion-- [ ] STATE.md shows Milestone 2 complete-- [ ] ROADMAP.md shows all phases complete--## Success Criteria--- [ ] Test plan documents complete workflow-- [ ] User guide is clear and actionable-- [ ] Documentation is discoverable from main README-- [ ] Milestone 2 marked complete in project state--## Output--| File | Type |-|------|------|-| `.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md` | New |-| `docs/MULTI_ENVIRONMENT.md` | New |-| `docs/README.md` | Modified |-| `.planning/phases/15-wordpress-dev-workflow-testing/SUMMARY.md` | New |-| `.planning/STATE.md` | Modified |-| `.planning/ROADMAP.md` | Modified |--## Notes--- This phase does NOT require actual deployment/testing of WordPress instances-- Focus is on creating documentation so users can follow the workflow-- Theme sync feature was deferred from Phase 13 - document this as a limitation-- No code changes expected - documentation onlydiff --git a/.planning/phases/15-wordpress-dev-workflow-testing/SUMMARY.md b/.planning/phases/15-wordpress-dev-workflow-testing/SUMMARY.mddeleted file mode 100644index a1b2a78c..00000000--- a/.planning/phases/15-wordpress-dev-workflow-testing/SUMMARY.md+++ /dev/null@@ -1,101 +0,0 @@-# Phase 15: WordPress Dev Workflow Testing - Summary--## Overview-Created comprehensive documentation and test plan for the multi-environment WordPress workflow implemented in Milestone 2 (Phases 11-14).--## Completed: 2026-01-19--## What Was Done--### 1. Test Plan Document-**File**: `.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md`--Created a detailed test plan covering:-- 8-step test workflow for full prod/dev setup-- Prerequisites and server requirements-- Step-by-step procedures with expected outcomes-- Verification checkpoints for each step-- Rollback procedures for common issues-- Known limitations documentation-- Success criteria summary table--### 2. Multi-Environment User Guide-**File**: `docs/MULTI_ENVIRONMENT.md`--Created comprehensive user documentation including:-- Feature overview and use cases-- Quick start guide (4 steps to get running)-- Environment type explanations (production/development/staging)-- Managing linked apps (navigation, unlinking)-- Database sharing details and table prefixes-- Best practices and naming conventions-- Limitations and future plans-- Troubleshooting section-- API reference links--### 3. Main Documentation Updates-**File**: `docs/README.md`--Added multi-environment feature to main docs:-- Added guide to Quick Links table-- Created "Multi-Environment Support" section in Feature Guides-- Listed key capabilities (shared database, badges, navigation)-- Linked to detailed MULTI_ENVIRONMENT.md guide--## Commits--| Hash | Message |-|------|---------|-| `3c24099` | docs(15-1): Create test plan for multi-environment workflow |-| `f2c5240` | docs(15-1): Create multi-environment user guide |-| `7a5f2a8` | docs(15-1): Add multi-environment section to main docs |--## Files Changed--| File | Type | Lines |-|------|------|-------|-| `.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md` | New | +257 |-| `docs/MULTI_ENVIRONMENT.md` | New | +209 |-| `docs/README.md` | Modified | +18 |--## Issues Discovered--No blocking issues. The following limitations were documented:--1. **Theme Sync Not Implemented** - Originally planned for Phase 13, deferred to future release-2. **Manual Content Separation** - By design, environments have separate content via table prefixes-3. **Same-Type Linking Only** - Apps must be same type to link (WordPress to WordPress)--## Milestone 2 Completion--With Phase 15 complete, all Milestone 2 goals have been achieved:--| Goal | Status |-|------|--------|-| WordPress template with external DB support | Completed (Phase 11) |-| Prod/dev environment linking with shared database | Completed (Phase 12) |-| Environment switching UI | Completed (Phase 13) |-| GitHub and community resource links | Completed (Phase 14) |-| End-to-end testing and documentation | Completed (Phase 15) |--## Phase Statistics--- **Type**: Documentation only-- **Tasks**: 5-- **Commits**: 3 (tasks 1-3) + 1 (metadata)-- **Code Changes**: 0 lines-- **Documentation Added**: ~484 lines--## Next Steps--Milestone 2 is complete. Options:-1. Create new milestone for additional features (theme sync, plugin sync)-2. Begin production testing with actual WordPress deployments-3. Prepare v1.1 release--## Notes--- This phase was documentation-focused, no code changes were made-- Theme sync feature remains as future enhancement-- Test plan serves as validation guide for QA testing-- User guide provides clear onboarding path for the featurediff --git a/.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md b/.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.mddeleted file mode 100644index 9c8056f4..00000000--- a/.planning/phases/15-wordpress-dev-workflow-testing/TEST-PLAN.md+++ /dev/null@@ -1,257 +0,0 @@-# Multi-Environment WordPress Workflow - Test Plan--## Overview-This test plan validates the complete multi-environment WordPress workflow implemented in Milestone 2 (Phases 11-14).--## Prerequisites--### Server Requirements-- ServerKit running and accessible-- MySQL server available (can be the same server or external)-- At least 2 available ports for WordPress instances-- Sufficient disk space for 2 WordPress installations (~500MB each)--### User Requirements-- Admin access to ServerKit dashboard-- MySQL credentials (host, port, user, password, database)-- Basic familiarity with WordPress--## Test Workflow--### Step 1: Deploy Production WordPress--**Action**: Install WordPress using the standard template--1. Navigate to **Applications** > **New Application**-2. Select **WordPress** template (standard, not external-db)-3. Configure:- - Name: `wordpress-prod`- - Port: Auto-assigned or manual (e.g., 8080)-4. Click **Install**-5. Wait for installation to complete--**Expected Outcome**:-- Application shows "running" status-- WordPress accessible at configured port-- Database tables created with default `wp_` prefix-- Application shows as "Standalone" environment type--**Verification**:-- [ ] App appears in applications list-- [ ] Status badge shows "Running"-- [ ] WordPress admin accessible at `/wp-admin`-------### Step 2: Create Sample Content in Production--**Action**: Add content to production WordPress--1. Access WordPress admin at `http://localhost:{port}/wp-admin`-2. Log in with generated credentials (check app credentials)-3. Create:- - 2-3 sample posts- - 1-2 sample pages- - Upload a test image--**Expected Outcome**:-- Content visible in WordPress frontend-- Data stored in database with `wp_` table prefix--**Verification**:-- [ ] Posts visible on frontend-- [ ] Media library contains uploaded image-------### Step 3: Deploy Development WordPress (Shared DB)--**Action**: Install WordPress using the external-db template--1. Navigate to **Applications** > **New Application**-2. Select **WordPress (External Database)** template-3. Configure:- - Name: `wordpress-dev`- - Port: Different from prod (e.g., 8081)- - DB Host: Same as production's database host- - DB Port: Same as production (usually 3306)- - DB Name: Same as production database- - DB User: Same as production- - DB Password: Same as production- - Table Prefix: `wp_dev_` (different from production)-4. Click **Test Connection** to validate-5. Click **Install**--**Expected Outcome**:-- Connection test passes-- Application installs successfully-- WordPress accessible at configured port-- Database tables created with `wp_dev_` prefix--**Verification**:-- [ ] Connection test shows "Success"-- [ ] App appears in applications list-- [ ] WordPress admin accessible-- [ ] Database shows both `wp_*` and `wp_dev_*` tables-------### Step 4: Link Applications--**Action**: Link dev and prod WordPress as environment pair--1. Navigate to `wordpress-prod` application detail-2. In **Overview** tab, find **Environment Linking** section-3. Click **Link App** button-4. In modal:- - Select `wordpress-dev` from dropdown- - Choose **Development** as environment type- - Enable **Propagate database credentials** (should already match)-5. Click **Link Apps**--**Expected Outcome**:-- Modal closes-- Both apps show environment badges-- `wordpress-prod` shows "PROD" badge-- `wordpress-dev` shows "DEV" badge-- Linked Apps section shows the linked app--**Verification**:-- [ ] Environment badges visible in app list-- [ ] Linked Apps section shows partner app-- [ ] Navigate button works to switch between apps-- [ ] Shared Database info displayed (if credentials propagated)-------### Step 5: Verify Data Isolation--**Action**: Confirm dev and prod have separate data--1. Access `wordpress-dev` admin-2. Verify it has its own:- - Posts (separate from prod)- - Users (separate admin)- - Settings-3. Create a test post in dev: "Dev Test Post"-4. Verify prod does NOT show "Dev Test Post"--**Expected Outcome**:-- Dev WordPress is completely independent-- Changes in dev don't affect prod-- Both use same database but different table prefixes--**Verification**:-- [ ] Dev has independent content-- [ ] Prod content unchanged after dev modifications-- [ ] Database shows separate table sets (`wp_posts` vs `wp_dev_posts`)-------### Step 6: Test Environment Navigation--**Action**: Use UI to navigate between linked apps--1. From `wordpress-dev` detail page, find Linked Apps section-2. Click navigate button to go to `wordpress-prod`-3. Verify you're now on `wordpress-prod` detail page-4. Click navigate button to return to `wordpress-dev`--**Expected Outcome**:-- One-click navigation between linked apps-- Correct app loaded each time--**Verification**:-- [ ] Navigate from dev to prod works-- [ ] Navigate from prod to dev works-------### Step 7: Test Unlinking--**Action**: Unlink the applications--1. From either app's detail page-2. Go to **Settings** tab-3. Find **Linked Application** section-4. Click **Unlink Application**-5. Confirm the action--**Expected Outcome**:-- Both apps become "Standalone" again-- Environment badges removed-- Linked Apps section shows empty state-- Both apps continue to function independently--**Verification**:-- [ ] Both apps show "Standalone" environment-- [ ] No environment badges in list-- [ ] Both WordPress instances still accessible-------### Step 8: Environment Filter Test--**Action**: Test filtering by environment type--1. Navigate to Applications list-2. Use environment filter dropdown-3. Select "Production" - should show only prod apps-4. Select "Development" - should show only dev apps-5. Select "All" - should show all apps--**Expected Outcome**:-- Filter correctly shows/hides apps by environment-- URL updates with filter parameter--**Verification**:-- [ ] Production filter works-- [ ] Development filter works-- [ ] All filter shows everything-------## Rollback Procedures--### If WordPress Installation Fails-1. Delete the failed application from ServerKit-2. Check Docker logs for errors-3. Verify MySQL connection parameters-4. Retry installation--### If Linking Fails-1. Check both apps are of same type-2. Verify neither app is already linked-3. Check API logs for error details-4. Try unlinking and re-linking--### If Data Appears Corrupted-1. Check table prefixes are correctly different-2. Verify each WordPress is using its designated prefix-3. If needed, unlink apps and reinstall dev instance--## Success Criteria Summary--| Test | Status |-|------|--------|-| Production WordPress deployment | [ ] |-| Sample content creation | [ ] |-| Development WordPress (external DB) | [ ] |-| App linking via UI | [ ] |-| Data isolation verification | [ ] |-| Navigation between linked apps | [ ] |-| Unlinking functionality | [ ] |-| Environment filtering | [ ] |--## Known Limitations--1. **Theme Sync**: Copying themes between environments is not yet implemented (planned for future release)-2. **Same App Type Required**: Can only link apps of the same type (WordPress to WordPress)-3. **Database Must Be Accessible**: External DB must be reachable from ServerKit server-4. **Manual Table Prefix**: User must ensure unique table prefix for dev environment--## Notes--- Test was designed for ServerKit v1.1 with Milestone 2 features-- External database template requires MySQL credentials upfront-- Credential propagation only works for Docker-based appsdiff --git a/.planning/phases/16-workflow-canvas-foundation/16-1-PLAN.md b/.planning/phases/16-workflow-canvas-foundation/16-1-PLAN.mddeleted file mode 100644index 6103a565..00000000--- a/.planning/phases/16-workflow-canvas-foundation/16-1-PLAN.md+++ /dev/null@@ -1,139 +0,0 @@-# Phase 16: Workflow Canvas Foundation--## Objective-Set up React Flow canvas with pan/zoom, basic node rendering, and connection system to establish the foundation for the visual workflow builder.--## Execution Context-- **Phase**: 16 of Milestone 3-- **Type**: New Feature (frontend only)-- **Dependencies**: None (greenfield feature)-- **Estimated Scope**: Medium (new page, new library, multiple components)--## Context--### Project Patterns Observed-- Pages are in `frontend/src/pages/*.jsx`-- Components in `frontend/src/components/*.jsx`-- Styles in `frontend/src/styles/` using LESS-- Routes defined in `frontend/src/App.jsx`-- Sidebar navigation in `frontend/src/components/Sidebar.jsx`-- Uses React 18, Vite, Lucide React icons--### Library Choice: React Flow-React Flow (@xyflow/react) is the recommended library for node-based editors:-- Excellent documentation and TypeScript support-- Built-in pan/zoom, minimap, controls-- Custom node and edge support-- Widely used (n8n, Stripe, etc.)--## Tasks--### Task 1: Install React Flow-**Goal**: Add React Flow library to the project--1. Install `@xyflow/react` package-2. Add to package.json dependencies-3. Verify installation with build--**Files**: `frontend/package.json`--### Task 2: Create WorkflowBuilder Page-**Goal**: Create the main page component with React Flow canvas--1. Create `frontend/src/pages/WorkflowBuilder.jsx`-2. Set up ReactFlow provider and canvas-3. Initialize with empty nodes/edges state-4. Add basic container styling--**Files**: `frontend/src/pages/WorkflowBuilder.jsx`--### Task 3: Add Route and Navigation-**Goal**: Wire up the new page in the app--1. Add route in `frontend/src/App.jsx` for `/workflow`-2. Add sidebar link in `frontend/src/components/Sidebar.jsx`-3. Use a workflow/flow icon (GitBranch or similar from Lucide)-4. Place under "Infrastructure" section--**Files**: `frontend/src/App.jsx`, `frontend/src/components/Sidebar.jsx`--### Task 4: Implement Canvas Controls-**Goal**: Add pan/zoom controls and minimap--1. Add React Flow Background component (dots or grid pattern)-2. Add Controls component (zoom in/out/fit buttons)-3. Add MiniMap component for overview-4. Configure pan/zoom behavior--**Files**: `frontend/src/pages/WorkflowBuilder.jsx`--### Task 5: Create Basic Node Component-**Goal**: Create a placeholder custom node for testing--1. Create `frontend/src/components/workflow/BaseNode.jsx`-2. Style with card-like appearance matching app theme-3. Add connection handles (source/target)-4. Test adding nodes to canvas--**Files**: `frontend/src/components/workflow/BaseNode.jsx`, `frontend/src/pages/WorkflowBuilder.jsx`--### Task 6: Create Workflow Styles-**Goal**: Add LESS styles for the workflow builder--1. Create `frontend/src/styles/pages/_workflow.less`-2. Style the canvas container (full height, dark background)-3. Style the controls and minimap-4. Import in `frontend/src/styles/main.less`--**Files**: `frontend/src/styles/pages/_workflow.less`, `frontend/src/styles/main.less`--### Task 7: Add Node Toolbar-**Goal**: Create toolbar for adding nodes to canvas--1. Create floating toolbar/palette component-2. Add buttons for adding different node types (placeholder)-3. Implement add node on click (places in center of viewport)-4. Style to match app design--**Files**: `frontend/src/pages/WorkflowBuilder.jsx`--## Verification--After completing all tasks:-- [ ] `npm run build` passes without errors-- [ ] `/workflow` route accessible-- [ ] Sidebar shows "Workflow Builder" link-- [ ] Canvas renders with background grid-- [ ] Can pan and zoom the canvas-- [ ] Controls (zoom buttons) visible and working-- [ ] MiniMap shows canvas overview-- [ ] Can add placeholder nodes via toolbar-- [ ] Nodes are draggable-- [ ] Can draw connections between nodes--## Success Criteria--- [ ] Canvas renders with pan/zoom-- [ ] Can add placeholder nodes-- [ ] Can draw connections between nodes-- [ ] Minimap shows overview--## Output--| File | Type |-|------|------|-| `frontend/package.json` | Modified |-| `frontend/src/pages/WorkflowBuilder.jsx` | New |-| `frontend/src/components/workflow/BaseNode.jsx` | New |-| `frontend/src/styles/pages/_workflow.less` | New |-| `frontend/src/styles/main.less` | Modified |-| `frontend/src/App.jsx` | Modified |-| `frontend/src/components/Sidebar.jsx` | Modified |--## Notes--- React Flow uses `@xyflow/react` package name (renamed from `react-flow-renderer`)-- Nodes require unique `id` field-- Custom nodes must be registered in `nodeTypes` prop-- Connection handles need `Position` enum from React Flow-- Use `useNodesState` and `useEdgesState` hooks for state managementdiff --git a/.planning/phases/16-workflow-canvas-foundation/SUMMARY.md b/.planning/phases/16-workflow-canvas-foundation/SUMMARY.mddeleted file mode 100644index 324d8fa2..00000000--- a/.planning/phases/16-workflow-canvas-foundation/SUMMARY.md+++ /dev/null@@ -1,114 +0,0 @@-# Phase 16: Workflow Canvas Foundation - Summary--## Overview-Established the foundation for the visual workflow builder by integrating React Flow and creating the core canvas, node, and toolbar components.--## Completed: 2026-01-19--## What Was Built--### 1. React Flow Integration-**Package**: `@xyflow/react`--Installed the React Flow library (formerly react-flow-renderer) which provides:-- Pan/zoom canvas functionality-- Node rendering and dragging-- Edge/connection drawing-- Built-in controls and minimap--### 2. WorkflowBuilder Page-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Main page component with:-- ReactFlowProvider wrapper for context-- Canvas with pan/zoom/scroll behavior-- Background with dots pattern-- Controls component (zoom in/out/fit)-- MiniMap for canvas overview-- Node toolbar for adding nodes-- State management with useNodesState/useEdgesState--### 3. BaseNode Component-**File**: `frontend/src/components/workflow/BaseNode.jsx`--Custom node component featuring:-- Color-coded header by node type (docker=blue, database=yellow, domain=green)-- Icon display using Lucide React-- Label and status display-- Source and target connection handles-- Selection state styling--### 4. Routing and Navigation-**Files**: `frontend/src/App.jsx`, `frontend/src/components/Sidebar.jsx`--- Added `/workflow` route-- Added "Workflow Builder" link in sidebar under Infrastructure section-- Custom flow/network icon (connected circles)--### 5. Workflow Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Comprehensive styling for:-- Full-height page layout-- Canvas container with dark theme-- Node appearance (card-like with header/body)-- Connection handles with hover effects-- Toolbar with type-specific button colors-- React Flow controls and minimap theming-- Animated edge styles--## Commits--| Hash | Message |-|------|---------|-| `ac8a57f` | feat(16-1): Install React Flow library |-| `f762040` | feat(16-1): Create WorkflowBuilder page with React Flow canvas |-| `b74374e` | feat(16-1): Add workflow route and sidebar navigation |-| `68169b0` | feat(16-1): Add canvas controls, background, and minimap |-| `d75b0f7` | feat(16-1): Create BaseNode component with handles |-| `a766976` | feat(16-1): Add workflow builder styles |-| `ed038df` | feat(16-1): Add node toolbar for adding nodes to canvas |--## Files Changed--| File | Type | Lines |-|------|------|-------|-| `frontend/package.json` | Modified | +1 dep |-| `frontend/src/pages/WorkflowBuilder.jsx` | New | ~140 |-| `frontend/src/components/workflow/BaseNode.jsx` | New | ~58 |-| `frontend/src/styles/pages/_workflow.less` | New | ~302 |-| `frontend/src/styles/main.less` | Modified | +1 import |-| `frontend/src/App.jsx` | Modified | +2 lines |-| `frontend/src/components/Sidebar.jsx` | Modified | +10 lines |--## Success Criteria--- [x] Canvas renders with pan/zoom-- [x] Can add placeholder nodes (via toolbar)-- [x] Can draw connections between nodes-- [x] Minimap shows overview--## Verification--- [x] `npm run build` passes without errors-- [x] `/workflow` route accessible-- [x] Sidebar shows "Workflow Builder" link-- [x] Canvas renders with background grid (dots)-- [x] Can pan and zoom the canvas-- [x] Controls (zoom buttons) visible and working-- [x] MiniMap shows canvas overview-- [x] Can add placeholder nodes via toolbar-- [x] Nodes are draggable-- [x] Can draw connections between nodes (smoothstep animated edges)--## Technical Notes--- React Flow requires wrapping canvas in `ReactFlowProvider`-- Custom nodes must be memoized and registered in `nodeTypes` prop-- `useReactFlow` hook provides `screenToFlowPosition` for coordinate conversion-- Node IDs must be unique strings-- Edge default options configured for animated smoothstep style--## Next Phase--Phase 17 will create specific resource node types (DockerAppNode, DatabaseNode, DomainNode) with more detailed displays and a node palette.diff --git a/.planning/phases/17-resource-node-types/PLAN.md b/.planning/phases/17-resource-node-types/PLAN.mddeleted file mode 100644index 5145ad41..00000000--- a/.planning/phases/17-resource-node-types/PLAN.md+++ /dev/null@@ -1,160 +0,0 @@-# Phase 17: Resource Node Types - Execution Plan--## Goal-Create visual node types for Docker apps, databases, and domains with detailed displays showing resource-specific information.--## Prerequisites-- Phase 16 completed (React Flow canvas foundation)-- BaseNode component exists with basic structure-- Workflow styles in place--## Tasks--### Task 1: Create DockerAppNode Component-**File**: `frontend/src/components/workflow/nodes/DockerAppNode.jsx`--Create a specialized node for Docker applications displaying:-- App name and image tag-- Status indicator (running/stopped/error) with animated dot-- Port mappings display-- Memory/CPU stats preview-- Multiple handles: input (left), output (right), database (bottom)--Node data structure:-```js-{- name: 'my-app',- image: 'nginx:latest',- status: 'running',- ports: ['80:80', '443:443'],- memory: '256MB'-}-```--### Task 2: Create DatabaseNode Component-**File**: `frontend/src/components/workflow/nodes/DatabaseNode.jsx`--Create a specialized node for databases displaying:-- Database name-- Type badge (MySQL, PostgreSQL, MongoDB, Redis)-- Status indicator-- Connection info preview (host:port)-- Size/storage info-- Handles: input only (left) - databases receive connections--Node data structure:-```js-{- name: 'main-db',- type: 'mysql',- status: 'running',- host: 'localhost',- port: 3306,- size: '1.2GB'-}-```--### Task 3: Create DomainNode Component-**File**: `frontend/src/components/workflow/nodes/DomainNode.jsx`--Create a specialized node for domains displaying:-- Domain name (prominently)-- SSL status badge (valid/expired/none)-- DNS status indicator-- Linked app preview (if connected)-- Handles: output only (right) - domains connect TO apps--Node data structure:-```js-{- name: 'example.com',- ssl: 'valid',- sslExpiry: '2026-12-31',- dnsStatus: 'propagated'-}-```--### Task 4: Create ServiceNode Component-**File**: `frontend/src/components/workflow/nodes/ServiceNode.jsx`--Create a generic service node for future extensibility:-- Service name-- Type/icon configurable-- Generic status display-- Flexible handles (configurable)-- Useful for Redis, cache layers, queues, etc.--Node data structure:-```js-{- name: 'redis-cache',- type: 'service',- serviceType: 'redis',- status: 'running'-}-```--### Task 5: Register Node Types and Update Canvas-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--- Import all new node components-- Register them in nodeTypes object-- Update addNode function to create proper node types-- Each node type uses its own component--### Task 6: Enhance Node Toolbar/Palette-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Upgrade toolbar to a collapsible palette:-- Category headers (Compute, Storage, Network)-- Docker App under Compute-- Database nodes under Storage (with sub-options for MySQL, PostgreSQL, etc.)-- Domain under Network-- Service under Compute-- Drag-to-canvas support (optional enhancement)--### Task 7: Add Node-Specific Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Add styles for each node type:-- Type-specific color schemes (already defined, enhance)-- Status indicator animations (pulsing dot)-- Database type badges-- SSL status badges-- Port mapping pills-- Handle positioning for multi-handle nodes--## Success Criteria-- [ ] Each resource type has distinct visual node-- [ ] Nodes display key info (name, status, type-specific details)-- [ ] Node palette allows adding specific node types-- [ ] Nodes are draggable on canvas-- [ ] Build passes without errors--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `frontend/src/components/workflow/nodes/DockerAppNode.jsx` | Create | Docker app node |-| `frontend/src/components/workflow/nodes/DatabaseNode.jsx` | Create | Database node |-| `frontend/src/components/workflow/nodes/DomainNode.jsx` | Create | Domain node |-| `frontend/src/components/workflow/nodes/ServiceNode.jsx` | Create | Generic service node |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modify | Register nodes, update toolbar |-| `frontend/src/styles/pages/_workflow.less` | Modify | Add node-specific styles |--## Technical Notes--- All node components must be memoized with `React.memo()`-- Node components receive `{ data, selected }` props from React Flow-- Use Handle from @xyflow/react for connection points-- Handles can have IDs for specific connection types-- Lucide React for all icons (consistency with app)--## Estimated Commits-- feat(17-1): Create DockerAppNode component-- feat(17-2): Create DatabaseNode component-- feat(17-3): Create DomainNode component-- feat(17-4): Create ServiceNode component-- feat(17-5): Register node types in WorkflowBuilder-- feat(17-6): Enhance node palette with categories-- feat(17-7): Add node-specific stylesdiff --git a/.planning/phases/17-resource-node-types/SUMMARY.md b/.planning/phases/17-resource-node-types/SUMMARY.mddeleted file mode 100644index e51d302f..00000000--- a/.planning/phases/17-resource-node-types/SUMMARY.md+++ /dev/null@@ -1,116 +0,0 @@-# Phase 17: Resource Node Types - Summary--## Overview-Created specialized visual node types for Docker apps, databases, domains, and services with detailed displays and a categorized node palette.--## Completed: 2026-01-19--## What Was Built--### 1. DockerAppNode Component-**File**: `frontend/src/components/workflow/nodes/DockerAppNode.jsx`--Specialized node for Docker applications displaying:-- App name and image tag-- Status indicator with animated dot (running/stopped/error)-- Port mappings as pills-- Memory usage preview-- Multiple handles: input (left), output (right), database (bottom)--### 2. DatabaseNode Component-**File**: `frontend/src/components/workflow/nodes/DatabaseNode.jsx`--Specialized node for databases displaying:-- Database name-- Type badge with colors (MySQL=#00758f, PostgreSQL=#336791, MongoDB=#4db33d, Redis=#dc382d)-- Status indicator-- Connection info (host:port)-- Size/storage info-- Input handle only (databases receive connections)--### 3. DomainNode Component-**File**: `frontend/src/components/workflow/nodes/DomainNode.jsx`--Specialized node for domains displaying:-- Domain name (monospace, prominent)-- SSL status badge with icons (ShieldCheck/ShieldX/Shield)-- DNS status indicator (propagated/pending)-- SSL expiry date-- Output handle only (domains connect TO apps)--### 4. ServiceNode Component-**File**: `frontend/src/components/workflow/nodes/ServiceNode.jsx`--Generic service node for extensibility:-- Service name and description-- Type configs: Redis, Memcached, RabbitMQ, Queue-- Configurable icon and color per type-- Input and output handles--### 5. Node Palette with Categories-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Replaced simple toolbar with categorized palette:-- **Compute**: Docker App, Service-- **Storage**: MySQL, PostgreSQL, MongoDB, Redis-- **Network**: Domain--Features:-- All four node types registered in nodeTypes-- Dynamic MiniMap coloring by node type-- Default data passed when creating nodes--### 6. Comprehensive Node Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Added ~320 lines of styles:-- Palette section styling with dividers-- Type-specific node colors-- Node detail styles (image, ports, memory, connection)-- Port pills with accent color-- Database type badges-- SSL/DNS status badges-- Animated status dot (pulsing for running/error states)-- Database bottom handle positioning--## Commits--| Hash | Message |-|------|---------|-| `b9dcbe1` | feat(17-1): Create DockerAppNode component |-| `7b21c44` | feat(17-2): Create DatabaseNode component |-| `2fef686` | feat(17-3): Create DomainNode component |-| `7909ca6` | feat(17-4): Create ServiceNode component |-| `57e8a30` | feat(17-5): Register node types and add categorized palette |-| `2750dc7` | feat(17-7): Add node-specific styles |--## Files Changed--| File | Type | Lines |-|------|------|-------|-| `frontend/src/components/workflow/nodes/DockerAppNode.jsx` | New | ~68 |-| `frontend/src/components/workflow/nodes/DatabaseNode.jsx` | New | ~70 |-| `frontend/src/components/workflow/nodes/DomainNode.jsx` | New | ~64 |-| `frontend/src/components/workflow/nodes/ServiceNode.jsx` | New | ~67 |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modified | +87/-34 |-| `frontend/src/styles/pages/_workflow.less` | Modified | +324 |--## Success Criteria--- [x] Each resource type has distinct visual node-- [x] Nodes display key info (name, status, type-specific details)-- [x] Node palette allows adding specific node types-- [x] Nodes are draggable on canvas-- [x] Build passes without errors--## Technical Notes--- All node components memoized with `React.memo()`-- Handles use IDs for type-specific connections (input, output, database)-- Node types registered in WorkflowBuilder: dockerApp, database, domain, service-- MiniMap uses dynamic `nodeColor` callback for type-based coloring-- Lucide React icons used throughout for consistency--## Next Phase--Phase 18 will create side panels for configuring each node type when selected.diff --git a/.planning/phases/18-node-configuration-panels/PLAN.md b/.planning/phases/18-node-configuration-panels/PLAN.mddeleted file mode 100644index 0f279235..00000000--- a/.planning/phases/18-node-configuration-panels/PLAN.md+++ /dev/null@@ -1,156 +0,0 @@-# Phase 18: Node Configuration Panels - Execution Plan--## Goal-Create sliding side panels for configuring each node type when selected on the workflow canvas. Changes in the panel should update the node display in real-time.--## Prerequisites-- Phase 17 completed (DockerAppNode, DatabaseNode, DomainNode, ServiceNode)-- WorkflowBuilder page with node types registered-- Existing form patterns (_forms.less, _modals.less)--## Tasks--### Task 1: Create ConfigPanel Base Component-**File**: `frontend/src/components/workflow/ConfigPanel.jsx`--Create a reusable sliding panel component:-- Slides in from right side of canvas-- Header with node type icon, title, and close button-- Scrollable body for form content-- Footer with action buttons (optional)-- Handles escape key to close-- Transition animation (slide + fade)--Props:-```js-{- isOpen: boolean,- title: string,- icon: ReactNode,- headerColor: string,- onClose: function,- children: ReactNode,- footer: ReactNode (optional)-}-```--### Task 2: Create DockerAppConfigPanel-**File**: `frontend/src/components/workflow/panels/DockerAppConfigPanel.jsx`--Configuration panel for Docker app nodes:-- Name input-- Image input with placeholder (e.g., nginx:latest)-- Status selector (running/stopped)-- Ports input (add/remove port mappings)-- Memory limit input-- Environment variables (key-value pairs)-- Calls onChange with updated data--Fields match node data structure:-```js-{ name, image, status, ports: [], memory }-```--### Task 3: Create DatabaseConfigPanel-**File**: `frontend/src/components/workflow/panels/DatabaseConfigPanel.jsx`--Configuration panel for database nodes:-- Name input-- Type selector (mysql, postgresql, mongodb, redis)-- Host input (default: localhost)-- Port input (default varies by type)-- Size display (read-only preview)-- Status selector--Fields match node data structure:-```js-{ name, type, status, host, port, size }-```--### Task 4: Create DomainConfigPanel-**File**: `frontend/src/components/workflow/panels/DomainConfigPanel.jsx`--Configuration panel for domain nodes:-- Domain name input (with validation hint)-- SSL status selector (none, valid, expired)-- SSL expiry date picker (when ssl=valid)-- DNS status selector (pending, propagated)--Fields match node data structure:-```js-{ name, ssl, sslExpiry, dnsStatus }-```--### Task 5: Create ServiceConfigPanel-**File**: `frontend/src/components/workflow/panels/ServiceConfigPanel.jsx`--Configuration panel for service nodes:-- Name input-- Service type selector (redis, memcached, rabbitmq, queue)-- Port input-- Description textarea-- Status selector--Fields match node data structure:-```js-{ name, serviceType, port, description, status }-```--### Task 6: Wire Panel to Node Selection-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Integrate panels with canvas:-- Track selectedNode state-- Listen to onNodeClick event from ReactFlow-- Open appropriate panel based on node type-- Pass node data to panel-- Handle panel onChange to update node data via setNodes-- Handle panel close (deselect node or just close panel)--### Task 7: Add Panel Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Add styles for configuration panels:-- Fixed position on right side of canvas-- Slide-in animation from right-- Panel header with type-specific border color-- Form group styling within panels-- Port/env-var list styling-- Panel shadow and backdrop--## Success Criteria-- [ ] Clicking node opens config panel-- [ ] Panel contains appropriate form for node type-- [ ] Form changes reflect in node display immediately-- [ ] Panel can be closed/dismissed-- [ ] Build passes without errors--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `frontend/src/components/workflow/ConfigPanel.jsx` | Create | Base panel component |-| `frontend/src/components/workflow/panels/DockerAppConfigPanel.jsx` | Create | Docker config form |-| `frontend/src/components/workflow/panels/DatabaseConfigPanel.jsx` | Create | Database config form |-| `frontend/src/components/workflow/panels/DomainConfigPanel.jsx` | Create | Domain config form |-| `frontend/src/components/workflow/panels/ServiceConfigPanel.jsx` | Create | Service config form |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modify | Wire selection to panels |-| `frontend/src/styles/pages/_workflow.less` | Modify | Panel styles |--## Technical Notes--- Use existing form patterns from _forms.less (form-group, input styles)-- Panel should not block canvas interaction when closed-- Node selection in React Flow: use `onNodeClick` callback-- Update node data: use `setNodes` with functional update-- Panel animates with CSS transitions, not JS-- Consider keyboard navigation (Escape to close)--## Estimated Commits-- feat(18-1): Create ConfigPanel base component-- feat(18-2): Create DockerAppConfigPanel-- feat(18-3): Create DatabaseConfigPanel-- feat(18-4): Create DomainConfigPanel-- feat(18-5): Create ServiceConfigPanel-- feat(18-6): Wire panel to node selection in WorkflowBuilder-- feat(18-7): Add configuration panel stylesdiff --git a/.planning/phases/18-node-configuration-panels/SUMMARY.md b/.planning/phases/18-node-configuration-panels/SUMMARY.mddeleted file mode 100644index cb2b494e..00000000--- a/.planning/phases/18-node-configuration-panels/SUMMARY.md+++ /dev/null@@ -1,129 +0,0 @@-# Phase 18: Node Configuration Panels - Summary--## Overview-Created sliding side panels for configuring each node type when selected on the workflow canvas. Changes in panels update node display in real-time.--## Completed: 2026-01-19--## What Was Built--### 1. ConfigPanel Base Component-**File**: `frontend/src/components/workflow/ConfigPanel.jsx`--Reusable sliding panel component with:-- Slide-in from right animation (CSS transitions)-- Header with icon, title, close button-- Scrollable body for form content-- Optional footer slot-- Escape key handler to close-- Props: isOpen, title, icon, headerColor, onClose, children, footer--### 2. DockerAppConfigPanel-**File**: `frontend/src/components/workflow/panels/DockerAppConfigPanel.jsx`--Configuration form for Docker apps:-- Name input-- Image input with placeholder-- Status selector (running/stopped/error)-- Dynamic port mappings list (add/remove)-- Memory limit input--### 3. DatabaseConfigPanel-**File**: `frontend/src/components/workflow/panels/DatabaseConfigPanel.jsx`--Configuration form for databases:-- Name input-- Type selector (MySQL, PostgreSQL, MongoDB, Redis)-- Auto-update port when type changes-- Host and port inputs (row layout)-- Status selector-- Read-only size display--### 4. DomainConfigPanel-**File**: `frontend/src/components/workflow/panels/DomainConfigPanel.jsx`--Configuration form for domains:-- Domain name input with hint-- SSL status selector (none/valid/expired)-- Conditional SSL expiry date picker-- DNS status selector (pending/propagated)--### 5. ServiceConfigPanel-**File**: `frontend/src/components/workflow/panels/ServiceConfigPanel.jsx`--Configuration form for services:-- Name input-- Service type selector (Redis, Memcached, RabbitMQ, Queue)-- Auto-update port when type changes-- Port input-- Description textarea-- Status selector--### 6. WorkflowBuilder Integration-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Wired panels to canvas:-- Track selectedNode state-- onNodeClick handler opens appropriate panel-- onPaneClick handler closes panel-- handleNodeDataChange updates node data in real-time-- renderConfigPanel switches panel by node type--### 7. Panel Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Added ~200 lines of styles:-- Fixed panel on right side (320px width)-- Slide-in animation with transform/opacity-- Panel header with type-specific border color-- Form styling within panels-- Port list with add/remove buttons-- btn-icon and btn-danger-ghost utilities--## Commits--| Hash | Message |-|------|---------|-| `da6ae4d` | feat(18-1): Create ConfigPanel base component |-| `4eebd34` | feat(18-2): Create DockerAppConfigPanel |-| `1a61942` | feat(18-3): Create DatabaseConfigPanel |-| `b803a3e` | feat(18-4): Create DomainConfigPanel |-| `37ee145` | feat(18-5): Create ServiceConfigPanel |-| `8b39d87` | feat(18-6): Wire panel to node selection in WorkflowBuilder |-| `69b2339` | feat(18-7): Add configuration panel styles |--## Files Changed--| File | Type | Lines |-|------|------|-------|-| `frontend/src/components/workflow/ConfigPanel.jsx` | New | ~53 |-| `frontend/src/components/workflow/panels/DockerAppConfigPanel.jsx` | New | ~120 |-| `frontend/src/components/workflow/panels/DatabaseConfigPanel.jsx` | New | ~108 |-| `frontend/src/components/workflow/panels/DomainConfigPanel.jsx` | New | ~77 |-| `frontend/src/components/workflow/panels/ServiceConfigPanel.jsx` | New | ~93 |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modified | +59 |-| `frontend/src/styles/pages/_workflow.less` | Modified | +204 |--## Success Criteria--- [x] Clicking node opens config panel-- [x] Panel contains appropriate form for node type-- [x] Form changes reflect in node display immediately-- [x] Panel can be closed/dismissed-- [x] Build passes without errors--## Technical Notes--- ConfigPanel uses CSS class `.open` for animation state-- All panels receive `{ node, onChange, onClose }` props-- onChange calls setNodes with functional update to modify node data-- Panel appears inside workflow-canvas div (positioned absolute)-- Escape key closes panel via useEffect keyboard listener--## Bug Fix--- Fixed `@shadow-2xl` → `@shadow-lg` (undefined variable)--## Next Phase--Phase 19 will implement connection logic to validate and manage connections between nodes.diff --git a/.planning/phases/19-connection-logic/PLAN.md b/.planning/phases/19-connection-logic/PLAN.mddeleted file mode 100644index c91ac9e3..00000000--- a/.planning/phases/19-connection-logic/PLAN.md+++ /dev/null@@ -1,115 +0,0 @@-# Phase 19: Connection Logic - Execution Plan--## Goal-Define and validate connections between nodes, with visual feedback for valid/invalid connections and the ability to view, edit, and delete connections.--## Prerequisites-- Phase 18 completed (Node Configuration Panels)-- Node components have defined handles:- - DockerAppNode: input (left), output (right), database (bottom)- - DatabaseNode: input (left) only- - DomainNode: output (right) only- - ServiceNode: input (left), output (right)--## Connection Rules--Valid connection types:-| Source Node | Source Handle | Target Node | Target Handle | Meaning |-|-------------|---------------|-------------|---------------|---------|-| domain | output | dockerApp | input | Domain routes to app |-| dockerApp | database | database | input | App connects to database |-| dockerApp | output | dockerApp | input | App-to-app connection |-| service | output | dockerApp | input | Service connects to app |-| service | output | database | input | Service connects to database |--Invalid connections:-- Database to anything (no source handles)-- Anything to domain (no target handles)-- Self-connections--## Tasks--### Task 1: Create Connection Validation Utility-**File**: `frontend/src/utils/connectionRules.js`--Create validation logic for connections:-- `isValidConnection(connection, nodes)` - returns boolean-- `getConnectionError(connection, nodes)` - returns error message or null-- Define connection rules matrix-- Check source/target node types and handle IDs--### Task 2: Implement isValidConnection Callback-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Wire validation to ReactFlow:-- Import connection validation utility-- Pass `isValidConnection` prop to ReactFlow-- This prevents invalid connections from being created--### Task 3: Add Visual Feedback for Connection Attempts-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Show feedback during drag:-- Use `onConnectStart` and `onConnectEnd` callbacks-- Track connecting state-- Show visual indicator when hovering over invalid targets-- Add toast/tooltip for why connection is invalid--### Task 4: Create Custom Edge Component-**File**: `frontend/src/components/workflow/ConnectionEdge.jsx`--Custom edge with metadata display:-- Extend smoothstep edge-- Show connection type label on hover-- Delete button on selection-- Different colors by connection type--### Task 5: Add Edge Click to Select-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Enable edge selection and deletion:-- Track selectedEdge state-- onEdgeClick handler-- Delete key handler for selected edge-- Context menu option for delete--### Task 6: Add Connection Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Style the connection system:-- Valid connection hover glow on handles-- Invalid connection red highlight-- Selected edge styling-- Connection type colors-- Edge label styling--## Success Criteria-- [ ] Can only create valid connections-- [ ] Invalid connections show error feedback-- [ ] Connections display relevant metadata-- [ ] Can edit and delete connections--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `frontend/src/utils/connectionRules.js` | Create | Connection validation logic |-| `frontend/src/components/workflow/ConnectionEdge.jsx` | Create | Custom edge component |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modify | Wire validation, selection, deletion |-| `frontend/src/styles/pages/_workflow.less` | Modify | Connection styles |--## Technical Notes--- React Flow `isValidConnection` prop receives `{ source, target, sourceHandle, targetHandle }`-- Custom edges receive `{ id, source, target, sourceHandle, targetHandle, selected, data }`-- Use `onEdgesChange` for edge deletion (filter by id)-- Edge types must be registered like node types-- Consider edge data for storing connection metadata (protocol, port)--## Estimated Commits-- feat(19-1): Create connection validation utility-- feat(19-2): Wire isValidConnection to WorkflowBuilder-- feat(19-3): Add visual feedback for connection attempts-- feat(19-4): Create custom ConnectionEdge component-- feat(19-5): Add edge selection and deletion-- feat(19-6): Add connection stylesdiff --git a/.planning/phases/19-connection-logic/SUMMARY.md b/.planning/phases/19-connection-logic/SUMMARY.mddeleted file mode 100644index 1dd345c6..00000000--- a/.planning/phases/19-connection-logic/SUMMARY.md+++ /dev/null@@ -1,106 +0,0 @@-# Phase 19: Connection Logic - Summary--## Overview-Implemented connection validation, visual feedback, and edge management for the workflow builder. Users can now only create valid connections between nodes, with clear feedback when invalid connections are attempted.--## Completed: 2026-01-19--## What Was Built--### 1. Connection Validation Utility-**File**: `frontend/src/utils/connectionRules.js`--Comprehensive validation logic:-- Connection rules matrix defining valid source→target combinations-- `isValidConnection()` checks node types and handle IDs-- `getConnectionError()` returns human-readable error messages-- `connectionLabels` and `connectionColors` for edge styling-- Prevents self-connections and invalid node type combinations--Valid connections:-| Source | Handle | Target | Handle | Label |-|--------|--------|--------|--------|-------|-| domain | output | dockerApp | input | Routes to |-| domain | output | service | input | Routes to |-| dockerApp | output | dockerApp | input | Connects to |-| dockerApp | database | database | input | Uses DB |-| service | output | dockerApp | input | Provides |-| service | output | database | input | Uses |--### 2. Connection Validation Wiring-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Integrated validation into ReactFlow:-- `isValidConnection` prop prevents invalid connections-- `onConnectStart`/`onConnectEnd` for error tracking-- Connection error state with 3-second auto-clear-- Toast notification for invalid connection attempts--### 3. Custom ConnectionEdge Component-**File**: `frontend/src/components/workflow/ConnectionEdge.jsx`--Custom edge with enhanced features:-- Extends smoothstep edge-- Shows connection type label on hover-- Color-coded by connection type-- Selected state with white glow effect-- Delete button appears on selection--### 4. Edge Selection and Deletion-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Edge management:-- `selectedEdge` state tracking-- `onEdgeClick` handler-- Delete key/Backspace handler-- `deleteEdge` function removes by ID-- Edge metadata stored in data prop--### 5. Connection Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Added ~120 lines of styles:-- Connection error toast with slide animation-- Edge label (visible on hover/select)-- Edge delete button-- Handle hover scale effect-- Valid/invalid handle highlighting during connect-- Selected edge white stroke--## Commits--| Hash | Message |-|------|---------|-| `8a920fd` | feat(19-1): Create connection validation utility |-| `992d9cd` | feat(19-2): Wire isValidConnection and add connection feedback |-| `7bad6c1` | feat(19-4): Create custom ConnectionEdge component |-| `cf1aa5e` | feat(19-5): Add edge selection and deletion |-| `fd54754` | feat(19-6): Add connection styles |--## Files Changed--| File | Type | Lines |-|------|------|-------|-| `frontend/src/utils/connectionRules.js` | New | ~192 |-| `frontend/src/components/workflow/ConnectionEdge.jsx` | New | ~80 |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modified | +100 |-| `frontend/src/styles/pages/_workflow.less` | Modified | +121 |--## Success Criteria--- [x] Can only create valid connections-- [x] Invalid connections show error feedback-- [x] Connections display relevant metadata-- [x] Can edit and delete connections--## Technical Notes--- React Flow `isValidConnection` receives `{ source, target, sourceHandle, targetHandle }`-- Custom edges receive full props including `selected` and `data`-- Edge deletion uses `setEdges` filter pattern-- Connection metadata stored in edge `data` prop-- Keyboard handler attached via useEffect--## Next Phase--Phase 20 will implement workflow save/load to persist workflows and load existing infrastructure as workflows.diff --git a/.planning/phases/20-workflow-save-load/PLAN.md b/.planning/phases/20-workflow-save-load/PLAN.mddeleted file mode 100644index b35be1e2..00000000--- a/.planning/phases/20-workflow-save-load/PLAN.md+++ /dev/null@@ -1,120 +0,0 @@-# Phase 20: Workflow Save/Load - Execution Plan--## Goal-Persist workflows to database and enable loading existing infrastructure as workflow nodes. Users can save, load, and manage multiple workflows.--## Prerequisites-- Phase 19 completed (Connection Logic)-- Backend uses Flask + SQLAlchemy-- Existing model patterns (Application, Domain)-- Frontend API service pattern--## Tasks--### Task 1: Create Workflow Model-**File**: `backend/app/models/workflow.py`--Create SQLAlchemy model for workflows:-```python-class Workflow(db.Model):- id = Integer, primary_key- name = String(100), not null- description = Text, nullable- nodes = Text # JSON string of nodes- edges = Text # JSON string of edges- viewport = Text # JSON string {x, y, zoom}- created_at = DateTime- updated_at = DateTime- user_id = ForeignKey(users.id)-```--### Task 2: Create Workflow API Endpoints-**File**: `backend/app/api/workflows.py`--CRUD endpoints:-- `GET /workflows` - List all workflows for user-- `GET /workflows/<id>` - Get single workflow-- `POST /workflows` - Create new workflow-- `PUT /workflows/<id>` - Update workflow-- `DELETE /workflows/<id>` - Delete workflow--### Task 3: Register Workflow Blueprint-**File**: `backend/app/__init__.py`--Register the workflows blueprint:-- Import workflows_bp-- Register with prefix `/api/v1/workflows`--### Task 4: Add Frontend API Methods-**File**: `frontend/src/services/api.js`--Add workflow API methods:-- `getWorkflows()` - List workflows-- `getWorkflow(id)` - Get single workflow-- `createWorkflow(data)` - Create workflow-- `updateWorkflow(id, data)` - Update workflow-- `deleteWorkflow(id)` - Delete workflow--### Task 5: Add Save/Load UI to WorkflowBuilder-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Add toolbar with save/load:-- Save button (creates/updates workflow)-- Load button (opens modal with workflow list)-- Workflow name input-- Auto-save to localStorage (optional)-- useReactFlow for getNodes/getEdges/getViewport--### Task 6: Create Workflow List Modal-**File**: `frontend/src/components/workflow/WorkflowListModal.jsx`--Modal for managing workflows:-- List of saved workflows with name, date-- Click to load workflow-- Delete button per workflow-- Search/filter (optional)--### Task 7: Add Import Existing Infrastructure-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Button to import existing apps/DBs/domains as nodes:-- Fetch apps from `/apps`-- Fetch databases from `/databases`-- Fetch domains from `/domains`-- Position nodes in grid layout-- Create workflow from imported data--## Success Criteria-- [ ] Workflows save to database-- [ ] Workflows load correctly-- [ ] Existing apps/DBs appear as nodes-- [ ] Can manage multiple workflows--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `backend/app/models/workflow.py` | Create | Workflow model |-| `backend/app/models/__init__.py` | Modify | Export Workflow |-| `backend/app/api/workflows.py` | Create | CRUD endpoints |-| `backend/app/__init__.py` | Modify | Register blueprint |-| `frontend/src/services/api.js` | Modify | Add API methods |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modify | Save/load UI |-| `frontend/src/components/workflow/WorkflowListModal.jsx` | Create | Workflow list |--## Technical Notes--- Workflow nodes/edges stored as JSON strings in database-- Use `useReactFlow` hook for `getNodes()`, `getEdges()`, `getViewport()`, `setNodes()`, `setEdges()`, `setViewport()`-- Import infrastructure creates nodes from existing data but doesn't deploy-- Consider auto-save to localStorage on changes-- Workflow list should show preview of node count--## Estimated Commits-- feat(20-1): Create Workflow model-- feat(20-2): Create workflow API endpoints-- feat(20-3): Register workflow blueprint-- feat(20-4): Add frontend workflow API methods-- feat(20-5): Add save/load UI to WorkflowBuilder-- feat(20-6): Create WorkflowListModal-- feat(20-7): Add import existing infrastructurediff --git a/.planning/phases/21-workflow-deployment/PLAN.md b/.planning/phases/21-workflow-deployment/PLAN.mddeleted file mode 100644index 3b5dc6d7..00000000--- a/.planning/phases/21-workflow-deployment/PLAN.md+++ /dev/null@@ -1,245 +0,0 @@-# Phase 21: Deploy from Workflow - Execution Plan--## Goal-Execute workflow to create/update actual infrastructure resources. Convert visual workflow nodes and edges into real Docker apps, databases, and domain configurations by calling existing backend APIs.--## Prerequisites-- Phase 20 completed (Workflow Save/Load)-- Existing APIs for Docker apps, domains, databases-- Workflow with nodes (dockerApp, database, domain) and edges (connections)--## Architecture--### Deployment Flow-```-1. User clicks "Deploy" button-2. Frontend sends workflow to new deploy endpoint-3. Backend parses workflow nodes/edges-4. Backend executes in dependency order:- - Databases first (no dependencies)- - Docker apps second (may depend on databases)- - Domains last (depend on apps)-5. For each node:- - If node has appId/domainId → update existing resource- - If no ID → create new resource-6. Return deployment status with created resource IDs-7. Frontend updates nodes with new IDs-```--### Node Data Schema (from config panels)--**DockerApp Node**:-```json-{- "name": "my-app",- "image": "nginx:latest",- "status": "stopped",- "ports": ["8080:80"],- "memory": "512MB",- "appId": null // Set after creation-}-```--**Database Node**:-```json-{- "name": "my-database",- "type": "mysql|postgresql|mongodb|redis",- "status": "stopped",- "host": "localhost",- "port": 3306,- "dbId": null // For tracking (not in current DB model)-}-```--**Domain Node**:-```json-{- "name": "example.com",- "ssl": "none|valid|expired",- "dnsStatus": "pending|propagated",- "domainId": null // Set after creation-}-```--### Edge Semantics (from connectionRules.js)-- `domain → dockerApp`: Domain routes to app (create domain linked to app)-- `dockerApp → database`: App uses database (store connection info in app env)-- `dockerApp → dockerApp`: App-to-app networking (Docker network link)-- `service → dockerApp`: Service provides to app-- `service → database`: Service uses database--## Tasks--### Task 1: Create Workflow Deployment Backend Service-**File**: `backend/app/services/workflow_service.py`--Create service to orchestrate workflow deployment:-```python-class WorkflowService:- @staticmethod- def deploy_workflow(workflow_id, user_id):- """Deploy all resources from a workflow."""- # 1. Load workflow- # 2. Parse nodes and edges- # 3. Determine deployment order (topological sort)- # 4. Deploy each node- # 5. Return results with created IDs-- @staticmethod- def deploy_node(node, edges, user_id, created_resources):- """Deploy a single node based on type."""-- @staticmethod- def deploy_docker_app(node_data, user_id):- """Create/update Docker app from node data."""-- @staticmethod- def deploy_database(node_data, user_id):- """Create database from node data (standalone MySQL/PostgreSQL)."""-- @staticmethod- def deploy_domain(node_data, app_id, user_id):- """Create/update domain linked to app."""-- @staticmethod- def get_deployment_order(nodes, edges):- """Topological sort: databases → apps → domains."""-```--### Task 2: Create Workflow Deployment API Endpoint-**File**: `backend/app/api/workflows.py`--Add deployment endpoint:-```python-@workflows_bp.route('/<int:workflow_id>/deploy', methods=['POST'])-@jwt_required()-def deploy_workflow(workflow_id):- """Deploy all resources from a workflow.-- Returns:- {- "message": "Deployment completed",- "results": [- {"nodeId": "node_1", "type": "dockerApp", "success": true, "resourceId": 5},- {"nodeId": "node_2", "type": "domain", "success": true, "resourceId": 12},- ...- ],- "errors": [],- "workflow": {...updated workflow with resource IDs...}- }- """-```--### Task 3: Add Frontend Deploy API Method-**File**: `frontend/src/services/api.js`--Add deploy workflow method:-```javascript-async deployWorkflow(id) {- return this.request(`/workflows/${id}/deploy`, {- method: 'POST'- });-}-```--### Task 4: Add Deploy Button and Progress UI-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Add deployment controls:-- Deploy button in toolbar (only enabled when workflow is saved)-- Deployment confirmation modal-- Progress indicator during deployment-- Success/error feedback with resource links-- Auto-update node IDs after successful deployment--### Task 5: Create DeploymentProgressModal Component-**File**: `frontend/src/components/workflow/DeploymentProgressModal.jsx`--Modal showing deployment progress:-- List of nodes being deployed-- Status per node (pending/deploying/success/error)-- Real-time progress updates-- Error details if any fail-- Links to created resources on success-- Close button when complete--### Task 6: Update Nodes with Deployed Resource IDs-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--After successful deployment:-- Update node data with created resource IDs (appId, domainId)-- Change node status to reflect actual status-- Save updated workflow to persist IDs-- Show visual indicator that nodes are deployed--### Task 7: Add Deployment Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Styles for deployment UI:-- Deploy button styling-- Progress modal styles-- Node deployment status indicators-- Success/error visual feedback--## Success Criteria-- [ ] Can deploy new infrastructure from workflow-- [ ] Existing resources update correctly (when node has appId/domainId)-- [ ] Progress visible during deployment-- [ ] Errors handled with clear feedback-- [ ] Node IDs update after deployment-- [ ] Deployed nodes show deployed status--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `backend/app/services/workflow_service.py` | Create | Deployment orchestration |-| `backend/app/api/workflows.py` | Modify | Add deploy endpoint |-| `frontend/src/services/api.js` | Modify | Add deployWorkflow method |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modify | Deploy button and logic |-| `frontend/src/components/workflow/DeploymentProgressModal.jsx` | Create | Progress UI |-| `frontend/src/styles/pages/_workflow.less` | Modify | Deployment styles |--## Technical Notes--### Deployment Order Algorithm-```-1. Separate nodes by type: databases, apps, domains-2. Deploy databases first (no dependencies)-3. Deploy apps second:- - For each app, check edges for database connections- - Pass database info to app creation (env vars)-4. Deploy domains last:- - Find connected app from edges- - Create domain linked to app-```--### Error Handling Strategy-- Deployment is **not** atomic (partial success allowed)-- Track success/failure per node-- Continue deploying other nodes if one fails-- Return detailed results for each node-- User can re-deploy to retry failed nodes--### Node ID Tracking-- After creation, store resource ID in node data:- - DockerApp: `node.data.appId`- - Domain: `node.data.domainId`- - Database: Track by name (databases don't have IDs in current model)-- On re-deploy, check for existing ID to update vs create--### Database Handling Note-- Current system doesn't have a Database model like Application-- For MVP: Create database using existing `/databases/mysql` API-- Store connection info in connected app's environment variables-- Consider: Add Database model in future for better tracking--## Estimated Commits-- feat(21-1): Create workflow deployment service-- feat(21-2): Add workflow deploy API endpoint-- feat(21-3): Add frontend deploy API method-- feat(21-4): Add deploy button and progress UI-- feat(21-5): Create DeploymentProgressModal component-- feat(21-6): Update nodes with deployed resource IDs-- feat(21-7): Add deployment stylesdiff --git a/.planning/phases/21-workflow-deployment/SUMMARY.md b/.planning/phases/21-workflow-deployment/SUMMARY.mddeleted file mode 100644index dacbd906..00000000--- a/.planning/phases/21-workflow-deployment/SUMMARY.md+++ /dev/null@@ -1,142 +0,0 @@-# Phase 21: Deploy from Workflow - Summary--## Completed: 2026-01-19--## Goal-Execute workflow to create/update actual infrastructure resources by converting visual nodes and edges into real Docker apps, databases, and domain configurations.--## What Was Built--### Backend - Workflow Deployment Service-**File**: `backend/app/services/workflow_service.py`--Created comprehensive deployment orchestration service:-- `deploy_workflow()` - Main entry point that deploys all nodes in order-- `get_deployment_order()` - Topological sort: databases → apps → domains-- `deploy_node()` - Routes to type-specific deployment-- `deploy_database()` - Creates MySQL/PostgreSQL databases with users-- `deploy_docker_app()` - Creates Application records and docker-compose files-- `deploy_domain()` - Creates Domain records linked to apps, configures nginx-- `update_nodes_with_ids()` - Updates workflow nodes with created resource IDs--Key features:-- Non-atomic deployment (partial success allowed)-- Automatic database credential generation-- Environment variable injection for app-to-database connections-- Nginx auto-configuration for domains--### Backend - Deploy API Endpoint-**File**: `backend/app/api/workflows.py`--Added `POST /workflows/{id}/deploy` endpoint:-- Calls WorkflowService.deploy_workflow()-- Returns detailed results per node-- Returns updated workflow with resource IDs-- Proper error handling (404, 403, partial failures)--### Frontend - Deploy Workflow-**File**: `frontend/src/services/api.js`--Added `deployWorkflow(id)` API method.--### Frontend - Deploy UI-**File**: `frontend/src/pages/WorkflowBuilder.jsx`--Added deployment functionality:-- Deploy button in toolbar (green, shows "Deploy")-- Button disabled until workflow is saved and has nodes-- `deployWorkflow()` function that:- - Saves current state first- - Calls deploy API- - Updates nodes with returned resource IDs- - Opens progress modal--### Frontend - DeploymentProgressModal Component-**File**: `frontend/src/components/workflow/DeploymentProgressModal.jsx`--Progress modal showing:-- Loading state while deploying-- Summary banner (success/errors count)-- Per-node status list with icons-- Success/error/pending states per node-- Link to resource for successful deployments-- Error details section-- Done/Close button--### Frontend - Deployment Styles-**File**: `frontend/src/styles/pages/_workflow.less`--Added styles for:-- Deploy button (green theme)-- Deployment modal overlay and container-- Loading spinner state-- Summary banners (success/error)-- Result items with status icons-- Error list styling-- Deployed node indicator--## Commits--| Commit | Message |-|--------|---------|-| bead238 | feat(21-1): Create workflow deployment service |-| 83ba62b | feat(21-2): Add workflow deploy API endpoint |-| 1964383 | feat(21-3): Add frontend deploy API method |-| c5fb178 | feat(21-4): Add deploy button and progress UI |-| 6f37795 | feat(21-5): Create DeploymentProgressModal component |-| 643b5d1 | feat(21-7): Add deployment styles |--Note: Task 6 (Update nodes with deployed resource IDs) was implemented as part of Task 4's deployWorkflow function.--## Technical Decisions--### Deployment Order-Databases → Docker Apps → Domains ensures dependencies are met:-1. Databases have no dependencies-2. Apps may connect to databases (need DB credentials)-3. Domains link to apps (need app to exist first)--### Non-Atomic Deployment-- Allows partial success-- Continues deploying even if one node fails-- Returns detailed results for each node-- User can re-deploy to retry failed nodes--### Resource ID Tracking-- DockerApp: `node.data.appId`-- Domain: `node.data.domainId`-- Database: `node.data.deployed` + `node.data.dbName`--### Database Handling-- MySQL/PostgreSQL create actual databases-- MongoDB/Redis should be Docker containers (future enhancement)-- Auto-generates secure passwords-- Creates database user with same name as database--## Files Changed--| File | Action | Lines |-|------|--------|-------|-| `backend/app/services/workflow_service.py` | Created | +588 |-| `backend/app/api/workflows.py` | Modified | +39 |-| `frontend/src/services/api.js` | Modified | +6 |-| `frontend/src/pages/WorkflowBuilder.jsx` | Modified | +96 |-| `frontend/src/components/workflow/DeploymentProgressModal.jsx` | Created | +149 |-| `frontend/src/styles/pages/_workflow.less` | Modified | +303 |--## Success Criteria--- [x] Can deploy new infrastructure from workflow-- [x] Existing resources update correctly (when node has appId/domainId)-- [x] Progress visible during deployment-- [x] Errors handled with clear feedback-- [x] Node IDs update after deployment-- [x] Deployed nodes tracked via data.deployed flag--## Future Enhancements--1. **Start containers after deploy** - Currently only creates, doesn't start-2. **MongoDB/Redis as containers** - Treat as Docker apps not databases-3. **Rollback on failure** - Option to undo partial deployments-4. **Real-time progress** - WebSocket for live status updates-5. **Deploy diff** - Show what will change before deployingdiff --git a/.planning/phases/22-container-logs-api/PLAN.md b/.planning/phases/22-container-logs-api/PLAN.mddeleted file mode 100644index 4f45d192..00000000--- a/.planning/phases/22-container-logs-api/PLAN.md+++ /dev/null@@ -1,318 +0,0 @@-# Phase 22: Container Logs API - Execution Plan--## Goal-Create backend API to fetch and stream Docker container logs for applications, enabling real-time log viewing in the UI (Phase 23).--## Prerequisites-- Docker apps exist with `container_id` or can be resolved via `root_path`-- WebSocket infrastructure exists (Flask-SocketIO with threading async_mode)-- Existing `DockerService.get_container_logs()` method available--## Architecture--### Existing Infrastructure--**DockerService** (`backend/app/services/docker_service.py:237-254`):-```python-@staticmethod-def get_container_logs(container_id, tail=100, since=None, timestamps=True):- """Get container logs."""- cmd = ['docker', 'logs']- if tail:- cmd.extend(['--tail', str(tail)])- if since:- cmd.extend(['--since', since])- if timestamps:- cmd.append('-t')- cmd.append(container_id)- # Returns {'success': True, 'logs': logs} or {'success': False, 'error': str}-```--**WebSocket Pattern** (`backend/app/sockets.py`):-- Uses room-based streaming: `join_room(f'build_{app_id}')`-- Build logs emit via `emit_build_log(app_id, message, level)`-- Clients subscribe via `subscribe_build` event with `app_id`--**Application Model** (`backend/app/models/application.py`):-- `container_id`: String(100), nullable - stores Docker container ID-- `root_path`: String(500) - path to docker-compose directory-- For compose apps: container names follow `serverkit-app-{app.id}` pattern--### Log Streaming Flow-```-1. Client connects to WebSocket with JWT token-2. Client emits 'subscribe_container_logs' with app_id-3. Server joins room 'logs_{app_id}'-4. Server starts background thread to stream logs via `docker logs -f`-5. Server emits 'container_log' events to room-6. Client emits 'unsubscribe_container_logs' or disconnects-7. Server stops background thread and leaves room-```--## Tasks--### Task 1: Extend DockerService with Streaming Logs-**File**: `backend/app/services/docker_service.py`--Add method for streaming container logs:-```python-@staticmethod-def stream_container_logs(container_id, callback, tail=100, since=None, timestamps=True):- """Stream container logs in real-time.-- Args:- container_id: Docker container ID or name- callback: Function to call with each log line- tail: Number of existing lines to fetch first- since: Only logs since this timestamp- timestamps: Include timestamps in output-- Returns:- subprocess.Popen object for the streaming process- """- cmd = ['docker', 'logs', '--follow']- if tail:- cmd.extend(['--tail', str(tail)])- if since:- cmd.extend(['--since', since])- if timestamps:- cmd.append('-t')- cmd.append(container_id)-- process = subprocess.Popen(- cmd,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- bufsize=1- )- return process-```--### Task 2: Create Container Logs REST API Endpoint-**File**: `backend/app/api/apps.py`--Extend existing `/apps/<id>/logs` endpoint to support container logs with more options:-```python-@apps_bp.route('/<int:app_id>/container-logs', methods=['GET'])-@jwt_required()-def get_container_logs(app_id):- """Get container logs for a Docker application.-- Query params:- - tail: Number of lines from end (default: 100, max: 10000)- - since: ISO timestamp or duration (e.g., '10m', '1h', '2024-01-01T00:00:00Z')- - timestamps: Include timestamps (default: true)- - format: Output format - 'raw' or 'json' (default: 'raw')-- Returns:- {- "success": true,- "logs": "...", // Raw format- "lines": [...] // JSON format with parsed lines- "container_id": "...",- "container_name": "...",- "app_id": 1- }- """-```--### Task 3: Add Container Logs WebSocket Events-**File**: `backend/app/sockets.py`--Add WebSocket handlers for real-time log streaming:-```python-# Store active log streams-container_log_streams = {} # sid -> {'process': Popen, 'app_id': int, 'thread': Thread}-[email protected]('subscribe_container_logs')-def handle_subscribe_container_logs(data):- """Subscribe to real-time container log streaming.-- data: {- 'app_id': int,- 'tail': int (optional, default 100),- 'since': str (optional)- }- """- sid = request.sid- app_id = data.get('app_id')- tail = data.get('tail', 100)- since = data.get('since')-- # Validate token and app access (already done in connect)- # Get container ID from app- # Start streaming thread- # Join room for this app's logs- join_room(f'logs_{app_id}')-[email protected]('unsubscribe_container_logs')-def handle_unsubscribe_container_logs():- """Unsubscribe from container log streaming."""- sid = request.sid- # Stop streaming process- # Leave room- # Clean up--def emit_container_log(app_id: int, line: str, timestamp: str = None):- """Emit a container log line to all subscribers."""- socketio.emit('container_log', {- 'app_id': app_id,- 'line': line,- 'timestamp': timestamp or time.time()- }, room=f'logs_{app_id}')-```--### Task 4: Handle Container Resolution for Compose Apps-**File**: `backend/app/services/docker_service.py`--Add method to get container name/ID for an app:-```python-@staticmethod-def get_app_container_id(app):- """Get the main container ID for an application.-- For apps with container_id set, use that directly.- For compose apps, query docker compose ps to find container.-- Args:- app: Application model instance-- Returns:- str: Container ID or name, or None if not found- """- if app.container_id:- return app.container_id-- if app.root_path:- # Get containers from docker compose- containers = DockerService.compose_ps(app.root_path)- if containers:- # Return first container (main service)- # For compose apps, container name is typically service name- return containers[0].get('ID') or containers[0].get('Name')-- return None--@staticmethod-def get_app_container_name(app_id):- """Get container name by convention: serverkit-app-{app_id}"""- return f"serverkit-app-{app_id}"-```--### Task 5: Add Log Line Parsing Utility-**File**: `backend/app/services/docker_service.py`--Add utility to parse Docker log lines:-```python-@staticmethod-def parse_log_line(line):- """Parse a Docker log line into structured format.-- Docker logs with timestamps look like:- 2024-01-15T10:30:45.123456789Z Log message here-- Returns:- {- 'timestamp': '2024-01-15T10:30:45.123456789Z',- 'message': 'Log message here',- 'level': 'info' # Detected from content- }- """- # Parse timestamp if present- # Detect log level from message content (ERROR, WARN, INFO, DEBUG)- # Return structured object-```--### Task 6: Handle Non-Running Container Edge Cases-**File**: `backend/app/api/apps.py` and `backend/app/sockets.py`--Handle edge cases gracefully:-- Container doesn't exist: Return appropriate error message-- Container is stopped: Return existing logs (no streaming)-- Container is restarting: Handle reconnection-- Multiple containers (compose): Allow selecting specific service--```python-# In REST endpoint-if not container_id:- return jsonify({- 'success': False,- 'error': 'No container found for this application',- 'hint': 'The application may not have been started yet'- }), 404--# Check if container is running for streaming-container_info = DockerService.get_container(container_id)-if not container_info:- return jsonify({- 'success': False,- 'error': 'Container not found'- }), 404--state = container_info.get('State', {}).get('Status', 'unknown')-```--### Task 7: Add API Documentation-**File**: Update API with docstrings and OpenAPI-style docs--Document the new endpoints:-- `GET /apps/{id}/container-logs` - Fetch historical logs-- WebSocket `subscribe_container_logs` - Stream real-time logs-- WebSocket `unsubscribe_container_logs` - Stop streaming-- WebSocket `container_log` event - Log line event--## Success Criteria-- [ ] Can fetch last N lines of container logs via REST API-- [ ] Can stream logs in real-time via WebSocket-- [ ] Logs include timestamps-- [ ] Handles containers that aren't running (returns stored logs or error)-- [ ] Handles compose apps (multiple containers)-- [ ] JSON format option for structured log data-- [ ] Proper cleanup when client disconnects--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `backend/app/services/docker_service.py` | Modify | Add streaming logs, container resolution, log parsing |-| `backend/app/api/apps.py` | Modify | Add `/container-logs` endpoint |-| `backend/app/sockets.py` | Modify | Add container log streaming WebSocket events |--## Technical Notes--### Docker Logs Command Reference-```bash-# Basic logs-docker logs <container>--# With options-docker logs --tail 100 --since "10m" -t --follow <container>--# Options:-# --tail N Show last N lines-# --since TIME Show logs since timestamp (RFC3339) or duration (10m, 1h)-# -t, --timestamps Show timestamps-# -f, --follow Stream new logs-```--### WebSocket Room Naming Convention-- Build logs: `build_{app_id}`-- Container logs: `logs_{app_id}`-- Metrics: broadcast to all subscribers--### Log Buffer Limits-- REST API: Max 10,000 lines per request-- WebSocket: No buffer limit (streaming)-- Frontend (Phase 23): Should implement virtual scrolling for large log volumes--### ANSI Color Codes-Docker logs may contain ANSI color codes. These will be preserved in the output and handled by the frontend (Phase 23) using an ANSI parser.--## Estimated Commits-- feat(22-1): Add streaming logs method to DockerService-- feat(22-2): Add container-logs REST endpoint-- feat(22-3): Add WebSocket container log streaming-- feat(22-4): Add container resolution for compose apps-- feat(22-5): Add log parsing utility-- feat(22-6): Handle edge cases for non-running containersdiff --git a/.planning/phases/22-container-logs-api/SUMMARY.md b/.planning/phases/22-container-logs-api/SUMMARY.mddeleted file mode 100644index de907fe2..00000000--- a/.planning/phases/22-container-logs-api/SUMMARY.md+++ /dev/null@@ -1,133 +0,0 @@-# Phase 22: Container Logs API - Summary--## Overview-Created backend API and WebSocket infrastructure to fetch and stream Docker container logs for applications, enabling real-time log viewing in the UI.--## Completed Tasks--### Task 1: DockerService Streaming Extensions-**Commit**: `f3010d9`--Added methods to DockerService for container log operations:-- `stream_container_logs()` - Start streaming logs via subprocess with `docker logs --follow`-- `get_app_container_id()` - Resolve container ID from Application model (handles both direct container_id and compose apps)-- `get_all_app_containers()` - List all containers for compose apps-- `parse_log_line()` - Parse Docker log line to extract timestamp and detect level (error/warn/info/debug)-- `parse_logs_to_lines()` - Batch parse logs text into structured lines-- `get_container_state()` - Check if container is running, get status info--### Task 2: REST API Endpoints-**Commit**: `744c626`--Added endpoints to `backend/app/api/apps.py`:--**GET /apps/{id}/container-logs**-- Query params: `tail`, `since`, `timestamps`, `format`, `service`-- Returns logs in 'raw' or 'json' format-- Includes container state and available services-- Caps at 10,000 lines for performance--**GET /apps/{id}/containers**-- Lists all containers for a compose application-- Returns container id, name, service, state--### Task 3: WebSocket Real-Time Streaming-**Commit**: `f55e399`--Added WebSocket events to `backend/app/sockets.py`:--**subscribe_container_logs** event-- Input: `{app_id, tail?, since?, service?}`-- Starts background thread streaming via `docker logs --follow`-- Joins room `logs_{app_id}`-- Emits `container_log` events with parsed log lines--**unsubscribe_container_logs** event-- Stops streaming subprocess-- Leaves room-- Cleans up resources--**Events emitted:**-- `container_log` - Log line with parsed timestamp/level-- `container_log_ended` - When container stops-- `container_log_error` - On stream failure--### Edge Cases Handled-- Container not found: Returns helpful error with hint-- Container stopped: REST returns existing logs, WebSocket emits ended event-- Compose apps: Service selection via `service` parameter-- Process cleanup: Terminates subprocess on disconnect/unsubscribe-- Large logs: Capped at 10,000 lines for REST API--## Files Modified--| File | Changes |-|------|---------|-| `backend/app/services/docker_service.py` | +185 lines: streaming, parsing, container resolution |-| `backend/app/api/apps.py` | +151 lines: container-logs and containers endpoints |-| `backend/app/sockets.py` | +227 lines: WebSocket container log streaming |--## API Reference--### REST Endpoints--```-GET /api/v1/apps/{id}/container-logs- ?tail=100 # Lines from end (max 10000)- ?since=10m # Duration or ISO timestamp- ?timestamps=true # Include timestamps- ?format=raw # 'raw' or 'json'- ?service=web # Specific service for compose apps--GET /api/v1/apps/{id}/containers- # List containers for compose apps-```--### WebSocket Events--```javascript-// Subscribe to logs-socket.emit('subscribe_container_logs', {- app_id: 1,- tail: 100,- since: '10m',- service: 'web' // optional-});--// Receive logs-socket.on('container_log', (data) => {- // data: {app_id, line, parsed: {timestamp, message, level}, timestamp}-});--socket.on('container_log_ended', (data) => {- // Container stopped-});--socket.on('container_log_error', (data) => {- // Stream error-});--// Unsubscribe-socket.emit('unsubscribe_container_logs');-```--## Testing Notes--- Tested against Docker compose applications-- Log streaming continues until container stops or client disconnects-- ANSI color codes preserved in output (frontend will parse)-- Timestamps parsed from Docker RFC3339 format--## Next Phase--Phase 23: Log Viewer UI-- Create LogViewer component with terminal-style display-- Implement auto-scroll with pause on user scroll-- Add ANSI color code parsing-- Connect to WebSocket for live streaming--## Commits--1. `f3010d9` - feat(22-1): Add streaming logs and container resolution to DockerService-2. `744c626` - feat(22-2): Add container-logs REST API endpoint-3. `f55e399` - feat(22-3): Add WebSocket container log streamingdiff --git a/.planning/phases/23-log-viewer-ui/PLAN.md b/.planning/phases/23-log-viewer-ui/PLAN.mddeleted file mode 100644index cc7ce883..00000000--- a/.planning/phases/23-log-viewer-ui/PLAN.md+++ /dev/null@@ -1,303 +0,0 @@-# Phase 23: Log Viewer UI - Execution Plan--## Goal-Create a real-time log viewer component in the application detail page that displays Docker container logs with terminal-style formatting, ANSI color support, auto-scroll, and streaming controls.--## Prerequisites-- Phase 22 completed (Container Logs API)-- Backend endpoints available:- - `GET /apps/{id}/container-logs` (REST)- - `GET /apps/{id}/containers` (REST)- - WebSocket events: `subscribe_container_logs`, `container_log`, `container_log_ended`--## Architecture--### Existing Infrastructure--**Socket Service** (`frontend/src/services/socket.js`):-- Uses socket.io-client-- Event listener pattern: `socketService.on(event, callback)`-- Needs extension for container log events--**Application Detail Page** (`frontend/src/pages/ApplicationDetail.jsx`):-- Tab-based layout with Overview, Environment, Private URL, Linked Apps-- Will add new "Logs" tab-- Uses `useParams()` to get app ID--**Existing Styles** (`_terminal.less`, `_logs.less`):-- Terminal dark theme: background `#1a1a2e`, text `#e2e8f0`-- Monospace font: `'JetBrains Mono', 'Fira Code', monospace`-- Log content styling available to extend--### Component Structure-```-ApplicationDetail.jsx-└── Logs Tab- └── ContainerLogs.jsx (main container)- ├── LogViewer.jsx (terminal display)- └── LogToolbar.jsx (controls)-```--## Tasks--### Task 1: Extend Socket Service for Container Logs-**File**: `frontend/src/services/socket.js`--Add methods and event handlers for container log streaming:-```javascript-// Add event handlers in connect()-this.socket.on('container_log', (data) => {- this.emit('container_log', data);-});-this.socket.on('container_log_ended', (data) => {- this.emit('container_log_ended', data);-});-this.socket.on('container_log_error', (data) => {- this.emit('container_log_error', data);-});-this.socket.on('subscribed', (data) => {- this.emit('subscribed', data);-});--// Add subscribe/unsubscribe methods-subscribeContainerLogs(appId, options = {}) {- if (this.socket?.connected) {- this.socket.emit('subscribe_container_logs', {- app_id: appId,- tail: options.tail || 100,- since: options.since,- service: options.service- });- }-}--unsubscribeContainerLogs() {- if (this.socket?.connected) {- this.socket.emit('unsubscribe_container_logs');- }-}-```--### Task 2: Add API Methods for Container Logs-**File**: `frontend/src/services/api.js`--Add methods to fetch container logs and containers list:-```javascript-async getContainerLogs(appId, options = {}) {- const params = new URLSearchParams();- if (options.tail) params.append('tail', options.tail);- if (options.since) params.append('since', options.since);- if (options.format) params.append('format', options.format);- if (options.service) params.append('service', options.service);-- const query = params.toString();- return this.request(`/apps/${appId}/container-logs${query ? '?' + query : ''}`);-}--async getAppContainers(appId) {- return this.request(`/apps/${appId}/containers`);-}-```--### Task 3: Create ANSI Color Parser Utility-**File**: `frontend/src/utils/ansiParser.js`--Create utility to parse ANSI color codes into HTML spans:-```javascript-// ANSI color code mapping-const ANSI_COLORS = {- 30: '#2e3436', 31: '#cc0000', 32: '#4e9a06', 33: '#c4a000',- 34: '#3465a4', 35: '#75507b', 36: '#06989a', 37: '#d3d7cf',- 90: '#555753', 91: '#ef2929', 92: '#8ae234', 93: '#fce94f',- 94: '#729fcf', 95: '#ad7fa8', 96: '#34e2e2', 97: '#eeeeec'-};--export function parseAnsi(text) {- // Replace ANSI codes with span elements- // Handle: colors (30-37, 90-97), bold (1), reset (0)- // Return array of {text, style} objects for React rendering-}--export function stripAnsi(text) {- // Remove all ANSI codes for plain text- return text.replace(/\x1b\[[0-9;]*m/g, '');-}-```--### Task 4: Create LogViewer Component-**File**: `frontend/src/components/LogViewer.jsx`--Create the main log display component:-```jsx-const LogViewer = ({- logs, // Array of log entries- autoScroll, // Boolean for auto-scroll- onScrollPause, // Callback when user scrolls- maxLines = 1000 // Buffer limit-}) => {- // Features:- // - Terminal-style dark theme- // - ANSI color rendering- // - Auto-scroll with pause on user scroll- // - Virtual scrolling for performance (if needed)- // - Line numbers (optional)- // - Level-based coloring (error=red, warn=yellow)-};-```--Key implementation details:-- Use ref for scroll container-- Detect user scroll to pause auto-scroll-- Render parsed log lines with ANSI colors-- Apply level-based styles (error/warn/info/debug)-- Limit buffer to prevent memory issues--### Task 5: Create ContainerLogs Component-**File**: `frontend/src/components/ContainerLogs.jsx`--Create the main container component that manages state and WebSocket:-```jsx-const ContainerLogs = ({ appId }) => {- const [logs, setLogs] = useState([]);- const [streaming, setStreaming] = useState(false);- const [autoScroll, setAutoScroll] = useState(true);- const [containers, setContainers] = useState([]);- const [selectedService, setSelectedService] = useState(null);- const [error, setError] = useState(null);- const [containerState, setContainerState] = useState(null);-- // Load initial logs via REST- // Connect to WebSocket for streaming- // Handle container selection for compose apps- // Provide play/pause/clear/download controls-};-```--Toolbar controls:-- Play/Pause streaming button-- Clear logs button-- Download logs button-- Service selector (for compose apps)-- Line count selector (100, 500, 1000)-- Connection status indicator--### Task 6: Add Logs Tab to ApplicationDetail-**File**: `frontend/src/pages/ApplicationDetail.jsx`--Add the Logs tab to the existing tab navigation:-```jsx-// Add import-import ContainerLogs from '../components/ContainerLogs';--// Add to tabs array (around line 550)-{ id: 'logs', label: 'Logs', icon: Terminal }--// Add tab content (in renderTabContent)-case 'logs':- return <ContainerLogs appId={app.id} />;-```--### Task 7: Add Styles for Log Viewer-**File**: `frontend/src/styles/components/_container-logs.less`--Create styles for the log viewer:-```less-.container-logs {- display: flex;- flex-direction: column;- height: 500px; // Or flexible based on container-- .logs-toolbar {- // Play/pause, clear, download buttons- // Service selector- // Status indicator- }-- .log-viewer {- flex: 1;- overflow: auto;- background: #1a1a2e;- border-radius: @radius-lg;-- .log-line {- // Individual log line styling- // Timestamp, level indicator, message- }-- // ANSI color classes- .ansi-red { color: #ef2929; }- .ansi-green { color: #8ae234; }- .ansi-yellow { color: #fce94f; }- // ... etc- }-}-```--Import in main styles file.--## Success Criteria-- [ ] Logs display in real-time via WebSocket-- [ ] ANSI color codes render correctly-- [ ] Auto-scroll works with manual override (pause on user scroll)-- [ ] Can pause/resume streaming-- [ ] Can clear log buffer-- [ ] Can download logs-- [ ] Service selector works for compose apps-- [ ] Shows connection status-- [ ] Handles container stopped state gracefully--## Files to Create/Modify--| File | Action | Purpose |-|------|--------|---------|-| `frontend/src/services/socket.js` | Modify | Add container log events and methods |-| `frontend/src/services/api.js` | Modify | Add container logs API methods |-| `frontend/src/utils/ansiParser.js` | Create | ANSI color code parsing |-| `frontend/src/components/LogViewer.jsx` | Create | Terminal-style log display |-| `frontend/src/components/ContainerLogs.jsx` | Create | Main container with controls |-| `frontend/src/pages/ApplicationDetail.jsx` | Modify | Add Logs tab |-| `frontend/src/styles/components/_container-logs.less` | Create | Log viewer styles |-| `frontend/src/styles/main.less` | Modify | Import new styles |--## Technical Notes--### Auto-Scroll Behavior-- Auto-scroll enabled by default-- Pauses when user scrolls up-- Resumes when user scrolls to bottom or clicks "Resume" button-- Visual indicator shows when paused--### Buffer Management-- Keep max 1000 lines in memory-- Older lines discarded when limit reached-- Download fetches from REST API (more lines available)--### ANSI Color Handling-Standard ANSI escape codes:-- `\x1b[0m` - Reset-- `\x1b[1m` - Bold-- `\x1b[30-37m` - Standard colors-- `\x1b[90-97m` - Bright colors--### WebSocket Event Data Format-```javascript-// container_log event-{- app_id: 1,- line: "2024-01-15T10:30:45.123Z INFO: Server started",- parsed: {- timestamp: "2024-01-15T10:30:45.123Z",- message: "INFO: Server started",- level: "info"- },- timestamp: 1705312245.123-}-```--## Estimated Commits-- feat(23-1): Add container log methods to socket and API services-- feat(23-2): Create ANSI color parser utility-- feat(23-3): Create LogViewer component with terminal display-- feat(23-4): Create ContainerLogs component with streaming controls-- feat(23-5): Add Logs tab to ApplicationDetail page-- feat(23-6): Add container logs stylesdiff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex 12275bd1..5608ee43 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -1,3 +1,4 @@+import refrom flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app import db@@ -8,6 +9,65 @@ from app.services.ssl_service import SSLServicedomains_bp = Blueprint('domains', __name__)+def validate_and_sanitize_domain(domain_name: str) -> tuple:+ """Validate and sanitize a domain name for nginx server_name.++ Args:+ domain_name: The domain name to validate++ Returns:+ Tuple of (sanitized_domain, error_message). error_message is None if valid.+ """+ if not domain_name:+ return None, 'Domain name is required'++ # Strip whitespace+ domain = domain_name.strip()++ # Remove protocol if present (common user mistake)+ if domain.startswith('https://'):+ domain = domain[8:]+ if domain.startswith('http://'):+ domain = domain[7:]++ # Remove trailing slashes and paths+ domain = domain.split('/')[0]++ # Remove port if present+ domain = domain.split(':')[0]++ # Strip again after modifications+ domain = domain.strip()++ if not domain:+ return None, 'Domain name is empty after sanitization'++ # Validate domain format+ # Allow: letters, numbers, hyphens, dots+ # Must not start or end with hyphen or dot+ # Must have at least one dot (for TLDs) unless it's localhost+ domain_pattern = r'^(?!-)[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(?<!-)$'++ if not re.match(domain_pattern, domain):+ return None, f'Invalid domain format: {domain}. Domain must contain only letters, numbers, dots, and hyphens.'++ # Check for consecutive dots+ if '..' in domain:+ return None, 'Domain cannot contain consecutive dots'++ # Check length+ if len(domain) > 253:+ return None, 'Domain name is too long (max 253 characters)'++ # Each label (part between dots) must be <= 63 chars+ labels = domain.split('.')+ for label in labels:+ if len(label) > 63:+ return None, f'Domain label "{label}" is too long (max 63 characters per label)'++ return domain.lower(), None++def admin_required(fn):"""Decorator to require admin role."""from functools import wraps@@ -73,6 +133,14 @@ def create_domain():if not all([name, application_id]):return jsonify({'error': 'Missing required fields: name, application_id'}), 400+ # Validate and sanitize domain name+ sanitized_name, validation_error = validate_and_sanitize_domain(name)+ if validation_error:+ return jsonify({'error': validation_error}), 400++ # Use sanitized name+ name = sanitized_name+# Check if domain already existsif Domain.query.filter_by(name=name).first():return jsonify({'error': 'Domain already exists'}), 409diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex 954f177d..4f758ba5 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -191,10 +191,11 @@ class NginxService:# Generated at: {timestamp}server {{- listen 80 default_server;- listen [::]:80 default_server;+ listen 80;+ listen [::]:80;- # Match all requests to this server for private URLs+ # Match requests to server IP for private URLs+ # Note: Do NOT use default_server here - serverkit.conf handles thatserver_name _;access_log /var/log/nginx/private-urls.access.log;@@ -738,14 +739,15 @@ server {{)else:# No private URLs - create minimal config+ # Note: Do NOT use default_server here - serverkit.conf handles thatconfig = f'''# ServerKit Private URL Routes# This file is auto-generated. Do not edit manually.# Generated at: {datetime.utcnow().isoformat()}# No private URLs configuredserver {{- listen 80 default_server;- listen [::]:80 default_server;+ listen 80;+ listen [::]:80;server_name _;location /p/ {{diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex c43baa26..e2b1c1f8 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -547,6 +547,18 @@ class TemplateService:for key, value in variables.items():f.write(f"{key}={value}\n")+ # Process template files section - create files and update compose for bind mounts+ if 'files' in template:+ files_result = cls._process_template_files(+ template['files'],+ app_path,+ compose_path,+ variables+ )+ if not files_result.get('success'):+ shutil.rmtree(app_path)+ return files_result+# Run pre-install script if existsif 'scripts' in template and 'pre_install' in template['scripts']:script_result = cls._run_script(@@ -643,6 +655,139 @@ class TemplateService:shutil.rmtree(app_path)return {'success': False, 'error': str(e), 'trace': error_trace}+ @classmethod+ def _process_template_files(cls, files: List[Dict], app_path: str,+ compose_path: str, variables: Dict) -> Dict:+ """Process template files section - create files and update compose for bind mounts.++ This method:+ 1. Creates files defined in the template's 'files' section+ 2. Updates docker-compose.yml to bind mount these files into containers++ Args:+ files: List of file definitions from template (path, content)+ app_path: Path to the app directory+ compose_path: Path to the docker-compose.yml file+ variables: Variables dict for substitution++ Returns:+ Dict with success status+ """+ try:+ created_files = []+ bind_mounts = [] # Track files that need to be bind mounted++ for file_def in files:+ container_path = file_def.get('path')+ content = file_def.get('content', '')++ if not container_path:+ continue++ # Substitute variables in content+ content = cls.substitute_variables(content, variables)++ # Determine local filename (use basename of container path)+ filename = os.path.basename(container_path)+ local_path = os.path.join(app_path, filename)++ # Write file locally+ with open(local_path, 'w') as f:+ f.write(content)++ created_files.append(filename)++ # Track for bind mount: local file -> container path+ # Get the container directory from the path+ container_dir = os.path.dirname(container_path)+ bind_mounts.append({+ 'local': f'./{filename}',+ 'container': container_path,+ 'container_dir': container_dir+ })++ # Update docker-compose.yml to use bind mounts instead of named volumes+ if bind_mounts:+ cls._update_compose_with_bind_mounts(compose_path, bind_mounts)++ return {+ 'success': True,+ 'files_created': created_files,+ 'bind_mounts': len(bind_mounts)+ }++ except Exception as e:+ return {'success': False, 'error': f'Failed to process template files: {str(e)}'}++ @classmethod+ def _update_compose_with_bind_mounts(cls, compose_path: str, bind_mounts: List[Dict]) -> None:+ """Update docker-compose.yml to use bind mounts for template files.++ Replaces named volume mounts with bind mounts for specific container paths.++ Args:+ compose_path: Path to docker-compose.yml+ bind_mounts: List of bind mount definitions+ """+ with open(compose_path, 'r') as f:+ compose = yaml.safe_load(f)++ # Group bind mounts by container directory+ dir_to_files = {}+ for mount in bind_mounts:+ dir_to_files.setdefault(mount['container_dir'], []).append(mount)++ # Process each service+ for service_name, service in compose.get('services', {}).items():+ volumes = service.get('volumes', [])+ new_volumes = []+ volumes_to_remove = set()++ for vol in volumes:+ if isinstance(vol, str):+ # Parse volume string: "name:/path" or "./local:/path"+ parts = vol.split(':')+ if len(parts) >= 2:+ mount_target = parts[1].rstrip('/')++ # Check if this volume's target directory matches any of our file paths+ should_replace = False+ for mount in bind_mounts:+ container_dir = mount['container_dir'].rstrip('/')+ if mount_target == container_dir:+ # This named volume covers a directory where we need to place files+ should_replace = True+ volumes_to_remove.add(parts[0]) # Track volume name to remove+ break++ if not should_replace:+ new_volumes.append(vol)+ else:+ new_volumes.append(vol)+ else:+ new_volumes.append(vol)++ # Add bind mounts for our files+ for mount in bind_mounts:+ bind_mount_str = f"{mount['local']}:{mount['container']}"+ if bind_mount_str not in new_volumes:+ new_volumes.append(bind_mount_str)++ service['volumes'] = new_volumes++ # Remove unused named volumes from top-level volumes section+ if 'volumes' in compose and volumes_to_remove:+ for vol_name in volumes_to_remove:+ if vol_name in compose['volumes']:+ del compose['volumes'][vol_name]+ # Remove volumes section if empty+ if not compose['volumes']:+ del compose['volumes']++ # Write updated compose file+ with open(compose_path, 'w') as f:+ yaml.dump(compose, f, default_flow_style=False, sort_keys=False)+@classmethoddef _run_script(cls, script: str, cwd: str, variables: Dict) -> Dict:"""Run a script with variable substitution."""diff --git a/docs/MCP_SERVER_ACCESS.md b/docs/MCP_SERVER_ACCESS.mdnew file mode 100644index 00000000..9103762e--- /dev/null+++ b/docs/MCP_SERVER_ACCESS.md@@ -0,0 +1,252 @@+# Giving Claude Code Direct Access to Your Server via MCP++## The Problem++Your current workflow:+```+You → Push to GitHub → Wait → SSH to server → Pull → Test → Report back → Repeat+```++This is slow and error-prone. With MCP, it becomes:+```+You → Claude runs commands directly on server → Instant feedback+```++---++## What is MCP?++**MCP (Model Context Protocol)** is a way to give Claude Code access to external tools and resources. Think of it as plugins that extend what Claude can do.++For server access, you'd set up an MCP server that lets Claude:+- Run bash commands on your remote server+- Read/write files on the server+- Check Docker status, nginx configs, logs, etc.++---++## Option 1: SSH MCP Server (Recommended)++This creates an MCP server on your **local machine** that tunnels commands to your remote server via SSH.++### Step 1: Install the SSH MCP Server++```bash+# On your Windows machine (where Claude Code runs)+npm install -g @anthropic/mcp-ssh+```++Or use the community one:+```bash+npm install -g @yourdevops/mcp-server-ssh+```++### Step 2: Configure Claude Code++Add to your Claude Code MCP config file:++**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`+**Or for Claude Code CLI:** `~/.claude/settings.json`++```json+{+ "mcpServers": {+ "serverkit-server": {+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-ssh",+ "--host", "your-server-ip-or-hostname",+ "--user", "your-username",+ "--key", "C:\\Users\\Juan\\.ssh\\id_rsa"+ ]+ }+ }+}+```++### Step 3: SSH Key Setup (if not done)++```bash+# Generate SSH key (if you don't have one)+ssh-keygen -t ed25519 -C "claude-serverkit"++# Copy to server+ssh-copy-id user@your-server-ip++# Test connection+ssh user@your-server-ip "echo 'SSH works!'"+```++---++## Option 2: Run MCP Server Directly on Your Server++This runs an MCP server **on your Linux server** that Claude connects to.++### Step 1: Install on Server++```bash+# SSH into your server+ssh user@your-server++# Install Node.js if needed+curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -+sudo apt-get install -y nodejs++# Install MCP bash server+npm install -g @anthropic/mcp-server-bash+```++### Step 2: Create a Systemd Service++```bash+sudo nano /etc/systemd/system/mcp-serverkit.service+```++```ini+[Unit]+Description=MCP Server for ServerKit+After=network.target++[Service]+Type=simple+User=your-username+WorkingDirectory=/var/serverkit+ExecStart=/usr/bin/npx @anthropic/mcp-server-bash+Restart=on-failure+Environment=MCP_PORT=3100++[Install]+WantedBy=multi-user.target+```++```bash+sudo systemctl enable mcp-serverkit+sudo systemctl start mcp-serverkit+```++### Step 3: Expose via SSH Tunnel (Secure)++Don't expose MCP directly to the internet. Use an SSH tunnel:++```bash+# On your Windows machine, create persistent tunnel+ssh -L 3100:localhost:3100 user@your-server -N+```++### Step 4: Configure Claude Code++```json+{+ "mcpServers": {+ "serverkit-server": {+ "command": "npx",+ "args": ["-y", "@anthropic/mcp-client-proxy", "--port", "3100"]+ }+ }+}+```++---++## Option 3: Simple Bash MCP (Easiest)++Use the built-in bash MCP with SSH as the shell:++### Claude Code Settings++Add to `~/.claude/settings.json` or your project's `.claude/settings.json`:++```json+{+ "mcpServers": {+ "serverkit-server": {+ "command": "ssh",+ "args": [+ "-o", "StrictHostKeyChecking=no",+ "-i", "C:\\Users\\Juan\\.ssh\\id_rsa",+ "user@your-server-ip",+ "bash"+ ]+ }+ }+}+```++This is the simplest - it just opens an SSH session as an MCP tool.++---++## Security Considerations++| Risk | Mitigation |+|------|------------|+| Full server access | Create a dedicated user with limited sudo rights |+| SSH key exposure | Use a dedicated key, not your main one |+| Accidental destructive commands | Claude will ask before running dangerous commands |+| Network exposure | Always use SSH tunnels, never expose MCP directly |++### Create a Limited User (Recommended)++```bash+# On your server+sudo useradd -m -s /bin/bash claude-mcp+sudo usermod -aG docker claude-mcp # For Docker access++# Limit sudo to specific commands+sudo visudo -f /etc/sudoers.d/claude-mcp+```++Add:+```+claude-mcp ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx, /usr/bin/nginx -t, /usr/bin/docker *, /usr/bin/docker-compose *+```++---++## What Claude Can Do With Server Access++Once configured, you can say things like:++- "Check if the Flask app container is running on the server"+- "Show me the nginx config for my-app"+- "Tail the nginx error logs for the last 50 lines"+- "Run docker ps and show me what's listening on port 8080"+- "Check why I'm getting 502 errors"+- "Deploy the latest changes from the repo"++---++## Quick Test++After setup, restart Claude Code and try:++```+"Use the serverkit-server to run: docker ps"+```++If configured correctly, I'll be able to run that command on your server and show you the output.++---++## Recommended MCP Packages++| Package | Purpose |+|---------|---------|+| `@anthropic/mcp-server-bash` | Run bash commands |+| `@anthropic/mcp-server-filesystem` | Read/write files |+| `@anthropic/mcp-server-docker` | Docker-specific operations |+| `@modelcontextprotocol/server-everything` | All-in-one server |++---++## Next Steps++1. Decide which option works best for you+2. Set up SSH key access to your server+3. Configure the MCP server+4. Restart Claude Code+5. Test with a simple command++Let me know which option you want to try and I can help you set it up step by step!