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.

refactor(frontend): centralize active workspace state

Juan Denis2ee8d9ed4223
diff --git a/frontend/package.json b/frontend/package.json
index 24a1a341..0cda6a4b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -6,6 +6,7 @@
"scripts": {
"dev": "vite",
"build": "vite build",
+ "test": "node --test",
"lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node ../scripts/check-html-sinks.mjs",
"lint:settings-index": "node scripts/check-settings-index.mjs",
"lint:html-sinks": "node ../scripts/check-html-sinks.mjs",
diff --git a/frontend/scripts/check-frontend-boundaries.mjs b/frontend/scripts/check-frontend-boundaries.mjs
index 0ea86847..4fd5f405 100644
--- a/frontend/scripts/check-frontend-boundaries.mjs
+++ b/frontend/scripts/check-frontend-boundaries.mjs
@@ -102,6 +102,13 @@ for (const path of files) {
failures.push(`${file}: do not read auth tokens in feature code; the centralized API client owns token access.`);
}
+ if (
+ file !== 'services/workspaceStore.js'
+ && /localStorage\s*\.\s*(?:getItem|setItem|removeItem)\s*\(\s*['"](?:active_workspace_id|active_workspace|workspace_accent)['"]/.test(source)
+ ) {
+ failures.push(`${file}: use WorkspaceContext/workspaceStore instead of reading or writing workspace persistence directly.`);
+ }
+
if (
/(?:^|\/)ui\/dialog['"]/.test(source)
&& file !== 'components/Modal.jsx'
@@ -125,4 +132,4 @@ if (failures.length) {
process.exit(1);
}
-console.log(`✓ frontend boundaries: no browser confirm/raw UI fetch/token reads/new clipboard or dialog bypasses (${LEGACY_CLIPBOARD.size} clipboard files remain ratcheted).`);
+console.log(`✓ frontend boundaries: no browser confirm/raw UI fetch/token or workspace persistence reads/new clipboard or dialog bypasses (${LEGACY_CLIPBOARD.size} clipboard files remain ratcheted).`);
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 9267e4ef..1b58821e 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -6,6 +6,7 @@ import { ThemeProvider } from './contexts/ThemeContext';
import { LayoutProvider } from './contexts/LayoutContext';
import { ResourceTierProvider } from './contexts/ResourceTierContext';
import { NotificationsProvider } from './contexts/NotificationsContext';
+import { WorkspaceProvider } from './contexts/WorkspaceContext';
import { rememberRedirect } from './utils/redirectAfterLogin';
import { Toaster } from './components/ui/sonner';
import ThemeSync from './components/ThemeSync';
@@ -530,25 +531,27 @@ function AppRoutes() {
function App() {
return (
<Router>
- <ThemeProvider>
- <LayoutProvider>
- <AuthProvider>
- {/* Inside AuthProvider — PageTitleUpdater reads panelTitle/
- publicTitle via useAuth (branding), so it must sit under
- the provider. It stays inside Router for useLocation. */}
- <PageTitleUpdater />
- <ThemeSync />
- <ResourceTierProvider>
- <ToastProvider>
- <NotificationsProvider>
- <AppRoutes />
- </NotificationsProvider>
- <Toaster />
- </ToastProvider>
- </ResourceTierProvider>
- </AuthProvider>
- </LayoutProvider>
- </ThemeProvider>
+ <WorkspaceProvider>
+ <ThemeProvider>
+ <LayoutProvider>
+ <AuthProvider>
+ {/* Inside AuthProvider — PageTitleUpdater reads panelTitle/
+ publicTitle via useAuth (branding), so it must sit under
+ the provider. It stays inside Router for useLocation. */}
+ <PageTitleUpdater />
+ <ThemeSync />
+ <ResourceTierProvider>
+ <ToastProvider>
+ <NotificationsProvider>
+ <AppRoutes />
+ </NotificationsProvider>
+ <Toaster />
+ </ToastProvider>
+ </ResourceTierProvider>
+ </AuthProvider>
+ </LayoutProvider>
+ </ThemeProvider>
+ </WorkspaceProvider>
</Router>
);
}
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 5dabff3b..35a24978 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -13,11 +13,13 @@ import { sanitizeSvgInner } from '../utils/sanitizeSvg';
import useModules from '../hooks/useModules';
import useDevMode from '../hooks/useDevMode';
import QuickCreate from './QuickCreate';
+import { useWorkspace } from '../contexts/WorkspaceContext';
const Sidebar = ({ mobileOpen = false, isMobile = false, onMobileClose = () => {} }) => {
const { user, logout, updateUser, hasPermission } = useAuth();
const { theme, resolvedTheme, setTheme, whiteLabel } = useTheme();
const { layout, setLayout } = useLayout();
+ const { activeWorkspace } = useWorkspace();
const navigate = useNavigate();
const [menuOpen, setMenuOpen] = useState(false);
const [wpInstalled, setWpInstalled] = useState(false);
@@ -204,17 +206,8 @@ const Sidebar = ({ mobileOpen = false, isMobile = false, onMobileClose = () => {
// Apply workspace-level nav permissions if an active workspace is set
// and it defines a nav map. This lets a workspace restrict which sidebar
// items its members see based on their effective workspace role.
- const activeWorkspaceRaw = localStorage.getItem('active_workspace');
- let activeWorkspace = null;
- if (activeWorkspaceRaw) {
- try {
- activeWorkspace = JSON.parse(activeWorkspaceRaw);
- } catch {
- activeWorkspace = null;
- }
- }
return applyWorkspaceNavPermissions(items, activeWorkspace, user);
- }, [user?.sidebar_config, pluginNav, pluginTabs, wpInstalled, gpuAvailable, wordpressEnabled, devMode, user, hasPermission]);
+ }, [user?.sidebar_config, pluginNav, pluginTabs, wpInstalled, gpuAvailable, wordpressEnabled, devMode, user, hasPermission, activeWorkspace]);
// Group visible items by category
const groupedItems = useMemo(() => {
diff --git a/frontend/src/components/WorkspaceSwitcher.jsx b/frontend/src/components/WorkspaceSwitcher.jsx
index 06013757..8f7e6913 100644
--- a/frontend/src/components/WorkspaceSwitcher.jsx
+++ b/frontend/src/components/WorkspaceSwitcher.jsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { Building2 } from 'lucide-react';
import { api } from '../services/api';
+import { useWorkspace } from '../contexts/WorkspaceContext';
import {
Select,
SelectContent,
@@ -9,37 +10,18 @@ import {
SelectValue,
} from './ui/select';
-const ACTIVE_KEY = 'active_workspace_id';
-const ACTIVE_WS_KEY = 'active_workspace'; // full workspace object for nav/brand settings
-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);
- }
-}
-
-function syncWorkspace(ws) {
- if (ws) {
- localStorage.setItem(ACTIVE_WS_KEY, JSON.stringify(ws));
- } else {
- localStorage.removeItem(ACTIVE_WS_KEY);
- }
- syncAccent(ws);
-}
-
// 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. Always rendered when at least one workspace exists so the scoping
-// concept stays visible even on single-workspace installs.
+// workspace through WorkspaceContext and reloads so existing pages re-fetch all
+// lists under the new scope. Always rendered when at least one workspace exists
+// so the scoping concept stays visible even on single-workspace installs.
const WorkspaceSwitcher = () => {
const [workspaces, setWorkspaces] = useState([]);
- const [active, setActive] = useState(() => localStorage.getItem(ACTIVE_KEY) || 'all');
+ const {
+ activeWorkspaceId,
+ clearActiveWorkspace,
+ refreshActiveWorkspace,
+ setActiveWorkspace,
+ } = useWorkspace();
useEffect(() => {
let alive = true;
@@ -48,37 +30,30 @@ const WorkspaceSwitcher = () => {
if (!alive) return;
const list = res?.workspaces || [];
setWorkspaces(list);
- const stored = localStorage.getItem(ACTIVE_KEY);
- if (stored && stored !== 'all') {
- const ws = list.find((w) => String(w.id) === stored);
+ if (activeWorkspaceId !== 'all') {
+ const ws = list.find((w) => String(w.id) === activeWorkspaceId);
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(ACTIVE_WS_KEY);
- localStorage.removeItem(ACCENT_KEY);
- setActive('all');
+ clearActiveWorkspace();
} else {
// Keep workspace settings (brand color, nav permissions) fresh.
- syncWorkspace(ws);
+ refreshActiveWorkspace(ws);
}
}
})
.catch(() => { /* best-effort; the selector just won't render */ });
return () => { alive = false; };
- }, []);
+ }, [activeWorkspaceId, clearActiveWorkspace, refreshActiveWorkspace]);
if (workspaces.length === 0) return null;
const handleChange = (value) => {
if (value === 'all') {
- localStorage.removeItem(ACTIVE_KEY);
- localStorage.removeItem(ACTIVE_WS_KEY);
- localStorage.removeItem(ACCENT_KEY);
+ clearActiveWorkspace();
} else {
const ws = workspaces.find((w) => String(w.id) === value);
- localStorage.setItem(ACTIVE_KEY, value);
- syncWorkspace(ws);
+ setActiveWorkspace(ws);
}
// Reload so every page re-fetches its lists (and re-applies the brand color)
// under the new workspace scope.
@@ -86,7 +61,7 @@ const WorkspaceSwitcher = () => {
};
return (
- <Select value={active} onValueChange={handleChange}>
+ <Select value={activeWorkspaceId} onValueChange={handleChange}>
<SelectTrigger className="workspace-switcher__trigger" aria-label="Active workspace">
<Building2 size={14} className="workspace-switcher__icon" aria-hidden="true" />
<SelectValue placeholder="All workspaces" />
diff --git a/frontend/src/contexts/ThemeContext.jsx b/frontend/src/contexts/ThemeContext.jsx
index f950ae58..fd6a9433 100644
--- a/frontend/src/contexts/ThemeContext.jsx
+++ b/frontend/src/contexts/ThemeContext.jsx
@@ -2,6 +2,7 @@ import { createContext, useContext, useState, useEffect, useCallback, useMemo }
import { BUNDLED_THEMES, BUNDLED_THEME_MAP, DEFAULT_THEME_SLUG } from '../data/bundledThemes';
import { applySkin } from '../utils/applySkin';
import api from '../services/api';
+import { useWorkspace } from './WorkspaceContext';
const ThemeContext = createContext(null);
@@ -83,6 +84,7 @@ function computeEffectiveAccent({ workspaceAccent, hasCustomAccent, accentColor,
}
export function ThemeProvider({ children }) {
+ const { workspaceAccent } = useWorkspace();
const [theme, setThemeState] = useState(() => {
return localStorage.getItem('theme') || 'dark';
});
@@ -126,11 +128,8 @@ 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;
+ // Active-workspace branding (#33) takes precedence over the user's personal
+ // accent and now reacts to same-tab and cross-tab workspace changes.
// All selectable themes (bundled seeds + installed), keyed by slug.
const themesMap = useMemo(
diff --git a/frontend/src/contexts/WorkspaceContext.jsx b/frontend/src/contexts/WorkspaceContext.jsx
new file mode 100644
index 00000000..6b39900d
--- /dev/null
+++ b/frontend/src/contexts/WorkspaceContext.jsx
@@ -0,0 +1,47 @@
+import { createContext, useCallback, useContext, useMemo, useSyncExternalStore } from 'react';
+import { workspaceStore } from '../services/workspaceStore';
+
+const WorkspaceContext = createContext(null);
+
+export function WorkspaceProvider({ children }) {
+ const snapshot = useSyncExternalStore(
+ workspaceStore.subscribe,
+ workspaceStore.getSnapshot,
+ workspaceStore.getServerSnapshot,
+ );
+
+ const setActiveWorkspace = useCallback((workspace) => {
+ workspaceStore.setActiveWorkspace(workspace);
+ }, []);
+
+ const clearActiveWorkspace = useCallback(() => {
+ workspaceStore.clearActiveWorkspace();
+ }, []);
+
+ const refreshActiveWorkspace = useCallback((workspace) => {
+ workspaceStore.refreshActiveWorkspace(workspace);
+ }, []);
+
+ const value = useMemo(() => ({
+ ...snapshot,
+ isAllWorkspaces: snapshot.activeWorkspaceId === 'all',
+ setActiveWorkspace,
+ clearActiveWorkspace,
+ refreshActiveWorkspace,
+ }), [snapshot, setActiveWorkspace, clearActiveWorkspace, refreshActiveWorkspace]);
+
+ return (
+ <WorkspaceContext.Provider value={value}>
+ {children}
+ </WorkspaceContext.Provider>
+ );
+}
+
+export function useWorkspace() {
+ const context = useContext(WorkspaceContext);
+ if (!context) {
+ throw new Error('useWorkspace must be used within a WorkspaceProvider');
+ }
+ return context;
+}
+
diff --git a/frontend/src/hooks/usePaletteAuthz.js b/frontend/src/hooks/usePaletteAuthz.js
index 3dddd576..903da531 100644
--- a/frontend/src/hooks/usePaletteAuthz.js
+++ b/frontend/src/hooks/usePaletteAuthz.js
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { SIDEBAR_ITEMS } from '../components/sidebarItems';
+import { useWorkspace } from '../contexts/WorkspaceContext';
// Sidebar items that can never be hidden (Dashboard, Marketplace) — the palette
// mirrors the sidebar's `alwaysVisible` so a workspace nav map can't hide them.
@@ -21,18 +22,11 @@ const ALWAYS_VISIBLE = new Set(
*/
export default function usePaletteAuthz() {
const { isAdmin, hasPermission } = useAuth();
+ const { activeWorkspace } = useWorkspace();
return useMemo(() => {
- let navMap = null;
- let role = 'member';
- try {
- const raw = localStorage.getItem('active_workspace');
- const ws = raw ? JSON.parse(raw) : null;
- navMap = ws?.settings?.nav || null;
- role = ws?.my_effective_role || ws?.my_role || 'member';
- } catch {
- navMap = null;
- }
+ const navMap = activeWorkspace?.settings?.nav || null;
+ const role = activeWorkspace?.my_effective_role || activeWorkspace?.my_role || 'member';
const allowNav = (navId) => {
if (!navId) return true;
@@ -53,7 +47,5 @@ export default function usePaletteAuthz() {
};
return { isAdmin, allowNav, allowItem };
- // Recomputes on login/role change (isAdmin flips); the workspace nav map
- // is read from localStorage at build time and isn't otherwise reactive.
- }, [isAdmin, hasPermission]);
+ }, [isAdmin, hasPermission, activeWorkspace]);
}
diff --git a/frontend/src/pages/SharedVariables.jsx b/frontend/src/pages/SharedVariables.jsx
index 84d067c9..dc8bb8cb 100644
--- a/frontend/src/pages/SharedVariables.jsx
+++ b/frontend/src/pages/SharedVariables.jsx
@@ -1,12 +1,14 @@
import SharedVariableGroups from '../components/shared/SharedVariableGroups';
+import { useWorkspace } from '../contexts/WorkspaceContext';
/**
* SharedVariables — workspace-scoped management of shared variable groups
* (the polymorphic facade: groups of variables that attach to any resource).
- * Scoped to the active workspace from localStorage; falls back to 'default'.
+ * Scoped to the active workspace context; falls back to 'default'.
*/
const SharedVariables = () => {
- const workspaceId = localStorage.getItem('active_workspace_id') || 'default';
+ const { activeWorkspaceId, isAllWorkspaces } = useWorkspace();
+ const workspaceId = isAllWorkspaces ? 'default' : activeWorkspaceId;
// No wrapper: SharedVariableGroups renders through ResourceListPage, which
// supplies the `sk-tabgroup__inner` box itself. Nesting a second one padded
diff --git a/frontend/src/pages/Vaults.jsx b/frontend/src/pages/Vaults.jsx
index ba1b6716..ee051adf 100644
--- a/frontend/src/pages/Vaults.jsx
+++ b/frontend/src/pages/Vaults.jsx
@@ -15,6 +15,7 @@ import { SearchField, ServiceTile } from '@/components/ds';
import { formatRelativeTime } from '@/utils/time';
import { useConfirm } from '@/hooks/useConfirm';
import { useClipboard } from '@/hooks/useClipboard';
+import { useWorkspace } from '../contexts/WorkspaceContext';
const formatDate = (d) => (d ? new Date(d).toLocaleString() : '—');
@@ -44,12 +45,13 @@ export default function Vaults() {
const toast = useToast();
const { confirm } = useConfirm();
const { copy } = useClipboard({ successMessage: 'Copied' });
+ const { activeWorkspaceId: workspaceScopeId, isAllWorkspaces } = useWorkspace();
const [vaults, setVaults] = useState([]);
const [workspaces, setWorkspaces] = useState([]);
const [loading, setLoading] = useState(true);
- const activeWorkspaceId = localStorage.getItem('active_workspace_id') || '';
+ const activeWorkspaceId = isAllWorkspaces ? '' : workspaceScopeId;
const [vaultForm, setVaultForm] = useState({ open: false, name: '', description: '', workspace_id: activeWorkspaceId });
const [selectedVault, setSelectedVault] = useState(null);
const [secretForm, setSecretForm] = useState({ open: false, name: '', value: '', description: '' });
diff --git a/frontend/src/pages/WorkspaceDetail.jsx b/frontend/src/pages/WorkspaceDetail.jsx
index 5fdef303..be3d5c8b 100644
--- a/frontend/src/pages/WorkspaceDetail.jsx
+++ b/frontend/src/pages/WorkspaceDetail.jsx
@@ -22,9 +22,7 @@ import WorkspaceServicesTab from '../components/workspaces/WorkspaceServicesTab'
import WorkspaceSitesTab from '../components/workspaces/WorkspaceSitesTab';
import WorkspaceMembersTab from '../components/workspaces/WorkspaceMembersTab';
import WorkspaceSettingsTab from '../components/workspaces/WorkspaceSettingsTab';
-
-const ACTIVE_KEY = 'active_workspace_id';
-const ACCENT_KEY = 'workspace_accent';
+import { useWorkspace } from '../contexts/WorkspaceContext';
const VALID_TABS = ['overview', 'servers', 'services', 'sites', 'members', 'settings'];
@@ -53,6 +51,12 @@ const WorkspaceDetail = () => {
const navigate = useNavigate();
const toast = useToast();
const { user } = useAuth();
+ const {
+ activeWorkspaceId,
+ clearActiveWorkspace,
+ refreshActiveWorkspace,
+ setActiveWorkspace: selectWorkspace,
+ } = useWorkspace();
const [activeTab, setActiveTab] = useTabParam(`/workspaces/${id}`, VALID_TABS, 'overview');
const [ws, setWs] = useState(null);
@@ -79,6 +83,7 @@ const WorkspaceDetail = () => {
api.getUsers().catch(() => ({ users: [] })),
]);
setWs(wsData);
+ refreshActiveWorkspace(wsData);
setMembers(mData.members || []);
setApps(appData.apps || []);
setServers(asServerList(srvData));
@@ -89,17 +94,14 @@ const WorkspaceDetail = () => {
} finally {
setLoading(false);
}
- }, [wsId, toast]);
+ }, [wsId, toast, refreshActiveWorkspace]);
useEffect(() => { setLoading(true); load(); }, [load]);
- const isCurrent = localStorage.getItem(ACTIVE_KEY) === String(wsId);
+ const isCurrent = activeWorkspaceId === String(wsId);
const setActiveWorkspace = () => {
- localStorage.setItem(ACTIVE_KEY, String(wsId));
- localStorage.setItem('active_workspace', JSON.stringify(ws));
- if (ws?.primary_color) localStorage.setItem(ACCENT_KEY, ws.primary_color);
- else localStorage.removeItem(ACCENT_KEY);
+ selectWorkspace(ws);
window.location.reload();
};
@@ -122,6 +124,7 @@ const WorkspaceDetail = () => {
const handleDelete = async () => {
try {
await api.deleteWorkspace(wsId);
+ if (isCurrent) clearActiveWorkspace();
toast.success('Workspace deleted');
navigate('/workspaces');
} catch (err) { toast.error(err.message); }
diff --git a/frontend/src/pages/Workspaces.jsx b/frontend/src/pages/Workspaces.jsx
index b4bd852e..7026bf6b 100644
--- a/frontend/src/pages/Workspaces.jsx
+++ b/frontend/src/pages/Workspaces.jsx
@@ -11,9 +11,7 @@ import useFocusParam from '@/hooks/useFocusParam';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
-
-// Matches WorkspaceSwitcher: the active workspace id lives in localStorage.
-const ACTIVE_KEY = 'active_workspace_id';
+import { useWorkspace } from '../contexts/WorkspaceContext';
// Preset views. `servers` and `users` are quota CEILINGS, not usage, so there
// is no column to express "near capacity" against.
@@ -84,6 +82,7 @@ const formatSince = (iso) => {
const Workspaces = () => {
const toast = useToast();
const navigate = useNavigate();
+ const { activeWorkspaceId } = useWorkspace();
const [workspaces, setWorkspaces] = useState([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
@@ -93,8 +92,6 @@ const Workspaces = () => {
useFocusParam('create', () => setShowCreateModal(true));
const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6d7cff' });
- const activeId = localStorage.getItem(ACTIVE_KEY);
-
const loadWorkspaces = useCallback(async () => {
try {
const data = await api.getWorkspaces();
@@ -195,12 +192,12 @@ const Workspaces = () => {
// rule would then match nothing at all.
value: (ws) => ws.status || 'unknown',
// Matches the pill: the active workspace (and active status) first.
- sortValue: (ws) => (activeId === String(ws.id) || ws.status === 'active' ? 0 : 1),
+ sortValue: (ws) => (activeWorkspaceId === String(ws.id) || ws.status === 'active' ? 0 : 1),
groupable: true,
groupValue: (ws) => ws.status,
groupLabel: (value) => (value ? value.charAt(0).toUpperCase() + value.slice(1) : 'None'),
render: (ws) => (
- activeId === String(ws.id)
+ activeWorkspaceId === String(ws.id)
? <Pill kind="green">active</Pill>
: <Pill kind={ws.status === 'active' ? 'green' : 'amber'}>{ws.status || 'unknown'}</Pill>
),
diff --git a/frontend/src/services/__tests__/workspaceStore.test.mjs b/frontend/src/services/__tests__/workspaceStore.test.mjs
new file mode 100644
index 00000000..59460ed9
--- /dev/null
+++ b/frontend/src/services/__tests__/workspaceStore.test.mjs
@@ -0,0 +1,122 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+import ApiClient from '../api/client.js';
+import {
+ ACTIVE_WORKSPACE_ID_KEY,
+ ACTIVE_WORKSPACE_KEY,
+ WORKSPACE_ACCENT_KEY,
+ createWorkspaceStore,
+} from '../workspaceStore.js';
+
+function createMemoryStorage() {
+ const values = new Map();
+ return {
+ getItem: (key) => (values.has(key) ? values.get(key) : null),
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ values,
+ };
+}
+
+test('persists one coherent workspace snapshot and publishes changes', () => {
+ const storage = createMemoryStorage();
+ const store = createWorkspaceStore({ storage, eventTarget: new EventTarget() });
+ let changes = 0;
+ const unsubscribe = store.subscribe(() => { changes += 1; });
+
+ const workspace = { id: 17, name: 'Production', primary_color: '#123456' };
+ store.setActiveWorkspace(workspace);
+
+ assert.equal(storage.getItem(ACTIVE_WORKSPACE_ID_KEY), '17');
+ assert.deepEqual(JSON.parse(storage.getItem(ACTIVE_WORKSPACE_KEY)), workspace);
+ assert.equal(storage.getItem(WORKSPACE_ACCENT_KEY), '#123456');
+ assert.deepEqual(store.getSnapshot(), {
+ activeWorkspaceId: '17',
+ activeWorkspace: workspace,
+ workspaceAccent: '#123456',
+ });
+ assert.equal(changes, 1);
+
+ store.refreshActiveWorkspace({ ...workspace, name: 'Production EU' });
+ assert.equal(store.getSnapshot().activeWorkspace.name, 'Production EU');
+ assert.equal(changes, 2);
+
+ store.clearActiveWorkspace();
+ assert.equal(store.getSnapshot().activeWorkspaceId, 'all');
+ assert.equal(storage.getItem(ACTIVE_WORKSPACE_ID_KEY), null);
+ assert.equal(storage.getItem(ACTIVE_WORKSPACE_KEY), null);
+ assert.equal(storage.getItem(WORKSPACE_ACCENT_KEY), null);
+ assert.equal(changes, 3);
+ unsubscribe();
+});
+
+test('storage events synchronize changes made by another tab', () => {
+ const storage = createMemoryStorage();
+ const eventTarget = new EventTarget();
+ const store = createWorkspaceStore({ storage, eventTarget });
+ let changes = 0;
+ store.subscribe(() => { changes += 1; });
+
+ const workspace = { id: '9', name: 'Shared tab' };
+ storage.setItem(ACTIVE_WORKSPACE_ID_KEY, '9');
+ storage.setItem(ACTIVE_WORKSPACE_KEY, JSON.stringify(workspace));
+ const storageEvent = new Event('storage');
+ Object.defineProperty(storageEvent, 'key', { value: ACTIVE_WORKSPACE_ID_KEY });
+ eventTarget.dispatchEvent(storageEvent);
+
+ assert.equal(changes, 1);
+ assert.equal(store.getSnapshot().activeWorkspaceId, '9');
+ assert.deepEqual(store.getSnapshot().activeWorkspace, workspace);
+ store.destroy();
+});
+
+test('keeps live workspace state when persistence is unavailable', () => {
+ const unavailableStorage = {
+ getItem: () => { throw new Error('blocked'); },
+ setItem: () => { throw new Error('blocked'); },
+ removeItem: () => { throw new Error('blocked'); },
+ };
+ const store = createWorkspaceStore({
+ storage: unavailableStorage,
+ eventTarget: new EventTarget(),
+ });
+
+ store.setActiveWorkspace({ id: 11, name: 'In memory' });
+
+ assert.equal(store.getSnapshot().activeWorkspaceId, '11');
+ assert.equal(store.getSnapshot().activeWorkspace.name, 'In memory');
+ store.destroy();
+});
+
+test('ApiClient scopes coalescing and request headers from the injected store', async () => {
+ const storage = createMemoryStorage();
+ globalThis.localStorage = storage;
+ storage.setItem('access_token', 'token');
+
+ let activeWorkspaceId = '42';
+ const workspace = {
+ getSnapshot: () => ({ activeWorkspaceId }),
+ clearActiveWorkspace: () => { activeWorkspaceId = 'all'; },
+ };
+ const requests = [];
+ globalThis.fetch = async (url, options) => {
+ requests.push({ url, options });
+ return {
+ ok: true,
+ status: 200,
+ url,
+ json: async () => ({ ok: true }),
+ };
+ };
+
+ const client = new ApiClient({ workspace });
+ client.baseUrl = '/api/v1';
+ await client.request('/servers');
+ assert.equal(requests[0].options.headers['X-Workspace-Id'], '42');
+ assert.equal(requests[0].options.headers.Authorization, 'Bearer token');
+
+ activeWorkspaceId = 'all';
+ await client.request('/servers');
+ assert.equal('X-Workspace-Id' in requests[1].options.headers, false);
+});
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index d0c3dfdd..d7cdbf59 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -1,4 +1,6 @@
// Base HTTP client - constructor, token management, core request methods
+import { workspaceStore } from '../workspaceStore.js';
+
const AUTH_EXPIRED_EVENT = 'serverkit:auth-expired';
const normalizeApiBaseUrl = (url) => {
@@ -28,9 +30,10 @@ const normalizeApiBaseUrl = (url) => {
// setup has an origin CORS does not expect. Socket.IO is unaffected: it stays
// on window.location.origin in dev (see services/socket.js) because a WebSocket
// upgrades out of the HTTP connection pool anyway.
-const API_BASE_URL = (import.meta.env.DEV && import.meta.env.VITE_API_PROXY === 'true')
+const viteEnv = import.meta.env || {};
+const API_BASE_URL = (viteEnv.DEV && viteEnv.VITE_API_PROXY === 'true')
? '/api/v1'
- : normalizeApiBaseUrl(import.meta.env.VITE_API_URL);
+ : normalizeApiBaseUrl(viteEnv.VITE_API_URL);
// Requests that are safe to share with a concurrent identical caller: a plain
// GET with no body, no custom headers (X-DB-Password and friends change what
@@ -56,8 +59,9 @@ const isCoalescable = (options) => (
);
class ApiClient {
- constructor() {
+ constructor({ workspace = workspaceStore } = {}) {
this.baseUrl = API_BASE_URL;
+ this.workspace = workspace;
// In-flight GET coalescing. Two callers asking for the same URL at the
// same moment share one network request instead of racing.
//
@@ -89,9 +93,7 @@ class ApiClient {
clearTokens() {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
- localStorage.removeItem('active_workspace_id'); // drop workspace context on logout
- localStorage.removeItem('active_workspace');
- localStorage.removeItem('workspace_accent');
+ this.workspace.clearActiveWorkspace(); // drop workspace context on logout
}
request(endpoint, options = {}) {
@@ -99,7 +101,8 @@ class ApiClient {
// Scope the key by workspace: the same path returns different rows
// under a different X-Workspace-Id.
- const key = `${localStorage.getItem('active_workspace_id') || ''}|${endpoint}`;
+ const { activeWorkspaceId } = this.workspace.getSnapshot();
+ const key = `${activeWorkspaceId}|${endpoint}`;
const existing = this._inflight.get(key);
if (existing) return existing.then(cloneResult);
@@ -125,7 +128,7 @@ class ApiClient {
// 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 { activeWorkspaceId } = this.workspace.getSnapshot();
// Spread `...options` FIRST, then set merged headers LAST — otherwise a
// call passing custom `headers` (e.g. X-DB-Password) would clobber the
@@ -136,7 +139,7 @@ class ApiClient {
headers: {
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
...(token && { Authorization: `Bearer ${token}` }),
- ...(activeWorkspace && activeWorkspace !== 'all' && { 'X-Workspace-Id': activeWorkspace }),
+ ...(activeWorkspaceId !== 'all' && { 'X-Workspace-Id': activeWorkspaceId }),
...fetchOptions.headers,
},
};
diff --git a/frontend/src/services/workspaceStore.js b/frontend/src/services/workspaceStore.js
new file mode 100644
index 00000000..dc884383
--- /dev/null
+++ b/frontend/src/services/workspaceStore.js
@@ -0,0 +1,174 @@
+export const ACTIVE_WORKSPACE_ID_KEY = 'active_workspace_id';
+export const ACTIVE_WORKSPACE_KEY = 'active_workspace';
+export const WORKSPACE_ACCENT_KEY = 'workspace_accent';
+
+const TRACKED_KEYS = new Set([
+ ACTIVE_WORKSPACE_ID_KEY,
+ ACTIVE_WORKSPACE_KEY,
+ WORKSPACE_ACCENT_KEY,
+]);
+
+const ALL_WORKSPACES_SNAPSHOT = Object.freeze({
+ activeWorkspaceId: 'all',
+ activeWorkspace: null,
+ workspaceAccent: null,
+});
+
+const safeGet = (storage, key) => {
+ try {
+ return storage?.getItem(key) ?? null;
+ } catch {
+ return null;
+ }
+};
+
+const safeSet = (storage, key, value) => {
+ try {
+ storage?.setItem(key, value);
+ } catch {
+ // Workspace persistence is a convenience. In-memory state still updates
+ // when storage is unavailable (private mode, quota, or sandboxed frames).
+ }
+};
+
+const safeRemove = (storage, key) => {
+ try {
+ storage?.removeItem(key);
+ } catch {
+ // See safeSet: keep the live store usable even without persistence.
+ }
+};
+
+const normalizeWorkspaceId = (value) => {
+ if (value == null) return 'all';
+ const id = String(value).trim();
+ return !id || id === 'all' ? 'all' : id;
+};
+
+const parseWorkspace = (raw) => {
+ if (!raw) return null;
+ try {
+ const workspace = JSON.parse(raw);
+ return workspace && typeof workspace === 'object' ? workspace : null;
+ } catch {
+ return null;
+ }
+};
+
+const readSnapshot = (storage) => {
+ const activeWorkspaceId = normalizeWorkspaceId(
+ safeGet(storage, ACTIVE_WORKSPACE_ID_KEY),
+ );
+ if (activeWorkspaceId === 'all') return ALL_WORKSPACES_SNAPSHOT;
+
+ const storedWorkspace = parseWorkspace(safeGet(storage, ACTIVE_WORKSPACE_KEY));
+ const activeWorkspace = storedWorkspace
+ && String(storedWorkspace.id) === activeWorkspaceId
+ ? storedWorkspace
+ : null;
+
+ return {
+ activeWorkspaceId,
+ activeWorkspace,
+ workspaceAccent: safeGet(storage, WORKSPACE_ACCENT_KEY),
+ };
+};
+
+const snapshotSignature = (snapshot) => JSON.stringify(snapshot);
+
+/**
+ * Framework-neutral active-workspace store.
+ *
+ * React subscribes through WorkspaceProvider, while ApiClient reads the same
+ * snapshot directly. The factory is exported so persistence and cross-tab
+ * behavior can be tested without a browser runtime.
+ */
+export function createWorkspaceStore({ storage, eventTarget } = {}) {
+ const resolvedStorage = storage
+ ?? (typeof window !== 'undefined' ? window.localStorage : null);
+ const resolvedEventTarget = eventTarget
+ ?? (typeof window !== 'undefined' ? window : null);
+ const listeners = new Set();
+ let snapshot = readSnapshot(resolvedStorage);
+ let signature = snapshotSignature(snapshot);
+
+ const publishSnapshot = (nextSnapshot) => {
+ const nextSignature = snapshotSignature(nextSnapshot);
+ if (nextSignature === signature) return false;
+ snapshot = nextSnapshot;
+ signature = nextSignature;
+ listeners.forEach((listener) => listener());
+ return true;
+ };
+
+ const syncFromStorage = () => publishSnapshot(readSnapshot(resolvedStorage));
+
+ const handleStorage = (event) => {
+ if (event?.key != null && !TRACKED_KEYS.has(event.key)) return;
+ syncFromStorage();
+ };
+
+ // ApiClient also consumes this store without mounting React, so cross-tab
+ // updates must be observed for the lifetime of the store rather than only
+ // while a component happens to be subscribed.
+ resolvedEventTarget?.addEventListener?.('storage', handleStorage);
+
+ const subscribe = (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ };
+
+ // useSyncExternalStore requires a cached, side-effect-free snapshot getter.
+ // Same-tab mutations and cross-tab storage events update this value.
+ const getSnapshot = () => snapshot;
+
+ const clearActiveWorkspace = () => {
+ safeRemove(resolvedStorage, ACTIVE_WORKSPACE_ID_KEY);
+ safeRemove(resolvedStorage, ACTIVE_WORKSPACE_KEY);
+ safeRemove(resolvedStorage, WORKSPACE_ACCENT_KEY);
+ publishSnapshot(ALL_WORKSPACES_SNAPSHOT);
+ };
+
+ const persistWorkspace = (workspace) => {
+ if (!workspace || workspace.id == null) {
+ clearActiveWorkspace();
+ return;
+ }
+
+ const activeWorkspaceId = normalizeWorkspaceId(workspace.id);
+ if (activeWorkspaceId === 'all') {
+ clearActiveWorkspace();
+ return;
+ }
+
+ const workspaceAccent = workspace.primary_color || null;
+ safeSet(resolvedStorage, ACTIVE_WORKSPACE_ID_KEY, activeWorkspaceId);
+ safeSet(resolvedStorage, ACTIVE_WORKSPACE_KEY, JSON.stringify(workspace));
+ if (workspaceAccent) {
+ safeSet(resolvedStorage, WORKSPACE_ACCENT_KEY, workspaceAccent);
+ } else {
+ safeRemove(resolvedStorage, WORKSPACE_ACCENT_KEY);
+ }
+ publishSnapshot({ activeWorkspaceId, activeWorkspace: workspace, workspaceAccent });
+ };
+
+ const refreshActiveWorkspace = (workspace) => {
+ if (!workspace || String(workspace.id) !== getSnapshot().activeWorkspaceId) return;
+ persistWorkspace(workspace);
+ };
+
+ return {
+ subscribe,
+ getSnapshot,
+ getServerSnapshot: () => ALL_WORKSPACES_SNAPSHOT,
+ setActiveWorkspace: persistWorkspace,
+ refreshActiveWorkspace,
+ clearActiveWorkspace,
+ destroy: () => {
+ resolvedEventTarget?.removeEventListener?.('storage', handleStorage);
+ listeners.clear();
+ },
+ };
+}
+
+export const workspaceStore = createWorkspaceStore();