Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
[CHOO-3906] Organizations in the dashboard
Petr Bauchf22f3d0784c2
diff --git a/console/tooling-e2e/src/browser/index.ts b/console/tooling-e2e/src/browser/index.tsindex 1b3e88232..201c05e97 100644--- a/console/tooling-e2e/src/browser/index.ts+++ b/console/tooling-e2e/src/browser/index.ts@@ -29,7 +29,7 @@ const everyPage: BrowserScenario = {const links = await ui.navLinks();expect(links.map((link) => link.path)).toEqual(expect.arrayContaining(['/rooms', '/agents']));for (const link of links) {- await ui.nav().getByRole('link', { name: link.label }).click();+ await ui.nav().getByRole('link', { name: link.label, exact: true }).click();await expect.poll(() => ui.path()).toBe(link.path);await ui.settled();log(`${link.label} (${link.path}) opened`);diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsxindex dbb8d490c..7663a1058 100644--- a/gateway/src/App.test.tsx+++ b/gateway/src/App.test.tsx@@ -6,8 +6,22 @@ import type { Session, TenantMembership } from "./data/api";import { AuthProvider } from "./data/AuthContext";import { clearPendingInvite, storePendingInvite } from "./data/sessionState";-const acme: TenantMembership = { id: "t1", slug: "acme", name: "Acme", role: "owner" };-const beta: TenantMembership = { id: "t2", slug: "beta", name: "Beta Co", role: "member" };+const acme: TenantMembership = {+ id: "t1",+ slug: "acme",+ name: "Acme",+ role: "owner",+ organization_role: "org_admin",+ organization_id: "o1",+};+const beta: TenantMembership = {+ id: "t2",+ slug: "beta",+ name: "Beta Co",+ role: "member",+ organization_role: "member",+ organization_id: "o2",+};function session(overrides: Partial<Session>): Session {return {@@ -16,6 +30,7 @@ function session(overrides: Partial<Session>): Session {tenants: [],state: "needs_workspace",can_create_workspace: true,+ can_add_workspace: false,invite_email_enabled: false,...overrides,};@@ -78,14 +93,14 @@ describe("AppRoutes", () => {mockFetch({ "/auth/session": [200, session({})] });renderAt("/");expect(await screen.findByText("Welcome to Switch")).toBeTruthy();- expect(screen.getByRole("button", { name: "Create workspace" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Create organization" })).toBeTruthy();});it("only offers an invite when workspaces cannot be created", async () => {mockFetch({ "/auth/session": [200, session({ can_create_workspace: false })] });renderAt("/");expect(await screen.findByText(/Ask a workspace admin for an invite link/)).toBeTruthy();- expect(screen.queryByRole("button", { name: "Create workspace" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Create organization" })).toBeNull();});it("asks someone in several workspaces to choose", async () => {diff --git a/gateway/src/App.tsx b/gateway/src/App.tsxindex bb4c3d863..6ff51e65d 100644--- a/gateway/src/App.tsx+++ b/gateway/src/App.tsx@@ -29,6 +29,8 @@ import WorkspacePickerPage from "./pages/onboarding/WorkspacePickerPage";import UsagePage from "./pages/usage/UsagePage";import UsersPage from "./pages/users/UsersPage";import WorkspacePage from "./pages/workspace/WorkspacePage";+import OrganizationPage from "./pages/organization/OrganizationPage";+import OperatorWorkspacesPage from "./pages/operator/OperatorWorkspacesPage";function FullScreen({ children }: { children: React.ReactNode }) {return (@@ -144,6 +146,8 @@ export function AppRoutes() {<Route path="users" element={<UsersPage />} /><Route path="connectors" element={<ConnectorAppsPage />} /><Route path="workspace" element={<WorkspacePage />} />+ <Route path="organization" element={<OrganizationPage />} />+ <Route path="operator/workspaces" element={<OperatorWorkspacesPage />} /></Route><Route path="/invite" element={<InviteCapture />} /><Route path="/login" element={<Navigate to="/" replace />} />diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex d13d97f63..b7189f274 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1130,11 +1130,15 @@ export interface AuthConfig {export type TenantRole = "owner" | "admin" | "member";+export type OrganizationRole = "org_admin" | "member";+export interface TenantMembership {id: string;slug: string;name: string;role: TenantRole;+ organization_role: OrganizationRole | null;+ organization_id: string | null;}export interface SessionUser {@@ -1151,7 +1155,10 @@ export interface Session {tenant: TenantMembership | null;tenants: TenantMembership[];state: SessionStateName;+ // Whether the caller may create a new organization with its first workspace.can_create_workspace: boolean;+ // Whether the caller may add a workspace to the current organization.+ can_add_workspace: boolean;// Whether an invitation naming an e-mail is sent there by this server.invite_email_enabled: boolean;}@@ -1188,6 +1195,10 @@ export interface Member {email: string;role: TenantRole;created_at: string;+ organization_role: OrganizationRole | null;+ // An organization admin with no membership of their own here, listed+ // because the organization makes them an admin of every workspace.+ via_organization: boolean;}export async function fetchMembers(tenantId: string): Promise<Member[]> {@@ -1213,6 +1224,79 @@ export async function removeMember(tenantId: string, userId: string): Promise<vo);}+export interface OrganizationSummary {+ id: string;+ slug: string;+ name: string;+ role: OrganizationRole;+}++export interface OrganizationMember {+ user_id: string;+ name: string;+ email: string;+ role: OrganizationRole;+ created_at: string;+}++export interface AuditEvent {+ id: string;+ occurred_at: string;+ actor_user_id: string | null;+ action: string;+ target_type: string;+ target_id: string | null;+ details: Record<string, unknown> | null;+}++export interface OperatorWorkspace {+ id: string;+ slug: string;+ name: string;+ organization_id: string | null;+}++export async function fetchOrganizations(): Promise<OrganizationSummary[]> {+ return jsonRequest<OrganizationSummary[]>("/organizations", "GET");+}++export async function fetchOrganizationWorkspaces(): Promise<TenantMembership[]> {+ return jsonRequest<TenantMembership[]>("/organizations/current/workspaces", "GET");+}++/** Add a workspace to the current organization. The session stays where it is. */+export async function createOrganizationWorkspace(name: string): Promise<TenantMembership> {+ return jsonRequest<TenantMembership>("/organizations/current/workspaces", "POST", { name });+}++export async function fetchOrganizationMembers(): Promise<OrganizationMember[]> {+ return jsonRequest<OrganizationMember[]>("/organizations/current/members", "GET");+}++export async function updateOrganizationRole(+ userId: string,+ role: OrganizationRole,+): Promise<OrganizationMember> {+ return jsonRequest<OrganizationMember>(+ `/organizations/current/members/${encodeURIComponent(userId)}`,+ "PATCH",+ { role },+ );+}++export async function removeOrganizationMember(userId: string): Promise<void> {+ await jsonRequest(`/organizations/current/members/${encodeURIComponent(userId)}`, "DELETE");+}++export async function fetchOrganizationAuditEvents(): Promise<AuditEvent[]> {+ return jsonRequest<AuditEvent[]>("/organizations/current/audit-events", "GET");+}++/** Every workspace on the server; the platform operator only. */+export async function fetchOperatorWorkspaces(): Promise<OperatorWorkspace[]> {+ return jsonRequest<OperatorWorkspace[]>("/operator/workspaces", "GET");+}+export interface Invitation {id: string;role: TenantRole;diff --git a/gateway/src/data/sessionState.test.ts b/gateway/src/data/sessionState.test.tsindex 4f091e892..beb97c406 100644--- a/gateway/src/data/sessionState.test.ts+++ b/gateway/src/data/sessionState.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it } from "vitest";import type { Session, TenantMembership } from "./api";import {+ administersOrganization,appView,canAdminTenant,clearPendingInvite,@@ -12,7 +13,14 @@ import {storePendingInvite,} from "./sessionState";-const acme: TenantMembership = { id: "t1", slug: "acme", name: "Acme", role: "member" };+const acme: TenantMembership = {+ id: "t1",+ slug: "acme",+ name: "Acme",+ role: "member",+ organization_role: "member",+ organization_id: "o1",+};function session(overrides: Partial<Session> = {}): Session {return {@@ -21,6 +29,7 @@ function session(overrides: Partial<Session> = {}): Session {tenants: [acme],state: "ready",can_create_workspace: true,+ can_add_workspace: false,invite_email_enabled: false,...overrides,};@@ -127,3 +136,17 @@ describe("deliveryNotice", () => {expect(notice.text).not.toContain("null");});});++describe("administersOrganization", () => {+ it("follows the organization role, not the operator bit", () => {+ expect(administersOrganization(session())).toBe(false);+ expect(+ administersOrganization(session({ tenant: { ...acme, organization_role: "org_admin" } })),+ ).toBe(true);+ expect(+ administersOrganization(+ session({ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: true } }),+ ),+ ).toBe(false);+ });+});diff --git a/gateway/src/data/sessionState.ts b/gateway/src/data/sessionState.tsindex 9d382fa7f..2b5ffeb4b 100644--- a/gateway/src/data/sessionState.ts+++ b/gateway/src/data/sessionState.ts@@ -28,6 +28,12 @@ export function canAdminTenant(session: Session | null): boolean {return role === "owner" || role === "admin";}+/** Is this session an admin of the current workspace's organization? The+ * platform operator is not, by the operator bit alone. */+export function administersOrganization(session: Session | null): boolean {+ return session?.tenant?.organization_role === "org_admin";+}+const INVITE_KEY = "switch.pendingInvite";/** Session storage, not local: an invite token is a bearer credential, anddiff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsxindex e4077a5e4..95b47261d 100644--- a/gateway/src/layout/NavRail.tsx+++ b/gateway/src/layout/NavRail.tsx@@ -1,5 +1,7 @@import AddOutlined from "@mui/icons-material/AddOutlined";import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";+import ApartmentOutlined from "@mui/icons-material/ApartmentOutlined";+import DnsOutlined from "@mui/icons-material/DnsOutlined";import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";import ComputerOutlined from "@mui/icons-material/ComputerOutlined";import DataUsageOutlined from "@mui/icons-material/DataUsageOutlined";@@ -52,6 +54,11 @@ const NAV_ITEMS: NavItem[] = [{ label: "Workspace", path: "/workspace", icon: WorkspacesOutlined },];+// Shown when the current workspace belongs to an organization.+const ORGANIZATION_ITEMS: NavItem[] = [+ { label: "Organization", path: "/organization", icon: ApartmentOutlined },+];+// Shown only when the server runs with agent management enabled.const MANAGEMENT_ITEMS: NavItem[] = [{ label: "Machines", path: "/machines", icon: ComputerOutlined },@@ -62,6 +69,7 @@ const WORKSPACE_ADMIN_ITEMS: NavItem[] = [];const ADMIN_ITEMS: NavItem[] = [+ { label: "All workspaces", path: "/operator/workspaces", icon: DnsOutlined },{ label: "Users", path: "/users", icon: PeopleOutlined },{ label: "Connectors", path: "/connectors", icon: PowerOutlined },];@@ -161,6 +169,7 @@ export default memo(function NavRail() {const items = [...NAV_ITEMS,+ ...(session?.tenant?.organization_id ? ORGANIZATION_ITEMS : []),...(managementAvailable ? MANAGEMENT_ITEMS : []),...(tenant?.administers ? WORKSPACE_ADMIN_ITEMS : []),...(isOperator ? ADMIN_ITEMS : []),@@ -286,7 +295,7 @@ export default memo(function NavRail() {</Typography>{isOperator && (<Typography variant="caption" sx={{ color: "text.secondary" }}>- Operator+ Platform operator</Typography>)}</Box>@@ -318,7 +327,7 @@ export default memo(function NavRail() {sx={{ gap: 1 }}><AddOutlined sx={{ fontSize: 16 }} />- Create workspace+ Create organization</MenuItem>)}<Divider sx={{ my: 0.5 }} />@@ -352,7 +361,7 @@ export default memo(function NavRail() {</Menu><Dialog open={createOpen} onClose={() => setCreateOpen(false)} maxWidth="xs" fullWidth>- <DialogTitle>Create a workspace</DialogTitle>+ <DialogTitle>Create an organization</DialogTitle><DialogContent sx={{ pt: "8px !important" }}><CreateWorkspaceForm onCancel={() => setCreateOpen(false)} /></DialogContent>diff --git a/gateway/src/layout/TopBar.tsx b/gateway/src/layout/TopBar.tsxindex 01a5c2df6..b81362975 100644--- a/gateway/src/layout/TopBar.tsx+++ b/gateway/src/layout/TopBar.tsx@@ -12,6 +12,8 @@ const SECTION_LABELS: [prefix: string, label: string][] = [["/registration-keys", "API Keys"],["/users", "Users"],["/workspace", "Workspace"],+ ["/organization", "Organization"],+ ["/operator/workspaces", "All workspaces"],];const DOCS_URL = "https://docs.switchagents.ai/switch-rooms/getting-started";diff --git a/gateway/src/pages/onboarding/CreateWorkspaceForm.tsx b/gateway/src/pages/onboarding/CreateWorkspaceForm.tsxindex 7fd4bb6b5..fcb2e236e 100644--- a/gateway/src/pages/onboarding/CreateWorkspaceForm.tsx+++ b/gateway/src/pages/onboarding/CreateWorkspaceForm.tsx@@ -2,8 +2,9 @@ import { Alert, Button, CircularProgress, Stack, TextField } from "@mui/materialimport { useState } from "react";import { createTenant } from "../../data/api";-/** Creating a workspace also switches the session into it (the server- * re-mints the cookie), so success reloads into the app. */+/** Creates an organization with a first workspace of the same name, and the+ * server switches the session into that workspace (it re-mints the cookie),+ * so success reloads into the app. */export default function CreateWorkspaceForm({ onCancel }: { onCancel?: () => void }) {const [name, setName] = useState("");const [error, setError] = useState<string | null>(null);@@ -17,7 +18,7 @@ export default function CreateWorkspaceForm({ onCancel }: { onCancel?: () => voiawait createTenant(name.trim());window.location.assign("/");} catch (err) {- setError(err instanceof Error ? err.message : "Could not create the workspace");+ setError(err instanceof Error ? err.message : "Could not create the organization");setSubmitting(false);}};@@ -26,10 +27,11 @@ export default function CreateWorkspaceForm({ onCancel }: { onCancel?: () => voi<Stack component="form" onSubmit={submit} spacing={2}>{error && <Alert severity="error">{error}</Alert>}<TextField- label="Workspace name"+ label="Organization name"value={name}onChange={(e) => setName(e.target.value)}placeholder="e.g. your company or team"+ helperText="It starts with one workspace of the same name. You can add more later."requiredautoFocus/>@@ -41,7 +43,7 @@ export default function CreateWorkspaceForm({ onCancel }: { onCancel?: () => voidisabled={submitting || name.trim() === ""}startIcon={submitting ? <CircularProgress size={16} /> : undefined}>- Create workspace+ Create organization</Button>{onCancel && (<Button onClick={onCancel} disabled={submitting}>diff --git a/gateway/src/pages/onboarding/OnboardingPage.tsx b/gateway/src/pages/onboarding/OnboardingPage.tsxindex 9aa8f2011..eac306b91 100644--- a/gateway/src/pages/onboarding/OnboardingPage.tsx+++ b/gateway/src/pages/onboarding/OnboardingPage.tsx@@ -30,7 +30,7 @@ export default function OnboardingPage() {title="Welcome to Switch"subtitle={canCreate- ? "Create a workspace for your team, or join one you've been invited to."+ ? "Create an organization for your team, or join a workspace you've been invited to.": "You're not in a workspace yet. Ask a workspace admin for an invite link."}>diff --git a/gateway/src/pages/operator/OperatorWorkspacesPage.tsx b/gateway/src/pages/operator/OperatorWorkspacesPage.tsxnew file mode 100644index 000000000..34537c587--- /dev/null+++ b/gateway/src/pages/operator/OperatorWorkspacesPage.tsx@@ -0,0 +1,80 @@+import { Alert, Box, Button, CircularProgress, Stack, Typography } from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { useAuth } from "../../data/AuthContext";+import { type OperatorWorkspace, fetchOperatorWorkspaces } from "../../data/api";+import { useLoad } from "../workspace/useLoad";++/** Every workspace on the server, for the platform operator. Listing records+ * nothing; entering one you hold no role in is recorded in its audit log, as+ * is every change you make there. */+export default function OperatorWorkspacesPage() {+ const load = useCallback(() => fetchOperatorWorkspaces(), []);+ const { data: workspaces, error, loading } = useLoad(load);+ const { session, switchTo } = useAuth();+ const [switchError, setSwitchError] = useState<string | null>(null);+ const currentId = session?.tenant?.id;++ const columns = useMemo<GridColDef<OperatorWorkspace>[]>(+ () => [+ {+ field: "name",+ headerName: "Workspace",+ flex: 1,+ minWidth: 160,+ renderCell: ({ row }) => (row.id === currentId ? `${row.name} (current)` : row.name),+ },+ { field: "slug", headerName: "Slug", flex: 1, minWidth: 140 },+ { field: "organization_id", headerName: "Organization", flex: 1, minWidth: 200 },+ {+ field: "actions",+ headerName: "",+ width: 110,+ sortable: false,+ renderCell: ({ row }) =>+ row.id === currentId ? null : (+ <Button+ size="small"+ onClick={() =>+ switchTo(row.id).catch((err: unknown) =>+ setSwitchError(err instanceof Error ? err.message : "Could not enter"),+ )+ }+ >+ Enter+ </Button>+ ),+ },+ ],+ [currentId, switchTo],+ );++ return (+ <Box>+ <Stack spacing={0.5} mb={2}>+ <Typography variant="h5">All workspaces</Typography>+ <Typography variant="body2" sx={{ color: "text.secondary" }}>+ Entering a workspace you hold no role in is recorded in its audit log, and so is every+ change you make there.+ </Typography>+ </Stack>+ {error && <Alert severity="error">{error}</Alert>}+ {switchError && (+ <Alert severity="error" onClose={() => setSwitchError(null)}>+ {switchError}+ </Alert>+ )}+ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={workspaces ?? []}+ columns={columns}+ height={Math.min(600, 108 + (workspaces?.length ?? 0) * 52)}+ pageSize={25}+ />+ )}+ </Box>+ );+}diff --git a/gateway/src/pages/organization/OrganizationAuditSection.tsx b/gateway/src/pages/organization/OrganizationAuditSection.tsxnew file mode 100644index 000000000..c0d6347a3--- /dev/null+++ b/gateway/src/pages/organization/OrganizationAuditSection.tsx@@ -0,0 +1,87 @@+import { Alert, CircularProgress, Stack, Typography } from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo } from "react";+import DataTable from "../../components/DataTable";+import {+ type AuditEvent,+ fetchOrganizationAuditEvents,+ fetchOrganizationMembers,+} from "../../data/api";+import { formatDate } from "../../theme/hootFormat";+import { useLoad } from "../workspace/useLoad";++const ACTION_LABELS: Record<string, string> = {+ "organization.created": "Organization created",+ "organization.workspace_created": "Workspace added",+ "organization.role_changed": "Organization role changed",+ "organization.member_removed": "Member removed",+};++/** What changed in the organization as a whole, newest first. A change the+ * platform operator made through operator access alone is marked. */+export default function OrganizationAuditSection() {+ const load = useCallback(+ () => Promise.all([fetchOrganizationAuditEvents(), fetchOrganizationMembers()]),+ [],+ );+ const { data, error, loading } = useLoad(load);+ const [events, members] = data ?? [[], []];+ const names = useMemo(() => new Map(members.map((m) => [m.user_id, m.name])), [members]);++ const columns = useMemo<GridColDef<AuditEvent>[]>(+ () => [+ {+ field: "occurred_at",+ headerName: "When",+ width: 160,+ valueFormatter: (value) => formatDate(value as string),+ },+ {+ field: "action",+ headerName: "What",+ flex: 1,+ minWidth: 180,+ valueFormatter: (value) => ACTION_LABELS[String(value)] ?? String(value),+ },+ {+ field: "actor_user_id",+ headerName: "Who",+ flex: 1,+ minWidth: 160,+ valueGetter: (value, row) => {+ const who = value ? (names.get(String(value)) ?? String(value)) : "Switch";+ return row.details?.platform_access ? `${who} (platform operator)` : who;+ },+ },+ {+ field: "target_id",+ headerName: "Of",+ flex: 1,+ minWidth: 160,+ valueGetter: (value, row) => {+ if (row.target_type === "user" && value) return names.get(String(value)) ?? value;+ const name = row.details?.name;+ return typeof name === "string" ? name : value;+ },+ },+ ],+ [names],+ );++ return (+ <Stack spacing={1.5}>+ <Typography variant="h6">Audit log</Typography>+ {error && <Alert severity="error">{error}</Alert>}+ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={events}+ columns={columns}+ height={Math.min(520, 108 + events.length * 52)}+ pageSize={25}+ />+ )}+ </Stack>+ );+}diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsxnew file mode 100644index 000000000..453f59724--- /dev/null+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx@@ -0,0 +1,169 @@+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import {+ Alert,+ CircularProgress,+ IconButton,+ MenuItem,+ Select,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { useAuth } from "../../data/AuthContext";+import {+ type OrganizationMember,+ type OrganizationRole,+ fetchOrganizationMembers,+ removeOrganizationMember,+ updateOrganizationRole,+} from "../../data/api";+import { formatDate } from "../../theme/hootFormat";+import { useLoad } from "../workspace/useLoad";++type MemberRow = OrganizationMember & { id: string };++const ROLE_LABELS: Record<OrganizationRole, string> = {+ org_admin: "Org Admin",+ member: "Member",+};++/** Everyone in the organization, across its workspaces, and their role in it.+ * The server refuses demoting or removing the last organization admin, and+ * removing someone still in one of its workspaces, naming them; its message+ * is shown as is. */+export default function OrganizationMembersSection({+ selfId,+ asOperator,+}: {+ selfId: string;+ // The platform operator, who is no admin here, may manage the members only+ // while the organization has no admin left, to make one.+ asOperator: boolean;+}) {+ const load = useCallback(() => fetchOrganizationMembers(), []);+ const { data: members, error, loading, refetch } = useLoad(load);+ const [actionError, setActionError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const { refresh } = useAuth();++ const act = useCallback(+ async (userId: string, action: () => Promise<unknown>) => {+ setBusy(userId);+ setActionError(null);+ try {+ await action();+ await refetch();+ // Your own role decides what this page offers you.+ if (userId === selfId) await refresh();+ } catch (err) {+ setActionError(err instanceof Error ? err.message : "The change failed");+ } finally {+ setBusy(null);+ }+ },+ [refetch, refresh, selfId],+ );++ const columns = useMemo<GridColDef<MemberRow>[]>(+ () => [+ {+ field: "name",+ headerName: "Name",+ flex: 1,+ minWidth: 140,+ renderCell: ({ row }) => (row.user_id === selfId ? `${row.name} (you)` : row.name),+ },+ { field: "email", headerName: "Email", flex: 1.5, minWidth: 200 },+ {+ field: "role",+ headerName: "Organization role",+ width: 170,+ renderCell: ({ row }) => (+ <Select+ size="small"+ value={row.role}+ disabled={busy !== null}+ onChange={(e) =>+ act(row.user_id, () =>+ updateOrganizationRole(row.user_id, e.target.value as OrganizationRole),+ )+ }+ aria-label={`Organization role for ${row.email}`}+ sx={{ fontSize: "0.875rem" }}+ >+ {(Object.keys(ROLE_LABELS) as OrganizationRole[]).map((role) => (+ <MenuItem key={role} value={role}>+ {ROLE_LABELS[role]}+ </MenuItem>+ ))}+ </Select>+ ),+ },+ {+ field: "created_at",+ headerName: "Joined",+ width: 140,+ valueFormatter: (value) => formatDate(value as string),+ },+ {+ field: "actions",+ headerName: "",+ width: 60,+ sortable: false,+ renderCell: ({ row }) =>+ row.user_id === selfId ? null : (+ <Tooltip title="Remove from organization">+ <span>+ <IconButton+ size="small"+ disabled={busy !== null}+ onClick={() => act(row.user_id, () => removeOrganizationMember(row.user_id))}+ aria-label={`Remove ${row.email} from the organization`}+ >+ <DeleteOutline fontSize="small" />+ </IconButton>+ </span>+ </Tooltip>+ ),+ },+ ],+ [act, busy, selfId],+ );++ return (+ <Stack spacing={1.5}>+ <Typography variant="h6">Members</Typography>+ <Typography variant="body2" sx={{ color: "text.secondary" }}>+ Organization admins administer every workspace in the organization. Someone is removed+ from each workspace before they can be removed from the organization.+ </Typography>+ {error &&+ (asOperator ? (+ <Alert severity="info">+ As platform operator you can manage this organization's members only while it has no+ admin, to make someone one. Changes you make are recorded in its audit log.+ </Alert>+ ) : (+ <Alert severity="error">{error}</Alert>+ ))}+ {actionError && (+ <Alert severity="error" onClose={() => setActionError(null)}>+ {actionError}+ </Alert>+ )}+ {loading ? (+ <CircularProgress />+ ) : error ? null : (+ <DataTable+ rows={(members ?? []).map((m) => ({ ...m, id: m.user_id }))}+ columns={columns}+ height={Math.min(520, 108 + (members?.length ?? 0) * 52)}+ pageSize={25}+ />+ )}+ </Stack>+ );+}diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsxnew file mode 100644index 000000000..16abb5f3e--- /dev/null+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx@@ -0,0 +1,177 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { GridColDef } from "@mui/x-data-grid";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { Session } from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import OrganizationPage from "./OrganizationPage";++vi.mock("../../data/AuthContext", () => ({ useAuth: vi.fn() }));++/** A cell's text as the grid would show it: through `valueGetter`, then+ * `valueFormatter`. */+function cellText(+ column: GridColDef<Record<string, unknown>>,+ row: Record<string, unknown>,+): string {+ const call = (fn: unknown, ...args: unknown[]) =>+ (fn as (...a: unknown[]) => unknown)(...args);+ let value: unknown = row[column.field];+ if (column.valueGetter) value = call(column.valueGetter, value, row, column, null);+ if (column.valueFormatter) value = call(column.valueFormatter, value, row, column, null);+ return String(value ?? "");+}++// The data grid renders no rows under jsdom; this draws every cell plainly.+vi.mock("../../components/DataTable", () => ({+ default: ({+ rows,+ columns,+ }: {+ rows: Record<string, unknown>[];+ columns: GridColDef<Record<string, unknown>>[];+ }) => (+ <div>+ {rows.map((row) => (+ <div key={String(row.id)} data-testid={`row-${String(row.id)}`}>+ {columns.map((column) => (+ <span key={column.field}>+ {column.renderCell ? column.renderCell({ row } as never) : cellText(column, row)}+ </span>+ ))}+ </div>+ ))}+ </div>+ ),+}));++function session(organizationRole: "org_admin" | "member", canAdd: boolean): Session {+ const tenant = {+ id: "t1",+ slug: "acme",+ name: "Acme",+ role: organizationRole === "org_admin" ? ("admin" as const) : ("member" as const),+ organization_role: organizationRole,+ organization_id: "o1",+ };+ return {+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: false },+ tenant,+ tenants: [tenant],+ state: "ready",+ can_create_workspace: true,+ can_add_workspace: canAdd,+ invite_email_enabled: false,+ };+}++function answer(routes: Record<string, unknown>) {+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = String(input).replace(/^\/gateway/, "").split("?")[0];+ const key = `${init?.method ?? "GET"} ${path}`;+ if (!(key in routes)) {+ return new Response(JSON.stringify({ detail: `unmocked ${key}` }), { status: 404 });+ }+ return new Response(JSON.stringify(routes[key]), { status: 200 });+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++const workspace = (id: string, name: string) => ({+ id,+ slug: id,+ name,+ role: "admin",+ organization_role: "org_admin",+ organization_id: "o1",+});++describe("OrganizationPage", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("shows an organization admin its members and audit log", async () => {+ vi.mocked(useAuth).mockReturnValue({+ session: session("org_admin", true),+ switchTo: vi.fn(),+ refresh: vi.fn(),+ } as unknown as ReturnType<typeof useAuth>);+ answer({+ "GET /organizations": [{ id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin" }],+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],+ "GET /organizations/current/members": [+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },+ ],+ "GET /organizations/current/audit-events": [+ {+ id: "e1",+ occurred_at: "2026-01-02",+ actor_user_id: "u2",+ action: "organization.role_changed",+ target_type: "user",+ target_id: "u2",+ details: { from: "member", to: "org_admin", platform_access: true },+ },+ ],+ });++ render(<OrganizationPage />);++ expect(await screen.findByText("Acme Inc")).toBeTruthy();+ expect(await screen.findByText("Acme (current)")).toBeTruthy();+ expect(screen.getByRole("heading", { name: "Members" })).toBeTruthy();+ expect(await screen.findByText("Organization role changed")).toBeTruthy();+ expect(screen.getByText("Bob (platform operator)")).toBeTruthy();+ });++ it("shows a member only the workspaces, with nothing to add", async () => {+ vi.mocked(useAuth).mockReturnValue({+ session: session("member", false),+ switchTo: vi.fn(),+ refresh: vi.fn(),+ } as unknown as ReturnType<typeof useAuth>);+ answer({+ "GET /organizations": [{ id: "o1", slug: "acme", name: "Acme Inc", role: "member" }],+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],+ });++ render(<OrganizationPage />);++ expect(await screen.findByText("Acme (current)")).toBeTruthy();+ expect(screen.queryByRole("heading", { name: "Members" })).toBeNull();+ expect(screen.queryByRole("heading", { name: "Audit log" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Add workspace" })).toBeNull();+ });++ it("adds a workspace and lists it", async () => {+ vi.mocked(useAuth).mockReturnValue({+ session: session("org_admin", true),+ switchTo: vi.fn(),+ refresh: vi.fn(),+ } as unknown as ReturnType<typeof useAuth>);+ const routes: Record<string, unknown> = {+ "GET /organizations": [],+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],+ "GET /organizations/current/members": [],+ "GET /organizations/current/audit-events": [],+ "POST /organizations/current/workspaces": workspace("t2", "Research"),+ };+ const fetchMock = answer(routes);++ render(<OrganizationPage />);+ fireEvent.click(await screen.findByRole("button", { name: "Add workspace" }));+ fireEvent.change(screen.getByLabelText(/Workspace name/), { target: { value: "Research" } });+ routes["GET /organizations/current/workspaces"] = [+ workspace("t1", "Acme"),+ workspace("t2", "Research"),+ ];+ fireEvent.click(screen.getAllByRole("button", { name: "Add workspace" }).at(-1)!);++ expect(await screen.findByText("Research")).toBeTruthy();+ const posted = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");+ expect(JSON.parse(String(posted?.[1]?.body))).toEqual({ name: "Research" });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });+});diff --git a/gateway/src/pages/organization/OrganizationPage.tsx b/gateway/src/pages/organization/OrganizationPage.tsxnew file mode 100644index 000000000..ba98a0183--- /dev/null+++ b/gateway/src/pages/organization/OrganizationPage.tsx@@ -0,0 +1,49 @@+import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";+import { useCallback } from "react";+import { useAuth } from "../../data/AuthContext";+import { fetchOrganizations } from "../../data/api";+import { administersOrganization } from "../../data/sessionState";+import { useLoad } from "../workspace/useLoad";+import OrganizationAuditSection from "./OrganizationAuditSection";+import OrganizationMembersSection from "./OrganizationMembersSection";+import WorkspacesSection from "./WorkspacesSection";++/** The organization the current workspace belongs to. Its workspaces are+ * listed to anyone in it; its members and audit log to its admins, the only+ * ones the server answers. */+export default function OrganizationPage() {+ const { session } = useAuth();+ const load = useCallback(() => fetchOrganizations(), []);+ const { data: organizations, error } = useLoad(load);+ const tenant = session?.tenant;+ if (!session || !tenant) return <CircularProgress />;+ if (tenant.organization_id === null) {+ return <Alert severity="info">This workspace belongs to no organization.</Alert>;+ }+ const organization = organizations?.find((o) => o.id === tenant.organization_id);+ const isAdmin = administersOrganization(session);++ return (+ <Box>+ <Stack spacing={0.5} mb={3}>+ <Typography variant="h5">{organization?.name ?? "Organization"}</Typography>+ <Typography variant="body2" sx={{ color: "text.secondary" }}>+ {isAdmin+ ? "You are an admin of this organization, and so of every workspace in it."+ : "You are a member of this organization."}+ </Typography>+ </Stack>+ {error && <Alert severity="error">{error}</Alert>}+ <Stack spacing={4}>+ <WorkspacesSection+ currentId={tenant.id}+ canAdd={session.can_add_workspace}+ />+ {(isAdmin || session.user.is_operator) && (+ <OrganizationMembersSection selfId={session.user.id} asOperator={!isAdmin} />+ )}+ {isAdmin && <OrganizationAuditSection />}+ </Stack>+ </Box>+ );+}diff --git a/gateway/src/pages/organization/WorkspacesSection.tsx b/gateway/src/pages/organization/WorkspacesSection.tsxnew file mode 100644index 000000000..5b2f76cae--- /dev/null+++ b/gateway/src/pages/organization/WorkspacesSection.tsx@@ -0,0 +1,172 @@+import AddCircleOutline from "@mui/icons-material/AddCircleOutline";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Stack,+ TextField,+ Typography,+} from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { useAuth } from "../../data/AuthContext";+import {+ type TenantMembership,+ createOrganizationWorkspace,+ fetchOrganizationWorkspaces,+} from "../../data/api";+import { titleCase } from "../../theme/hootFormat";+import { useLoad } from "../workspace/useLoad";++interface Props {+ currentId: string;+ canAdd: boolean;+}++/** The organization's workspaces the person may enter: every one for an+ * organization admin, their own for a member. Adding one keeps the session+ * where it is; switching into it is a separate step. */+export default function WorkspacesSection({ currentId, canAdd }: Props) {+ const load = useCallback(() => fetchOrganizationWorkspaces(), []);+ const { data: workspaces, error, loading, refetch } = useLoad(load);+ const { switchTo } = useAuth();+ const [actionError, setActionError] = useState<string | null>(null);+ const [addOpen, setAddOpen] = useState(false);++ const columns = useMemo<GridColDef<TenantMembership>[]>(+ () => [+ {+ field: "name",+ headerName: "Workspace",+ flex: 1,+ minWidth: 160,+ renderCell: ({ row }) => (row.id === currentId ? `${row.name} (current)` : row.name),+ },+ {+ field: "role",+ headerName: "Your role",+ width: 140,+ valueFormatter: (value) => titleCase(String(value)),+ },+ {+ field: "actions",+ headerName: "",+ width: 120,+ sortable: false,+ renderCell: ({ row }) =>+ row.id === currentId ? null : (+ <Button+ size="small"+ onClick={() =>+ switchTo(row.id).catch((err: unknown) =>+ setActionError(err instanceof Error ? err.message : "Could not switch"),+ )+ }+ >+ Switch+ </Button>+ ),+ },+ ],+ [currentId, switchTo],+ );++ return (+ <Stack spacing={1.5}>+ <Stack direction="row" alignItems="center" justifyContent="space-between">+ <Typography variant="h6">Workspaces</Typography>+ {canAdd && (+ <Button startIcon={<AddCircleOutline />} onClick={() => setAddOpen(true)}>+ Add workspace+ </Button>+ )}+ </Stack>+ {error && <Alert severity="error">{error}</Alert>}+ {actionError && (+ <Alert severity="error" onClose={() => setActionError(null)}>+ {actionError}+ </Alert>+ )}+ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={workspaces ?? []}+ columns={columns}+ height={Math.min(420, 108 + (workspaces?.length ?? 0) * 52)}+ pageSize={25}+ />+ )}+ <AddWorkspaceDialog open={addOpen} onClose={() => setAddOpen(false)} onAdded={refetch} />+ </Stack>+ );+}++function AddWorkspaceDialog({+ open,+ onClose,+ onAdded,+}: {+ open: boolean;+ onClose: () => void;+ onAdded: () => Promise<void>;+}) {+ const [name, setName] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [submitting, setSubmitting] = useState(false);++ const close = () => {+ setName("");+ setError(null);+ onClose();+ };++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ setSubmitting(true);+ setError(null);+ try {+ await createOrganizationWorkspace(name.trim());+ await onAdded();+ close();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not add the workspace");+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={open} onClose={close} maxWidth="xs" fullWidth>+ <form onSubmit={submit}>+ <DialogTitle>Add a workspace</DialogTitle>+ <DialogContent sx={{ pt: "8px !important" }}>+ <Stack spacing={2}>+ {error && <Alert severity="error">{error}</Alert>}+ <TextField+ label="Workspace name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ helperText="You become its owner. Every organization admin administers it."+ required+ autoFocus+ />+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={close} disabled={submitting}>+ Cancel+ </Button>+ <Button type="submit" variant="contained" disabled={submitting || name.trim() === ""}>+ Add workspace+ </Button>+ </DialogActions>+ </form>+ </Dialog>+ );+}diff --git a/gateway/src/pages/users/CreateUserDialog.tsx b/gateway/src/pages/users/CreateUserDialog.tsxindex b962ff729..096cb6749 100644--- a/gateway/src/pages/users/CreateUserDialog.tsx+++ b/gateway/src/pages/users/CreateUserDialog.tsx@@ -88,7 +88,7 @@ export default function CreateUserDialog({ open, onClose, onCreated }: Props) {onChange={(e) => setRole(e.target.value as UserRole)}><MenuItem value="user">User</MenuItem>- <MenuItem value="admin">Admin</MenuItem>+ <MenuItem value="admin">Platform operator</MenuItem></TextField></Stack></DialogContent>diff --git a/gateway/src/pages/users/UsersPage.tsx b/gateway/src/pages/users/UsersPage.tsxindex ec06cbd8e..5c45b568d 100644--- a/gateway/src/pages/users/UsersPage.tsx+++ b/gateway/src/pages/users/UsersPage.tsx@@ -5,7 +5,7 @@ import { useMemo, useState } from "react";import DataTable from "../../components/DataTable";import type { UserInfo } from "../../data/api";import { useUsers } from "../../data/hooks";-import { formatDate, titleCase } from "../../theme/hootFormat";+import { formatDate } from "../../theme/hootFormat";import CreateUserDialog from "./CreateUserDialog";export default function UsersPage() {@@ -19,10 +19,10 @@ export default function UsersPage() {{field: "role",headerName: "Role",- width: 120,+ width: 160,renderCell: ({ value }) => (<Chip- label={titleCase(String(value))}+ label={value === "admin" ? "Platform operator" : "User"}size="small"color={value === "admin" ? "primary" : "default"}/>diff --git a/gateway/src/pages/workspace/MembersSection.test.tsx b/gateway/src/pages/workspace/MembersSection.test.tsxnew file mode 100644index 000000000..808d1e015--- /dev/null+++ b/gateway/src/pages/workspace/MembersSection.test.tsx@@ -0,0 +1,75 @@+import { cleanup, render, screen } from "@testing-library/react";+import type { GridColDef } from "@mui/x-data-grid";+import { afterEach, describe, expect, it, vi } from "vitest";+import MembersSection from "./MembersSection";++vi.mock("../../data/AuthContext", () => ({ useAuth: () => ({ refresh: vi.fn() }) }));++vi.mock("../../components/DataTable", () => ({+ default: ({+ rows,+ columns,+ }: {+ rows: Record<string, unknown>[];+ columns: GridColDef<Record<string, unknown>>[];+ }) => (+ <div>+ {rows.map((row) => (+ <div key={String(row.id)} data-testid={`row-${String(row.id)}`}>+ {columns.map((column) => (+ <span key={column.field}>+ {column.renderCell ? column.renderCell({ row } as never) : null}+ </span>+ ))}+ </div>+ ))}+ </div>+ ),+}));++const member = (overrides: Record<string, unknown>) => ({+ name: "x",+ email: "[email protected]",+ role: "member",+ created_at: "2026-01-01",+ organization_role: "member",+ via_organization: false,+ ...overrides,+});++describe("MembersSection", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("shows organization admins read-only, and the rest manageable", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(+ async () =>+ new Response(+ JSON.stringify([+ member({ user_id: "u2", name: "Bob", email: "[email protected]" }),+ member({+ user_id: "u3",+ name: "Cy",+ email: "[email protected]",+ role: "admin",+ organization_role: "org_admin",+ via_organization: true,+ }),+ ]),+ ),+ ),+ );++ render(<MembersSection tenantId="t1" selfId="u1" canAdmin isOwner />);++ expect(await screen.findByText("Org Admin, via organization")).toBeTruthy();+ expect(screen.queryByLabelText("Role for [email protected]")).toBeNull();+ expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();+ expect(screen.getByLabelText("Role for [email protected]")).toBeTruthy();+ expect(screen.getByLabelText("Remove [email protected]")).toBeTruthy();+ });+});diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsxindex a8027a7d6..fcd4e099a 100644--- a/gateway/src/pages/workspace/MembersSection.tsx+++ b/gateway/src/pages/workspace/MembersSection.tsx@@ -35,7 +35,12 @@ interface Props {/** An admin may manage members and admins; only an owner may grant the owner* role or touch an existing owner. The server enforces the same, and refuses- * the last owner — its message is shown as is. */+ * the last owner — its message is shown as is.+ *+ * An organization admin administers every workspace of the organization, so+ * their row here is read-only: the role comes from the organization, and is+ * changed on its page. One with no membership of their own here is listed+ * "via the organization". */export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }: Props) {const load = useCallback(() => fetchMembers(tenantId), [tenantId]);const { data: members, error, loading, refetch } = useLoad(load);@@ -62,7 +67,8 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:);const columns = useMemo<GridColDef<MemberRow>[]>(() => {- const mayManage = (row: MemberRow) => canAdmin && (isOwner || row.role !== "owner");+ const mayManage = (row: MemberRow) =>+ canAdmin && row.organization_role !== "org_admin" && (isOwner || row.role !== "owner");const roles: TenantRole[] = isOwner ? ["owner", "admin", "member"] : ["admin", "member"];return [{@@ -76,7 +82,7 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:{field: "role",headerName: "Role",- width: 150,+ width: 210,renderCell: ({ row }) =>mayManage(row) ? (<Select@@ -97,6 +103,21 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:</MenuItem>))}</Select>+ ) : row.organization_role === "org_admin" ? (+ <Tooltip+ title={+ row.via_organization+ ? "Administers this workspace through the organization. Change it on the Organization page."+ : "An organization admin, and so an admin of every workspace in it. Change it on the Organization page."+ }+ >+ <Chip+ label={row.via_organization ? "Org Admin, via organization" : "Org Admin"}+ size="small"+ color="primary"+ variant="outlined"+ />+ </Tooltip>) : (<Chiplabel={titleCase(row.role)}