Skip to content

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.

feat(workspaces): active-workspace selector + ambient X-Workspace-Id header (#33)

Juan Denisddff69020bab
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index f266a323..1809f583 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -299,6 +299,7 @@ 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.)*
### #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/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 756495fc..84d2f795 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -5,6 +5,7 @@ import { useTheme } from '../contexts/ThemeContext';
import { Star, Settings, LogOut, Sun, Moon, Monitor, ChevronRight, ChevronDown, ChevronUp, Layers, Palette, PanelLeft, Check, X } from 'lucide-react';
import { api } from '../services/api';
import ServerKitLogo from './ServerKitLogo';
+import WorkspaceSwitcher from './WorkspaceSwitcher';
import { SIDEBAR_CATEGORIES, CATEGORY_LABELS, SIDEBAR_PRESETS, getHiddenItemIds, getVisibleItems } from './sidebarItems';
import { useContributions } from '../plugins/contributions';
@@ -285,6 +286,8 @@ const Sidebar = ({ mobileOpen = false, isMobile = false, onMobileClose = () => {
</div>
)}
+ <WorkspaceSwitcher />
+
<div className="nav-scroll">
{SIDEBAR_CATEGORIES.map(cat => {
const items = groupedItems[cat];
diff --git a/frontend/src/components/WorkspaceSwitcher.jsx b/frontend/src/components/WorkspaceSwitcher.jsx
new file mode 100644
index 00000000..1fcdc393
--- /dev/null
+++ b/frontend/src/components/WorkspaceSwitcher.jsx
@@ -0,0 +1,66 @@
+import { useEffect, useState } from 'react';
+import { Building2 } from 'lucide-react';
+import { api } from '../services/api';
+
+const ACTIVE_KEY = 'active_workspace_id';
+
+// Active-workspace selector (#33). Self-contained: it reads/writes the active
+// workspace in localStorage (which services/api/client.js sends ambiently as the
+// X-Workspace-Id header) and reloads so every page re-fetches its lists under the
+// new scope. Hidden unless the user belongs to more than one workspace, so
+// single-tenant installs stay uncluttered.
+const WorkspaceSwitcher = () => {
+ const [workspaces, setWorkspaces] = useState([]);
+ const [active, setActive] = useState(() => localStorage.getItem(ACTIVE_KEY) || 'all');
+
+ useEffect(() => {
+ let alive = true;
+ api.getWorkspaces()
+ .then((res) => {
+ 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');
+ }
+ })
+ .catch(() => { /* best-effort; the selector just won't render */ });
+ return () => { alive = false; };
+ }, []);
+
+ if (workspaces.length < 2) return null;
+
+ const handleChange = (e) => {
+ const value = e.target.value;
+ if (value === 'all') {
+ localStorage.removeItem(ACTIVE_KEY);
+ } else {
+ localStorage.setItem(ACTIVE_KEY, value);
+ }
+ // Reload so every page re-fetches its lists under the new workspace scope.
+ window.location.reload();
+ };
+
+ return (
+ <div className="workspace-switcher">
+ <Building2 size={14} className="workspace-switcher__icon" aria-hidden="true" />
+ <select
+ className="workspace-switcher__select"
+ value={active}
+ onChange={handleChange}
+ aria-label="Active workspace"
+ >
+ <option value="all">All workspaces</option>
+ {workspaces.map((w) => (
+ <option key={w.id} value={String(w.id)}>{w.name}</option>
+ ))}
+ </select>
+ </div>
+ );
+};
+
+export default WorkspaceSwitcher;
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index 6cc117fb..4f37b384 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -31,6 +31,7 @@ class ApiClient {
clearTokens() {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
+ localStorage.removeItem('active_workspace_id'); // drop workspace context on logout
}
async request(endpoint, options = {}) {
@@ -41,10 +42,16 @@ class ApiClient {
// and must NOT be JSON-stringified. Detect and bypass both.
const isFormData = options.body instanceof FormData;
+ // Active workspace context (#33). Sent ambiently so the backend can scope
+ // resources; endpoints that don't honor it ignore it. A stale value is safe
+ // — the backend resolves it leniently (falls back to no scope).
+ const activeWorkspace = localStorage.getItem('active_workspace_id');
+
const config = {
headers: {
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
...(token && { Authorization: `Bearer ${token}` }),
+ ...(activeWorkspace && activeWorkspace !== 'all' && { 'X-Workspace-Id': activeWorkspace }),
...options.headers,
},
...options,
diff --git a/frontend/src/styles/layout/_sidebar.scss b/frontend/src/styles/layout/_sidebar.scss
index 057df0e5..4da84892 100644
--- a/frontend/src/styles/layout/_sidebar.scss
+++ b/frontend/src/styles/layout/_sidebar.scss
@@ -269,6 +269,39 @@
}
// Scrollable Navigation Container
+// Active-workspace selector (#33) — sits between the brand and the nav.
+.workspace-switcher {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ margin: 0 $space-3 $space-2;
+ padding: $space-1 $space-2;
+ background-color: $bg-card;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+
+ &__icon {
+ flex-shrink: 0;
+ color: $text-secondary;
+ }
+
+ &__select {
+ flex: 1;
+ min-width: 0;
+ border: none;
+ background: transparent;
+ color: $text-primary;
+ font-size: $font-size-sm;
+ cursor: pointer;
+ outline: none;
+
+ &:focus-visible {
+ outline: 2px solid $accent-primary;
+ outline-offset: 1px;
+ }
+ }
+}
+
.nav-scroll {
flex: 1;
overflow-y: auto;