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
Introduce unified dev launcher and SCSS migration
Juan Denisb4414aa5b823
diff --git a/.gitignore b/.gitignoreindex 33989c57..02d1c9d4 100644--- a/.gitignore+++ b/.gitignore@@ -27,6 +27,7 @@/backend/*.pyd/backend/.env/backend/.venv+/backend/.venv-wsl//backend/pip-log.txt/backend/pip-delete-this-directory.txt/backend/dev-data/@@ -54,6 +55,7 @@*.csr/backend/.env/frontend/.env.local+/frontend/.env.development.local# Docker.docker-compose.untracked.yml@@ -110,3 +112,4 @@ UI_REPORT.md!agent/internal/setupui/serverkit_header.pngdocs/PLAN_AGENT_FLEET.md/docs/plans+/.agentsdiff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..e8822922--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,122 @@+# AGENTS.md++This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.++## Project Overview++ServerKit is a server control panel for managing web applications, databases, Docker containers, and security on VPS/dedicated servers. Flask backend (Python 3.11+), React frontend (Vite + SCSS), SQLite/PostgreSQL database, real-time updates via Socket.IO.++## Development Commands++```bash+# Backend (port 5000, hot-reload)+cd backend && python -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate+pip install -r requirements.txt+python run.py++# Frontend (port 5173, Vite HMR)+cd frontend && npm install && npm run dev++# Both at once (Linux/WSL)+./dev.sh++# Frontend lint+cd frontend && npm run lint++# Frontend production build+cd frontend && npm run build++# Backend tests+cd backend && pytest+cd backend && pytest --cov=app++# Docker+docker compose -f docker-compose.dev.yml up --build+```++Default dev credentials: `admin` / `admin`++## Architecture++### Backend (`backend/`)++Flask app factory in `app/__init__.py` using `create_app()`. Three-layer architecture:++- **`app/api/`** — Flask Blueprints, one file per feature (36 files). All routes prefixed `/api/v1/`. JWT-protected via `@jwt_required()`.+- **`app/services/`** — Business logic (48 files). Services are stateless modules called by API routes. Heavy lifting (shell commands, Docker API, file operations) happens here.+- **`app/models/`** — SQLAlchemy ORM models (15 files). Tables auto-created on startup via `db.create_all()`.++Other backend components:+- `app/sockets.py` — Socket.IO event handlers for real-time metrics, logs, terminal+- `app/agent_gateway.py` — Multi-server agent communication+- `app/middleware/security.py` — Security headers middleware+- `config.py` — Environment-based config (development/production/testing)+- `run.py` — Entry point++### Frontend (`frontend/src/`)++React 18 SPA with client-side routing:++- **`pages/`** — Route-level components (~29 files). Each maps to a route in `App.jsx`.+- **`components/`** — Reusable UI components shared across pages.+- **`contexts/`** — React Context providers: `AuthContext` (JWT auth + token refresh), `ThemeContext`, `ToastContext`, `ResourceTierContext` (feature gating).+- **`services/api.js`** — Centralized `ApiService` class handling all HTTP requests, token management, and auto-refresh.+- **`hooks/`** — Custom React hooks for reusable logic.+- **`styles/`** — SCSS stylesheets with design system variables. Main entry is `main.scss`. Page-specific styles in `styles/pages/`.+- **`layouts/`** — `DashboardLayout` wraps authenticated pages (sidebar + header).++Route guards: `PrivateRoute` (auth check), `PublicRoute` (redirect if logged in), `SetupRoute` (redirect to `/setup` if not configured).++### Request Flow++Browser → Nginx (`:80`/`:443`) → proxy_pass to Docker containers (`:8001-8999`) for managed apps, or to Flask (`:5000`) for the panel API. The 404 handler in Flask serves `index.html` for SPA client-side routing; API routes return JSON errors.++### Production Build++The Dockerfile is multi-stage: Node 20 builds frontend, Python 3.11 serves everything via Gunicorn with GeventWebSocket workers. Built frontend is served from Flask's static folder.++## Platform & Distro Awareness++ServerKit deploys on Linux (bare metal, VPS, or Docker). Development may happen on Windows/macOS.++- **Service layer is Linux-only** — nginx, systemctl, apt/dnf, PHP-FPM, etc. are inherently Linux. No need to abstract these for Windows.+- **Platform-agnostic code** (config management, storage, API layer) should guard Unix-only calls like `os.chmod` with `if os.name != 'nt'` so the dev server can run locally on any OS.+- **Distro differences matter** — use `backend/app/utils/system.py` helpers (`get_package_manager`, `is_package_installed`, `install_package`) instead of calling `apt`/`dpkg`/`dnf` directly. Not all targets are Debian-based.++## Code Style++### Python+- PEP 8, type hints where helpful+- Service functions are standalone (no classes unless stateful)+- Consistent JSON error responses: `{'error': 'message'}, status_code`++### React/JavaScript+- Functional components with hooks only+- PascalCase for components (`Sidebar.jsx`), camelCase for everything else+- SCSS for styling — use existing design system variables (`$bg-card`, `$primary-color`, `$spacing-md`, etc.) and BEM-like naming (`.block__element--modifier`)+- Context API for global state; props drilling is fine for 2-3 levels+- No inline styles; no Tailwind/CSS-in-JS++### Diffs & Commits+- One logical change per commit+- Minimal, focused diffs — don't silently refactor surrounding code+- Branch naming: `feature/`, `fix/`, `docs/`, `refactor/` prefixes++## Adding a New Feature (Full Stack)++1. **Model**: Add SQLAlchemy model in `backend/app/models/`+2. **Service**: Add business logic in `backend/app/services/`+3. **API**: Create Blueprint in `backend/app/api/`, register it in `app/__init__.py` with `url_prefix='/api/v1/<feature>'`+4. **Frontend API**: Add methods to `ApiService` in `frontend/src/services/api.js`+5. **Page**: Create page component in `frontend/src/pages/`, add route in `App.jsx`+6. **Styles**: Add SCSS file in `frontend/src/styles/pages/`, import in `main.scss`++## Key Environment Variables++| Variable | Purpose |+|----------|---------|+| `SECRET_KEY` | Flask session signing |+| `JWT_SECRET_KEY` | JWT token signing |+| `DATABASE_URL` | DB connection string (`sqlite:///...` or PostgreSQL) |+| `CORS_ORIGINS` | Comma-separated allowed origins |+| `FLASK_ENV` | `development` or `production` |diff --git a/CLAUDE.md b/CLAUDE.mdindex 436bb494..dd9cd25a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co## Project Overview-ServerKit is a server control panel for managing web applications, databases, Docker containers, and security on VPS/dedicated servers. Flask backend (Python 3.11+), React frontend (Vite + LESS), SQLite/PostgreSQL database, real-time updates via Socket.IO.+ServerKit is a server control panel for managing web applications, databases, Docker containers, and security on VPS/dedicated servers. Flask backend (Python 3.11+), React frontend (Vite + SCSS), SQLite/PostgreSQL database, real-time updates via Socket.IO.## Development Commands@@ -62,7 +62,7 @@ React 18 SPA with client-side routing:- **`contexts/`** — React Context providers: `AuthContext` (JWT auth + token refresh), `ThemeContext`, `ToastContext`, `ResourceTierContext` (feature gating).- **`services/api.js`** — Centralized `ApiService` class handling all HTTP requests, token management, and auto-refresh.- **`hooks/`** — Custom React hooks for reusable logic.-- **`styles/`** — LESS stylesheets with design system variables. Main entry is `main.less`. Page-specific styles in `styles/pages/`.+- **`styles/`** — SCSS stylesheets with design system variables. Main entry is `main.scss`. Page-specific styles in `styles/pages/`.- **`layouts/`** — `DashboardLayout` wraps authenticated pages (sidebar + header).Route guards: `PrivateRoute` (auth check), `PublicRoute` (redirect if logged in), `SetupRoute` (redirect to `/setup` if not configured).@@ -93,7 +93,7 @@ ServerKit deploys on Linux (bare metal, VPS, or Docker). Development may happen### React/JavaScript- Functional components with hooks only- PascalCase for components (`Sidebar.jsx`), camelCase for everything else-- LESS for styling — use existing design system variables (`@card-bg`, `@primary-color`, `@spacing-md`, etc.) and BEM-like naming (`.block__element--modifier`)+- SCSS for styling — use existing design system variables (`$bg-card`, `$primary-color`, `$spacing-md`, etc.) and BEM-like naming (`.block__element--modifier`)- Context API for global state; props drilling is fine for 2-3 levels- No inline styles; no Tailwind/CSS-in-JS@@ -109,7 +109,7 @@ ServerKit deploys on Linux (bare metal, VPS, or Docker). Development may happen3. **API**: Create Blueprint in `backend/app/api/`, register it in `app/__init__.py` with `url_prefix='/api/v1/<feature>'`4. **Frontend API**: Add methods to `ApiService` in `frontend/src/services/api.js`5. **Page**: Create page component in `frontend/src/pages/`, add route in `App.jsx`-6. **Styles**: Add LESS file in `frontend/src/styles/pages/`, import in `main.less`+6. **Styles**: Add SCSS file in `frontend/src/styles/pages/`, import in `main.scss`## Key Environment Variablesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex cf83ea52..4ea92448 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -115,7 +115,7 @@ ServerKit/│ │ ├── components/ # Reusable components│ │ ├── pages/ # Page components│ │ ├── services/ # API client-│ │ └── styles/ # LESS stylesheets+│ │ └── styles/ # SCSS stylesheets│ ├── package.json│ └── vite.config.js│@@ -137,7 +137,7 @@ ServerKit/- `frontend/src/pages/` - Page components- `frontend/src/components/` - Shared components- `frontend/src/services/api.js` - API client-- `frontend/src/styles/` - LESS stylesheets+- `frontend/src/styles/` - SCSS stylesheets---@@ -201,7 +201,7 @@ def get_system_stats() -> dict:- Use functional components with hooks- Use meaningful component and variable names- Keep components focused and small-- Use LESS for styling (not inline styles)+- Use SCSS for styling (not inline styles)```jsxconst ServerStats = ({ serverId }) => {@@ -217,24 +217,24 @@ const ServerStats = ({ serverId }) => {};```-### LESS/CSS (Styles)+### SCSS/CSS (Styles)- Use the existing design system variables- Follow BEM-like naming conventions- Keep specificity low- Use the component/page file structure-```less+```scss.notification-card {- background: @card-bg;- border-radius: @border-radius-md;+ background: $bg-card;+ border-radius: $radius-md;&__header {- padding: @spacing-md;+ padding: $spacing-md;}&--expanded {- border-color: @primary-color;+ border-color: $primary-color;}}```diff --git a/dev.ps1 b/dev.ps1index c9ff27d5..0ac908d8 100644--- a/dev.ps1+++ b/dev.ps1@@ -1,360 +1,113 @@#Requires -Version 5.1<#.SYNOPSIS- ServerKit development launcher and validation tool.+ Windows entry point for the ServerKit development environment..DESCRIPTION- Start backend, frontend, both, or expose backend via an ngrok tunnel.- Run validation checks.-.PARAMETER Mode- Operation mode: start (default), backend, frontend, tunnel, validate+ Delegates to dev/dev.sh through WSL so local development runs in a+ Linux-like environment and stays in sync with the Bash launcher..EXAMPLE- .\dev.ps1 # Start backend + frontend- .\dev.ps1 backend # Backend only- .\dev.ps1 frontend # Frontend only- .\dev.ps1 tunnel # Backend + frontend + ngrok tunnel for the backend- .\dev.ps1 validate # Run all linters/checks-.NOTES- Optional environment variables for tunnel mode:- NGROK_DOMAIN - reserved ngrok domain (e.g. my-app.ngrok-free.app)- NGROK_AUTHTOKEN - ngrok authtoken (alternatively run `ngrok config add-authtoken`)+ .\dev.ps1+ Start backend + frontend through WSL on stable non-default ports.+.EXAMPLE+ .\dev.ps1 frontend -BackendPort 5600+ Start Vite through WSL, targeting an existing backend on port 5600.#>-param(- [Parameter(Position = 0)]- [ValidateSet('start', 'backend', 'frontend', 'tunnel', 'validate')]- [string]$Mode = 'start'-)-$ProjectRoot = $PSScriptRoot-$BackendDir = Join-Path $ProjectRoot 'backend'-$FrontendDir = Join-Path $ProjectRoot 'frontend'-function Write-Header {- param([string]$Text)- Write-Host ""- Write-Host "=== $Text ===" -ForegroundColor Cyan- Write-Host ""+if (-not (Get-Command wsl.exe -ErrorAction SilentlyContinue)) {+ Write-Host "Error: WSL is required for .\dev.ps1." -ForegroundColor Red+ Write-Host "Install WSL, then run this again, or run ./dev.sh directly from Linux/WSL." -ForegroundColor Yellow+ exit 1}-function Write-Pass {- param([string]$Text)- Write-Host " PASS " -ForegroundColor Green -NoNewline- Write-Host $Text+$wslRoot = (& wsl.exe --exec wslpath -a -u "$ProjectRoot" 2>$null)+if ($LASTEXITCODE -ne 0 -or -not $wslRoot) {+ Write-Host "Error: Could not map this Windows path into WSL: $ProjectRoot" -ForegroundColor Red+ Write-Host "Make sure a WSL distro is installed and can access this repository." -ForegroundColor Yellow+ exit 1}-function Write-Fail {- param([string]$Text)- Write-Host " FAIL " -ForegroundColor Red -NoNewline- Write-Host $Text-}+$wslRoot = $wslRoot.Trim()+$devArgs = @($args)+$forwardedEnv = @()-function Start-Backend {- Write-Header "Starting Backend (http://localhost:5000)"- Push-Location $BackendDir- try {- if (Test-Path 'venv\Scripts\Activate.ps1') {- & 'venv\Scripts\Activate.ps1'+function Get-DevMode {+ foreach ($arg in $devArgs) {+ if ($arg -in @('start', 'backend', 'frontend', 'tunnel', 'validate')) {+ return $arg}- python run.py- }- finally {- Pop-Location- }-}--function Start-Frontend {- Write-Header "Starting Frontend (http://localhost:5173)"- Push-Location $FrontendDir- try {- npm run dev- }- finally {- Pop-Location}+ return 'start'}-function Start-Both {- Write-Host ""- Write-Host "ServerKit Dev Server" -ForegroundColor Cyan- Write-Host " Backend: http://localhost:5000"- Write-Host " Frontend: http://localhost:5173"- Write-Host ""-- $backendJob = Start-Job -ScriptBlock {- param($dir)- Set-Location $dir- if (Test-Path 'venv\Scripts\Activate.ps1') {- & 'venv\Scripts\Activate.ps1'- }- python run.py- } -ArgumentList $BackendDir-- Start-Sleep -Seconds 2-- $frontendJob = Start-Job -ScriptBlock {- param($dir)- Set-Location $dir- npm run dev- } -ArgumentList $FrontendDir-- try {- Write-Host "Press Ctrl+C to stop..." -ForegroundColor DarkGray- while ($true) {- # Stream output from both jobs- Receive-Job $backendJob -ErrorAction SilentlyContinue- Receive-Job $frontendJob -ErrorAction SilentlyContinue+function Get-DevPort {+ param(+ [string[]]$Names,+ [string]$EnvName,+ [int]$Default+ )- if ($backendJob.State -eq 'Failed') {- Write-Host "Backend crashed!" -ForegroundColor Red- Receive-Job $backendJob- break+ for ($i = 0; $i -lt $devArgs.Count; $i++) {+ $arg = [string]$devArgs[$i]+ foreach ($name in $Names) {+ if ($arg -eq $name -and ($i + 1) -lt $devArgs.Count) {+ return [int]$devArgs[$i + 1]}- if ($frontendJob.State -eq 'Failed') {- Write-Host "Frontend crashed!" -ForegroundColor Red- Receive-Job $frontendJob- break+ if ($arg.StartsWith("$name=")) {+ return [int]$arg.Substring($name.Length + 1)}- Start-Sleep -Seconds 1}}- finally {- Stop-Job $backendJob -ErrorAction SilentlyContinue- Stop-Job $frontendJob -ErrorAction SilentlyContinue- Remove-Job $backendJob -Force -ErrorAction SilentlyContinue- Remove-Job $frontendJob -Force -ErrorAction SilentlyContinue- Write-Host "`nStopped." -ForegroundColor Yellow- }-}--function Start-Tunnel {- if (-not (Get-Command ngrok -ErrorAction SilentlyContinue)) {- Write-Host "Error: ngrok is not installed or not in PATH." -ForegroundColor Red- Write-Host ""- Write-Host "Install ngrok:"- Write-Host " - https://ngrok.com/download"- Write-Host " - Windows: choco install ngrok (or scoop install ngrok)"- Write-Host " - WSL: snap install ngrok (or download the .tgz)"- Write-Host ""- Write-Host "Then authenticate once: ngrok config add-authtoken <YOUR_TOKEN>"- exit 1- }- Write-Host ""- Write-Host "ServerKit Dev Server (with ngrok tunnel)" -ForegroundColor Cyan- Write-Host " Backend: http://localhost:5000"- Write-Host " Frontend: http://localhost:5173"- Write-Host " Tunnel: exposing backend (port 5000) via ngrok"- Write-Host ""- Write-Host "NOTE: " -ForegroundColor Yellow -NoNewline- Write-Host "Agents and remote callers should use the public ngrok URL"- Write-Host " printed below as their --server / control plane URL."- Write-Host ""-- if (-not $env:CORS_ORIGINS) {- $env:CORS_ORIGINS = 'http://localhost:5173,http://localhost:5000,https://*.ngrok-free.app,https://*.ngrok.app,https://*.ngrok.io'- }-- $envSnapshot = @{- CORS_ORIGINS = $env:CORS_ORIGINS+ $item = Get-Item -Path "Env:$EnvName" -ErrorAction SilentlyContinue+ if ($item -and $item.Value) {+ return [int]$item.Value}- $backendJob = Start-Job -ScriptBlock {- param($dir, $envVars)- foreach ($k in $envVars.Keys) { Set-Item -Path "Env:$k" -Value $envVars[$k] }- Set-Location $dir- if (Test-Path 'venv\Scripts\Activate.ps1') {- & 'venv\Scripts\Activate.ps1'- }- python run.py- } -ArgumentList $BackendDir, $envSnapshot-- Start-Sleep -Seconds 2-- $frontendJob = Start-Job -ScriptBlock {- param($dir)- Set-Location $dir- npm run dev- } -ArgumentList $FrontendDir-- Start-Sleep -Seconds 1-- $ngrokArgs = @('http', '5000', '--log=stdout')- if ($env:NGROK_DOMAIN) { $ngrokArgs += "--domain=$($env:NGROK_DOMAIN)" }- if ($env:NGROK_AUTHTOKEN) { $ngrokArgs += "--authtoken=$($env:NGROK_AUTHTOKEN)" }-- $ngrokProc = Start-Process -FilePath 'ngrok' -ArgumentList $ngrokArgs -PassThru -WindowStyle Hidden-- $urlPrinted = $false- try {- Write-Host "Press Ctrl+C to stop..." -ForegroundColor DarkGray- $polls = 0- while ($true) {- Receive-Job $backendJob -ErrorAction SilentlyContinue- Receive-Job $frontendJob -ErrorAction SilentlyContinue-- if (-not $urlPrinted -and $polls -lt 30) {- try {- $resp = Invoke-RestMethod -Uri 'http://127.0.0.1:4040/api/tunnels' -TimeoutSec 1 -ErrorAction Stop- $publicUrl = ($resp.tunnels | Where-Object { $_.public_url -like 'https://*' } | Select-Object -First 1).public_url- if ($publicUrl) {- Write-Host ""- Write-Host "=========================================================" -ForegroundColor Green- Write-Host " Public tunnel URL: " -ForegroundColor Green -NoNewline- Write-Host $publicUrl -ForegroundColor Cyan- Write-Host " Use this as your agent --server / control plane URL." -ForegroundColor Green- Write-Host "=========================================================" -ForegroundColor Green- Write-Host ""- $urlPrinted = $true- }- }- catch { }- $polls++- }-- if ($backendJob.State -eq 'Failed') {- Write-Host "Backend crashed!" -ForegroundColor Red- Receive-Job $backendJob- break- }- if ($frontendJob.State -eq 'Failed') {- Write-Host "Frontend crashed!" -ForegroundColor Red- Receive-Job $frontendJob- break- }- if ($ngrokProc.HasExited) {- Write-Host "ngrok exited." -ForegroundColor Red- break- }- Start-Sleep -Seconds 1- }- }- finally {- Stop-Job $backendJob -ErrorAction SilentlyContinue- Stop-Job $frontendJob -ErrorAction SilentlyContinue- Remove-Job $backendJob -Force -ErrorAction SilentlyContinue- Remove-Job $frontendJob -Force -ErrorAction SilentlyContinue- if ($ngrokProc -and -not $ngrokProc.HasExited) {- Stop-Process -Id $ngrokProc.Id -ErrorAction SilentlyContinue- }- Write-Host "`nStopped." -ForegroundColor Yellow- }+ return $Default}-function Invoke-Check {+function Stop-WindowsListenersOnPort {param(- [string]$Name,- [string]$WorkDir,- [scriptblock]$Command+ [int]$Port,+ [string]$Label)- Write-Host "Running $Name..." -ForegroundColor Yellow- $prev = $PWD- if ($WorkDir) { Set-Location $WorkDir }- $ErrorActionPreference = 'Continue'- & $Command 2>&1 | Tee-Object -Variable output | Out-Null- $exitCode = $LASTEXITCODE- if ($WorkDir) { Set-Location $prev }-- if ($exitCode -eq 0) {- Write-Pass $Name- return $true- }- else {- Write-Fail $Name- $output | ForEach-Object { Write-Host " $_" }- return $false- }-}--function Run-Validate {- Write-Header "ServerKit Validation Suite"- $failed = 0- $passed = 0-- # --- ESLint (warn-only, does not block) ---- Write-Host "Running ESLint..." -ForegroundColor Yellow- Push-Location $FrontendDir- $ErrorActionPreference = 'Continue'- npm run lint 2>&1 | Out-Null- $eslintExit = $LASTEXITCODE- Pop-Location- if ($eslintExit -eq 0) {- Write-Pass "ESLint"- $passed++- }- else {- Write-Host " WARN " -ForegroundColor Yellow -NoNewline- Write-Host "ESLint (has warnings/errors - run 'cd frontend && npm run lint' for details)"- $passed++ # count as pass — pre-existing issues should not block- }-- # --- Bandit ---- if (Get-Command bandit -ErrorAction SilentlyContinue) {- if (Invoke-Check "Bandit (security scan)" "" { bandit -r "$BackendDir\app" --ini "$BackendDir\.bandit" --severity-level medium }) { $passed++ } else { $failed++ }- }- else {- Write-Fail "Bandit (not installed - pip install bandit)"- $failed++- }- # --- Pytest ---- if (Test-Path "$BackendDir\venv\Scripts\Activate.ps1") {- & "$BackendDir\venv\Scripts\Activate.ps1"- }- if (Invoke-Check "Pytest" $BackendDir { pytest --tb=short -q }) { $passed++ } else { $failed++ }+ $listeners = @(Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |+ Select-Object -ExpandProperty OwningProcess -Unique |+ Where-Object { $_ -and $_ -ne 0 -and $_ -ne $PID })- # --- Frontend build ---- if (Invoke-Check "Frontend build" $FrontendDir { npm run build }) { $passed++ } else { $failed++ }+ foreach ($processId in $listeners) {+ $proc = Get-Process -Id $processId -ErrorAction SilentlyContinue+ if (-not $proc) {+ continue+ }- # --- Summary ---- Write-Header "Results"- Write-Host " Passed: $passed" -ForegroundColor Green- if ($failed -gt 0) {- Write-Host " Failed: $failed" -ForegroundColor Red- exit 1- }- else {- Write-Host " All checks passed!" -ForegroundColor Green+ Write-Host "Stopping existing $Label listener on port $Port ($($proc.ProcessName) PID $processId)..." -ForegroundColor Yellow+ Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue}}-function Run-ValidateWatch {- Write-Host "Watching for changes... (Ctrl+C to stop)" -ForegroundColor DarkGray- Run-Validate+$mode = Get-DevMode+$backendPort = Get-DevPort -Names @('--backend-port', '-BackendPort') -EnvName 'SERVERKIT_BACKEND_PORT' -Default 47927+$frontendPort = Get-DevPort -Names @('--frontend-port', '-FrontendPort') -EnvName 'SERVERKIT_FRONTEND_PORT' -Default 41921+$isHelp = $devArgs -contains '-h' -or $devArgs -contains '--help'- $watcher = [System.IO.FileSystemWatcher]::new()- $watcher.Path = $ProjectRoot- $watcher.IncludeSubdirectories = $true- $watcher.Filter = '*.*'- $watcher.EnableRaisingEvents = $true-- $lastRun = [DateTime]::MinValue+if (-not $isHelp -and $mode -in @('start', 'backend', 'tunnel')) {+ Stop-WindowsListenersOnPort -Port $backendPort -Label 'backend'+}+if (-not $isHelp -and $mode -in @('start', 'frontend', 'tunnel')) {+ Stop-WindowsListenersOnPort -Port $frontendPort -Label 'frontend'+}- try {- while ($true) {- $result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::All, 2000)- if (-not $result.TimedOut) {- $ext = [System.IO.Path]::GetExtension($result.Name)- if ($ext -in '.py', '.js', '.jsx', '.ts', '.tsx') {- $now = [DateTime]::Now- if (($now - $lastRun).TotalSeconds -gt 3) {- $lastRun = $now- Write-Host "`nChange detected: $($result.Name)" -ForegroundColor Yellow- Run-Validate- }- }- }- }- }- finally {- $watcher.Dispose()+foreach ($name in @('SERVERKIT_BACKEND_PORT', 'SERVERKIT_FRONTEND_PORT', 'SERVERKIT_BROWSER_BACKEND_HOST', 'SERVERKIT_BACKEND_VENV', 'SERVERKIT_KILL_PORTS', 'NGROK_DOMAIN', 'NGROK_AUTHTOKEN', 'CORS_ORIGINS')) {+ $item = Get-Item -Path "Env:$name" -ErrorAction SilentlyContinue+ if ($item -and $item.Value) {+ $forwardedEnv += "$name=$($item.Value)"}}-# --- Main ----switch ($Mode) {- 'backend' { Start-Backend }- 'frontend' { Start-Frontend }- 'tunnel' { Start-Tunnel }- 'validate' { Run-ValidateWatch }- default { Start-Both }-}+Write-Host "Launching ServerKit dev environment in WSL..." -ForegroundColor Cyan+& wsl.exe --cd "$wslRoot" --exec env @forwardedEnv bash ./dev/dev.sh @devArgs+exit $LASTEXITCODEdiff --git a/dev.sh b/dev.shindex cdee06d2..d8685b8e 100644--- a/dev.sh+++ b/dev.sh@@ -1,272 +1,5 @@#!/usr/bin/env bash-# ServerKit development launcher and validation tool.-#-# Usage:-# ./dev.sh Start backend + frontend (default)-# ./dev.sh backend Backend only-# ./dev.sh frontend Frontend only-# ./dev.sh tunnel Start backend + frontend + expose backend via ngrok-# ./dev.sh validate Run all linters/checks-#-# Environment variables:-# NGROK_DOMAIN Optional reserved ngrok domain (e.g. my-app.ngrok-free.app)-# NGROK_AUTHTOKEN Optional ngrok authtoken (alternatively run `ngrok config add-authtoken`)-set -euo pipefail-PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-BACKEND_DIR="$PROJECT_ROOT/backend"-FRONTEND_DIR="$PROJECT_ROOT/frontend"--# Colors-CYAN='\033[0;36m'-GREEN='\033[0;32m'-RED='\033[0;31m'-YELLOW='\033[1;33m'-DIM='\033[2m'-NC='\033[0m'--header() {- echo ""- echo -e "${CYAN}=== $1 ===${NC}"- echo ""-}--pass() {- echo -e " ${GREEN}PASS${NC} $1"-}--fail() {- echo -e " ${RED}FAIL${NC} $1"-}--start_backend() {- header "Starting Backend (http://localhost:5000)"- cd "$BACKEND_DIR"- if [ -f venv/bin/activate ]; then- source venv/bin/activate- fi- python run.py-}--start_frontend() {- header "Starting Frontend (http://localhost:5173)"- cd "$FRONTEND_DIR"- npm run dev-}--start_both() {- echo ""- echo -e "${CYAN}ServerKit Dev Server${NC}"- echo " Backend: http://localhost:5000"- echo " Frontend: http://localhost:5173"- echo ""-- cd "$BACKEND_DIR"- if [ -f venv/bin/activate ]; then- source venv/bin/activate- fi- python run.py &- BACKEND_PID=$!-- sleep 2-- cd "$FRONTEND_DIR"- npm run dev &- FRONTEND_PID=$!-- cleanup() {- echo ""- echo -e "${YELLOW}Stopping...${NC}"- kill "$BACKEND_PID" "$FRONTEND_PID" 2>/dev/null || true- wait "$BACKEND_PID" "$FRONTEND_PID" 2>/dev/null || true- echo "Stopped."- }- trap cleanup INT TERM-- echo -e "${DIM}Press Ctrl+C to stop...${NC}"- wait-}--start_tunnel() {- if ! command -v ngrok &>/dev/null; then- echo -e "${RED}Error:${NC} ngrok is not installed or not in PATH."- echo ""- echo "Install ngrok:"- echo " - https://ngrok.com/download"- echo " - macOS: brew install ngrok/ngrok/ngrok"- echo " - Linux: snap install ngrok (or download the .tgz)"- echo " - Windows: choco install ngrok (or scoop install ngrok)"- echo ""- echo "Then authenticate once: ngrok config add-authtoken <YOUR_TOKEN>"- exit 1- fi-- echo ""- echo -e "${CYAN}ServerKit Dev Server (with ngrok tunnel)${NC}"- echo " Backend: http://localhost:5000"- echo " Frontend: http://localhost:5173"- echo " Tunnel: exposing backend (port 5000) via ngrok"- echo ""- echo -e "${YELLOW}NOTE:${NC} Agents and remote callers should use the public ngrok URL"- echo " printed below as their --server / control plane URL."- echo ""-- # Allow CORS from any ngrok domain by default unless caller already set it.- export CORS_ORIGINS="${CORS_ORIGINS:-http://localhost:5173,http://localhost:5000,https://*.ngrok-free.app,https://*.ngrok.app,https://*.ngrok.io}"-- cd "$BACKEND_DIR"- if [ -f venv/bin/activate ]; then- source venv/bin/activate- fi- python run.py &- BACKEND_PID=$!-- sleep 2-- cd "$FRONTEND_DIR"- npm run dev &- FRONTEND_PID=$!-- sleep 1-- NGROK_ARGS=(http 5000 --log=stdout)- if [ -n "${NGROK_DOMAIN:-}" ]; then- NGROK_ARGS+=("--domain=$NGROK_DOMAIN")- fi- if [ -n "${NGROK_AUTHTOKEN:-}" ]; then- NGROK_ARGS+=("--authtoken=$NGROK_AUTHTOKEN")- fi-- ngrok "${NGROK_ARGS[@]}" &- NGROK_PID=$!-- # Poll the local ngrok API for the public URL and print it prominently.- (- for _ in $(seq 1 20); do- sleep 1- if command -v curl &>/dev/null; then- URL=$(curl -fsS http://127.0.0.1:4040/api/tunnels 2>/dev/null \- | grep -oE '"public_url":"https://[^"]+' \- | head -n1 \- | sed 's/"public_url":"//')- if [ -n "$URL" ]; then- echo ""- echo -e "${GREEN}=========================================================${NC}"- echo -e "${GREEN} Public tunnel URL: ${NC}${CYAN}$URL${NC}"- echo -e "${GREEN} Use this as your agent --server / control plane URL.${NC}"- echo -e "${GREEN}=========================================================${NC}"- echo ""- break- fi- fi- done- ) &-- cleanup_tunnel() {- echo ""- echo -e "${YELLOW}Stopping...${NC}"- kill "$BACKEND_PID" "$FRONTEND_PID" "$NGROK_PID" 2>/dev/null || true- wait "$BACKEND_PID" "$FRONTEND_PID" "$NGROK_PID" 2>/dev/null || true- echo "Stopped."- }- trap cleanup_tunnel INT TERM-- echo -e "${DIM}Press Ctrl+C to stop...${NC}"- wait-}--run_validate() {- header "ServerKit Validation Suite"- local failed=0- local passed=0-- # --- ESLint (warn-only, does not block) ---- echo -e "${YELLOW}Running ESLint...${NC}"- if (cd "$FRONTEND_DIR" && npm run lint 2>&1); then- pass "ESLint"- ((passed++))- else- echo -e " ${YELLOW}WARN${NC} ESLint (has warnings/errors - run 'cd frontend && npm run lint' for details)"- ((passed++)) # pre-existing issues should not block- fi-- # --- Bandit ---- echo -e "${YELLOW}Running Bandit...${NC}"- if command -v bandit &>/dev/null; then- if bandit -r "$BACKEND_DIR/app" --ini "$BACKEND_DIR/.bandit" --severity-level medium 2>&1; then- pass "Bandit (security scan)"- ((passed++))- else- fail "Bandit (security scan)"- ((failed++))- fi- else- fail "Bandit (not installed — pip install bandit)"- ((failed++))- fi-- # --- Pytest ---- echo -e "${YELLOW}Running Pytest...${NC}"- if (cd "$BACKEND_DIR" && {- [ -f venv/bin/activate ] && source venv/bin/activate- pytest --tb=short -q 2>&1- }); then- pass "Pytest"- ((passed++))- else- fail "Pytest"- ((failed++))- fi-- # --- Frontend build ---- echo -e "${YELLOW}Running Frontend build...${NC}"- if (cd "$FRONTEND_DIR" && npm run build 2>&1); then- pass "Frontend build"- ((passed++))- else- fail "Frontend build"- ((failed++))- fi-- # --- Summary ---- header "Results"- echo -e " ${GREEN}Passed: $passed${NC}"- if [ "$failed" -gt 0 ]; then- echo -e " ${RED}Failed: $failed${NC}"- return 1- else- echo -e " ${GREEN}All checks passed!${NC}"- fi-}--run_validate_watch() {- run_validate || true-- if command -v inotifywait &>/dev/null; then- echo -e "${DIM}Watching for changes... (Ctrl+C to stop)${NC}"- while true; do- inotifywait -r -q -e modify,create,delete \- --include '\.(py|js|jsx|ts|tsx)$' \- "$BACKEND_DIR/app" "$FRONTEND_DIR/src" 2>/dev/null || break- echo -e "\n${YELLOW}Change detected, re-running...${NC}"- sleep 1- run_validate || true- done- else- echo ""- echo -e "${DIM}Install inotify-tools for file watching (apt install inotify-tools).${NC}"- echo -e "${DIM}Running one-shot validation only.${NC}"- fi-}--# --- Main ----MODE="${1:-start}"--case "$MODE" in- backend) start_backend ;;- frontend) start_frontend ;;- tunnel) start_tunnel ;;- validate) run_validate_watch ;;- start|*) start_both ;;-esac+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+exec bash "$SCRIPT_DIR/dev/dev.sh" "$@"diff --git a/dev/dev.sh b/dev/dev.shnew file mode 100644index 00000000..53d01db6--- /dev/null+++ b/dev/dev.sh@@ -0,0 +1,853 @@+#!/usr/bin/env bash+# Unified ServerKit development launcher.+#+# Root wrappers:+# ./dev.sh Linux/WSL/macOS entry point+# .\dev.ps1 Windows entry point, delegates to this script via WSL+#+# Usage:+# ./dev.sh Start backend + frontend on stable non-default ports+# ./dev.sh backend Start backend only+# ./dev.sh frontend Start frontend only, targeting BackendPort for API calls+# ./dev.sh tunnel Start backend + frontend + expose backend via ngrok+# ./dev.sh validate Run checks+#+# Options:+# --backend-port, -BackendPort Pin/prefer a backend port+# --frontend-port, -FrontendPort Pin/prefer a frontend port+# --no-auto-port, -NoAutoPort Fail when a preferred port is busy++set -euo pipefail++DEV_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_ROOT="$(cd "$DEV_DIR/.." && pwd)"+BACKEND_DIR="$PROJECT_ROOT/backend"+FRONTEND_DIR="$PROJECT_ROOT/frontend"+BACKEND_VENV_DIR="${SERVERKIT_BACKEND_VENV:-$BACKEND_DIR/.venv-wsl}"++MODE="start"+MODE_SET=0+BACKEND_PORT="${SERVERKIT_BACKEND_PORT:-47927}"+FRONTEND_PORT="${SERVERKIT_FRONTEND_PORT:-41921}"+FRONTEND_ONLY_DEFAULT_BACKEND_PORT="$BACKEND_PORT"+AUTO_PORT=1+KILL_PORTS="${SERVERKIT_KILL_PORTS:-1}"++CYAN='\033[0;36m'+GREEN='\033[0;32m'+RED='\033[0;31m'+YELLOW='\033[1;33m'+DIM='\033[2m'+NC='\033[0m'++usage() {+ cat <<'EOF'+ServerKit development launcher++Usage:+ ./dev.sh [mode] [options]+ .\dev.ps1 [mode] [options]++Modes:+ start Start backend + frontend (default)+ backend Start backend only+ frontend Start frontend only, targeting BackendPort for API calls+ tunnel Start backend + frontend + ngrok tunnel+ validate Run validation checks++Options:+ --backend-port PORT, -BackendPort PORT Pin/prefer a backend port+ --frontend-port PORT, -FrontendPort PORT Pin/prefer a frontend port+ --no-auto-port, -NoAutoPort Fail if a pinned/preferred port is busy+ -h, --help Show this help++Environment:+ SERVERKIT_BACKEND_PORT Optional pinned/preferred backend port+ SERVERKIT_FRONTEND_PORT Optional pinned/preferred frontend port+ NGROK_DOMAIN Optional reserved ngrok domain+ NGROK_AUTHTOKEN Optional ngrok authtoken+ SERVERKIT_KILL_PORTS=0 Disable startup cleanup of configured dev ports++Defaults:+ ServerKit uses stable non-default local ports: backend 47927, frontend 41921.+ If either port is busy, the launcher moves to the next free nearby port unless+ --no-auto-port is provided.+EOF+}++header() {+ echo+ echo -e "${CYAN}=== $1 ===${NC}"+ echo+}++pass() {+ echo -e " ${GREEN}PASS${NC} $1"+}++fail() {+ echo -e " ${RED}FAIL${NC} $1"+}++die() {+ echo -e "${RED}Error:${NC} $*" >&2+ exit 1+}++python_command_works() {+ local candidate="$1"++ [ -n "$candidate" ] || return 1+ "$candidate" -c 'import sys' >/dev/null 2>&1+}++find_python() {+ local name path++ for name in python3 python; do+ path="$(command -v "$name" 2>/dev/null || true)"+ [ -n "$path" ] || continue++ # WSL can inherit Windows PATH entries. Those shims look executable to+ # Bash but cannot run as Linux interpreters.+ case "$path" in+ /mnt/*) continue ;;+ esac++ if python_command_works "$path"; then+ echo "$path"+ return 0+ fi+ done++ for path in /usr/bin/python3 /usr/local/bin/python3; do+ if [ -x "$path" ] && python_command_works "$path"; then+ echo "$path"+ return 0+ fi+ done++ return 1+}++backend_python() {+ local path++ path="$(command -v python 2>/dev/null || true)"+ if python_command_works "$path"; then+ echo "$path"+ return 0+ fi++ require_python+ echo "$PYTHON_BIN"+}++PYTHON_BIN="$(find_python || true)"++require_python() {+ if [ -z "$PYTHON_BIN" ]; then+ die "python3 or python is required for local development."+ fi+}++validate_port() {+ local name="$1"+ local port="$2"++ if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then+ die "$name port must be between 1 and 65535. Got $port."+ fi+}++validate_optional_port() {+ local name="$1"+ local port="$2"++ if [ -n "$port" ]; then+ validate_port "$name" "$port"+ fi+}++parse_args() {+ while [ "$#" -gt 0 ]; do+ case "$1" in+ start|backend|frontend|tunnel|validate)+ if [ "$MODE_SET" -eq 1 ]; then+ die "Only one mode can be provided."+ fi+ MODE="$1"+ MODE_SET=1+ shift+ ;;+ --backend-port|-BackendPort)+ [ "$#" -ge 2 ] || die "$1 requires a port."+ BACKEND_PORT="$2"+ shift 2+ ;;+ --backend-port=*|-BackendPort=*)+ BACKEND_PORT="${1#*=}"+ shift+ ;;+ --frontend-port|-FrontendPort)+ [ "$#" -ge 2 ] || die "$1 requires a port."+ FRONTEND_PORT="$2"+ shift 2+ ;;+ --frontend-port=*|-FrontendPort=*)+ FRONTEND_PORT="${1#*=}"+ shift+ ;;+ --no-auto-port|-NoAutoPort)+ AUTO_PORT=0+ shift+ ;;+ -h|--help)+ usage+ exit 0+ ;;+ *)+ die "Unknown argument: $1"+ ;;+ esac+ done++ validate_optional_port "Backend" "$BACKEND_PORT"+ validate_optional_port "Frontend" "$FRONTEND_PORT"+}++port_available() {+ local port="$1"+ require_python++ "$PYTHON_BIN" - "$port" <<'PY'+import socket+import sys++port = int(sys.argv[1])+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+try:+ sock.bind(("0.0.0.0", port))+except OSError:+ sys.exit(1)+finally:+ sock.close()+PY+}++is_reserved_port() {+ local candidate="$1"+ shift || true++ local reserved+ for reserved in "$@"; do+ if [ "$candidate" = "$reserved" ]; then+ return 0+ fi+ done+ return 1+}++listener_pids_for_port() {+ local port="$1"++ if command -v ss >/dev/null 2>&1; then+ ss -ltnp 2>/dev/null |+ awk -v suffix=":$port" '$4 ~ suffix "$" { print }' |+ grep -oE 'pid=[0-9]+' |+ cut -d= -f2 |+ sort -u+ elif command -v lsof >/dev/null 2>&1; then+ lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null | sort -u+ fi+}++stop_listeners_on_port() {+ local port="$1"+ local label="$2"++ [ "$KILL_PORTS" = "1" ] || return 0+ [ -n "$port" ] || return 0++ local pids=()+ local pid+ while IFS= read -r pid; do+ [ -n "$pid" ] || continue+ [ "$pid" != "$$" ] || continue+ pids+=("$pid")+ done < <(listener_pids_for_port "$port")++ [ "${#pids[@]}" -gt 0 ] || return 0++ echo -e "${YELLOW}Stopping existing $label listener on port $port: ${pids[*]}${NC}"+ kill "${pids[@]}" 2>/dev/null || true+ sleep 1++ local still_running=()+ for pid in "${pids[@]}"; do+ if kill -0 "$pid" 2>/dev/null; then+ still_running+=("$pid")+ fi+ done++ if [ "${#still_running[@]}" -gt 0 ]; then+ kill -9 "${still_running[@]}" 2>/dev/null || true+ fi+}++RESOLVED_PORT=""+RESOLVED_CHANGED=0++resolve_random_port() {+ local name="$1"+ shift+ local reserved_ports=("$@")+ require_python++ RESOLVED_PORT="$("$PYTHON_BIN" - "${reserved_ports[@]}" <<'PY'+import socket+import sys++reserved = {int(port) for port in sys.argv[1:]}++for _ in range(100):+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ sock.bind(("0.0.0.0", 0))+ port = sock.getsockname()[1]+ finally:+ sock.close()++ if port not in reserved:+ print(port)+ raise SystemExit(0)++raise SystemExit(1)+PY+)" || die "Could not find a random free $name port."++ if is_reserved_port "$RESOLVED_PORT" "${reserved_ports[@]}" || ! port_available "$RESOLVED_PORT"; then+ die "Could not reserve random $name port $RESOLVED_PORT."+ fi++ RESOLVED_CHANGED=0+}++resolve_dev_port() {+ local name="$1"+ local preferred="$2"+ shift 2+ local reserved_ports=("$@")++ if [ -z "$preferred" ]; then+ resolve_random_port "$name" "${reserved_ports[@]}"+ return+ fi++ if ! is_reserved_port "$preferred" "${reserved_ports[@]}" && port_available "$preferred"; then+ RESOLVED_PORT="$preferred"+ RESOLVED_CHANGED=0+ return+ fi++ if [ "$AUTO_PORT" -eq 0 ]; then+ if is_reserved_port "$preferred" "${reserved_ports[@]}"; then+ die "$name port $preferred is already reserved by another local service in this launch."+ fi+ die "$name port $preferred is already in use. Stop the other process or omit --no-auto-port."+ fi++ local upper_bound=$((preferred + 200))+ if [ "$upper_bound" -gt 65535 ]; then+ upper_bound=65535+ fi++ local candidate+ for ((candidate = preferred + 1; candidate <= upper_bound; candidate++)); do+ if is_reserved_port "$candidate" "${reserved_ports[@]}"; then+ continue+ fi+ if port_available "$candidate"; then+ RESOLVED_PORT="$candidate"+ RESOLVED_CHANGED=1+ return+ fi+ done++ die "Could not find a free $name port near $preferred."+}++trim() {+ local value="$1"+ value="${value#"${value%%[![:space:]]*}"}"+ value="${value%"${value##*[![:space:]]}"}"+ printf '%s' "$value"+}++join_unique_csv() {+ local result=()+ local value clean existing++ for value in "$@"; do+ clean="$(trim "$value")"+ [ -n "$clean" ] || continue++ for existing in "${result[@]}"; do+ if [ "$existing" = "$clean" ]; then+ continue 2+ fi+ done+ result+=("$clean")+ done++ local IFS=,+ printf '%s' "${result[*]}"+}++BACKEND_ACTUAL_PORT=""+BACKEND_PORT_CHANGED=0+FRONTEND_ACTUAL_PORT=""+FRONTEND_PORT_CHANGED=0+BACKEND_URL=""+FRONTEND_URL=""+API_URL=""+DEV_CORS_ORIGINS=""++is_wsl() {+ [ -n "${WSL_DISTRO_NAME:-}" ] || grep -qi microsoft /proc/version 2>/dev/null+}++browser_backend_host() {+ if [ -n "${SERVERKIT_BROWSER_BACKEND_HOST:-}" ]; then+ printf '%s' "$SERVERKIT_BROWSER_BACKEND_HOST"+ return+ fi++ if is_wsl; then+ hostname -I 2>/dev/null | awk '{print $1}'+ return+ fi++ printf 'localhost'+}++new_dev_settings() {+ local backend_may_already_be_running="${1:-0}"+ local include_ngrok_origins="${2:-0}"++ if [ "$backend_may_already_be_running" -eq 1 ]; then+ BACKEND_ACTUAL_PORT="${BACKEND_PORT:-$FRONTEND_ONLY_DEFAULT_BACKEND_PORT}"+ BACKEND_PORT_CHANGED=0+ else+ resolve_dev_port "Backend" "$BACKEND_PORT"+ BACKEND_ACTUAL_PORT="$RESOLVED_PORT"+ BACKEND_PORT_CHANGED="$RESOLVED_CHANGED"+ fi++ resolve_dev_port "Frontend" "$FRONTEND_PORT" "$BACKEND_ACTUAL_PORT"+ FRONTEND_ACTUAL_PORT="$RESOLVED_PORT"+ FRONTEND_PORT_CHANGED="$RESOLVED_CHANGED"++ local backend_host+ backend_host="$(browser_backend_host)"+ [ -n "$backend_host" ] || backend_host="localhost"++ BACKEND_URL="http://$backend_host:$BACKEND_ACTUAL_PORT"+ FRONTEND_URL="http://localhost:$FRONTEND_ACTUAL_PORT"+ API_URL="$BACKEND_URL/api/v1"++ local origins=()+ if [ -n "${CORS_ORIGINS:-}" ]; then+ IFS=',' read -r -a origins <<< "$CORS_ORIGINS"+ fi++ origins+=(+ "$FRONTEND_URL"+ "http://127.0.0.1:$FRONTEND_ACTUAL_PORT"+ "$BACKEND_URL"+ "http://localhost:$BACKEND_ACTUAL_PORT"+ "http://127.0.0.1:$BACKEND_ACTUAL_PORT"+ )++ if [ "$include_ngrok_origins" -eq 1 ]; then+ origins+=(+ "https://*.ngrok-free.app"+ "https://*.ngrok.app"+ "https://*.ngrok.io"+ )+ if [ -n "${NGROK_DOMAIN:-}" ]; then+ origins+=("https://$NGROK_DOMAIN")+ fi+ fi++ DEV_CORS_ORIGINS="$(join_unique_csv "${origins[@]}")"+}++export_dev_env() {+ mkdir -p "$BACKEND_DIR/instance"++ export FLASK_ENV=development+ export PORT="$BACKEND_ACTUAL_PORT"+ export DATABASE_URL="sqlite:///$BACKEND_DIR/instance/serverkit.db"+ export CORS_ORIGINS="$DEV_CORS_ORIGINS"+ export VITE_API_URL="$API_URL"+}++write_frontend_env() {+ local env_file="$FRONTEND_DIR/.env.development.local"+ local tmp_file="$env_file.tmp.$$"++ mkdir -p "$FRONTEND_DIR"++ if [ -f "$env_file" ]; then+ awk '+ $0 == "# BEGIN SERVERKIT DEV" { skip = 1; next }+ $0 == "# END SERVERKIT DEV" { skip = 0; next }+ !skip { print }+ ' "$env_file" > "$tmp_file"+ else+ : > "$tmp_file"+ fi++ if [ -s "$tmp_file" ] && [ "$(tail -c 1 "$tmp_file" 2>/dev/null || true)" != "" ]; then+ printf '\n' >> "$tmp_file"+ fi++ cat >> "$tmp_file" <<EOF+# BEGIN SERVERKIT DEV+VITE_API_URL=$API_URL+# END SERVERKIT DEV+EOF++ mv "$tmp_file" "$env_file"+}++print_dev_summary() {+ local title="${1:-ServerKit Dev Server}"++ echo+ echo -e "${CYAN}${title}${NC}"+ echo " Open app: $FRONTEND_URL"+ echo " Backend: $BACKEND_URL"+ echo " Health: $API_URL/system/health"+ echo " API env: VITE_API_URL=$API_URL"++ if [ "$BACKEND_PORT_CHANGED" -eq 1 ]; then+ echo -e " ${YELLOW}Note:${NC} backend port $BACKEND_PORT was busy; using $BACKEND_ACTUAL_PORT."+ fi+ if [ "$FRONTEND_PORT_CHANGED" -eq 1 ]; then+ echo -e " ${YELLOW}Note:${NC} frontend port $FRONTEND_PORT was busy; using $FRONTEND_ACTUAL_PORT."+ fi+ echo+}++activate_backend_venv() {+ local venv_dir++ for venv_dir in "$BACKEND_VENV_DIR" "$BACKEND_DIR/venv" "$BACKEND_DIR/.venv"; do+ if [ -f "$venv_dir/bin/activate" ] && python_command_works "$venv_dir/bin/python"; then+ # shellcheck disable=SC1091+ source "$venv_dir/bin/activate"+ return 0+ fi+ done++ require_python++ echo -e "${YELLOW}Backend WSL virtualenv is missing or not runnable; creating $BACKEND_VENV_DIR${NC}"+ if ! "$PYTHON_BIN" -m venv "$BACKEND_VENV_DIR"; then+ die "Could not create backend venv. In WSL, install venv support with: sudo apt install python3-venv"+ fi++ if [ -f "$BACKEND_VENV_DIR/bin/activate" ]; then+ # shellcheck disable=SC1091+ source "$BACKEND_VENV_DIR/bin/activate"+ else+ die "Backend venv was created but activate script was not found."+ fi+}++ensure_backend_packages() {+ if python_command_works "$(backend_python)" && "$(backend_python)" - <<'PY' >/dev/null 2>&1+import dotenv+import flask+import flask_socketio+import sqlalchemy+PY+ then+ return 0+ fi++ echo -e "${YELLOW}Installing backend Python dependencies in WSL venv...${NC}"+ "$(backend_python)" -m pip install --upgrade pip+ "$(backend_python)" -m pip install -r "$BACKEND_DIR/requirements.txt"+}++start_backend_process() {+ export_dev_env+ cd "$BACKEND_DIR"+ activate_backend_venv+ ensure_backend_packages+ "$(backend_python)" run.py+}++start_frontend_process() {+ export_dev_env+ write_frontend_env+ cd "$FRONTEND_DIR"+ npm run dev -- --host 127.0.0.1 --port "$FRONTEND_ACTUAL_PORT" --strictPort+}++start_backend() {+ stop_listeners_on_port "$BACKEND_PORT" "backend"+ new_dev_settings 0 0+ header "Starting Backend ($BACKEND_URL)"+ start_backend_process+}++start_frontend() {+ stop_listeners_on_port "$FRONTEND_PORT" "frontend"+ new_dev_settings 1 0+ header "Starting Frontend ($FRONTEND_URL)"+ echo " API target: $API_URL"+ if [ "$FRONTEND_PORT_CHANGED" -eq 1 ]; then+ echo -e " ${YELLOW}Note:${NC} frontend port $FRONTEND_PORT was busy; using $FRONTEND_ACTUAL_PORT."+ fi+ echo+ start_frontend_process+}++cleanup_pids() {+ local pid+ for pid in "$@"; do+ if [ -n "${pid:-}" ]; then+ kill "$pid" 2>/dev/null || true+ fi+ done+ for pid in "$@"; do+ if [ -n "${pid:-}" ]; then+ wait "$pid" 2>/dev/null || true+ fi+ done+}++wait_for_first_exit() {+ if help wait 2>/dev/null | grep -q -- '-n'; then+ set +e+ wait -n "$@"+ local status=$?+ set -e+ return "$status"+ fi++ local pid running+ while true; do+ running="$(jobs -pr)"+ for pid in "$@"; do+ if ! printf '%s\n' "$running" | grep -qx "$pid"; then+ set +e+ wait "$pid" 2>/dev/null+ local status=$?+ set -e+ return "$status"+ fi+ done+ sleep 1+ done+}++start_both() {+ stop_listeners_on_port "$BACKEND_PORT" "backend"+ stop_listeners_on_port "$FRONTEND_PORT" "frontend"+ new_dev_settings 0 0+ print_dev_summary++ start_backend_process &+ local backend_pid=$!++ sleep 2++ start_frontend_process &+ local frontend_pid=$!++ trap 'echo; echo -e "${YELLOW}Stopping...${NC}"; cleanup_pids "$backend_pid" "$frontend_pid"; echo "Stopped."; exit 0' INT TERM++ echo -e "${DIM}Press Ctrl+C to stop...${NC}"+ set +e+ wait_for_first_exit "$backend_pid" "$frontend_pid"+ local status=$?+ set -e++ echo+ echo -e "${YELLOW}One dev process stopped; shutting down the rest.${NC}"+ cleanup_pids "$backend_pid" "$frontend_pid"+ return "$status"+}++start_tunnel() {+ if ! command -v ngrok >/dev/null 2>&1; then+ echo -e "${RED}Error:${NC} ngrok is not installed or not in PATH."+ echo+ echo "Install ngrok:"+ echo " - https://ngrok.com/download"+ echo " - Windows: choco install ngrok (or scoop install ngrok)"+ echo " - WSL/Linux: snap install ngrok (or download the .tgz)"+ echo+ echo "Then authenticate once: ngrok config add-authtoken <YOUR_TOKEN>"+ exit 1+ fi++ stop_listeners_on_port "$BACKEND_PORT" "backend"+ stop_listeners_on_port "$FRONTEND_PORT" "frontend"+ new_dev_settings 0 1+ print_dev_summary "ServerKit Dev Server (with ngrok tunnel)"+ echo " Tunnel: exposing backend port $BACKEND_ACTUAL_PORT via ngrok"+ echo+ echo -e "${YELLOW}NOTE:${NC} Agents and remote callers should use the public ngrok URL"+ echo " printed below as their --server / control plane URL."+ echo++ start_backend_process &+ local backend_pid=$!++ sleep 2++ start_frontend_process &+ local frontend_pid=$!++ sleep 1++ local ngrok_args=(http "$BACKEND_ACTUAL_PORT" --log=stdout)+ if [ -n "${NGROK_DOMAIN:-}" ]; then+ ngrok_args+=("--domain=$NGROK_DOMAIN")+ fi+ if [ -n "${NGROK_AUTHTOKEN:-}" ]; then+ ngrok_args+=("--authtoken=$NGROK_AUTHTOKEN")+ fi++ ngrok "${ngrok_args[@]}" &+ local ngrok_pid=$!++ (+ local url+ for _ in $(seq 1 30); do+ sleep 1+ if command -v curl >/dev/null 2>&1; then+ url="$(curl -fsS http://127.0.0.1:4040/api/tunnels 2>/dev/null \+ | grep -oE '"public_url":"https://[^"]+' \+ | head -n1 \+ | sed 's/"public_url":"//')" || true+ if [ -n "$url" ]; then+ echo+ echo -e "${GREEN}=========================================================${NC}"+ echo -e "${GREEN} Public tunnel URL: ${NC}${CYAN}$url${NC}"+ echo -e "${GREEN} Use this as your agent --server / control plane URL.${NC}"+ echo -e "${GREEN}=========================================================${NC}"+ echo+ break+ fi+ fi+ done+ ) &+ local poll_pid=$!++ trap 'echo; echo -e "${YELLOW}Stopping...${NC}"; cleanup_pids "$backend_pid" "$frontend_pid" "$ngrok_pid" "$poll_pid"; echo "Stopped."; exit 0' INT TERM++ echo -e "${DIM}Press Ctrl+C to stop...${NC}"+ set +e+ wait_for_first_exit "$backend_pid" "$frontend_pid" "$ngrok_pid"+ local status=$?+ set -e++ echo+ echo -e "${YELLOW}One tunnel process stopped; shutting down the rest.${NC}"+ cleanup_pids "$backend_pid" "$frontend_pid" "$ngrok_pid" "$poll_pid"+ return "$status"+}++run_validate() {+ header "ServerKit Validation Suite"+ local failed=0+ local passed=0++ echo -e "${YELLOW}Running ESLint...${NC}"+ if (cd "$FRONTEND_DIR" && npm run lint 2>&1); then+ pass "ESLint"+ passed=$((passed + 1))+ else+ echo -e " ${YELLOW}WARN${NC} ESLint (has warnings/errors - run 'cd frontend && npm run lint' for details)"+ passed=$((passed + 1))+ fi++ echo -e "${YELLOW}Running Bandit...${NC}"+ if command -v bandit >/dev/null 2>&1; then+ if bandit -r "$BACKEND_DIR/app" --ini "$BACKEND_DIR/.bandit" --severity-level medium 2>&1; then+ pass "Bandit (security scan)"+ passed=$((passed + 1))+ else+ fail "Bandit (security scan)"+ failed=$((failed + 1))+ fi+ else+ fail "Bandit (not installed - pip install bandit)"+ failed=$((failed + 1))+ fi++ echo -e "${YELLOW}Running Pytest...${NC}"+ if (cd "$BACKEND_DIR" && activate_backend_venv && pytest --tb=short -q 2>&1); then+ pass "Pytest"+ passed=$((passed + 1))+ else+ fail "Pytest"+ failed=$((failed + 1))+ fi++ echo -e "${YELLOW}Running Frontend build...${NC}"+ if (cd "$FRONTEND_DIR" && npm run build 2>&1); then+ pass "Frontend build"+ passed=$((passed + 1))+ else+ fail "Frontend build"+ failed=$((failed + 1))+ fi++ header "Results"+ echo -e " ${GREEN}Passed: $passed${NC}"+ if [ "$failed" -gt 0 ]; then+ echo -e " ${RED}Failed: $failed${NC}"+ return 1+ fi++ echo -e " ${GREEN}All checks passed!${NC}"+}++run_validate_watch() {+ run_validate || true++ if command -v inotifywait >/dev/null 2>&1; then+ echo -e "${DIM}Watching for changes... (Ctrl+C to stop)${NC}"+ while true; do+ inotifywait -r -q -e modify,create,delete \+ --include '\.(py|js|jsx|ts|tsx)$' \+ "$BACKEND_DIR/app" "$FRONTEND_DIR/src" 2>/dev/null || break+ echo -e "\n${YELLOW}Change detected, re-running...${NC}"+ sleep 1+ run_validate || true+ done+ else+ echo+ echo -e "${DIM}Install inotify-tools for file watching. Running one-shot validation only.${NC}"+ fi+}++parse_args "$@"++case "$MODE" in+ backend) start_backend ;;+ frontend) start_frontend ;;+ tunnel) start_tunnel ;;+ validate) run_validate_watch ;;+ start) start_both ;;+ *) die "Unknown mode: $MODE" ;;+esacdiff --git a/docs/README.es.md b/docs/README.es.mdindex 64eb8197..55b92122 100644--- a/docs/README.es.md+++ b/docs/README.es.md@@ -247,7 +247,7 @@ Detalles completos: [ROADMAP.md](../ROADMAP.md)| Capa | Tecnología ||-------|------------|| Backend | Python 3.11, Flask, SQLAlchemy, Flask-SocketIO |-| Frontend | React 18, Vite, LESS |+| Frontend | React 18, Vite, SCSS || Base de Datos | SQLite / PostgreSQL || Servidor Web | Nginx, Gunicorn || Contenedores | Docker, Docker Compose |diff --git a/docs/README.pt.md b/docs/README.pt.mdindex 5e9e2133..97dd7780 100644--- a/docs/README.pt.md+++ b/docs/README.pt.md@@ -247,7 +247,7 @@ Detalhes completos: [ROADMAP.md](../ROADMAP.md)| Camada | Tecnologia ||-------|------------|| Backend | Python 3.11, Flask, SQLAlchemy, Flask-SocketIO |-| Frontend | React 18, Vite, LESS |+| Frontend | React 18, Vite, SCSS || Banco de Dados | SQLite / PostgreSQL || Servidor Web | Nginx, Gunicorn || Containers | Docker, Docker Compose |diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdindex 8b35f24c..db21b86c 100644--- a/docs/README.zh-CN.md+++ b/docs/README.zh-CN.md@@ -247,7 +247,7 @@ docker compose up -d # 访问 http://localhost| 层级 | 技术 ||-------|------------|| 后端 | Python 3.11, Flask, SQLAlchemy, Flask-SocketIO |-| 前端 | React 18, Vite, LESS |+| 前端 | React 18, Vite, SCSS || 数据库 | SQLite / PostgreSQL || Web 服务器 | Nginx, Gunicorn || 容器 | Docker, Docker Compose |diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 855bb40d..f6dcbf08 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -50,6 +50,8 @@ import StatusPages from './pages/StatusPages';import CloudProvision from './pages/CloudProvision';import Marketplace from './pages/Marketplace';import StyleGuide from './pages/StyleGuide';+import AppMap from './pages/AppMap';+import Documentation from './pages/Documentation';import Deployments from './pages/Deployments';// Page title mapping@@ -92,6 +94,8 @@ const PAGE_TITLES = {'/cloud': 'Cloud Provisioning','/marketplace': 'Marketplace','/style-guide': 'Style Guide',+ '/app-map': 'App Map',+ '/documentation': 'Documentation',};function PageTitleUpdater() {@@ -239,6 +243,9 @@ function AppRoutes() {<Route path="marketplace" element={<Marketplace />} /><Route path="style-guide" element={<StyleGuide />} /><Route path="style-guide/:tab" element={<StyleGuide />} />+ <Route path="app-map" element={<AppMap />} />+ <Route path="app-map/:tab" element={<AppMap />} />+ <Route path="documentation" element={<Documentation />} /><Route path="downloads" element={<Downloads />} /><Route path="firewall" element={<Navigate to="/security/firewall" replace />} /><Route path="git" element={<Git />} />diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex 04713744..4f828664 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -242,11 +242,32 @@ const Sidebar = () => {{import.meta.env.DEV && (<>- <div className="nav-category">Dev Tools</div>+ <div className="nav-category nav-category--dev">Dev Tools</div><nav className="nav">+ <NavLink+ to="/app-map"+ className={({ isActive }) => `nav-item nav-item--dev ${isActive ? 'active' : ''}`}+ >+ <svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/>+ <line x1="8" y1="2" x2="8" y2="18"/>+ <line x1="16" y1="6" x2="16" y2="22"/>+ </svg>+ App Map+ </NavLink>+ <NavLink+ to="/documentation"+ className={({ isActive }) => `nav-item nav-item--dev ${isActive ? 'active' : ''}`}+ >+ <svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>+ <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>+ </svg>+ Documentation+ </NavLink><NavLinkto="/style-guide"- className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}+ className={({ isActive }) => `nav-item nav-item--dev ${isActive ? 'active' : ''}`}><svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="13.5" cy="6.5" r="2.5"/><path d="M17 2H7a5 5 0 0 0-5 5v10a5 5 0 0 0 5 5h10a5 5 0 0 0 5-5V7a5 5 0 0 0-5-5z"/><path d="M9.5 14.5l-3 3"/><path d="M14.5 9.5l3-3"/>diff --git a/frontend/src/components/StatusBadge.jsx b/frontend/src/components/StatusBadge.jsxindex 4ca4af27..7303c02f 100644--- a/frontend/src/components/StatusBadge.jsx+++ b/frontend/src/components/StatusBadge.jsx@@ -13,7 +13,7 @@ const STATUS_VARIANT = {const DOT_COLOR = {success: 'bg-green-400',- destructive: 'bg-red-400',+ destructive: 'bg-white',warning: 'bg-yellow-400',info: 'bg-blue-400',secondary: 'bg-muted-foreground/60',diff --git a/frontend/src/components/file-manager/ContextMenu.jsx b/frontend/src/components/file-manager/ContextMenu.jsxindex 5a111ce4..b480fb86 100644--- a/frontend/src/components/file-manager/ContextMenu.jsx+++ b/frontend/src/components/file-manager/ContextMenu.jsx@@ -1,18 +1,16 @@import {- Folder, Eye, Download, Edit3, Lock, Copy, Star, StarOff, Trash2,+ Folder, Eye, Download, Edit3, Lock, Copy, Trash2,} from 'lucide-react';export default function ContextMenu({menu, // { x, y, entry }selectionCount, // total items selected- isPinned,onClose,onOpen,onDownload,onRename,onPermissions,onCopyPath,- onTogglePin,onDelete,}) {if (!menu) return null;@@ -43,13 +41,6 @@ export default function ContextMenu({<button onClick={() => { onCopyPath(entry.path); onClose(); }}><Copy size={14} /> Copy path</button>- {entry.is_dir && (- <button onClick={() => { onTogglePin(entry); onClose(); }}>- {isPinned(entry.path)- ? <><StarOff size={14} /> Unpin</>- : <><Star size={14} /> Pin to Quick Access</>}- </button>- )}<div className="context-menu-divider" /><button className="danger" onClick={() => { onDelete(entry); onClose(); }}><Trash2 size={14} /> Delete{multi ? ` ${selectionCount} items` : ''}diff --git a/frontend/src/pages/AppMap.jsx b/frontend/src/pages/AppMap.jsxnew file mode 100644index 00000000..4cff335b--- /dev/null+++ b/frontend/src/pages/AppMap.jsx@@ -0,0 +1,343 @@+import React, { useMemo, useState } from 'react';+import {+ ReactFlow,+ ReactFlowProvider,+ Background,+ Controls,+ MiniMap,+ MarkerType,+} from '@xyflow/react';+import '@xyflow/react/dist/style.css';+import {+ Map as MapIcon, Layers, Compass, Network, Info,+} from 'lucide-react';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import useTabParam from '../hooks/useTabParam';++const VIEWS = [+ {+ id: 'stack',+ label: 'Request Stack',+ icon: Layers,+ description: 'How a request flows from the browser through the frontend, backend, services and database.',+ },+ {+ id: 'routes',+ label: 'Routes & APIs',+ icon: Compass,+ description: 'Sidebar navigation → pages → backend API blueprints they call.',+ },+ {+ id: 'topology',+ label: 'Runtime Topology',+ icon: Network,+ description: 'How the panel connects to servers, agents, services and apps in production.',+ },+];++// ─── shared node styling ────────────────────────────────────────────────────+const nodeBase = {+ border: '1px solid var(--border-default)',+ borderRadius: 10,+ padding: '10px 14px',+ fontSize: 12,+ fontWeight: 500,+ color: 'var(--text-primary)',+ background: 'var(--bg-card)',+ boxShadow: '0 1px 2px rgba(0,0,0,0.04)',+ minWidth: 150,+ textAlign: 'center',+};+const tone = (bg, border, color) => ({ background: bg, borderColor: border, color });++const STYLES = {+ client: tone('rgba(99,102,241,0.10)', 'rgba(99,102,241,0.45)', 'var(--text-primary)'),+ frontend: tone('rgba(59,130,246,0.10)', 'rgba(59,130,246,0.40)', 'var(--text-primary)'),+ backend: tone('rgba(16,185,129,0.10)', 'rgba(16,185,129,0.40)', 'var(--text-primary)'),+ service: tone('rgba(245,158,11,0.10)', 'rgba(245,158,11,0.40)', 'var(--text-primary)'),+ data: tone('rgba(168,85,247,0.10)', 'rgba(168,85,247,0.40)', 'var(--text-primary)'),+ infra: tone('rgba(236,72,153,0.10)', 'rgba(236,72,153,0.40)', 'var(--text-primary)'),+ agent: tone('rgba(20,184,166,0.10)', 'rgba(20,184,166,0.40)', 'var(--text-primary)'),+};++const mk = (id, label, x, y, kind, sub) => ({+ id,+ position: { x, y },+ data: { label: sub ? (+ <div>+ <div style={{ fontWeight: 600 }}>{label}</div>+ <div style={{ fontSize: 10.5, opacity: 0.7, marginTop: 2 }}>{sub}</div>+ </div>+ ) : label },+ style: { ...nodeBase, ...STYLES[kind] },+});++const edge = (id, source, target, label, animated = false) => ({+ id,+ source,+ target,+ label,+ animated,+ type: 'smoothstep',+ style: { stroke: 'var(--border-default)', strokeWidth: 1.5 },+ labelStyle: { fontSize: 10, fill: 'var(--text-secondary)' },+ labelBgStyle: { fill: 'var(--bg-card)' },+ markerEnd: { type: MarkerType.ArrowClosed, color: 'var(--border-default)' },+});++// ─── 1. Request stack view ──────────────────────────────────────────────────+function buildStackGraph() {+ const nodes = [+ mk('browser', 'Browser', 360, 0, 'client', 'User session, cookies, JWT'),+ mk('nginx', 'Nginx', 360, 90, 'infra', 'TLS, reverse proxy, static'),+ mk('vite', 'Vite Dev Server', 80, 90, 'frontend', 'HMR (dev only)'),+ mk('react', 'React SPA', 360, 180, 'frontend', 'pages/, components/, contexts/'),+ mk('api-svc', 'ApiService', 360, 270, 'frontend', 'frontend/src/services/api.js'),+ mk('socket', 'Socket.IO Client', 660, 270, 'frontend', 'metrics, logs, terminal'),+ mk('flask', 'Flask App', 360, 380, 'backend', 'create_app(), JWT middleware'),+ mk('blueprints', 'API Blueprints', 360, 470, 'backend', 'app/api/* (60+ files)'),+ mk('sockio', 'Socket Handlers', 660, 470, 'backend', 'app/sockets.py'),+ mk('services', 'Service Layer', 360, 570, 'service', 'app/services/* (stateless)'),+ mk('models', 'SQLAlchemy Models', 180, 670, 'data', 'app/models/*'),+ mk('agentgw', 'Agent Gateway', 560, 670, 'agent', 'app/agent_gateway.py'),+ mk('db', 'SQLite / PostgreSQL', 180, 760, 'data'),+ mk('shell', 'Shell / Docker / FS', 360, 760, 'infra', 'subprocess, docker SDK'),+ mk('agents', 'Remote Agents', 560, 760, 'agent', 'managed servers'),+ ];+ const edges = [+ edge('e1', 'browser', 'nginx', 'HTTPS'),+ edge('e2', 'nginx', 'react', 'static'),+ edge('e3', 'browser', 'vite', 'dev'),+ edge('e4', 'react', 'api-svc'),+ edge('e5', 'react', 'socket'),+ edge('e6', 'api-svc', 'flask', '/api/v1/*', true),+ edge('e7', 'socket', 'sockio', 'WebSocket', true),+ edge('e8', 'flask', 'blueprints'),+ edge('e9', 'blueprints', 'services'),+ edge('e10', 'sockio', 'services'),+ edge('e11', 'services', 'models'),+ edge('e12', 'services', 'shell'),+ edge('e13', 'services', 'agentgw'),+ edge('e14', 'models', 'db'),+ edge('e15', 'agentgw', 'agents', 'mTLS'),+ ];+ return { nodes, edges };+}++// ─── 2. Routes & APIs view ──────────────────────────────────────────────────+const ROUTE_MAP = [+ ['Dashboard', '/', ['system', 'metrics', 'monitoring']],+ ['Servers', '/servers', ['servers', 'fleet']],+ ['Agent Fleet', '/fleet', ['fleet', 'pairing']],+ ['Cloud', '/cloud', ['cloud']],+ ['Domains', '/domains', ['domains', 'nginx']],+ ['DNS Zones', '/dns', ['dns']],+ ['SSL', '/ssl', ['ssl', 'ssl/advanced']],+ ['Services', '/services', ['apps', 'templates']],+ ['Deployments', '/deployments', ['deploy', 'deployment-jobs', 'builds']],+ ['Workflow', '/workflow', ['workflows']],+ ['WordPress', '/wordpress', ['wordpress']],+ ['Databases', '/databases', ['databases']],+ ['Docker', '/docker', ['docker']],+ ['Files', '/files', ['files']],+ ['Git', '/git', ['git']],+ ['Backups', '/backups', ['backups']],+ ['Monitoring', '/monitoring', ['monitoring', 'metrics', 'logs']],+ ['Cron', '/cron', ['cron']],+ ['Security', '/security', ['security', 'firewall']],+ ['Email', '/email', ['email']],+ ['Terminal', '/terminal', ['(socket)']],+ ['Settings', '/settings', ['auth', 'admin', 'api-keys', 'sso']],+];++function buildRoutesGraph() {+ const nodes = [];+ const edges = [];+ nodes.push(mk('sidebar', 'Sidebar Nav', 0, 360, 'frontend', 'frontend/src/components/Sidebar.jsx'));+ nodes.push(mk('apisvc', 'ApiService', 740, 360, 'frontend', 'frontend/src/services/api.js'));++ const apiSet = new Map();+ ROUTE_MAP.forEach(([label, route, apis], i) => {+ const y = i * 60;+ const pid = `p-${route}`;+ nodes.push(mk(pid, label, 320, y, 'frontend', route));+ edges.push(edge(`s-${pid}`, 'sidebar', pid));+ edges.push(edge(`pa-${pid}`, pid, 'apisvc'));+ apis.forEach(api => {+ const key = api;+ if (!apiSet.has(key)) {+ apiSet.set(key, { y: apiSet.size * 38 });+ }+ });+ });++ let i = 0;+ apiSet.forEach((_, key) => {+ const aid = `a-${key}`;+ nodes.push(mk(aid, key === '(socket)' ? 'Socket.IO' : `/api/v1/${key}`, 1100, i * 38, 'backend'));+ ROUTE_MAP.forEach(([, route, apis]) => {+ if (apis.includes(key)) {+ edges.push(edge(`api-${route}-${key}`, 'apisvc', aid));+ }+ });+ i++;+ });++ // Dedupe ApiService→endpoint edges+ const seen = new Set();+ const filtered = edges.filter(e => {+ const k = `${e.source}->${e.target}`;+ if (seen.has(k)) return false;+ seen.add(k);+ return true;+ });+ return { nodes, edges: filtered };+}++// ─── 3. Runtime topology view ───────────────────────────────────────────────+function buildTopologyGraph() {+ const nodes = [+ mk('user', 'Operator', 0, 200, 'client', 'Browser / Mobile'),+ mk('panel', 'ServerKit Panel', 240, 200, 'backend', 'Flask + Socket.IO'),+ mk('paneldb', 'Panel DB', 240, 320, 'data', 'SQLite / Postgres'),+ mk('gateway', 'Agent Gateway', 480, 200, 'agent', 'mTLS / WebSocket'),++ mk('srv1', 'Server: prod-web-01', 760, 40, 'infra', 'Linux VPS'),+ mk('srv2', 'Server: db-01', 760, 200, 'infra', 'Linux VPS'),+ mk('srv3', 'Server: edge-cloud', 760, 360, 'infra', 'Cloud-provisioned'),++ mk('ag1', 'serverkit-agent', 1020, 40, 'agent'),+ mk('ag2', 'serverkit-agent', 1020, 200, 'agent'),+ mk('ag3', 'serverkit-agent', 1020, 360, 'agent'),++ mk('app1', 'Nginx + PHP-FPM', 1280, -20, 'service', 'WordPress site'),+ mk('app2', 'Docker containers', 1280, 60, 'service', 'app:8001-8999'),+ mk('app3', 'PostgreSQL', 1280, 180, 'data'),+ mk('app4', 'Redis', 1280, 240, 'data'),+ mk('app5', 'Custom workload', 1280, 360, 'service'),++ mk('cloud', 'Cloud Providers', 480, 360, 'infra', 'Hetzner / DO / AWS'),+ ];+ const edges = [+ edge('t1', 'user', 'panel', 'HTTPS', true),+ edge('t2', 'panel', 'paneldb'),+ edge('t3', 'panel', 'gateway'),+ edge('t4', 'gateway', 'srv1', 'mTLS', true),+ edge('t5', 'gateway', 'srv2', 'mTLS', true),+ edge('t6', 'gateway', 'srv3', 'mTLS', true),+ edge('t7', 'srv1', 'ag1'),+ edge('t8', 'srv2', 'ag2'),+ edge('t9', 'srv3', 'ag3'),+ edge('t10', 'ag1', 'app1'),+ edge('t11', 'ag1', 'app2'),+ edge('t12', 'ag2', 'app3'),+ edge('t13', 'ag2', 'app4'),+ edge('t14', 'ag3', 'app5'),+ edge('t15', 'panel', 'cloud', 'provision API'),+ edge('t16', 'cloud', 'srv3', 'spawns'),+ ];+ return { nodes, edges };+}++const GRAPHS = {+ stack: buildStackGraph,+ routes: buildRoutesGraph,+ topology: buildTopologyGraph,+};++const LEGEND = [+ ['Client / Browser', 'client'],+ ['Frontend (React)', 'frontend'],+ ['Backend (Flask)', 'backend'],+ ['Service layer', 'service'],+ ['Data / Models', 'data'],+ ['Infrastructure', 'infra'],+ ['Agents', 'agent'],+];++function Diagram({ viewId }) {+ const { nodes, edges } = useMemo(() => GRAPHS[viewId](), [viewId]);+ return (+ <ReactFlow+ nodes={nodes}+ edges={edges}+ fitView+ fitViewOptions={{ padding: 0.15 }}+ proOptions={{ hideAttribution: true }}+ nodesDraggable+ nodesConnectable={false}+ elementsSelectable+ minZoom={0.2}+ maxZoom={1.5}+ >+ <Background gap={18} size={1} color="var(--border-subtle)" />+ <MiniMap pannable zoomable style={{ background: 'var(--bg-elevated)' }} />+ <Controls showInteractive={false} />+ </ReactFlow>+ );+}++export default function AppMap() {+ const [activeView, setActiveView] = useTabParam('/app-map', VIEWS.map(v => v.id), 'stack');+ const [showLegend, setShowLegend] = useState(true);+ const view = VIEWS.find(v => v.id === activeView) || VIEWS[0];++ return (+ <div className="app-map">+ <div className="page-header">+ <div>+ <h1>+ <MapIcon size={22} style={{ verticalAlign: '-4px', marginRight: 8 }} />+ App Map+ </h1>+ <p className="subtitle">+ Visual map of how the panel is wired together — dev only+ </p>+ </div>+ </div>++ <Tabs value={activeView} onValueChange={setActiveView}>+ <TabsList>+ {VIEWS.map(v => (+ <TabsTrigger key={v.id} value={v.id}>+ <v.icon size={14} />+ {v.label}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>++ <div className="app-map__viewmeta">+ <Info size={14} />+ <span>{view.description}</span>+ <button+ type="button"+ className="app-map__legend-toggle"+ onClick={() => setShowLegend(s => !s)}+ >+ {showLegend ? 'Hide legend' : 'Show legend'}+ </button>+ </div>++ {showLegend && (+ <div className="app-map__legend">+ {LEGEND.map(([label, kind]) => (+ <span key={kind} className="app-map__legend-item">+ <span className="app-map__legend-swatch" style={{+ background: STYLES[kind].background,+ borderColor: STYLES[kind].borderColor,+ }} />+ {label}+ </span>+ ))}+ </div>+ )}++ <div className="app-map__canvas">+ <ReactFlowProvider>+ <Diagram viewId={activeView} />+ </ReactFlowProvider>+ </div>+ </div>+ );+}diff --git a/frontend/src/pages/Deployments.jsx b/frontend/src/pages/Deployments.jsxindex 1c7c333c..662ee266 100644--- a/frontend/src/pages/Deployments.jsx+++ b/frontend/src/pages/Deployments.jsx@@ -1,4 +1,4 @@-import React, { useState, useEffect, useRef, useMemo } from 'react';+import { useState, useEffect, useRef, useMemo } from 'react';import {Activity,CheckCircle2,@@ -11,7 +11,6 @@ import {PlayCircle,} from 'lucide-react';import api from '../services/api';-import { useToast } from '../contexts/ToastContext';import { Button } from '@/components/ui/button';const STATUS_COLORS = {@@ -43,28 +42,14 @@ const StatusBadge = ({ status }) => {const Icon = cfg.icon;const spin = status === 'running';return (- <span- style={{- display: 'inline-flex',- alignItems: 'center',- gap: 6,- padding: '4px 10px',- borderRadius: 999,- background: cfg.bg,- color: cfg.fg,- fontSize: 12,- fontWeight: 600,- textTransform: 'capitalize',- }}- >- <Icon size={14} className={spin ? 'spin' : ''} />+ <span className="deployments-page__status-badge" style={{ background: cfg.bg, color: cfg.fg }}>+ <Icon size={14} className={spin ? 'deployments-page__spin' : ''} />{status}</span>);};const Deployments = () => {- const toast = useToast();const [jobs, setJobs] = useState([]);const [loading, setLoading] = useState(true);const [statusFilter, setStatusFilter] = useState('all');@@ -147,18 +132,18 @@ const Deployments = () => {}, [jobs]);return (- <div className="page-container">- <div className="page-header">- <div>+ <div className="page-container deployments-page">+ <div className="page-header deployments-page__header">+ <div className="deployments-page__heading"><h1 className="page-title">- <Activity size={24} style={{ marginRight: 8, verticalAlign: 'middle' }} />+ <Activity size={22} />Deployments</h1>- <p className="page-description">+ <p className="deployments-page__description">Track deployment jobs across all servers — see real-time status, step-by-step progress, and logs.</p></div>- <div style={{ display: 'flex', gap: 8 }}>+ <div className="deployments-page__actions"><Buttonvariant={autoRefresh ? 'default' : 'outline'}onClick={() => setAutoRefresh((v) => !v)}@@ -173,14 +158,7 @@ const Deployments = () => {</div></div>- <div- style={{- display: 'grid',- gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',- gap: 12,- marginBottom: 16,- }}- >+ <div className="deployments-page__summary">{[{ label: 'Running', value: summary.running, icon: Loader2, color: '#6366f1' },{ label: 'Succeeded', value: summary.succeeded, icon: CheckCircle2, color: '#22c55e' },@@ -189,22 +167,20 @@ const Deployments = () => {].map((s) => {const Icon = s.icon;return (- <div key={s.label} className="card" style={{ padding: 16 }}>- <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>- <Icon size={20} style={{ color: s.color }} />- <div>- <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{s.label}</div>- <div style={{ fontSize: 22, fontWeight: 700 }}>{s.value}</div>- </div>+ <div key={s.label} className="deployments-page__stat-card">+ <Icon size={18} style={{ color: s.color }} />+ <div>+ <div className="deployments-page__stat-label">{s.label}</div>+ <div className="deployments-page__stat-value">{s.value}</div></div></div>);})}</div>- <div className="card" style={{ padding: 16, marginBottom: 16, display: 'flex', gap: 12, flexWrap: 'wrap' }}>- <div>- <label style={{ fontSize: 12, color: 'var(--text-secondary)', display: 'block' }}>Status</label>+ <div className="deployments-page__toolbar">+ <div className="deployments-page__filter">+ <label>Status</label><select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}><option value="all">All</option><option value="pending">Pending</option>@@ -213,8 +189,8 @@ const Deployments = () => {<option value="failed">Failed</option></select></div>- <div>- <label style={{ fontSize: 12, color: 'var(--text-secondary)', display: 'block' }}>Target server</label>+ <div className="deployments-page__filter">+ <label>Target server</label><select value={serverFilter} onChange={(e) => setServerFilter(e.target.value)}><option value="all">All servers</option>{servers.map((s) => (@@ -226,20 +202,26 @@ const Deployments = () => {</div></div>- <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.2fr)', gap: 16 }}>- <div className="card" style={{ padding: 0, overflow: 'hidden' }}>+ <div className="deployments-page__workspace">+ <div className="deployments-page__panel deployments-page__jobs-panel">+ <div className="deployments-page__panel-header">+ <div>+ <h2>Jobs</h2>+ <span>{jobs.length} visible</span>+ </div>+ </div>{loading ? (- <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-secondary)' }}>Loading…</div>+ <div className="deployments-page__empty">Loading...</div>) : jobs.length === 0 ? (- <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-secondary)' }}>- <PlayCircle size={32} style={{ marginBottom: 8, opacity: 0.5 }} />- <div>No deployment jobs yet.</div>- <div style={{ fontSize: 13, marginTop: 4 }}>+ <div className="deployments-page__empty">+ <PlayCircle size={34} />+ <strong>No deployment jobs yet</strong>+ <span>Install a template or trigger a deploy to see it here.- </div>+ </span></div>) : (- <table className="data-table" style={{ width: '100%' }}>+ <table className="deployments-page__jobs-table"><thead><tr><th>Status</th>@@ -255,43 +237,32 @@ const Deployments = () => {<trkey={job.id}onClick={() => setSelectedJob(job.id)}- style={{- cursor: 'pointer',- background: selectedJob === job.id ? 'var(--accent-glow)' : 'transparent',- }}+ className={selectedJob === job.id ? 'is-selected' : ''}><td><StatusBadge status={job.status} /></td><td>{job.kind}</td><td>- <Server size={12} style={{ marginRight: 4, verticalAlign: 'middle' }} />- {job.target_server_name || 'Local server'}+ <span className="deployments-page__server-cell">+ <Server size={12} />+ {job.target_server_name || 'Local server'}+ </span></td><td>{job.app_name || '—'}</td><td>- <div- style={{- height: 6,- background: 'var(--bg-elevated)',- borderRadius: 3,- overflow: 'hidden',- minWidth: 80,- }}- >+ <div className="deployments-page__progress"><divstyle={{width: `${job.progress_percent || 0}%`,- height: '100%',background:job.status === 'failed' ? '#ef4444' : 'var(--accent-primary)',- transition: 'width 200ms ease',}}/></div>- <div style={{ fontSize: 11, color: 'var(--text-secondary)', marginTop: 2 }}>+ <div className="deployments-page__progress-meta">{job.current_step || 0}/{job.total_steps || 0}</div></td>- <td style={{ fontSize: 12 }}>{formatTime(job.started_at || job.created_at)}</td>+ <td className="deployments-page__time-cell">{formatTime(job.started_at || job.created_at)}</td></tr>))}</tbody>@@ -299,98 +270,70 @@ const Deployments = () => {)}</div>- <div className="card" style={{ padding: 16, minHeight: 400 }}>+ <div className="deployments-page__panel deployments-page__detail-panel">+ <div className="deployments-page__panel-header">+ <div>+ <h2>Details</h2>+ <span>Plan and logs</span>+ </div>+ </div>{!selectedJob ? (- <div style={{ color: 'var(--text-secondary)', textAlign: 'center', padding: 48 }}>+ <div className="deployments-page__empty">+ <Activity size={34} />+ <strong>No job selected</strong>Select a job to view its plan and logs.</div>) : !jobDetail ? (- <div style={{ color: 'var(--text-secondary)', textAlign: 'center', padding: 48 }}>Loading…</div>+ <div className="deployments-page__empty">Loading...</div>) : (- <>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>+ <div className="deployments-page__detail-content">+ <div className="deployments-page__detail-title"><div>- <h3 style={{ margin: 0 }}>{jobDetail.app_name || jobDetail.kind}</h3>- <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 4 }}>+ <h3>{jobDetail.app_name || jobDetail.kind}</h3>+ <div>{jobDetail.id}</div></div><StatusBadge status={jobDetail.status} /></div>- <div- style={{- display: 'grid',- gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',- gap: 12,- marginTop: 16,- fontSize: 13,- }}- >- <div>- <div style={{ color: 'var(--text-secondary)', fontSize: 11 }}>Target</div>+ <div className="deployments-page__detail-grid">+ <div className="deployments-page__detail-metric">+ <span>Target</span><div>{jobDetail.target_server_name}</div></div>- <div>- <div style={{ color: 'var(--text-secondary)', fontSize: 11 }}>Step</div>+ <div className="deployments-page__detail-metric">+ <span>Step</span><div>{jobDetail.current_step || 0} / {jobDetail.total_steps || 0}</div></div>- <div>- <div style={{ color: 'var(--text-secondary)', fontSize: 11 }}>Duration</div>+ <div className="deployments-page__detail-metric">+ <span>Duration</span><div>{formatDuration(jobDetail.duration)}</div></div>- <div>- <div style={{ color: 'var(--text-secondary)', fontSize: 11 }}>Started</div>+ <div className="deployments-page__detail-metric">+ <span>Started</span><div>{formatTime(jobDetail.started_at)}</div></div></div>{jobDetail.current_step_name && jobDetail.status === 'running' && (- <div- style={{- marginTop: 12,- padding: 10,- background: 'rgba(99,102,241,0.1)',- borderRadius: 6,- fontSize: 13,- }}- >- <Loader2 size={14} className="spin" style={{ marginRight: 6, verticalAlign: 'middle' }} />+ <div className="deployments-page__notice deployments-page__notice--running">+ <Loader2 size={14} className="deployments-page__spin" />{jobDetail.current_step_name}</div>)}{jobDetail.error_message && (- <div- style={{- marginTop: 12,- padding: 10,- background: 'rgba(239,68,68,0.1)',- border: '1px solid rgba(239,68,68,0.3)',- borderRadius: 6,- color: '#ef4444',- fontSize: 13,- }}- >- <AlertTriangle size={14} style={{ marginRight: 6, verticalAlign: 'middle' }} />+ <div className="deployments-page__notice deployments-page__notice--error">+ <AlertTriangle size={14} />{jobDetail.error_message}</div>)}- <h4 style={{ marginTop: 20, marginBottom: 8 }}>Logs</h4>+ <h4 className="deployments-page__logs-title">Logs</h4><divref={detailRef}- style={{- background: '#0b0f1a',- color: '#cbd5e1',- padding: 12,- borderRadius: 6,- fontFamily: 'ui-monospace, SFMono-Regular, monospace',- fontSize: 12,- height: 360,- overflowY: 'auto',- whiteSpace: 'pre-wrap',- }}+ className="deployments-page__logs">{(jobDetail.logs || []).length === 0? 'Waiting for logs…'@@ -405,22 +348,17 @@ const Deployments = () => {: '#cbd5e1';return (<div key={log.id} style={{ color }}>- <span style={{ color: '#64748b' }}>{ts}</span>{' '}- <span style={{ color: '#94a3b8' }}>{log.level.toUpperCase()}</span>{' '}+ <span className="deployments-page__log-time">{ts}</span>{' '}+ <span className="deployments-page__log-level">{log.level.toUpperCase()}</span>{' '}{stepPrefix}{log.message}</div>);})}</div>- </>+ </div>)}</div></div>-- <style>{`- .spin { animation: spin 1s linear infinite; }- @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }- `}</style></div>);};diff --git a/frontend/src/pages/Documentation.jsx b/frontend/src/pages/Documentation.jsxnew file mode 100644index 00000000..1e0d6360--- /dev/null+++ b/frontend/src/pages/Documentation.jsx@@ -0,0 +1,153 @@+import React, { useMemo, useState } from 'react';+import { BookOpen, Search, ExternalLink, FileText } from 'lucide-react';+import { Input } from '@/components/ui/input';++const REPO_DOCS_URL = 'https://github.com/jhd3197/ServerKit/blob/main/docs';++const DOC_GROUPS = [+ {+ id: 'getting-started',+ title: 'Getting Started',+ docs: [+ { file: 'README.md', title: 'Docs Home', desc: 'Documentation index' },+ { file: 'INSTALLATION.md', title: 'Installation', desc: 'Install ServerKit on a server' },+ { file: 'LOCAL_DEVELOPMENT.md', title: 'Local Development', desc: 'Run the panel locally' },+ { file: 'DEPLOYMENT.md', title: 'Deployment', desc: 'Production deployment guide' },+ ],+ },+ {+ id: 'reference',+ title: 'Reference',+ docs: [+ { file: 'ARCHITECTURE.md', title: 'Architecture', desc: 'How ServerKit is structured' },+ { file: 'API.md', title: 'API Reference', desc: 'REST API documentation' },+ { file: 'MULTI_ENVIRONMENT.md', title: 'Multi-Environment', desc: 'Manage multiple environments' },+ { file: 'MCP_SERVER_ACCESS.md', title: 'MCP Server Access', desc: 'Model Context Protocol access' },+ { file: 'pairing.md', title: 'Pairing', desc: 'Pairing servers with the panel' },+ { file: 'PLAN_AGENT_FLEET.md', title: 'Agent Fleet Plan', desc: 'Multi-server agent design' },+ ],+ },+ {+ id: 'product',+ title: 'Product Notes',+ docs: [+ { file: 'FEATURE_GAPS.md', title: 'Feature Gaps', desc: 'Known gaps and limitations' },+ { file: 'COMPETITIVE_ANALYSIS.md', title: 'Competitive Analysis', desc: 'Market comparison' },+ { file: 'MARKET_POSITIONING.md', title: 'Market Positioning', desc: 'Product positioning notes' },+ ],+ },+ {+ id: 'translations',+ title: 'Translations',+ docs: [+ { file: 'README.es.md', title: 'README (Español)', desc: 'Spanish translation' },+ { file: 'README.pt.md', title: 'README (Português)', desc: 'Portuguese translation' },+ { file: 'README.zh-CN.md', title: 'README (简体中文)', desc: 'Simplified Chinese translation' },+ ],+ },+];++const ROOT_DOCS = [+ { file: 'README.md', title: 'Project README', desc: 'Top-level project overview', root: true },+ { file: 'CONTRIBUTING.md', title: 'Contributing', desc: 'How to contribute', root: true },+ { file: 'AGENTS.md', title: 'AGENTS.md', desc: 'Guidance for AI/agent contributors', root: true },+ { file: 'CLAUDE.md', title: 'CLAUDE.md', desc: 'Guidance for Claude Code', root: true },+ { file: 'ROADMAP.md', title: 'Roadmap', desc: 'Planned features', root: true },+ { file: 'SECURITY_AUDIT.md', title: 'Security Audit', desc: 'Security findings', root: true },+];++const REPO_ROOT_URL = 'https://github.com/jhd3197/ServerKit/blob/main';++export default function Documentation() {+ const [query, setQuery] = useState('');++ const matches = (s) => s.toLowerCase().includes(query.trim().toLowerCase());++ const groups = useMemo(() => {+ if (!query.trim()) return DOC_GROUPS;+ return DOC_GROUPS.map(g => ({+ ...g,+ docs: g.docs.filter(d => matches(d.title) || matches(d.file) || matches(d.desc)),+ })).filter(g => g.docs.length);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [query]);++ const rootDocs = useMemo(() => {+ if (!query.trim()) return ROOT_DOCS;+ return ROOT_DOCS.filter(d => matches(d.title) || matches(d.file) || matches(d.desc));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [query]);++ const empty = !groups.length && !rootDocs.length;++ return (+ <div className="documentation">+ <div className="page-header">+ <div>+ <h1>+ <BookOpen size={22} style={{ verticalAlign: '-4px', marginRight: 8 }} />+ Documentation+ </h1>+ <p className="subtitle">+ Quick links to project docs, guides, and references — dev only+ </p>+ </div>+ <div className="documentation__search">+ <Search size={14} />+ <Input+ placeholder="Filter docs…"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ />+ </div>+ </div>++ {empty && (+ <div className="documentation__empty">No docs match “{query}”.</div>+ )}++ {!!rootDocs.length && (+ <section className="documentation__group">+ <h3 className="documentation__group-title">Repository Root</h3>+ <ul className="documentation__list">+ {rootDocs.map(d => (+ <DocItem key={d.file} doc={d} baseUrl={REPO_ROOT_URL} pathPrefix="" />+ ))}+ </ul>+ </section>+ )}++ {groups.map(g => (+ <section key={g.id} className="documentation__group">+ <h3 className="documentation__group-title">{g.title}</h3>+ <ul className="documentation__list">+ {g.docs.map(d => (+ <DocItem key={d.file} doc={d} baseUrl={REPO_DOCS_URL} pathPrefix="docs/" />+ ))}+ </ul>+ </section>+ ))}+ </div>+ );+}++function DocItem({ doc, baseUrl, pathPrefix }) {+ return (+ <li>+ <a+ href={`${baseUrl}/${doc.file}`}+ target="_blank"+ rel="noreferrer noopener"+ className="documentation__link"+ >+ <span className="documentation__icon">+ <FileText size={14} />+ </span>+ <span className="documentation__label">{doc.title}</span>+ <span className="documentation__path">{pathPrefix}{doc.file}</span>+ <ExternalLink size={12} className="documentation__ext" />+ </a>+ {doc.desc && <span className="documentation__note">{doc.desc}</span>}+ </li>+ );+}diff --git a/frontend/src/pages/Downloads.jsx b/frontend/src/pages/Downloads.jsxindex d9444682..22da2c18 100644--- a/frontend/src/pages/Downloads.jsx+++ b/frontend/src/pages/Downloads.jsx@@ -97,7 +97,7 @@ function Downloads() {if (import.meta.env.PROD) {return window.location.origin;}- return import.meta.env.VITE_API_URL?.replace('/api/v1', '') || 'http://localhost:5000';+ return import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;};const platforms = [diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsxindex 533c5d30..66119537 100644--- a/frontend/src/pages/FileManager.jsx+++ b/frontend/src/pages/FileManager.jsx@@ -6,14 +6,12 @@ import ConfirmDialog from '../components/ConfirmDialog';import {Folder, File, Upload, FolderPlus, FilePlus,ArrowLeft, ArrowRight, ArrowUp, Search, X, RefreshCw, Eye, EyeOff,- Download, Edit3, Trash2, BarChart3, ChevronDown, ChevronRight,- HardDrive, PieChart, Clock, PanelLeftClose, PanelLeftOpen,- LayoutGrid, List, Home, CloudUpload, Star, StarOff,- Check, Copy, ArrowUpDown, ZoomIn, ZoomOut, Code2, FileJson,- Image as ImageIcon, Film, Music, Archive, FileType, FileText,+ Download, Edit3, Trash2, ChevronDown, ChevronRight,+ HardDrive, Clock, PanelLeftClose, PanelLeftOpen,+ LayoutGrid, List, Home, CloudUpload,+ Check, Copy, ArrowUpDown,FolderTree as FolderTreeIcon, MousePointer2,} from 'lucide-react';-import { PieChart as RechartsPie, Pie, Cell, ResponsiveContainer, Tooltip } from 'recharts';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';@@ -24,7 +22,7 @@ import FileRow from '../components/file-manager/FileRow';import PreviewDrawer from '../components/file-manager/PreviewDrawer';import ContextMenu from '../components/file-manager/ContextMenu';import TargetPicker from '../components/TargetPicker';-import { TREE_ROOTS, DEFAULT_PINNED, getFileType, formatBytes } from '../components/file-manager/fileTypes';+import { TREE_ROOTS, getFileType, formatBytes } from '../components/file-manager/fileTypes';// File manager operations that the agent can serve over file:* commands.// Anything else (mkdir, delete, rename, copy, chmod, search, disk usage,@@ -52,26 +50,23 @@ function unwrapAgentData(res) {const STORAGE = {sidebar: 'serverkit-fm-sidebar',treeCollapsed: 'serverkit-fm-tree-collapsed',- quickCollapsed: 'serverkit-fm-quick-collapsed',diskCollapsed: 'serverkit-fm-disk-collapsed',expanded: 'serverkit-fm-tree-expanded',viewMode: 'serverkit-fm-view-mode',- gridSize: 'serverkit-fm-grid-size',sortBy: 'serverkit-fm-sort-by',sortDir: 'serverkit-fm-sort-dir',- pinned: 'serverkit-fm-pinned',};-const FILTER_CHIPS = [- { id: 'all', label: 'All', icon: FileType },- { id: 'folder', label: 'Folders', icon: Folder },- { id: 'image', label: 'Images', icon: ImageIcon },- { id: 'code', label: 'Code', icon: Code2 },- { id: 'text', label: 'Documents', icon: FileText },- { id: 'data', label: 'Data', icon: FileJson },- { id: 'video', label: 'Videos', icon: Film },- { id: 'audio', label: 'Audio', icon: Music },- { id: 'archive', label: 'Archives', icon: Archive },+const FILTER_OPTIONS = [+ { id: 'all', label: 'All' },+ { id: 'folder', label: 'Folders' },+ { id: 'image', label: 'Images' },+ { id: 'code', label: 'Code' },+ { id: 'text', label: 'Documents' },+ { id: 'data', label: 'Data' },+ { id: 'video', label: 'Videos' },+ { id: 'audio', label: 'Audio' },+ { id: 'archive', label: 'Archives' },];function FileManager() {@@ -124,11 +119,10 @@ function FileManager() {// ─── view prefs ──────────────────────────────────────const [viewMode, setViewMode] = useState(() => localStorage.getItem(STORAGE.viewMode) || 'grid');- const [gridSize, setGridSize] = useState(() => localStorage.getItem(STORAGE.gridSize) || 'lg');+ const gridSize = 'md';const [sortBy, setSortBy] = useState(() => localStorage.getItem(STORAGE.sortBy) || 'name');const [sortDir, setSortDir] = useState(() => localStorage.getItem(STORAGE.sortDir) || 'asc');const [activeFilter, setActiveFilter] = useState('all');- const [sortOpen, setSortOpen] = useState(false);// ─── left sidebar ────────────────────────────────────const [sidebarVisible, setSidebarVisible] = useState(() => {@@ -136,8 +130,10 @@ function FileManager() {return v !== null ? v === 'true' : true;});const [treeCollapsed, setTreeCollapsed] = useState(() => localStorage.getItem(STORAGE.treeCollapsed) === 'true');- const [quickCollapsed, setQuickCollapsed] = useState(() => localStorage.getItem(STORAGE.quickCollapsed) === 'true');- const [diskCollapsed, setDiskCollapsed] = useState(() => localStorage.getItem(STORAGE.diskCollapsed) === 'true');+ const [diskCollapsed, setDiskCollapsed] = useState(() => {+ const v = localStorage.getItem(STORAGE.diskCollapsed);+ return v !== null ? v === 'true' : true;+ });// ─── folder tree state ───────────────────────────────const [treeExpanded, setTreeExpanded] = useState(() => {@@ -154,20 +150,6 @@ function FileManager() {const [diskLastUpdated, setDiskLastUpdated] = useState(null);const [diskLoading, setDiskLoading] = useState(false);- // ─── pinned ──────────────────────────────────────────- const [pinned, setPinned] = useState(() => {- try {- const stored = localStorage.getItem(STORAGE.pinned);- return stored ? JSON.parse(stored) : DEFAULT_PINNED;- } catch { return DEFAULT_PINNED; }- });-- // ─── analysis ────────────────────────────────────────- const [analysisLoading, setAnalysisLoading] = useState(false);- const [directoryAnalysis, setDirectoryAnalysis] = useState(null);- const [typeBreakdown, setTypeBreakdown] = useState(null);- const [analysisView, setAnalysisView] = useState('directories');-// ─── history ─────────────────────────────────────────const [history, setHistory] = useState(['/home']);const [historyIdx, setHistoryIdx] = useState(0);@@ -181,13 +163,10 @@ function FileManager() {// ─── persistence ─────────────────────────────────────useEffect(() => { localStorage.setItem(STORAGE.sidebar, sidebarVisible); }, [sidebarVisible]);useEffect(() => { localStorage.setItem(STORAGE.treeCollapsed, treeCollapsed); }, [treeCollapsed]);- useEffect(() => { localStorage.setItem(STORAGE.quickCollapsed, quickCollapsed); }, [quickCollapsed]);useEffect(() => { localStorage.setItem(STORAGE.diskCollapsed, diskCollapsed); }, [diskCollapsed]);useEffect(() => { localStorage.setItem(STORAGE.viewMode, viewMode); }, [viewMode]);- useEffect(() => { localStorage.setItem(STORAGE.gridSize, gridSize); }, [gridSize]);useEffect(() => { localStorage.setItem(STORAGE.sortBy, sortBy); }, [sortBy]);useEffect(() => { localStorage.setItem(STORAGE.sortDir, sortDir); }, [sortDir]);- useEffect(() => { localStorage.setItem(STORAGE.pinned, JSON.stringify(pinned)); }, [pinned]);useEffect(() => {localStorage.setItem(STORAGE.expanded, JSON.stringify([...treeExpanded]));}, [treeExpanded]);@@ -244,8 +223,6 @@ function FileManager() {const loadDirectory = useCallback(async (path) => {setLoading(true);setSearchResults(null);- setDirectoryAnalysis(null);- setTypeBreakdown(null);setSelectedPaths(new Set());try {const data = await fileApi.browse(path, showHidden);@@ -300,24 +277,6 @@ function FileManager() {}};- // ─── analysis ────────────────────────────────────────- const analyzeDirectory = async () => {- setAnalysisLoading(true);- try {- const [analysisData, breakdownData] = await Promise.all([- api.analyzeDirectory(currentPath, 2, 15),- api.getFileTypeBreakdown(currentPath, 3),- ]);- setDirectoryAnalysis(analysisData);- setTypeBreakdown(breakdownData);- if (!sidebarVisible) setSidebarVisible(true);- } catch (error) {- toast.error(`Analysis failed: ${error.message}`);- } finally {- setAnalysisLoading(false);- }- };-// ─── tree expand/collapse ────────────────────────────const toggleTreeExpand = useCallback(async (path) => {if (treeExpanded.has(path)) {@@ -621,18 +580,6 @@ function FileManager() {if (e.dataTransfer.files?.length > 0) uploadFiles(e.dataTransfer.files);};- // ─── pinned ──────────────────────────────────────────- const isPinned = useCallback((path) => pinned.some((p) => p.path === path), [pinned]);- const togglePin = useCallback((target) => {- const path = typeof target === 'string' ? target : target.path;- const name = typeof target === 'string' ? path.split('/').pop() || path : (target.name || target.path.split('/').pop());- if (isPinned(path)) {- setPinned((p) => p.filter((x) => x.path !== path));- } else {- setPinned((p) => [...p, { path, name }]);- }- }, [isPinned]);-// ─── derived ─────────────────────────────────────────const breadcrumbs = useMemo(() => {const parts = currentPath.split('/').filter(Boolean);@@ -661,7 +608,7 @@ function FileManager() {const filterCounts = useMemo(() => {const counts = { all: entries.length };- FILTER_CHIPS.forEach((c) => { if (c.id !== 'all') counts[c.id] = 0; });+ FILTER_OPTIONS.forEach((c) => { if (c.id !== 'all') counts[c.id] = 0; });entries.forEach((e) => { const t = getFileType(e); if (counts[t] !== undefined) counts[t]++; });return counts;}, [entries]);@@ -681,6 +628,13 @@ function FileManager() {? activeUploads.reduce((s, u) => s + u.progress, 0) / activeUploads.length: 0;+ const sortValue = `${sortBy}-${sortDir}`;+ const handleSortChange = (value) => {+ const [nextSortBy, nextSortDir] = value.split('-');+ setSortBy(nextSortBy);+ setSortDir(nextSortDir);+ };+const selectedEntries = useMemo(() => sortedFiltered.filter((e) => selectedPaths.has(e.path)),[sortedFiltered, selectedPaths],@@ -693,7 +647,6 @@ function FileManager() {if (inInput) return;if (e.key === 'Escape') {if (contextMenu) setContextMenu(null);- else if (sortOpen) setSortOpen(false);else if (previewFile) setPreviewFile(null);else if (selectedPaths.size > 0) clearSelection();}@@ -710,15 +663,15 @@ function FileManager() {};window.addEventListener('keydown', handler);return () => window.removeEventListener('keydown', handler);- }, [selectedEntries, sortedFiltered, contextMenu, sortOpen, previewFile, parentPath, selectedPaths]); // eslint-disable-line+ }, [selectedEntries, sortedFiltered, contextMenu, previewFile, parentPath, selectedPaths]); // eslint-disable-line// ─── close popovers ──────────────────────────────────useEffect(() => {- if (!contextMenu && !sortOpen) return;- const close = () => { setContextMenu(null); setSortOpen(false); };+ if (!contextMenu) return;+ const close = () => { setContextMenu(null); };document.addEventListener('click', close);return () => document.removeEventListener('click', close);- }, [contextMenu, sortOpen]);+ }, [contextMenu]);const openContextMenu = (e, entry) => {e.preventDefault();@@ -757,16 +710,9 @@ function FileManager() {<div className="page-header"><div className="page-header-content"><h1>File Manager</h1>- <p className="page-description">Browse, edit, and manage your server files</p></div><div className="page-header-actions"><TargetPicker feature="files" value={target} onChange={setTarget} />- <Button variant="outline" onClick={() => fileInputRef.current?.click()} disabled={isRemote}>- <Upload size={16} /> Upload- </Button>- <Button variant="outline" onClick={() => setShowNewFolderModal(true)} disabled={isRemote}>- <FolderPlus size={16} /> New Folder- </Button><Button onClick={() => setShowNewFileModal(true)} disabled={isRemote}><FilePlus size={16} /> New File</Button>@@ -854,13 +800,6 @@ function FileManager() {</button></span>))}- <button- className={`crumb-pin ${isPinned(currentPath) ? 'pinned' : ''}`}- onClick={() => togglePin(currentPath)}- title={isPinned(currentPath) ? 'Unpin' : 'Pin to Quick Access'}- >- {isPinned(currentPath) ? <Star size={12} fill="currentColor" /> : <StarOff size={12} />}- </button></div></div><div className="toolbar-right">@@ -883,47 +822,33 @@ function FileManager() {</button>)}</div>- <div className="sort-control" onClick={(e) => e.stopPropagation()}>- <button className="toolbar-chip" onClick={() => setSortOpen(!sortOpen)} title="Sort">- <ArrowUpDown size={14} />- <span>Sort</span>- </button>- {sortOpen && (- <div className="sort-popover">- <div className="sort-popover-label">Sort by</div>- {[- { id: 'name', label: 'Name' },- { id: 'size', label: 'Size' },- { id: 'modified', label: 'Modified' },- { id: 'type', label: 'Type' },- ].map((opt) => (- <button- key={opt.id}- className={`sort-popover-item ${sortBy === opt.id ? 'active' : ''}`}- onClick={() => { setSortBy(opt.id); setSortOpen(false); }}- >- {sortBy === opt.id && <Check size={12} />}- <span>{opt.label}</span>- </button>- ))}- <div className="sort-popover-divider" />- <button- className={`sort-popover-item ${sortDir === 'asc' ? 'active' : ''}`}- onClick={() => { setSortDir('asc'); setSortOpen(false); }}- >- {sortDir === 'asc' && <Check size={12} />}- <span>Ascending</span>- </button>- <button- className={`sort-popover-item ${sortDir === 'desc' ? 'active' : ''}`}- onClick={() => { setSortDir('desc'); setSortOpen(false); }}- >- {sortDir === 'desc' && <Check size={12} />}- <span>Descending</span>- </button>- </div>- )}- </div>+ <button className="toolbar-chip" onClick={() => fileInputRef.current?.click()} disabled={isRemote}>+ <Upload size={14} />+ <span>Upload</span>+ </button>+ <label className="toolbar-select">+ <span>Type</span>+ <select value={activeFilter} onChange={(e) => setActiveFilter(e.target.value)}>+ {FILTER_OPTIONS.map((opt) => (+ <option key={opt.id} value={opt.id}>+ {opt.label} ({filterCounts[opt.id] ?? 0})+ </option>+ ))}+ </select>+ </label>+ <label className="toolbar-select">+ <ArrowUpDown size={14} />+ <select value={sortValue} onChange={(e) => handleSortChange(e.target.value)}>+ <option value="name-asc">Name A-Z</option>+ <option value="name-desc">Name Z-A</option>+ <option value="modified-desc">Newest</option>+ <option value="modified-asc">Oldest</option>+ <option value="size-desc">Largest</option>+ <option value="size-asc">Smallest</option>+ <option value="type-asc">Type</option>+ <option value="type-desc">Type Z-A</option>+ </select>+ </label><buttonclassName={`toolbar-chip ${selectMode ? 'active' : ''}`}onClick={() => { setSelectMode(!selectMode); if (selectMode) clearSelection(); }}@@ -932,31 +857,6 @@ function FileManager() {<MousePointer2 size={14} /><span>Select</span></button>- {viewMode === 'grid' && (- <div className="view-toggle">- <button- className={`view-toggle-btn ${gridSize === 'sm' ? 'active' : ''}`}- onClick={() => setGridSize('sm')}- title="Small thumbnails"- >- <ZoomOut size={14} />- </button>- <button- className={`view-toggle-btn ${gridSize === 'md' ? 'active' : ''}`}- onClick={() => setGridSize('md')}- title="Medium thumbnails"- >- <LayoutGrid size={14} />- </button>- <button- className={`view-toggle-btn ${gridSize === 'lg' ? 'active' : ''}`}- onClick={() => setGridSize('lg')}- title="Large thumbnails"- >- <ZoomIn size={14} />- </button>- </div>- )}<div className="view-toggle"><buttonclassName={`view-toggle-btn ${viewMode === 'grid' ? 'active' : ''}`}@@ -981,15 +881,6 @@ function FileManager() {{showHidden ? <Eye size={14} /> : <EyeOff size={14} />}<span>Hidden</span></button>- <button- className="toolbar-chip"- onClick={analyzeDirectory}- disabled={analysisLoading}- title="Analyze directory sizes"- >- <BarChart3 size={14} />- <span>{analysisLoading ? 'Analyzing…' : 'Analyze'}</span>- </button><buttonclassName="toolbar-icon-btn"onClick={() => loadDirectory(currentPath)}@@ -1000,25 +891,6 @@ function FileManager() {</div></div>- <div className="filter-chips-row">- {FILTER_CHIPS.map((chip) => {- const Icon = chip.icon;- const count = filterCounts[chip.id] ?? 0;- return (- <button- key={chip.id}- className={`filter-chip ${activeFilter === chip.id ? 'active' : ''}`}- onClick={() => setActiveFilter(chip.id)}- disabled={chip.id !== 'all' && count === 0}- >- <Icon size={13} />- <span>{chip.label}</span>- <span className="filter-chip-count">{count}</span>- </button>- );- })}- </div>-{selectedPaths.size > 0 && (<div className="bulk-bar"><div className="bulk-bar-info">@@ -1054,11 +926,21 @@ function FileManager() {<aside className="file-manager-sidebar left">{/* Folder Tree */}<div className="sidebar-section">- <button className="sidebar-section-header" onClick={() => setTreeCollapsed(!treeCollapsed)}>- <FolderTreeIcon size={16} />- <span>Folders</span>- {treeCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}- </button>+ <div className="sidebar-section-header sidebar-section-header--split">+ <button className="sidebar-section-toggle" onClick={() => setTreeCollapsed(!treeCollapsed)}>+ <FolderTreeIcon size={16} />+ <span>Folders</span>+ {treeCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}+ </button>+ <button+ className="sidebar-action-btn"+ onClick={() => setShowNewFolderModal(true)}+ disabled={isRemote}+ title="New folder"+ >+ <FolderPlus size={14} />+ </button>+ </div>{!treeCollapsed && (<div className="sidebar-section-content tree-content"><FolderTree@@ -1074,44 +956,6 @@ function FileManager() {)}</div>- {/* Quick Access */}- <div className="sidebar-section">- <button className="sidebar-section-header" onClick={() => setQuickCollapsed(!quickCollapsed)}>- <Star size={16} />- <span>Quick Access</span>- {quickCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}- </button>- {!quickCollapsed && (- <div className="sidebar-section-content quick-access-list">- {pinned.length === 0 && (- <div className="quick-access-empty">- Star folders from the breadcrumb to pin them here.- </div>- )}- {pinned.map((p) => (- <div- key={p.path}- className={`quick-access-item ${currentPath === p.path ? 'active' : ''}`}- onClick={() => navigateTo(p.path)}- >- <Folder size={14} fill="currentColor" fillOpacity={0.15} />- <div className="quick-access-text">- <div className="quick-access-name">{p.name}</div>- <div className="quick-access-path">{p.path}</div>- </div>- <button- className="quick-access-remove"- onClick={(e) => { e.stopPropagation(); togglePin(p.path); }}- title="Unpin"- >- <X size={12} />- </button>- </div>- ))}- </div>- )}- </div>-{/* Disk Usage */}<div className="sidebar-section"><button className="sidebar-section-header" onClick={() => setDiskCollapsed(!diskCollapsed)}>@@ -1153,127 +997,6 @@ function FileManager() {)}</div>- {/* Analysis */}- {(directoryAnalysis || analysisLoading) && (- <div className="sidebar-section analysis-section">- <div className="sidebar-section-header static">- <BarChart3 size={16} />- <span>Directory Analysis</span>- <button className="toolbar-icon-btn small" onClick={() => { setDirectoryAnalysis(null); setTypeBreakdown(null); }}>- <X size={14} />- </button>- </div>- <div className="sidebar-section-content">- {analysisLoading ? (- <div className="analysis-loading">- <Spinner /><span>Analyzing…</span>- </div>- ) : (- <>- <div className="analysis-total">- Total: {directoryAnalysis.total_size_human}- </div>- <div className="analysis-tabs">- <button- className={`analysis-tab ${analysisView === 'directories' ? 'active' : ''}`}- onClick={() => setAnalysisView('directories')}- >- <Folder size={14} /> Directories- </button>- <button- className={`analysis-tab ${analysisView === 'files' ? 'active' : ''}`}- onClick={() => setAnalysisView('files')}- >- <File size={14} /> Files- </button>- </div>- {analysisView === 'directories' && (- <div className="analysis-bars">- {directoryAnalysis.directories.slice(0, 10).map((dir, idx) => (- <div- key={idx}- className="analysis-bar-item"- onClick={() => navigateTo(dir.path)}- >- <div className="analysis-bar-header">- <span className="analysis-bar-name">- <Folder size={12} />- {dir.name}- </span>- <span className="analysis-bar-size">{dir.size_human}</span>- </div>- <div className="analysis-bar-track">- <div className="analysis-bar-fill" style={{ width: `${dir.percent}%` }} />- </div>- </div>- ))}- {directoryAnalysis.directories.length === 0 && <div className="analysis-empty">No subdirectories</div>}- </div>- )}- {analysisView === 'files' && (- <div className="analysis-files">- {directoryAnalysis.largest_files.slice(0, 10).map((file, idx) => (- <div key={idx} className="analysis-file-item" onClick={() => handleOpen(file)}>- <File size={12} />- <span className="analysis-file-name">{file.name}</span>- <span className="analysis-file-size">{file.size_human}</span>- </div>- ))}- {directoryAnalysis.largest_files.length === 0 && <div className="analysis-empty">No files</div>}- </div>- )}- </>- )}- </div>- </div>- )}-- {/* Type breakdown chart */}- {typeBreakdown && typeBreakdown.breakdown && typeBreakdown.breakdown.length > 0 && (- <div className="sidebar-section">- <div className="sidebar-section-header static">- <PieChart size={16} />- <span>File Types</span>- </div>- <div className="sidebar-section-content">- <div className="type-breakdown-chart">- <ResponsiveContainer width="100%" height={180}>- <RechartsPie>- <Pie- data={typeBreakdown.breakdown}- dataKey="size"- nameKey="name"- cx="50%"- cy="50%"- outerRadius={60}- innerRadius={35}- paddingAngle={2}- >- {typeBreakdown.breakdown.map((entry, idx) => (- <Cell key={idx} fill={entry.color} />- ))}- </Pie>- <Tooltip- formatter={(value, name) => [- typeBreakdown.breakdown.find(b => b.name === name)?.size_human || value,- name,- ]}- />- </RechartsPie>- </ResponsiveContainer>- </div>- <div className="type-breakdown-legend">- {typeBreakdown.breakdown.map((cat, idx) => (- <div key={idx} className="type-legend-item">- <span className="type-legend-color" style={{ background: cat.color }} />- <span className="type-legend-name">{cat.name}</span>- <span className="type-legend-size">{cat.size_human}</span>- </div>- ))}- </div>- </div>- </div>- )}</aside>)}@@ -1407,14 +1130,12 @@ function FileManager() {<ContextMenumenu={contextMenu}selectionCount={selectedEntries.length}- isPinned={isPinned}onClose={() => setContextMenu(null)}onOpen={handleOpen}onDownload={(e) => api.downloadFile(e.path)}onRename={openRenameModal}onPermissions={openPermissionsModal}onCopyPath={copyPathToClipboard}- onTogglePin={togglePin}onDelete={(e) => handleDelete(selectedEntries.length > 1 ? selectedEntries : e)}/>diff --git a/frontend/src/pages/StyleGuide.jsx b/frontend/src/pages/StyleGuide.jsxindex bfdba27e..37d4b7a2 100644--- a/frontend/src/pages/StyleGuide.jsx+++ b/frontend/src/pages/StyleGuide.jsx@@ -29,6 +29,9 @@ import { Input } from '@/components/ui/input';import { Textarea } from '@/components/ui/textarea';import { Badge } from '@/components/ui/badge';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';+import {+ Sheet, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription, SheetClose,+} from '@/components/ui/sheet';const SECTIONS = [{ id: 'colors', label: 'Colors', icon: Palette },@@ -70,6 +73,8 @@ export default function StyleGuide() {const [activeSection, setActiveSection] = useTabParam('/style-guide', SECTION_IDS, 'colors');const { openDrawer } = useLogsDrawer();const [modalOpen, setModalOpen] = useState(false);+ const [sheetSide, setSheetSide] = useState('right');+ const [sheetOpen, setSheetOpen] = useState(false);const [confirmOpen, setConfirmOpen] = useState(false);const [confirmVariant, setConfirmVariant] = useState('danger');const [controlledDemoTab, setControlledDemoTab] = useState('general');@@ -731,6 +736,45 @@ export default function StyleGuide() {</Modal></div>+ <SectionTitle title="Side Drawer (Sheet)" />+ <p className="text-sm text-secondary mb-2">Right/left-anchored panel built on Radix Dialog. Used for forms like “Add Server” or “Add Service” where a slide-in panel is preferred over a centered modal.</p>+ <div className="card" style={{ padding: 24 }}>+ <div className="flex flex-wrap gap-3">+ <Button onClick={() => { setSheetSide('right'); setSheetOpen(true); }}>+ <Plus size={16} /> Open Right Drawer+ </Button>+ <Button variant="outline" onClick={() => { setSheetSide('left'); setSheetOpen(true); }}>+ <Plus size={16} /> Open Left Drawer+ </Button>+ </div>+ <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>+ <SheetContent side={sheetSide}>+ <SheetHeader>+ <SheetTitle>Add Service</SheetTitle>+ <SheetDescription>+ Configure a new service. This drawer pattern is the panel-style alternative to a centered modal.+ </SheetDescription>+ </SheetHeader>+ <div className="space-y-4" style={{ padding: '16px 0' }}>+ <div className="form-group">+ <label>Service name</label>+ <Input type="text" placeholder="my-service" />+ </div>+ <div className="form-group">+ <label>Description</label>+ <Textarea placeholder="What does this service do?" rows={3} />+ </div>+ </div>+ <SheetFooter>+ <SheetClose asChild>+ <Button variant="outline">Cancel</Button>+ </SheetClose>+ <Button onClick={() => setSheetOpen(false)}>Create Service</Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ </div>+<SectionTitle title="Logs Drawer (LogsDrawer)" /><p className="text-sm text-secondary mb-2">Global bottom-pinned drawer for streaming logs. Opens via the LogsDrawer context.</p><div className="card" style={{ padding: 24 }}>diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsxindex a507b4b0..14b6dd09 100644--- a/frontend/src/pages/Templates.jsx+++ b/frontend/src/pages/Templates.jsx@@ -4,7 +4,7 @@ import {Search, X, Star, ExternalLink, BookOpen, Container, Globe, BarChart3,Database, Shield, Cloud, MessageSquare, Video, Music, Image, Home,Code, Server, GitBranch, Workflow, HardDrive, Lock, Users, FileText,- Settings, Layers, ChevronDown, Copy, Check, Tag, Cpu, HardDriveIcon,+ Settings, Layers, ChevronDown, Copy, Check, Tag, Cpu,Newspaper, TrendingUp} from 'lucide-react';import api from '../services/api';@@ -108,11 +108,12 @@ const Templates = () => {const [selectedTemplate, setSelectedTemplate] = useState(null);const [showInstallModal, setShowInstallModal] = useState(false);const [copiedCompose, setCopiedCompose] = useState(false);+ const [showAllCategories, setShowAllCategories] = useState(false);// Initialize from URL paramsconst selectedCategory = searchParams.get('category') || null;const searchQuery = searchParams.get('search') || '';- const sortBy = searchParams.get('sort') || 'name-asc';+ const sortBy = searchParams.get('sort') || 'featured';const installTemplateId = searchParams.get('install');useEffect(() => {@@ -291,6 +292,8 @@ const Templates = () => {const sortedTemplates = sortTemplates(templates);const hasActiveFilters = selectedCategory || searchQuery;+ const visibleCategories = showAllCategories ? categories : categories.slice(0, 10);+ const hiddenCategoryCount = Math.max(categories.length - visibleCategories.length, 0);if (loading) {return (@@ -302,13 +305,8 @@ const Templates = () => {return (<div className="page-container templates-page">- <div className="page-header">+ <div className="page-header templates-page-header"><h1>App Templates</h1>- <p className="page-description">One-click deployment for popular self-hosted applications</p>- </div>-- {/* Search and Filters */}- <div className="templates-filters"><div className="search-box"><Search size={18} className="search-icon" /><Input@@ -323,14 +321,21 @@ const Templates = () => {</Button>)}</div>- <div className="category-filters">+ </div>++ {/* Results and Filters */}+ <div className="templates-results-header">+ <span className="results-count">+ {sortedTemplates.length} template{sortedTemplates.length !== 1 ? 's' : ''}+ </span>+ <div className="category-filters" aria-label="Template categories"><buttonclassName={`category-btn ${!selectedCategory ? 'active' : ''}`}onClick={() => setSelectedCategoryFilter(null)}>All</button>- {categories.slice(0, 12).map(category => (+ {visibleCategories.map(category => (<buttonkey={category}className={`category-btn ${selectedCategory === category ? 'active' : ''}`}@@ -339,6 +344,23 @@ const Templates = () => {{getCategoryIcon(category)} {category}</button>))}+ {categories.length > 10 && (+ <button+ className="category-btn category-btn--more"+ onClick={() => setShowAllCategories(prev => !prev)}+ >+ {showAllCategories ? 'Less' : `More +${hiddenCategoryCount}`}+ </button>+ )}+ </div>+ <div className="sort-dropdown">+ <label>Sort by:</label>+ <select value={sortBy} onChange={(e) => setSortByFilter(e.target.value)}>+ <option value="name-asc">Name (A-Z)</option>+ <option value="name-desc">Name (Z-A)</option>+ <option value="featured">Featured First</option>+ </select>+ <ChevronDown size={16} className="dropdown-icon" /></div></div>@@ -357,7 +379,7 @@ const Templates = () => {{searchQuery && (<span className="filter-chip"><Search size={14} />- "{searchQuery}"+ “{searchQuery}”<button onClick={() => setSearchQueryFilter('')}><X size={14} /></button>@@ -369,22 +391,6 @@ const Templates = () => {</div>)}- {/* Results Header */}- <div className="templates-results-header">- <span className="results-count">- {sortedTemplates.length} template{sortedTemplates.length !== 1 ? 's' : ''}- </span>- <div className="sort-dropdown">- <label>Sort by:</label>- <select value={sortBy} onChange={(e) => setSortByFilter(e.target.value)}>- <option value="name-asc">Name (A-Z)</option>- <option value="name-desc">Name (Z-A)</option>- <option value="featured">Featured First</option>- </select>- <ChevronDown size={16} className="dropdown-icon" />- </div>- </div>-{/* Templates Grid */}<div className="templates-grid">{sortedTemplates.length === 0 ? (diff --git a/frontend/src/pages/WordPressProject.jsx b/frontend/src/pages/WordPressProject.jsxindex 4d495921..59101532 100644--- a/frontend/src/pages/WordPressProject.jsx+++ b/frontend/src/pages/WordPressProject.jsx@@ -26,7 +26,7 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';-const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || 'http://localhost:5000';+const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;const VALID_TABS = ['pipeline', 'activity', 'health'];diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.jsindex 5d196b9d..a76ba8bd 100644--- a/frontend/src/services/api/client.js+++ b/frontend/src/services/api/client.js@@ -1,6 +1,6 @@// Base HTTP client — constructor, token management, core request methodsconst API_BASE_URL = import.meta.env.VITE_API_URL ||- (import.meta.env.PROD ? '/api/v1' : 'http://localhost:5000/api/v1');+ (import.meta.env.PROD ? '/api/v1' : '/api/v1');class ApiClient {constructor() {diff --git a/frontend/src/services/socket.js b/frontend/src/services/socket.jsindex 1f21c318..b5d340d0 100644--- a/frontend/src/services/socket.js+++ b/frontend/src/services/socket.js@@ -1,6 +1,6 @@import { io } from 'socket.io-client';-const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || 'http://localhost:5000';+const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;class SocketService {constructor() {diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex fb7864eb..485deb09 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -74,6 +74,7 @@@import 'pages/_domains';@import 'pages/_monitoring';@import 'pages/_backups';+@import 'pages/_deployments';@import 'pages/_terminal';@import 'pages/_settings';@import 'pages/_file-manager';@@ -105,3 +106,4 @@@import 'pages/_cloud-provision';@import 'pages/_marketplace';@import 'pages/_style-guide';+@import 'pages/_app-map';diff --git a/frontend/src/styles/pages/_app-map.scss b/frontend/src/styles/pages/_app-map.scssnew file mode 100644index 00000000..903a8981--- /dev/null+++ b/frontend/src/styles/pages/_app-map.scss@@ -0,0 +1,217 @@+.app-map {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;++ .page-header {+ flex: 0 0 auto;+ }++ &__viewmeta {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0.75rem 0 0.5rem;+ font-size: 0.82rem;+ color: $text-secondary;++ span {+ flex: 1;+ }+ }++ &__legend-toggle {+ background: transparent;+ border: 1px solid $border-subtle;+ color: $text-secondary;+ font-size: 0.75rem;+ padding: 3px 10px;+ border-radius: $radius-sm;+ cursor: pointer;++ &:hover {+ background: $bg-hover;+ color: $text-primary;+ }+ }++ &__legend {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem 1rem;+ padding: 0.5rem 0.75rem;+ margin-bottom: 0.5rem;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ font-size: 0.75rem;+ color: $text-secondary;+ }++ &__legend-item {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ }++ &__legend-swatch {+ display: inline-block;+ width: 12px;+ height: 12px;+ border: 1px solid;+ border-radius: 3px;+ }++ &__canvas {+ flex: 1 1 auto;+ min-height: 480px;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ background: $bg-card;+ overflow: hidden;+ position: relative;++ .react-flow__attribution {+ display: none;+ }+ }+}++.documentation {+ .page-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 1rem;+ flex-wrap: wrap;+ }++ &__search {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ min-width: 240px;+ color: $text-secondary;++ input {+ min-width: 220px;+ }+ }++ &__group {+ margin-top: 1.25rem;+ }++ &__group-title {+ font-size: 0.72rem;+ font-weight: $font-weight-semibold;+ color: $text-secondary;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ margin: 0 0 0.6rem;+ }++ &__list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 0.5rem;++ li {+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 0.7rem 0.85rem;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ background: $bg-card;+ transition: border-color 0.15s ease, background-color 0.15s ease;++ &:hover {+ background: $bg-hover;+ border-color: $border-hover;+ }+ }+ }++ &__link {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ text-decoration: none;+ color: $text-primary;+ font-size: 0.88rem;+ line-height: 1.3;+ }++ &__icon {+ display: inline-flex;+ color: $text-secondary;+ }++ &__label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__path {+ font-family: $font-mono, monospace;+ font-size: 0.72rem;+ color: $text-tertiary;+ background: $bg-elevated;+ padding: 1px 6px;+ border-radius: $radius-sm;+ }++ &__ext {+ color: $text-tertiary;+ }++ &__note {+ font-size: 0.75rem;+ color: $text-secondary;+ }++ &__empty {+ color: $text-secondary;+ font-style: italic;+ padding: 1rem;+ }+}++// Dev Tools sidebar section: visually distinct.+.sidebar .nav-category--dev {+ margin-top: 1.75rem;+ padding-top: 0.75rem;+ border-top: 1px dashed $border-subtle;+ color: $primary-color;+ opacity: 0.9;+ display: flex;+ align-items: center;+ gap: 0.4rem;++ &::before {+ content: '';+ display: inline-block;+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: $primary-color;+ box-shadow: 0 0 0 3px rgba($accent-primary-raw, 0.18);+ }+}++.sidebar .nav-item--dev {+ border: 1px dashed transparent;++ &.active,+ &:hover {+ border-color: rgba($accent-primary-raw, 0.35);+ }+}diff --git a/frontend/src/styles/pages/_deployments.scss b/frontend/src/styles/pages/_deployments.scssnew file mode 100644index 00000000..eedd42e2--- /dev/null+++ b/frontend/src/styles/pages/_deployments.scss@@ -0,0 +1,460 @@+// ============================================+// DEPLOYMENTS PAGE+// ============================================++.deployments-page {+ --deployments-panel-min-height: 430px;++ &__header {+ align-items: flex-start;+ gap: $space-4;+ margin-bottom: $space-5;++ .page-title {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin: 0;++ svg {+ color: $text-secondary;+ }+ }+ }++ &__heading {+ min-width: 0;+ }++ &__description {+ margin: $space-1 0 0;+ color: $text-tertiary;+ font-size: $font-size-sm;+ line-height: 1.45;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-shrink: 0;+ }++ &__summary {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: $space-3;+ margin-bottom: $space-3;+ }++ &__stat-card {+ display: flex;+ align-items: center;+ gap: $space-3;+ min-height: 68px;+ padding: $space-3 $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ }++ &__stat-label {+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ line-height: 1;+ }++ &__stat-value {+ margin-top: $space-1;+ color: $text-primary;+ font-size: $font-size-xl;+ font-weight: $font-weight-bold;+ line-height: 1;+ }++ &__toolbar {+ display: flex;+ align-items: center;+ gap: $space-3;+ margin-bottom: $space-3;+ padding: $space-3;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ }++ &__filter {+ display: grid;+ gap: 3px;+ min-width: 180px;++ label {+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ }++ select {+ min-height: 34px;+ padding: $space-1 $space-8 $space-1 $space-2;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-primary;+ font-size: $font-size-sm;+ cursor: pointer;++ &:focus {+ outline: none;+ border-color: $accent-primary;+ box-shadow: 0 0 0 3px $accent-glow;+ }+ }+ }++ &__workspace {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(360px, 1.12fr);+ gap: $space-4;+ }++ &__panel {+ min-height: var(--deployments-panel-min-height);+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ overflow: hidden;+ }++ &__panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 52px;+ padding: $space-3 $space-4;+ border-bottom: 1px solid $border-subtle;++ h2 {+ margin: 0;+ color: $text-primary;+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ }++ span {+ display: block;+ margin-top: 2px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ }+ }++ &__empty {+ min-height: calc(var(--deployments-panel-min-height) - 52px);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: $space-2;+ padding: $space-8;+ color: $text-tertiary;+ text-align: center;++ svg {+ color: $text-tertiary;+ opacity: 0.72;+ }++ strong {+ color: $text-secondary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ span {+ max-width: 280px;+ font-size: $font-size-sm;+ line-height: 1.45;+ }+ }++ &__jobs-table {+ width: 100%;+ border-collapse: collapse;+ font-size: $font-size-sm;++ th {+ padding: $space-3 $space-4;+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ text-align: left;+ text-transform: uppercase;+ border-bottom: 1px solid $border-subtle;+ white-space: nowrap;+ }++ td {+ padding: $space-3 $space-4;+ color: $text-primary;+ border-bottom: 1px solid $border-subtle;+ vertical-align: middle;+ }++ tbody tr {+ cursor: pointer;+ transition: background $transition-fast;++ &:hover,+ &.is-selected {+ background: $bg-hover;+ }++ &.is-selected {+ box-shadow: inset 3px 0 0 $accent-primary;+ }++ &:last-child td {+ border-bottom: none;+ }+ }+ }++ &__server-cell {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ color: $text-secondary;+ white-space: nowrap;+ }++ &__progress {+ width: 100%;+ min-width: 88px;+ height: 6px;+ background: $bg-elevated;+ border-radius: $radius-full;+ overflow: hidden;++ > div {+ height: 100%;+ border-radius: inherit;+ transition: width 200ms ease;+ }+ }++ &__progress-meta,+ &__time-cell {+ color: $text-tertiary;+ font-size: $font-size-xs;+ }++ &__progress-meta {+ margin-top: 3px;+ }++ &__detail-panel {+ display: flex;+ flex-direction: column;+ }++ &__detail-content {+ display: flex;+ min-height: calc(var(--deployments-panel-min-height) - 52px);+ flex-direction: column;+ padding: $space-4;+ }++ &__detail-title {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: $space-3;++ h3 {+ margin: 0;+ color: $text-primary;+ font-size: $font-size-lg;+ }++ div div {+ margin-top: 3px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ word-break: break-all;+ }+ }++ &__detail-grid {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: $space-3;+ margin-top: $space-4;+ }++ &__detail-metric {+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;++ span {+ display: block;+ margin-bottom: 3px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ text-transform: uppercase;+ }++ div {+ color: $text-primary;+ font-size: $font-size-sm;+ word-break: break-word;+ }+ }++ &__notice {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin-top: $space-3;+ padding: $space-3;+ border-radius: $radius-md;+ font-size: $font-size-sm;++ &--running {+ background: rgba(99, 102, 241, 0.1);+ color: #818cf8;+ }++ &--error {+ background: rgba(239, 68, 68, 0.1);+ border: 1px solid rgba(239, 68, 68, 0.3);+ color: #ef4444;+ }+ }++ &__logs-title {+ margin: $space-5 0 $space-2;+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ &__logs {+ flex: 1;+ min-height: 260px;+ max-height: 420px;+ padding: $space-3;+ overflow-y: auto;+ background: #0b0f1a;+ border: 1px solid rgba(148, 163, 184, 0.16);+ border-radius: $radius-md;+ color: #cbd5e1;+ font-family: $font-mono;+ font-size: $font-size-xs;+ line-height: 1.6;+ white-space: pre-wrap;+ }++ &__log-time {+ color: #64748b;+ }++ &__log-level {+ color: #94a3b8;+ }++ &__status-badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border-radius: $radius-full;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ line-height: 1;+ text-transform: capitalize;+ white-space: nowrap;+ }++ &__spin {+ animation: deployments-spin 1s linear infinite;+ }+}++@keyframes deployments-spin {+ from {+ transform: rotate(0deg);+ }++ to {+ transform: rotate(360deg);+ }+}++@media (max-width: $breakpoint-xl) {+ .deployments-page {+ &__detail-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ }+}++@media (max-width: $breakpoint-lg) {+ .deployments-page {+ &__summary {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }++ &__workspace {+ grid-template-columns: 1fr;+ }+ }+}++@media (max-width: $breakpoint-md) {+ .deployments-page {+ &__header {+ flex-direction: column;+ }++ &__actions,+ &__toolbar {+ width: 100%;+ }++ &__toolbar {+ flex-direction: column;+ align-items: stretch;+ }++ &__filter {+ min-width: 0;+ }++ &__jobs-panel {+ overflow-x: auto;+ }++ &__jobs-table {+ min-width: 760px;+ }+ }+}++@media (max-width: $breakpoint-sm) {+ .deployments-page {+ &__summary,+ &__detail-grid {+ grid-template-columns: 1fr;+ }++ &__actions {+ flex-direction: column;+ align-items: stretch;+ }+ }+}diff --git a/frontend/src/styles/pages/_file-manager.scss b/frontend/src/styles/pages/_file-manager.scssindex c8d7ee20..911a38b3 100644--- a/frontend/src/styles/pages/_file-manager.scss+++ b/frontend/src/styles/pages/_file-manager.scss@@ -17,16 +17,17 @@ $ft-default: #94a3b8;.file-manager {display: flex;flex-direction: column;- gap: $space-3;+ gap: $space-2;position: relative;// ─── Page header ────────────────────────────────────.page-header {display: flex;justify-content: space-between;- align-items: flex-start;+ align-items: center;flex-wrap: wrap;- gap: $space-4;+ gap: $space-3;+ margin-bottom: $space-1;.page-header-content {h1 {@@ -35,10 +36,6 @@ $ft-default: #94a3b8;margin: 0 0 $space-1 0;letter-spacing: -0.01em;}- .page-description {- color: $text-secondary;- margin: 0;- }}.page-header-actions {@@ -135,11 +132,11 @@ $ft-default: #94a3b8;display: flex;justify-content: space-between;align-items: center;- padding: $space-2 $space-3;+ padding: $space-2;background: $bg-card;border: 1px solid $border-default;- border-radius: $radius-xl;- gap: $space-3;+ border-radius: $radius-lg;+ gap: $space-2;flex-wrap: wrap;.toolbar-left {@@ -152,7 +149,7 @@ $ft-default: #94a3b8;.toolbar-right {display: flex;align-items: center;- gap: $space-2;+ gap: $space-1;flex-wrap: wrap;}}@@ -235,7 +232,7 @@ $ft-default: #94a3b8;background: $bg-tertiary;border: 1px solid transparent;border-radius: $radius-md;- min-width: 220px;+ width: clamp(180px, 24vw, 280px);@include transition(all);&:focus-within {@@ -351,6 +348,47 @@ $ft-default: #94a3b8;svg { flex-shrink: 0; }}+ .toolbar-select {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ min-height: 34px;+ padding: 0 $space-2;+ background: $bg-tertiary;+ border: 1px solid transparent;+ border-radius: $radius-md;+ color: $text-secondary;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ white-space: nowrap;++ span {+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ }++ svg {+ color: $text-tertiary;+ flex-shrink: 0;+ }++ select {+ min-width: 92px;+ background: transparent;+ border: none;+ color: $text-primary;+ font: inherit;+ outline: none;+ cursor: pointer;+ }++ &:focus-within {+ border-color: fade($accent-primary-raw, 35%);+ background: $bg-body;+ }+ }+.toolbar-icon-btn {background: transparent;border: none;@@ -522,7 +560,7 @@ $ft-default: #94a3b8;// ─── Body layout: left sidebar + main ──────────────.file-manager-body {display: grid;- grid-template-columns: 280px 1fr;+ grid-template-columns: 248px 1fr;gap: $space-3;min-height: 0;align-items: start;@@ -545,11 +583,11 @@ $ft-default: #94a3b8;.file-manager-sidebar.left {display: flex;flex-direction: column;- gap: $space-3;- max-height: calc(100vh - 200px);+ gap: $space-2;+ max-height: calc(100vh - 158px);overflow-y: auto;position: sticky;- top: $space-4;+ top: $space-2;scrollbar-width: thin;&::-webkit-scrollbar { width: 4px; }@@ -585,7 +623,7 @@ $ft-default: #94a3b8;display: flex;align-items: center;gap: $space-2;- padding: $space-3 $space-4;+ padding: $space-3;background: $bg-elevated;border: none;width: 100%;@@ -603,6 +641,67 @@ $ft-default: #94a3b8;span { flex: 1; }}+ .sidebar-section-header--split {+ padding: 0;+ cursor: default;++ &:hover {+ background: $bg-elevated;+ }++ .sidebar-section-toggle {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex: 1;+ min-width: 0;+ padding: $space-3;+ background: transparent;+ border: none;+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;++ &:hover {+ background: $bg-tertiary;+ }++ > svg:first-child {+ color: $accent-primary;+ }++ span {+ flex: 1;+ }+ }+ }++ .sidebar-action-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 30px;+ height: 30px;+ margin-right: $space-2;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $accent-primary;+ cursor: pointer;+ @include transition(all);++ &:hover:not(:disabled) {+ background: $accent-glow;+ border-color: fade($accent-primary-raw, 35%);+ }++ &:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }+ }+.sidebar-section-content { padding: $space-3 $space-4; }.tree-content { padding: $space-2; }@@ -960,7 +1059,7 @@ $ft-default: #94a3b8;border-radius: $radius-lg;overflow: hidden;position: relative;- min-height: 540px;+ min-height: calc(100vh - 250px);}.loading-state, .empty-state {@@ -1359,7 +1458,7 @@ $ft-default: #94a3b8;display: flex;justify-content: space-between;align-items: center;- padding: $space-2 $space-3;+ padding: $space-1 $space-3;background: $bg-card;border: 1px solid $border-default;border-radius: $radius-md;@@ -1411,7 +1510,6 @@ $ft-default: #94a3b8;color: $text-tertiary;opacity: 0.7;display: none;- @media (min-width: $breakpoint-lg) { display: inline; }}}diff --git a/frontend/src/styles/pages/_templates.scss b/frontend/src/styles/pages/_templates.scssindex 3d53b394..1818ba40 100644--- a/frontend/src/styles/pages/_templates.scss+++ b/frontend/src/styles/pages/_templates.scss@@ -3,6 +3,19 @@// ============================================.templates-page {+ .templates-page-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-4;+ margin-bottom: $space-4;++ h1 {+ margin: 0;+ white-space: nowrap;+ }+ }+.page-description {color: $text-secondary;margin-top: $space-2;@@ -40,6 +53,7 @@.search-box {position: relative;max-width: 400px;+ width: min(400px, 42vw);.search-icon {position: absolute;@@ -52,7 +66,8 @@input {width: 100%;- padding: $space-3 $space-4;+ min-height: 40px;+ padding: $space-2 $space-4;padding-left: $space-10;padding-right: $space-10;background: $bg-card;@@ -98,6 +113,7 @@display: flex;flex-wrap: wrap;gap: $space-2;+ min-width: 0;}.category-btn {@@ -125,6 +141,11 @@border-color: $accent-primary;color: $accent-primary;}++ &--more {+ color: $accent-primary;+ border-color: $border-active;+ }}// Active Filters@@ -133,7 +154,7 @@align-items: center;flex-wrap: wrap;gap: $space-2;- margin-bottom: $space-4;+ margin: -$space-2 0 $space-4;}.filter-chip {@@ -191,9 +212,10 @@// Results Header.templates-results-header {- display: flex;+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;align-items: center;- justify-content: space-between;+ gap: $space-3;margin-bottom: $space-4;padding-bottom: $space-3;border-bottom: 1px solid $border-subtle;@@ -202,6 +224,7 @@.results-count {font-size: $font-size-sm;color: $text-secondary;+ white-space: nowrap;}.sort-dropdown {@@ -707,16 +730,37 @@// Responsive@media (max-width: $breakpoint-md) {+ .templates-page {+ .templates-page-header {+ flex-direction: column;+ align-items: stretch;+ gap: $space-3;++ h1 {+ white-space: normal;+ }+ }+ }++ .search-box {+ width: 100%;+ max-width: none;+ }+.templates-grid {grid-template-columns: 1fr;}.templates-results-header {- flex-direction: column;+ grid-template-columns: 1fr;align-items: flex-start;gap: $space-3;}+ .category-filters {+ width: 100%;+ }+.sort-dropdown {width: 100%;diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex 15ebf91f..0e8c1086 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -1,45 +1,61 @@-import { defineConfig } from 'vite'+import { defineConfig, loadEnv } from 'vite'import react from '@vitejs/plugin-react'import tailwindcss from '@tailwindcss/vite'import { fileURLToPath } from 'url'-export default defineConfig({- plugins: [react(), tailwindcss()],- resolve: {- alias: {- '@': fileURLToPath(new URL('./src', import.meta.url)),+export default defineConfig(({ mode }) => {+ const env = loadEnv(mode, process.cwd(), '')+ const apiTarget = (env.VITE_API_URL || 'http://localhost:5000/api/v1').replace(/\/api\/v1\/?$/, '')++ return {+ plugins: [react(), tailwindcss()],+ resolve: {+ alias: {+ '@': fileURLToPath(new URL('./src', import.meta.url)),+ },},- },- server: {- port: 5274,- // Enable polling for WSL (Windows filesystem doesn't support inotify)- watch: {- usePolling: true,- interval: 1000,+ server: {+ port: 5274,+ proxy: {+ '/api': {+ target: apiTarget,+ changeOrigin: true,+ },+ '/socket.io': {+ target: apiTarget,+ changeOrigin: true,+ ws: true,+ },+ },+ // Enable polling for WSL (Windows filesystem doesn't support inotify)+ watch: {+ usePolling: true,+ interval: 1000,+ },},- },- css: {- preprocessorOptions: {- scss: {- // Silence Dart Sass deprecation warnings for @import and slash-div- // These are expected during migration from LESS and will be addressed- // when moving to @use/@forward module system- silenceDeprecations: ['import', 'slash-div', 'legacy-js-api', 'global-builtin', 'color-functions', 'strict-unary'],+ css: {+ preprocessorOptions: {+ scss: {+ // Silence Dart Sass deprecation warnings for @import and slash-div+ // These are expected during migration from LESS and will be addressed+ // when moving to @use/@forward module system+ silenceDeprecations: ['import', 'slash-div', 'legacy-js-api', 'global-builtin', 'color-functions', 'strict-unary'],+ },},},- },- build: {- sourcemap: false,- rollupOptions: {- output: {- manualChunks: {- 'vendor-react': ['react', 'react-dom', 'react-router-dom'],- 'vendor-charts': ['recharts'],- 'vendor-flow': ['@xyflow/react'],- 'vendor-xterm': ['@xterm/xterm', '@xterm/addon-fit', '@xterm/addon-web-links'],- 'vendor-icons': ['lucide-react'],+ build: {+ sourcemap: false,+ rollupOptions: {+ output: {+ manualChunks: {+ 'vendor-react': ['react', 'react-dom', 'react-router-dom'],+ 'vendor-charts': ['recharts'],+ 'vendor-flow': ['@xyflow/react'],+ 'vendor-xterm': ['@xterm/xterm', '@xterm/addon-fit', '@xterm/addon-web-links'],+ 'vendor-icons': ['lucide-react'],+ },},},},- },+ }})