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
Surface Docker DBs, add base port & migration fixes
Juan Denis986909a95595
diff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex fbbb0674..b795fdad 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -607,6 +607,38 @@ def list_docker_databases():return jsonify({'containers': containers}), 200+@databases_bp.route('/docker/databases', methods=['GET'])+@jwt_required()+def list_all_docker_databases():+ """Flat list of databases discovered across every Docker app the caller can+ access, each tagged with its owning app and engine.++ Powers grouping Docker-hosted databases under their engine node — e.g. a+ containerised MySQL created by a WordPress stack appears under+ 'MySQL / MariaDB', not only buried under 'Docker apps'.+ """+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ out = []+ apps = Application.query.filter_by(app_type='docker').all()+ for app in apps:+ if not app.root_path:+ continue+ if not ResourceGrantService.can_access_app(user, app):+ continue+ info = DatabaseService.get_app_database_info(app.name, app.root_path)+ if not info:+ continue+ for db in info:+ entry = dict(db)+ entry['app_id'] = app.id+ entry['app_name'] = app.name+ out.append(entry)++ return jsonify({'databases': out}), 200++@databases_bp.route('/docker/app/<int:app_id>', methods=['GET'])@jwt_required()def get_app_databases(app_id):diff --git a/backend/app/services/database_service.py b/backend/app/services/database_service.pyindex 1cc64e3a..76819bb0 100644--- a/backend/app/services/database_service.py+++ b/backend/app/services/database_service.py@@ -1365,6 +1365,37 @@ class DatabaseService:except Exception as e:return {'success': False, 'error': str(e)}+ @staticmethod+ def _resolve_app_container(app_path, service_name, fallback=None, env_vars=None):+ """Resolve the real running container name for a compose service.++ docker-compose v2 names containers ``<project>-<service>-N`` and our+ templates leave ``container_name`` as an unexpanded ``${APP_NAME}-db``+ in the on-disk compose, so neither the literal value nor a+ ``<app>_<service>`` guess reliably matches the live container — which is+ why ``docker exec`` silently failed and tables showed as empty. Ask+ ``docker compose ps`` what the container is actually called and match on+ the service; fall back to expanding ``${VARS}`` from .env, then to the+ raw fallback.+ """+ # 1. Authoritative: ask docker what the container is actually called.+ if app_path:+ try:+ from app.services.docker_service import DockerService+ for c in DockerService.compose_ps(app_path):+ svc = c.get('Service') or c.get('service')+ if svc == service_name:+ name = c.get('Name') or c.get('name') or c.get('ID') or c.get('id')+ if name:+ return name+ except Exception:+ pass+ # 2. Best-effort: expand ${VARS} in the declared/guessed name from .env.+ if fallback and env_vars and '${' in fallback:+ fallback = re.sub(r'\$\{([^}]+)\}',+ lambda m: env_vars.get(m.group(1), m.group(0)), fallback)+ return fallback+@staticmethoddef get_app_database_info(app_name, app_path):"""Get database info for a Docker app by reading its compose file."""@@ -1398,6 +1429,7 @@ class DatabaseService:# Check for MySQL containersif any(db in image for db in ['mysql', 'mariadb', 'percona']):container_name = service_config.get('container_name', f'{app_name}_{service_name}')+ container_name = DatabaseService._resolve_app_container(app_path, service_name, container_name, env_vars)environment = service_config.get('environment', [])# Extract credentials from environment@@ -1458,6 +1490,7 @@ class DatabaseService:# Check for PostgreSQL containerselif 'postgres' in image:container_name = service_config.get('container_name', f'{app_name}_{service_name}')+ container_name = DatabaseService._resolve_app_container(app_path, service_name, container_name, env_vars)environment = service_config.get('environment', [])pg_user = 'postgres'diff --git a/backend/app/services/migration_service.py b/backend/app/services/migration_service.pyindex 8e4612a6..4ddf07a5 100644--- a/backend/app/services/migration_service.py+++ b/backend/app/services/migration_service.py@@ -170,9 +170,21 @@ class MigrationService:@classmethoddef get_status(cls):- """Return current migration status."""+ """Return current migration status.++ ``needs_migration`` is derived from the live revision vs head rather than+ the cached boot flag, so the login gate (App.jsx) prompts whenever the+ database isn't at head — including when the boot auto-upgrade couldn't+ complete (e.g. an orphaned revision). When current == head it stays false,+ so a normally up-to-date instance never sees the gate.+ """+ needs = bool(+ cls._current_revision+ and cls._head_revision+ and cls._current_revision != cls._head_revision+ )return {- 'needs_migration': cls._needs_migration,+ 'needs_migration': needs,'current_revision': cls._current_revision,'head_revision': cls._head_revision,'pending_count': len(cls._pending_migrations),@@ -233,15 +245,57 @@ class MigrationService:@classmethoddef apply_migrations(cls, app):- """Run all pending Alembic migrations."""+ """Run all pending Alembic migrations.++ Self-heals an orphaned ``alembic_version``: if the DB records a revision+ that no longer exists in the migration scripts (renamed/removed during+ development), Alembic can't compute an upgrade path. Because the boot+ schema sync (``_fix_missing_columns`` + ``create_all``) already brings the+ live schema up to the ORM models (== head), we re-stamp to head to repair+ the bookkeeping instead of failing.+ """try:cfg = cls._get_alembic_config(app)+ script = ScriptDirectory.from_config(cfg)++ from app import db++ # What revision does the DB think it's at, and does Alembic still know it?+ with db.engine.connect() as conn:+ context = MigrationContext.configure(conn)+ db_heads = list(context.get_current_heads())++ def _known(rev):+ try:+ script.get_revision(rev)+ return True+ except Exception:+ return False++ orphaned = bool(db_heads) and not all(_known(r) for r in db_heads)with app.app_context():- command.upgrade(cfg, 'head')+ if orphaned:+ # command.stamp() can't help here: it still resolves the+ # (unknown) current revision and fails the same way. The live+ # schema already matches head via the boot sync, so reset the+ # alembic_version table directly to head.+ head = script.get_current_head()+ logger.warning(+ f'Recorded revision {db_heads} not found in migration scripts — '+ f'resetting alembic_version to head ({head})'+ )+ with db.engine.begin() as conn:+ conn.execute(text('DELETE FROM alembic_version'))+ if head:+ conn.execute(+ text('INSERT INTO alembic_version (version_num) VALUES (:v)'),+ {'v': head},+ )+ else:+ command.upgrade(cfg, 'head')# Update internal state- from app import dbwith db.engine.connect() as conn:context = MigrationContext.configure(conn)current_heads = context.get_current_heads()diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex 19876147..8e47adf2 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -38,6 +38,11 @@ class SettingsService:'type': 'boolean','description': 'Enable developer mode for debugging tools and icon reference'},+ 'managed_app_base_port': {+ 'value': 0,+ 'type': 'integer',+ 'description': 'Starting host port when auto-assigning ports to managed apps/sites (0 = use each template\'s own default). The scanner still skips ports already in use.'+ },# SSO / OAuth settings'sso_google_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable Google OAuth login'},'sso_google_client_id': {'value': '', 'type': 'string', 'description': 'Google OAuth client ID'},diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex 34787e2f..2ce06d7d 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -153,6 +153,11 @@ class TemplateService:elif var_type == 'port':# ALWAYS find an available port - never trust defaultsstart_port = int(default) if default else 8000+ # A global base-port setting (Settings > managed_app_base_port)+ # overrides the per-template default when configured (non-zero).+ base = cls._managed_app_base_port()+ if base:+ start_port = basereturn str(cls._find_available_port(start_port))elif var_type == 'uuid':@@ -226,6 +231,20 @@ class TemplateService:'error': f'Connection check failed: {str(e)}'}+ @classmethod+ def _managed_app_base_port(cls) -> int:+ """Return the admin-configured base port for managed apps, or 0 if unset.++ Reads the ``managed_app_base_port`` system setting. Returns 0 (meaning+ "use each template's own default") on any error, e.g. if the settings+ table isn't ready yet during early startup.+ """+ try:+ from app.services.settings_service import SettingsService+ return int(SettingsService.get('managed_app_base_port', 0) or 0)+ except Exception:+ return 0+@classmethoddef _find_available_port(cls, start_port: int = 8000, max_attempts: int = 1000) -> int:"""Find an available port that's not in use by the system, Docker, or database.diff --git a/backend/templates/wordpress.yaml b/backend/templates/wordpress.yamlindex 5e0592ab..ac0461c1 100644--- a/backend/templates/wordpress.yaml+++ b/backend/templates/wordpress.yaml@@ -19,7 +19,7 @@ variables:- name: HTTP_PORTdescription: HTTP porttype: port- default: "8080"+ default: "8300"hidden: true- name: DB_PASSWORDdescription: MySQL root passworddiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 5f1dcbd6..dafce05d 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -35,6 +35,7 @@"lucide-react": "^0.363.0","react": "^18.3.1","react-dom": "^18.3.1",+ "react-icons": "^5.6.0","react-router-dom": "^6.22.3","recharts": "^2.12.3","socket.io-client": "^4.7.2",@@ -6561,6 +6562,15 @@"react": "^18.3.1"}},+ "node_modules/react-icons": {+ "version": "5.6.0",+ "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.6.0.tgz",+ "integrity": "sha512-RH93p5ki6LfOiIt0UtDyNg/cee+HLVR6cHHtW3wALfo+eOHTp8RnU2kRkI6E+H19zMIs03DyxUG/GfZMOGvmiA==",+ "license": "MIT",+ "peerDependencies": {+ "react": "*"+ }+ },"node_modules/react-is": {"version": "16.13.1","resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 33361945..9cfd7cc8 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -40,6 +40,7 @@"lucide-react": "^0.363.0","react": "^18.3.1","react-dom": "^18.3.1",+ "react-icons": "^5.6.0","react-router-dom": "^6.22.3","recharts": "^2.12.3","socket.io-client": "^4.7.2",diff --git a/frontend/src/components/databases/ConsoleTab.jsx b/frontend/src/components/databases/ConsoleTab.jsxindex 4ff1a62b..15718d74 100644--- a/frontend/src/components/databases/ConsoleTab.jsx+++ b/frontend/src/components/databases/ConsoleTab.jsx@@ -7,6 +7,12 @@ import ResultsGrid from './ResultsGrid';const HISTORY_KEY = 'serverkit_query_history';const MAX_HISTORY = 50;+// Platform-aware run shortcut. Operators run ServerKit from Linux/Windows far more+// often than macOS, so default the modifier label to Ctrl and only show ⌘ on Mac.+const IS_MAC = typeof navigator !== 'undefined'+ && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent || '');+const MOD_KEY = IS_MAC ? '⌘' : 'Ctrl';+// One SQL console bound to a single connection. Owns its editor text, results,// readonly flag, and per-connection history. `active` gates keyboard handling so// background (hidden) consoles don't steal Ctrl+Enter.@@ -116,11 +122,11 @@ export default function ConsoleTab({ conn, tabId, active, isAdmin, initialQueryclassName="dbx-run"onClick={execute}disabled={loading || !query.trim()}- title="Run query (Ctrl+Enter)"+ title={`Run query (${MOD_KEY}+Enter)`}><Play size={14} aria-hidden="true" />{loading ? 'Running…' : 'Run'}- <kbd>⌘↵</kbd>+ <kbd>{MOD_KEY} ↵</kbd></button>{isAdmin && (@@ -223,7 +229,7 @@ export default function ConsoleTab({ conn, tabId, active, isAdmin, initialQuery</>) : (<div className="dbx-console-hint">- <p>Write SQL above and press <kbd>Ctrl</kbd> + <kbd>Enter</kbd> to run.</p>+ <p>Write SQL above and press <kbd>{MOD_KEY}</kbd> + <kbd>Enter</kbd> to run.</p></div>)}</div>diff --git a/frontend/src/components/databases/SourceTree.jsx b/frontend/src/components/databases/SourceTree.jsxindex 59acfaef..fd358d13 100644--- a/frontend/src/components/databases/SourceTree.jsx+++ b/frontend/src/components/databases/SourceTree.jsx@@ -1,15 +1,15 @@-import { ChevronRight, ChevronDown, Database, HardDrive, Box, Table2, Loader2, MoreHorizontal } from 'lucide-react';+import { ChevronRight, ChevronDown, Table2, Loader2, MoreHorizontal } from 'lucide-react';+import { EngineIcon } from '../icons/DatabaseBrands';-// Icon per node kind / engine. Tint comes from `.is-<engine>` in SCSS.+// Icon per node kind / engine. Brand glyphs come from DatabaseBrands; tint comes+// from `.is-<engine>` in SCSS (the brand icons use currentColor).function NodeIcon({ node }) {if (node.kind === 'engine' || node.kind === 'database') {- if (node.engine === 'sqlite') return <HardDrive size={15} aria-hidden="true" />;- if (node.engine === 'docker') return <Box size={15} aria-hidden="true" />;- return <Database size={15} aria-hidden="true" />;+ return <EngineIcon engine={node.engine} size={15} />;}- if (node.kind === 'app') return <Box size={15} aria-hidden="true" />;+ if (node.kind === 'app') return <EngineIcon engine="docker" size={15} />;if (node.kind === 'table') return <Table2 size={14} aria-hidden="true" />;- return <Database size={15} aria-hidden="true" />;+ return <EngineIcon engine={node.engine} size={15} />;}const STATUS_LABEL = { active: 'Running', inactive: 'Stopped', missing: 'Not installed' };@@ -64,6 +64,13 @@ function TreeRow({ node, depth, expanded, childrenCache, loading, activeKey, sel<span className="dbx-tree-icon"><NodeIcon node={node} /></span><span className="dbx-tree-label">{node.label}</span>+ {node.kind === 'database' && node.source === 'docker' && (+ <span className="dbx-tree-source" title={node.appName ? `Docker container · ${node.appName}` : 'Docker container'}>+ <EngineIcon engine="docker" size={11} />+ {node.appName || 'docker'}+ </span>+ )}+{node.kind === 'engine' && node.status && node.status !== 'available' && (<span className={`dbx-tree-status is-${node.status}`}><span className="dbx-status-dot" aria-hidden="true" />diff --git a/frontend/src/components/databases/dbAdapter.js b/frontend/src/components/databases/dbAdapter.jsindex 6d90026a..8f70352d 100644--- a/frontend/src/components/databases/dbAdapter.js+++ b/frontend/src/components/databases/dbAdapter.js@@ -48,7 +48,7 @@ export async function listTables(conn) {case 'mysql': return api.getMySQLTables(conn.name);case 'postgresql': return api.getPostgreSQLTables(conn.name);case 'sqlite': return api.getSQLiteTables(conn.path);- case 'docker': return api.getDockerDatabaseTables(conn.container, conn.name, conn.password);+ case 'docker': return api.getDockerDatabaseTables(conn.container, conn.name, conn.password, conn.user);default: return { tables: [] };}}@@ -69,7 +69,7 @@ export async function runQuery(conn, sql, readonly) {case 'mysql': return api.executeMySQLQuery(conn.name, sql, readonly);case 'postgresql': return api.executePostgreSQLQuery(conn.name, sql, readonly);case 'sqlite': return api.executeSQLiteQuery(conn.path, sql, readonly);- case 'docker': return api.executeDockerQuery(conn.container, conn.name, sql, conn.password, readonly);+ case 'docker': return api.executeDockerQuery(conn.container, conn.name, sql, conn.password, readonly, conn.user);default: return { success: false, error: 'Unknown database type' };}}diff --git a/frontend/src/components/icons/DatabaseBrands.jsx b/frontend/src/components/icons/DatabaseBrands.jsxnew file mode 100644index 00000000..80579142--- /dev/null+++ b/frontend/src/components/icons/DatabaseBrands.jsx@@ -0,0 +1,35 @@+// Brand-authentic database engine icons. These wrap Simple Icons (via+// react-icons) so each engine is instantly recognizable — MySQL dolphin,+// PostgreSQL elephant, MongoDB leaf, Redis, SQLite, Docker whale — instead of+// the generic lucide glyph every engine shared before.+//+// All Simple Icons render with `fill="currentColor"`, so the existing+// `.is-<engine>` SCSS tinting still controls the color with no inline styles.+import {+ SiMysql, SiMariadb, SiPostgresql, SiSqlite, SiMongodb, SiRedis, SiDocker,+} from 'react-icons/si';+import { Database } from 'lucide-react';++// engine key -> brand icon component. Keys match ENGINE_META / node.engine.+const ENGINE_ICONS = {+ mysql: SiMysql,+ mariadb: SiMariadb,+ postgresql: SiPostgresql,+ sqlite: SiSqlite,+ mongodb: SiMongodb,+ redis: SiRedis,+ docker: SiDocker,+};++export function hasBrandIcon(engine) {+ return Boolean(ENGINE_ICONS[engine]);+}++// Renders the brand icon for an engine, falling back to the generic lucide+// Database glyph for anything we don't have a brand for.+export function EngineIcon({ engine, size = 15, className }) {+ const Cmp = ENGINE_ICONS[engine] || Database;+ return <Cmp size={size} className={className} aria-hidden="true" />;+}++export default EngineIcon;diff --git a/frontend/src/components/settings/MigrationHistoryTab.jsx b/frontend/src/components/settings/MigrationHistoryTab.jsxindex 4cf23885..fe222c87 100644--- a/frontend/src/components/settings/MigrationHistoryTab.jsx+++ b/frontend/src/components/settings/MigrationHistoryTab.jsx@@ -1,27 +1,97 @@-import React, { useState, useEffect } from 'react';+import { useState, useEffect, useCallback } from 'react';import api from '../../services/api';-import { Database, Loader, CheckCircle, ArrowUpCircle } from 'lucide-react';+import { Database, Loader, CheckCircle, ArrowUpCircle, ShieldCheck } from 'lucide-react';import { Badge } from '@/components/ui/badge';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { ConfirmDialog } from '../../components/ConfirmDialog';++// Revisions in this project are short descriptive slugs (e.g. 016_resource_grants),+// so show them in full rather than truncating mid-word.+const short = (rev) => rev || '';const MigrationHistoryTab = () => {+ const toast = useToast();+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();+const [revisions, setRevisions] = useState([]);+ const [status, setStatus] = useState(null);const [loading, setLoading] = useState(true);const [error, setError] = useState(null);+ const [applying, setApplying] = useState(false);+ const [backupFirst, setBackupFirst] = useState(true);- useEffect(() => {- loadHistory();- }, []);-- async function loadHistory() {+ const load = useCallback(async () => {try {setLoading(true);- const data = await api.getMigrationHistory();- setRevisions(data.revisions || []);+ setError(null);+ const [hist, stat] = await Promise.all([+ api.getMigrationHistory(),+ api.getMigrationStatus(),+ ]);+ setRevisions(hist.revisions || []);+ setStatus(stat);} catch (err) {setError(err.message || 'Failed to load migration history');} finally {setLoading(false);}+ }, []);++ useEffect(() => { load(); }, [load]);++ // History is returned oldest -> newest along a linear chain. Everything after+ // the applied (current) revision is unapplied, through head. status.pending_count+ // is computed once at boot and can be stale, so trust the ordered history.+ const currentIdx = revisions.findIndex((r) => r.is_current);+ const pending = currentIdx >= 0 ? revisions.slice(currentIdx + 1) : revisions.slice();+ const pendingIds = new Set(pending.map((r) => r.revision));+ const hasPending = pending.length > 0;++ const currentRev = status?.current_revision;+ const headRev = status?.head_revision;+ const count = pending.length;+ const plural = count === 1 ? '' : 's';++ // The DB records a revision that no longer exists in the migration scripts+ // (renamed during development). The schema is already in sync, so applying+ // re-stamps the version pointer rather than running DDL.+ const orphaned = Boolean(currentRev) && currentIdx === -1 && revisions.length > 0;++ async function runMigrations() {+ const ok = await confirm({+ title: orphaned ? 'Re-sync database version?' : `Apply ${count} migration${plural}?`,+ message: orphaned+ ? `Your schema already matches ${short(headRev) || 'head'}; this repairs the version pointer${backupFirst ? ' after creating a backup' : ' (no backup will be created)'}.`+ : backupFirst+ ? `A database backup is created first, then the schema is upgraded from ${short(currentRev) || 'none'} to ${short(headRev) || 'head'}.`+ : `The schema is upgraded from ${short(currentRev) || 'none'} to ${short(headRev) || 'head'}. No backup will be created.`,+ confirmText: orphaned ? 'Re-sync database' : `Apply migration${plural}`,+ cancelText: 'Cancel',+ variant: 'warning',+ });+ if (!ok) return;++ setApplying(true);+ try {+ if (backupFirst) {+ try {+ const b = await api.createMigrationBackup();+ const name = b?.path ? b.path.split(/[\\/]/).pop() : null;+ toast.success(name ? `Database backed up (${name})` : 'Database backed up');+ } catch (err) {+ toast.error(`Backup failed: ${err.message || 'unknown error'} — migrations not applied`);+ return;+ }+ }+ const res = await api.applyMigrations();+ toast.success(`Migrations applied — now at ${short(res?.revision || headRev)}`);+ await load();+ } catch (err) {+ toast.error(`Migration failed: ${err.message || 'unknown error'}`);+ } finally {+ setApplying(false);+ }}if (loading) {@@ -50,10 +120,67 @@ const MigrationHistoryTab = () => {<div className="settings-section-header"><h2>Database Migrations</h2><p className="settings-section-description">- History of all database schema versions applied to this instance.+ Schema versions applied to this instance. Apply pending updates after upgrading ServerKit.</p></div>+ {hasPending ? (+ <div className="migration-pending-banner">+ <ArrowUpCircle size={20} className="migration-pending-icon" aria-hidden="true" />+ <div className="migration-pending-body">+ <p className="migration-pending-title">+ {orphaned ? 'Database version needs repair' : `${count} migration${plural} pending`}+ </p>+ <p className="migration-pending-desc">+ {orphaned ? (+ <>+ Recorded version <code>{short(currentRev)}</code> isn’t in the migration+ history (it was renamed). Your schema already matches{' '}+ <code>{short(headRev) || 'head'}</code> — re-sync to repair the version pointer.+ </>+ ) : (+ <>+ Your database is at <code>{short(currentRev) || 'none'}</code>, latest is{' '}+ <code>{short(headRev) || 'unknown'}</code>. Apply to bring the schema up to date.+ </>+ )}+ </p>+ <div className="migration-pending-actions">+ <button+ type="button"+ className="btn btn-primary btn-sm"+ onClick={runMigrations}+ disabled={applying}+ >+ {applying ? (+ <><Loader size={14} className="spin" /> {orphaned ? 'Repairing…' : 'Applying…'}</>+ ) : orphaned ? (+ <><Database size={14} /> Re-sync database</>+ ) : (+ <><Database size={14} /> Apply {count} migration{plural}</>+ )}+ </button>+ <label className="migration-backup-toggle">+ <input+ type="checkbox"+ checked={backupFirst}+ onChange={(e) => setBackupFirst(e.target.checked)}+ disabled={applying}+ />+ Back up database first+ </label>+ </div>+ </div>+ </div>+ ) : (+ revisions.length > 0 && (+ <div className="migration-uptodate">+ <ShieldCheck size={16} aria-hidden="true" />+ Schema is up to date{currentRev && <> — revision <code>{short(currentRev)}</code></>}.+ </div>+ )+ )}+{revisions.length === 0 ? (<div className="empty-state"><Database size={32} />@@ -73,21 +200,19 @@ const MigrationHistoryTab = () => {{revisions.map((rev, i) => (<tr key={i}><td>- <code>{rev.revision.substring(0, 16)}</code>+ <code>{short(rev.revision)}</code></td><td>{rev.description || 'Schema update'}</td><td>- {rev.is_current && (+ {rev.is_current ? (<Badge variant="success"><CheckCircle size={12} /> Current</Badge>- )}- {rev.is_head && !rev.is_current && (+ ) : pendingIds.has(rev.revision) ? (<Badge variant="warning"><ArrowUpCircle size={12} /> Pending</Badge>- )}- {!rev.is_current && !rev.is_head && (+ ) : (<Badge variant="secondary">Applied</Badge>)}</td>@@ -97,6 +222,17 @@ const MigrationHistoryTab = () => {</table></div>)}++ <ConfirmDialog+ isOpen={confirmState.isOpen}+ title={confirmState.title}+ message={confirmState.message}+ confirmText={confirmState.confirmText}+ cancelText={confirmState.cancelText}+ variant={confirmState.variant}+ onConfirm={handleConfirm}+ onCancel={handleCancel}+ /></div>);};diff --git a/frontend/src/components/settings/SiteSettingsTab.jsx b/frontend/src/components/settings/SiteSettingsTab.jsxindex a6aebf72..911dce3d 100644--- a/frontend/src/components/settings/SiteSettingsTab.jsx+++ b/frontend/src/components/settings/SiteSettingsTab.jsx@@ -2,14 +2,18 @@ import React, { useState, useEffect } from 'react';import api from '../../services/api';import { Switch } from '@/components/ui/switch';import { Label } from '@/components/ui/label';+import { Input } from '@/components/ui/input';+import { Button } from '@/components/ui/button';const SiteSettingsTab = ({ onDevModeChange }) => {const [settings, setSettings] = useState({registration_enabled: false,dev_mode: false});+ const [basePort, setBasePort] = useState('0');const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);+ const [savingPort, setSavingPort] = useState(false);const [message, setMessage] = useState(null);useEffect(() => {@@ -23,6 +27,7 @@ const SiteSettingsTab = ({ onDevModeChange }) => {registration_enabled: data.registration_enabled || false,dev_mode: data.dev_mode || false});+ setBasePort(String(data.managed_app_base_port ?? 0));} catch (err) {console.error('Failed to load settings:', err);} finally {@@ -30,6 +35,30 @@ const SiteSettingsTab = ({ onDevModeChange }) => {}}+ async function handleSaveBasePort() {+ const value = parseInt(basePort, 10);+ if (Number.isNaN(value) || value < 0 || value > 65535) {+ setMessage({ type: 'error', text: 'Base port must be between 0 and 65535 (0 = template default)' });+ return;+ }+ setSavingPort(true);+ setMessage(null);+ try {+ await api.updateSystemSetting('managed_app_base_port', value);+ setBasePort(String(value));+ setMessage({+ type: 'success',+ text: value === 0+ ? 'Base port reset — new apps use each template\'s default'+ : `New apps will be assigned ports starting from ${value}`+ });+ } catch (err) {+ setMessage({ type: 'error', text: err.message || 'Failed to update base port' });+ } finally {+ setSavingPort(false);+ }+ }+async function handleToggleSetting(key, label) {setSaving(true);setMessage(null);@@ -83,6 +112,39 @@ const SiteSettingsTab = ({ onDevModeChange }) => {</div></div>+ <div className="settings-card">+ <h3>Managed App Ports</h3>+ <p>Control the host port assigned to new WordPress sites and other managed apps.</p>++ <div className="form-group">+ <div className="settings-row">+ <div className="settings-label">+ <Label htmlFor="managed-app-base-port">Base port</Label>+ </div>+ <div className="settings-control">+ <Input+ id="managed-app-base-port"+ type="number"+ min={0}+ max={65535}+ value={basePort}+ onChange={(e) => setBasePort(e.target.value)}+ disabled={savingPort}+ className="w-32"+ />+ <Button onClick={handleSaveBasePort} disabled={savingPort}>+ {savingPort ? 'Saving…' : 'Save'}+ </Button>+ </div>+ </div>+ <span className="form-help">+ New apps get the first free port at or above this number. Set to <strong>0</strong> to+ use each template's own default (WordPress starts at 8300). Ports already in use are+ always skipped, so collisions can't happen.+ </span>+ </div>+ </div>+<div className="settings-card"><h3>Developer Mode</h3><p>Enable developer tools and diagnostics.</p>diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsxindex 0e27d369..36897384 100644--- a/frontend/src/pages/Databases.jsx+++ b/frontend/src/pages/Databases.jsx@@ -46,6 +46,21 @@ function dbNode(engine, conn, label, size, idOverride) {};}+// A database living inside a Docker container, surfaced under its engine node+// (e.g. a WordPress stack's MySQL appears under "MySQL / MariaDB"). Tagged with+// source/appName so the tree can show a Docker badge.+function dockerDbNode(engine, db, i) {+ return {+ id: `${engine}:docker:${db.container}:${db.database || 'default'}:${i}`,+ kind: 'database', engine, label: db.database || 'default', expandable: true,+ conn: {+ dbType: 'docker', container: db.container, name: db.database,+ password: db.password || db.root_password, user: db.user, dockerType: db.type,+ },+ source: 'docker', appName: db.app_name,+ };+}+function TabIcon({ tab }) {if (tab.kind === 'backups') return <Archive size={13} aria-hidden="true" />;if (tab.kind === 'console') return <Terminal size={13} aria-hidden="true" />;@@ -97,8 +112,10 @@ export default function Databases() {}, []);const roots = useMemo(() => ([- { id: 'eng:mysql', kind: 'engine', engine: 'mysql', label: ENGINE_META.mysql.label, status: engineState('mysql', status), expandable: engineState('mysql', status) === 'active' },- { id: 'eng:postgresql', kind: 'engine', engine: 'postgresql', label: ENGINE_META.postgresql.label, status: engineState('postgresql', status), expandable: engineState('postgresql', status) === 'active' },+ // mysql/postgresql stay expandable even when the host engine is absent —+ // they can still contain databases that live in Docker containers.+ { id: 'eng:mysql', kind: 'engine', engine: 'mysql', label: ENGINE_META.mysql.label, status: engineState('mysql', status), expandable: true },+ { id: 'eng:postgresql', kind: 'engine', engine: 'postgresql', label: ENGINE_META.postgresql.label, status: engineState('postgresql', status), expandable: true },{ id: 'eng:sqlite', kind: 'engine', engine: 'sqlite', label: ENGINE_META.sqlite.label, status: 'available', expandable: true },{ id: 'eng:docker', kind: 'engine', engine: 'docker', label: ENGINE_META.docker.label, status: 'available', expandable: true },]), [status]);@@ -107,12 +124,22 @@ export default function Databases() {const loadChildren = useCallback(async (node) => {if (node.kind === 'engine') {if (node.engine === 'mysql') {- const d = await api.getMySQLDatabases();- return (d.databases || []).map((db) => dbNode('mysql', { dbType: 'mysql', name: db.name }, db.name, db.size));+ const [host, docker] = await Promise.all([+ api.getMySQLDatabases().catch(() => ({ databases: [] })),+ api.getAllDockerDatabases().catch(() => ({ databases: [] })),+ ]);+ const hostNodes = (host.databases || []).map((db) => dbNode('mysql', { dbType: 'mysql', name: db.name }, db.name, db.size));+ const dockerNodes = (docker.databases || []).filter((db) => db.type === 'mysql').map((db, i) => dockerDbNode('mysql', db, i));+ return [...hostNodes, ...dockerNodes];}if (node.engine === 'postgresql') {- const d = await api.getPostgreSQLDatabases();- return (d.databases || []).map((db) => dbNode('postgresql', { dbType: 'postgresql', name: db.name }, db.name, db.size));+ const [host, docker] = await Promise.all([+ api.getPostgreSQLDatabases().catch(() => ({ databases: [] })),+ api.getAllDockerDatabases().catch(() => ({ databases: [] })),+ ]);+ const hostNodes = (host.databases || []).map((db) => dbNode('postgresql', { dbType: 'postgresql', name: db.name }, db.name, db.size));+ const dockerNodes = (docker.databases || []).filter((db) => db.type === 'postgresql').map((db, i) => dockerDbNode('postgresql', db, i));+ return [...hostNodes, ...dockerNodes];}if (node.engine === 'sqlite') {const d = await api.getSQLiteDatabases();@@ -128,7 +155,9 @@ export default function Databases() {if (node.kind === 'app') {const d = await api.getAppDatabases(node.appId);return (d.databases || []).map((db, i) => ({- id: `app:${node.appId}:db:${i}`, kind: 'database', engine: 'docker',+ // engine = the brand (mysql/postgresql) so the row shows the right+ // brand icon/tint; the connection is still routed over docker exec.+ id: `app:${node.appId}:db:${i}`, kind: 'database', engine: db.type || 'docker',label: db.database || 'default', expandable: true,conn: { dbType: 'docker', container: db.container, name: db.database, password: db.password || db.root_password, user: db.user, dockerType: db.type },}));diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.jsindex 56472557..9df91824 100644--- a/frontend/src/services/api/client.js+++ b/frontend/src/services/api/client.js@@ -48,14 +48,18 @@ class ApiClient {// — the backend resolves it leniently (falls back to no scope).const activeWorkspace = localStorage.getItem('active_workspace_id');+ // Spread `...options` FIRST, then set merged headers LAST — otherwise a+ // call passing custom `headers` (e.g. X-DB-Password) would clobber the+ // whole merged set, dropping Content-Type/Authorization and triggering+ // 415 (no application/json) on JSON POSTs.const config = {+ ...options,headers: {...(isFormData ? {} : { 'Content-Type': 'application/json' }),...(token && { Authorization: `Bearer ${token}` }),...(activeWorkspace && activeWorkspace !== 'all' && { 'X-Workspace-Id': activeWorkspace }),...options.headers,},- ...options,};if (diff --git a/frontend/src/services/api/databases.js b/frontend/src/services/api/databases.jsindex 878ec1e8..b9f2c312 100644--- a/frontend/src/services/api/databases.js+++ b/frontend/src/services/api/databases.js@@ -184,6 +184,12 @@ export async function getDockerDatabases() {return this.request('/databases/docker');}+// Flat list of databases discovered across all Docker apps, tagged with engine+// + owning app — used to surface containerised DBs under their engine node.+export async function getAllDockerDatabases() {+ return this.request('/databases/docker/databases');+}+export async function getAppDatabases(appId) {return this.request(`/databases/docker/app/${appId}`);}@@ -193,16 +199,17 @@ export async function getDockerContainerDatabases(container, password = null) {return this.request(`/databases/docker/${container}/databases`, { headers });}-export async function getDockerDatabaseTables(container, database, password = null) {+export async function getDockerDatabaseTables(container, database, password = null, user = null) {const headers = password ? { 'X-DB-Password': password } : {};- return this.request(`/databases/docker/${container}/${database}/tables`, { headers });+ const params = user ? `?user=${encodeURIComponent(user)}` : '';+ return this.request(`/databases/docker/${container}/${database}/tables${params}`, { headers });}-export async function executeDockerQuery(container, database, query, password = null, readonly = true) {+export async function executeDockerQuery(container, database, query, password = null, readonly = true, user = null) {const headers = password ? { 'X-DB-Password': password } : {};return this.request(`/databases/docker/${container}/${database}/query`, {method: 'POST',- body: { query, readonly, password },+ body: { query, readonly, password, user },headers});}diff --git a/frontend/src/styles/_variables.scss b/frontend/src/styles/_variables.scssindex 5d466958..98a4f4c5 100644--- a/frontend/src/styles/_variables.scss+++ b/frontend/src/styles/_variables.scss@@ -105,6 +105,9 @@ $color-mysql: #f29111;$color-mysql-secondary: #00758f;$color-postgresql: #336791;$color-postgresql-secondary: #5f9ab8;+$color-mariadb: #c0765a;+$color-mongodb: #00ed64;+$color-redis: #ff4438;$color-docker: #2496ed;$color-php: #777bb4;$color-python: #3776ab;diff --git a/frontend/src/styles/pages/_databases.scss b/frontend/src/styles/pages/_databases.scssindex 155f9d74..5e2644d9 100644--- a/frontend/src/styles/pages/_databases.scss+++ b/frontend/src/styles/pages/_databases.scss@@ -74,7 +74,7 @@ $dbx-sqlite: #3d8fd1;font-size: $font-size-sm;font-weight: $font-weight-semibold;cursor: pointer;- box-shadow: 0 6px 16px fade($accent-primary-raw, 22%);+ box-shadow: $shadow-accent;transition: background $transition-fast, transform $transition-fast;&:hover { background: $accent-hover; }@@ -272,11 +272,32 @@ $dbx-sqlite: #3d8fd1;// engine tints on the leading icon&.is-mysql .dbx-tree-icon { color: $color-mysql; }&.is-postgresql .dbx-tree-icon { color: $color-postgresql; }+ &.is-mariadb .dbx-tree-icon { color: $color-mariadb; }+ &.is-mongodb .dbx-tree-icon { color: $color-mongodb; }+ &.is-redis .dbx-tree-icon { color: $color-redis; }&.is-sqlite .dbx-tree-icon { color: $dbx-sqlite; }&.is-docker .dbx-tree-icon { color: $color-docker; }&.is-table .dbx-tree-icon { color: $text-tertiary; }}+ // "lives in a Docker container" badge on a database row surfaced under its+ // engine node — a small docker-blue chip carrying the owning app's name.+ .dbx-tree-source {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ flex-shrink: 0;+ margin-left: $space-1;+ padding: 1px 6px;+ font-size: 10px;+ font-weight: $font-weight-medium;+ line-height: 1.5;+ border-radius: $radius-full;+ color: $color-docker;+ background: fade($color-docker, 12%);+ svg { flex-shrink: 0; }+ }+.dbx-tree-chevron {display: flex;align-items: center;@@ -450,6 +471,19 @@ $dbx-sqlite: #3d8fd1;padding: $space-8;}+ // The workspace is already a bordered card, so the global .empty-state card+ // (components/_cards.scss) renders here as a faint card-in-card outline — its+ // fill matches the workspace, so only the border shows. That guard only drops+ // inside `.card`, which this surface isn't. Neutralize it for empty/result+ // states so they read as clean centered content, not a nested card.+ .dbx-welcome .empty-state,+ .dbx-grid-status .empty-state {+ background: transparent;+ border: none;+ border-radius: 0;+ padding: $space-6 $space-5;+ }+// ─── Console ──────────────────────────────────────────.dbx-console { display: flex; flex-direction: column; height: 100%; min-height: 0; }@@ -479,10 +513,12 @@ $dbx-sqlite: #3d8fd1;font-size: $font-size-sm;font-weight: $font-weight-semibold;cursor: pointer;- transition: background $transition-fast;+ box-shadow: $shadow-accent;+ transition: background $transition-fast, transform $transition-fast;&:hover:not(:disabled) { background: $accent-hover; }- &:disabled { opacity: 0.5; cursor: not-allowed; }+ &:active:not(:disabled) { transform: translateY(1px); }+ &:disabled { opacity: 0.5; cursor: not-allowed; box-shadow: none; }kbd {font-family: $font-mono;font-size: 10px;@@ -822,7 +858,7 @@ $dbx-sqlite: #3d8fd1;padding: $space-1 $space-3;background: $bg-card;border: 1px solid $border-default;- border-radius: $radius-md;+ border-radius: $radius-lg;flex-shrink: 0;flex-wrap: wrap;}diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scssindex d8d482ef..afb3ede6 100644--- a/frontend/src/styles/pages/_settings.scss+++ b/frontend/src/styles/pages/_settings.scss@@ -1882,6 +1882,75 @@}}+// ─── Database Migrations ──────────────────────────────────────+// Pending-update banner + apply action on the Settings → Migrations tab.+.migration-pending-banner {+ display: flex;+ align-items: flex-start;+ gap: $space-3;+ padding: $space-4;+ margin-bottom: $space-4;+ background: fade($warning, 10%);+ border: 1px solid fade($warning, 20%);+ border-radius: $radius-md;++ .migration-pending-icon { color: $warning; flex-shrink: 0; margin-top: 1px; }+ .migration-pending-body { flex: 1; min-width: 0; }++ .migration-pending-title {+ margin: 0 0 $space-1;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }++ .migration-pending-desc {+ margin: 0 0 $space-3;+ font-size: $font-size-sm;+ color: $text-secondary;+ }++ .migration-pending-actions {+ display: flex;+ align-items: center;+ gap: $space-4;+ flex-wrap: wrap;+ }++ .migration-backup-toggle {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ font-size: $font-size-sm;+ color: $text-secondary;+ cursor: pointer;+ user-select: none;++ input { accent-color: $accent-primary; cursor: pointer; }+ }+}++.migration-uptodate {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ margin-bottom: $space-4;+ font-size: $font-size-sm;+ color: $text-secondary;++ svg { color: $success; flex-shrink: 0; }+}++// Inline code chips shared by the banner and the up-to-date line.+.migration-pending-desc code,+.migration-uptodate code {+ font-family: $font-mono;+ font-size: $font-size-xs;+ padding: 1px 5px;+ background: $bg-tertiary;+ border-radius: $radius-sm;+ color: $text-primary;+}+// Items toggle list.sidebar-items-list {display: flex;