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): manage servers in the workspace Resources modal (#33)
Juan Denis35c7a73d8c61
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 4a1eeac3..39bc2ef7 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -301,7 +301,7 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c- **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 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.)*-- **Landed (resource reassignment):** completes the organizing loop — existing resources were stuck wherever the backfill put them (Default); now they can be moved into client workspaces. New endpoints `PUT /apps/<id>/workspace` (owner-or-admin on the app) and `PUT /servers/<id>/workspace` (developer+), both requiring the **target** be a workspace the caller can access (member or admin); a null target moves a resource back to Default. UI: an **Apps** management modal on each Workspaces card (mirrors the Members modal) listing the workspace's apps with move-in/move-out — it fetches with `allWorkspaces` (an empty `X-Workspace-Id` header) so it can see apps in other workspaces to move them in, sidestepping the ambient scope. **Fixed a real bug** caught by tests: the ownership check compared `app.user_id` to the *stringified* `get_jwt_identity()` (int≠str → spurious 403); now uses `user.id`. Verified: backend `py_compile`, **2 new endpoint tests** (ownership + target-membership + null→Default + role gates), full suite **122 passed**, frontend lint-clean + production build. *(Servers reassignment is API-only for now; the management modal is apps-only.)*+- **Landed (resource reassignment):** completes the organizing loop — existing resources were stuck wherever the backfill put them (Default); now they can be moved into client workspaces. New endpoints `PUT /apps/<id>/workspace` (owner-or-admin on the app) and `PUT /servers/<id>/workspace` (developer+), both requiring the **target** be a workspace the caller can access (member or admin); a null target moves a resource back to Default. UI: an **Apps** management modal on each Workspaces card (mirrors the Members modal) listing the workspace's apps with move-in/move-out — it fetches with `allWorkspaces` (an empty `X-Workspace-Id` header) so it can see apps in other workspaces to move them in, sidestepping the ambient scope. **Fixed a real bug** caught by tests: the ownership check compared `app.user_id` to the *stringified* `get_jwt_identity()` (int≠str → spurious 403); now uses `user.id`. Verified: backend `py_compile`, **2 new endpoint tests** (ownership + target-membership + null→Default + role gates), full suite **122 passed**, frontend lint-clean + production build. The management modal now handles **both apps and servers** (a "Resources" modal on each Workspaces card), each with move-in/move-out; servers fetch with the same `allWorkspaces` header bypass.- **Landed (WordPress hub workspace scoping):** the active-workspace switcher now also filters the **WordPress sites hub**, not just apps/servers (it was the inconsistent gap). WP sites carry no `workspace_id` of their own, so `WordPressService.get_sites(workspace_id=…)` scopes **join-based** through the site's parent `Application.workspace_id`; `list_sites` resolves the active workspace and passes it. The hub is global today, so with no workspace context behavior is unchanged (additive, narrow-only). **No frontend change** — the WP hub already fetches through the header-injecting `api.request`, so it auto-scopes on the ambient `X-Workspace-Id`. Verified: backend `py_compile`, a new API test (global vs workspace-scoped), full suite **123 passed**. *(Follow-on for broad adoption: databases/domains are murkier — server-level vs app-child — and need their own analysis before scoping.)*### #34 — Horizontal scaling `[XL]` ❌ — ⏸️ Deferred (XL + blocked on the same per-site reverse-proxy/upstream layer as #21)diff --git a/frontend/src/pages/Workspaces.jsx b/frontend/src/pages/Workspaces.jsxindex df7b5762..8d3b4669 100644--- a/frontend/src/pages/Workspaces.jsx+++ b/frontend/src/pages/Workspaces.jsx@@ -23,6 +23,7 @@ const Workspaces = () => {const [allUsers, setAllUsers] = useState([]);const [showResourcesModal, setShowResourcesModal] = useState(null);const [apps, setApps] = useState([]);+ const [servers, setServers] = useState([]);const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6366f1' });const loadWorkspaces = useCallback(async () => {@@ -105,14 +106,20 @@ const Workspaces = () => {}};+ const asServerList = (data) => (Array.isArray(data) ? data : (data?.servers || []));+const loadResources = async (wsId) => {try {- // allWorkspaces so we can see apps in OTHER workspaces to move them in.- const data = await api.getApps({ allWorkspaces: true });- setApps(data.apps || []);+ // allWorkspaces so we can see resources in OTHER workspaces to move them in.+ const [appData, srvData] = await Promise.all([+ api.getApps({ allWorkspaces: true }),+ api.getServers({ allWorkspaces: true }).catch(() => []),+ ]);+ setApps(appData.apps || []);+ setServers(asServerList(srvData));setShowResourcesModal(wsId);} catch (err) {- toast.error('Failed to load applications');+ toast.error('Failed to load resources');}};@@ -127,6 +134,16 @@ const Workspaces = () => {}};+ const handleMoveServer = async (serverId, workspaceId) => {+ try {+ await api.setServerWorkspace(serverId, workspaceId);+ toast.success('Server moved');+ setServers(asServerList(await api.getServers({ allWorkspaces: true })));+ } catch (err) {+ toast.error(err.message);+ }+ };+if (loading) return <Spinner />;return (@@ -170,7 +187,7 @@ const Workspaces = () => {)}<div className="workspace-card__actions"><Button size="sm" variant="outline" onClick={() => loadMembers(ws.id)}>Members</Button>- <Button size="sm" variant="outline" onClick={() => loadResources(ws.id)}>Apps</Button>+ <Button size="sm" variant="outline" onClick={() => loadResources(ws.id)}>Resources</Button>{ws.status === 'active' && (<Button size="sm" variant="secondary" onClick={() => handleArchive(ws.id)}>Archive</Button>)}@@ -271,39 +288,58 @@ const Workspaces = () => {)}{showResourcesModal && (() => {- const inWs = apps.filter(a => a.workspace_id === showResourcesModal);- const elsewhere = apps.filter(a => a.workspace_id !== showResourcesModal);+ const appsIn = apps.filter(a => a.workspace_id === showResourcesModal);+ const appsOut = apps.filter(a => a.workspace_id !== showResourcesModal);+ const srvIn = servers.filter(s => s.workspace_id === showResourcesModal);+ const srvOut = servers.filter(s => s.workspace_id !== showResourcesModal);return (<div className="modal-overlay" onClick={() => setShowResourcesModal(null)}><div className="modal" onClick={e => e.stopPropagation()}><div className="modal-header">- <h2>Workspace Applications</h2>+ <h2>Workspace Resources</h2><button className="modal-close" onClick={() => setShowResourcesModal(null)}>×</button></div><div className="modal-body">+ <h4>Applications</h4><div className="members-list">- {inWs.length === 0 && <p className="form-hint">No applications in this workspace yet.</p>}- {inWs.map(a => (+ {appsIn.length === 0 && <p className="form-hint">No applications in this workspace yet.</p>}+ {appsIn.map(a => (<div key={a.id} className="member-row">- <div>- <strong>{a.name}</strong>- <Badge variant="outline" className="ml-2">{a.app_type}</Badge>- </div>+ <div><strong>{a.name}</strong> <Badge variant="outline" className="ml-2">{a.app_type}</Badge></div><Button size="sm" variant="destructive" onClick={() => handleMoveApp(a.id, null)}>Remove</Button></div>))}</div>+ {appsOut.length > 0 && (+ <div className="server-select-list">+ {appsOut.map(a => (+ <div key={a.id} className="server-select-item" onClick={() => handleMoveApp(a.id, showResourcesModal)}>+ <span>{a.name}</span>+ <Badge variant="outline" className="ml-2">{a.app_type}</Badge>+ </div>+ ))}+ </div>+ )}<hr />- <h4>Add Application</h4>- <div className="server-select-list">- {elsewhere.length === 0 && <p className="form-hint">No other applications to add.</p>}- {elsewhere.map(a => (- <div key={a.id} className="server-select-item" onClick={() => handleMoveApp(a.id, showResourcesModal)}>- <span>{a.name}</span>- <Badge variant="outline" className="ml-2">{a.app_type}</Badge>+ <h4>Servers</h4>+ <div className="members-list">+ {srvIn.length === 0 && <p className="form-hint">No servers in this workspace yet.</p>}+ {srvIn.map(s => (+ <div key={s.id} className="member-row">+ <div><strong>{s.name}</strong></div>+ <Button size="sm" variant="destructive" onClick={() => handleMoveServer(s.id, null)}>Remove</Button></div>))}</div>+ {srvOut.length > 0 && (+ <div className="server-select-list">+ {srvOut.map(s => (+ <div key={s.id} className="server-select-item" onClick={() => handleMoveServer(s.id, showResourcesModal)}>+ <span>{s.name}</span>+ </div>+ ))}+ </div>+ )}</div></div></div>diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.jsindex 29e6b80c..3d8e3955 100644--- a/frontend/src/services/api/servers.js+++ b/frontend/src/services/api/servers.js@@ -1,8 +1,19 @@// Server management, remote Docker, fleet management, terminals, cloud provisioning// Servers (Multi-Server Management) endpoints-export async function getServers() {- return this.request('/servers');+export async function getServers(options = {}) {+ // allWorkspaces neutralizes the ambient X-Workspace-Id header so a+ // cross-workspace view (resource management) sees every server.+ const config = options.allWorkspaces ? { headers: { 'X-Workspace-Id': '' } } : {};+ return this.request('/servers', config);+}++// Reassign a server to a workspace (#33). Pass null to move it to Default.+export async function setServerWorkspace(serverId, workspaceId) {+ return this.request(`/servers/${serverId}/workspace`, {+ method: 'PUT',+ body: { workspace_id: workspaceId },+ });}export async function getServer(id) {