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
feat(workspaces): workspace-scoped brand color recolors the panel (#33)
Juan Denis567d6059f7dc
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 1809f583..2fabe536 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -299,7 +299,8 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c- **Assessment / why deferred:** A genuine **`XL`** multi-day epic (the roadmap's own guidance is "split before starting"), and it cuts across the whole system rather than the WordPress object: (1) `workspace_id` FK migrations on `Application`/`WordPressSite`/`Server` + backfill + scoping *every* list/query; (2) a per-site **ACL** model + enforcement woven through promote/sync/bulk endpoints; (3) moving white-label from `localStorage` to server-rendered, workspace-scoped branding; (4) a monthly **reports** generator aggregating the now-existing uptime (#26) / updates (#29) / backups / security (#28/#30) signals. Each sub-part is its own feature; done together they're a milestone, not a single change — and the cross-cutting FK + RBAC rework is high-blast-radius. **Foundation now in place from this session:** the report's data sources (per-site uptime/incidents #26, update history #29, vuln findings #28) all exist, so the reports sub-feature is the most self-contained slice to start with. Deferred to a dedicated milestone.- **Landed (reports slice):** the self-contained **monthly client reports** sub-feature shipped — the milestone's first slice, deliberately built *without* the high-blast-radius `workspace_id` rework. New `WpReportsService` aggregates a calendar month's signals into a single persisted, printable report: **uptime % + a daily series + incidents** re-aggregated from the bound status component's `HealthCheck` samples for the exact month (#26), **update runs** (counts + components-updated, #29), **DatabaseSnapshot backups** (count + bytes), and the **current vulnerability posture** (#28) + health/disk — each section honestly labelled PERSISTED-history vs point-in-time (vulns are snapshot-replaced each scan, so they're captured *as-of* generation; traffic/on-demand security scans are noted as excluded). **Why persisted, not live:** generation snapshots the point-in-time sources so a report regenerated months later still shows the right month's posture; the true-historical sources are re-queried per month. Generation is **synchronous** (pure DB aggregation — no WP-CLI/HTTP, so no background thread), and **upserts** per `(site, YYYY-MM)` so regenerating replaces. Client grouping is derived from the **`client-*` / `client:*` tag** (#20) — *no* `workspace_id` FK needed. New `WordPressReport` model (Alembic **014**, chains off `013_ai_assistant`; defined in `wordpress_site.py` + imported lazily in the service so the concurrent AI agent's `models/__init__.py` is never touched), routes `GET /sites/<id>/reports`, `POST …/reports/generate` (`@admin_required`), `DELETE …/reports/<rid>`, client `getReports`/`generateReport`/`deleteReport`, and a new **Reports tab** (month picker → generate, per-month selector, a recharts daily-uptime chart, summary stat cards, incident/update/backup/vuln sections) with a **Print → Save-as-PDF** path (scoped `@media print` isolation, no PDF dependency) and a **Download JSON** export. Verified: backend `py_compile`, **9 new pytest tests** (helpers, bound + unbound aggregation, upsert, future-month guard, API round-trip, + 2 regression tests for review fixes), frontend lint-clean + production build, and a 3-lens adversarial review (5 findings; 4 fixed — daily-series future-day off-by-one, ongoing-incident duration clamped to the in-month window, dead error branch, robust print-cleanup; the 5th — admin-only buttons shown to non-admin owners — left for parity with #28/#29/#30 which do the same). *(Still deferred for the dedicated milestone: cross-cutting `workspace_id` FKs + per-site ACL + server-side workspace-scoped branding. The report already inherits the operator's existing client-side white-label in-app; server-side branding upgrades cleanly later by feeding the same `{name, logo, color}` triplet into the print view.)* Not runtime-exercised on a real Docker host (Windows dev).- **Landed (workspace foundation slice):** the cross-cutting backbone the rest of #33 needs — a **nullable `workspace_id` FK** on `applications` + `servers` (Alembic **015**, chains off `014`, with an idempotent raw-SQL backfill that creates a **Default** workspace, attaches every workspace-less row, and makes every existing user a member so nobody loses visibility) + a **centralized scope helper** in `WorkspaceService` (`ensure_default_workspace`, `resolve_workspace_id`, `scope_query`). The design rule is **opt-in + narrow-only**: a request only filters by workspace when it carries an `X-Workspace-Id` header / `?workspace_id=`, and `scope_query` *intersects* the workspace filter with the existing per-user ownership filter so it can only ever **narrow** visibility, never broaden it — with no workspace context the behavior is byte-identical to before (admin→all, owner→own apps, servers global). Wired into `apps.py` (list + create) and `servers.py` (list + create), replacing the duplicated `if admin … else filter_by(user_id)` branch and **stamping** new resources with the active-or-default workspace. **Deliberately *not* a 36-route rewrite:** this lands the mechanism + the two core resource surfaces as the proven pattern; broad route adoption, per-site ACL, the workspace↔User role reconciliation, server-side branding, and a frontend active-workspace selector are the follow-on slices. Verified: backend `py_compile`, **10 new pytest tests** (helper branches, scope-narrowing, an explicit *can't-broaden-access* regression, deactivated-user gate, default-stamping, the raw-SQL backfill run against real SQLite + idempotency), full suite **120 passed**, a real end-to-end `alembic upgrade` to `015` on a fresh DB (columns + both indexes created), and a 2-lens adversarial review (3 findings, all fixed — `is_active` gate on the workspace path, FK-add guarded on the `workspaces` table existing, and the missing `workspace_id` indexes for upgraded installs). The earlier draft's biggest risk — that the backfill (everything→Default, everyone→member) plus a workspace filter would let a non-admin enumerate *all* resources via the default workspace — was caught and fixed pre-review by making `scope_query` intersect with ownership.-- **Landed (frontend workspace selector):** the keystone that makes the foundation user-visible — the research flagged "no current-workspace context in the frontend" as *the* gap #33 must close. A self-contained `WorkspaceSwitcher` in the sidebar reads/writes an `active_workspace_id` in `localStorage`, which the central API client (`services/api/client.js`) now sends ambiently as the **`X-Workspace-Id` header** on every request (endpoints that don't honor it ignore it; cleared on logout). Switching reloads so all lists re-fetch under the new scope; the switcher self-hides for single-workspace installs and drops a stale selection on load. To make an ambient header safe, backend `resolve_workspace_id` was first made **lenient** (a deleted/forbidden workspace degrades to no-scope instead of 403/404, so a stale header can never break the apps/servers lists — still safe since no-scope only ever shows the user's *own* resources). Verified: frontend lint-clean + production build; the header→scoping path is covered end-to-end by the backend API tests. *(Follow-on: surfacing `workspace_id` in more list endpoints, a workspace management UX beyond the existing admin list, and server-side branding keyed off the active workspace.)*+- **Landed (frontend workspace selector):** the keystone that makes the foundation user-visible — the research flagged "no current-workspace context in the frontend" as *the* gap #33 must close. A self-contained `WorkspaceSwitcher` in the sidebar reads/writes an `active_workspace_id` in `localStorage`, which the central API client (`services/api/client.js`) now sends ambiently as the **`X-Workspace-Id` header** on every request (endpoints that don't honor it ignore it; cleared on logout). Switching reloads so all lists re-fetch under the new scope; the switcher self-hides for single-workspace installs and drops a stale selection on load. To make an ambient header safe, backend `resolve_workspace_id` was first made **lenient** (a deleted/forbidden workspace degrades to no-scope instead of 403/404, so a stale header can never break the apps/servers lists — still safe since no-scope only ever shows the user's *own* resources). Verified: frontend lint-clean + production build; the header→scoping path is covered end-to-end by the backend API tests. *(Follow-on: surfacing `workspace_id` in more list endpoints, a workspace management UX beyond the existing admin list, and per-workspace logo override.)*+- **Landed (workspace-scoped brand color):** the visible payoff — selecting a client workspace now recolors the whole panel to that client's brand. A workspace's `primary_color` (already on the model; now editable via a color picker added to the Workspaces create modal) is mirrored by the `WorkspaceSwitcher` into a `workspace_accent` localStorage key, and `ThemeContext` applies it via the existing `applyAccentToDOM` with **precedence over the user's personal accent** (`workspace_accent || accentColor`) — recoloring the logo gradient, buttons, and highlights. Deterministic (no effect-ordering races) because switching reloads and the value is read once on mount; cleared on logout and on a stale selection; reverts to the user accent on "All workspaces". Default color is the app accent, so a workspace is unbranded unless a custom color is chosen. Verified: frontend lint-clean (no new warnings) + production build. *(Deferred: per-workspace logo swap in the sidebar brand — the accent recolor is the high-impact piece and the default logo already recolors with the accent.)*### #34 — Horizontal scaling `[XL]` ❌ — ⏸️ Deferred (XL + blocked on the same per-site reverse-proxy/upstream layer as #21)- **Today:** `nginx_advanced_service` has load-balancing primitives (round-robin/least-conn/IP-hash) but WP containers are stateful (local uploads, no shared object cache).diff --git a/frontend/src/components/WorkspaceSwitcher.jsx b/frontend/src/components/WorkspaceSwitcher.jsxindex 1fcdc393..d34c2aea 100644--- a/frontend/src/components/WorkspaceSwitcher.jsx+++ b/frontend/src/components/WorkspaceSwitcher.jsx@@ -3,6 +3,17 @@ import { Building2 } from 'lucide-react';import { api } from '../services/api';const ACTIVE_KEY = 'active_workspace_id';+const ACCENT_KEY = 'workspace_accent'; // ThemeContext applies this with precedence over the user accent++// Mirror a workspace's brand color into localStorage so ThemeContext can apply it+// (with precedence over the user's accent), or clear it when there's no color.+function syncAccent(ws) {+ if (ws && ws.primary_color) {+ localStorage.setItem(ACCENT_KEY, ws.primary_color);+ } else {+ localStorage.removeItem(ACCENT_KEY);+ }+}// Active-workspace selector (#33). Self-contained: it reads/writes the active// workspace in localStorage (which services/api/client.js sends ambiently as the@@ -20,12 +31,19 @@ const WorkspaceSwitcher = () => {if (!alive) return;const list = res?.workspaces || [];setWorkspaces(list);- // Drop a stale selection (workspace deleted / access lost) so a dead- // X-Workspace-Id header isn't sent on every request.const stored = localStorage.getItem(ACTIVE_KEY);- if (stored && stored !== 'all' && !list.some((w) => String(w.id) === stored)) {- localStorage.removeItem(ACTIVE_KEY);- setActive('all');+ if (stored && stored !== 'all') {+ const ws = list.find((w) => String(w.id) === stored);+ if (!ws) {+ // Stale selection (workspace deleted / access lost): clear it so+ // a dead X-Workspace-Id header / brand color isn't applied.+ localStorage.removeItem(ACTIVE_KEY);+ localStorage.removeItem(ACCENT_KEY);+ setActive('all');+ } else {+ // Keep the brand color fresh for the next load if the admin changed it.+ syncAccent(ws);+ }}}).catch(() => { /* best-effort; the selector just won't render */ });@@ -38,10 +56,13 @@ const WorkspaceSwitcher = () => {const value = e.target.value;if (value === 'all') {localStorage.removeItem(ACTIVE_KEY);+ localStorage.removeItem(ACCENT_KEY);} else {localStorage.setItem(ACTIVE_KEY, value);+ syncAccent(workspaces.find((w) => String(w.id) === value));}- // Reload so every page re-fetches its lists under the new workspace scope.+ // Reload so every page re-fetches its lists (and re-applies the brand color)+ // under the new workspace scope.window.location.reload();};diff --git a/frontend/src/contexts/ThemeContext.jsx b/frontend/src/contexts/ThemeContext.jsxindex ba42f333..bfabada4 100644--- a/frontend/src/contexts/ThemeContext.jsx+++ b/frontend/src/contexts/ThemeContext.jsx@@ -76,6 +76,12 @@ export function ThemeProvider({ children }) {}});+ // Active-workspace branding (#33): when a workspace is selected, its accent+ // color (written to localStorage by the WorkspaceSwitcher) takes precedence+ // over the user's personal accent. It only changes on reload — the switcher+ // reloads on switch — so a one-time read is deterministic and sufficient.+ const workspaceAccent = localStorage.getItem('workspace_accent') || null;+// Update the DOM attribute and resolved themeconst applyTheme = useCallback((newTheme) => {document.documentElement.setAttribute('data-theme', newTheme);@@ -89,12 +95,13 @@ export function ThemeProvider({ children }) {applyTheme(newTheme);}, [applyTheme]);- // Public setter for accent color+ // Public setter for accent color. Persists the user's choice but keeps an+ // active workspace's brand color in precedence while one is selected.const setAccentColor = useCallback((hex) => {setAccentColorState(hex);localStorage.setItem('accent_color', hex);- applyAccentToDOM(hex);- }, []);+ applyAccentToDOM(workspaceAccent || hex);+ }, [workspaceAccent]);// Public setter for white label config (accepts partial updates)const setWhiteLabel = useCallback((partial) => {@@ -119,11 +126,11 @@ export function ThemeProvider({ children }) {return () => mediaQuery.removeEventListener('change', handleChange);}, [theme]);- // Apply theme and accent on mount+ // Apply theme and accent on mount (workspace brand color wins when active).useEffect(() => {applyTheme(theme);- applyAccentToDOM(accentColor);- }, [theme, applyTheme, accentColor]);+ applyAccentToDOM(workspaceAccent || accentColor);+ }, [theme, applyTheme, accentColor, workspaceAccent]);const value = {theme, // Current setting: 'dark' | 'light' | 'system'diff --git a/frontend/src/pages/Workspaces.jsx b/frontend/src/pages/Workspaces.jsxindex 8061149e..db27e0eb 100644--- a/frontend/src/pages/Workspaces.jsx+++ b/frontend/src/pages/Workspaces.jsx@@ -21,7 +21,7 @@ const Workspaces = () => {const [members, setMembers] = useState([]);const [deleteConfirm, setDeleteConfirm] = useState(null);const [allUsers, setAllUsers] = useState([]);- const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0 });+ const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6366f1' });const loadWorkspaces = useCallback(async () => {try {@@ -41,7 +41,7 @@ const Workspaces = () => {await api.createWorkspace(form);toast.success('Workspace created');setShowCreateModal(false);- setForm({ name: '', description: '', max_servers: 0, max_users: 0 });+ setForm({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6366f1' });loadWorkspaces();} catch (err) {toast.error(err.message);@@ -190,6 +190,17 @@ const Workspaces = () => {<Input type="number" value={form.max_users} onChange={e => setForm({...form, max_users: parseInt(e.target.value) || 0})} /></div></div>+ <div className="form-group">+ <label>Brand Color</label>+ <input+ type="color"+ className="workspace-color-input"+ value={form.primary_color}+ onChange={e => setForm({...form, primary_color: e.target.value})}+ aria-label="Workspace brand color"+ />+ <span className="form-hint">Recolors the panel for anyone viewing this workspace. Leave the default for no custom branding.</span>+ </div></div><div className="modal-footer"><Button variant="outline" onClick={() => setShowCreateModal(false)}>Cancel</Button>diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.jsindex 4f37b384..56472557 100644--- a/frontend/src/services/api/client.js+++ b/frontend/src/services/api/client.js@@ -32,6 +32,7 @@ class ApiClient {localStorage.removeItem('access_token');localStorage.removeItem('refresh_token');localStorage.removeItem('active_workspace_id'); // drop workspace context on logout+ localStorage.removeItem('workspace_accent');}async request(endpoint, options = {}) {diff --git a/frontend/src/styles/pages/_workspaces.scss b/frontend/src/styles/pages/_workspaces.scssindex 24258f71..a2f9202f 100644--- a/frontend/src/styles/pages/_workspaces.scss+++ b/frontend/src/styles/pages/_workspaces.scss@@ -103,3 +103,15 @@&:hover { background: $hover-bg; }}}++// Brand-color picker in the workspace create modal (#33). Top-level because the+// modal renders outside the .workspaces page block.+.workspace-color-input {+ width: 48px;+ height: 32px;+ padding: 2px;+ border: 1px solid $border-color;+ border-radius: $radius-md;+ background: transparent;+ cursor: pointer;+}