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] Address review: the operator's path, audit names and paging
Petr Bauch6b8627f636a7
diff --git a/gateway/src/App.tsx b/gateway/src/App.tsxindex 6ff51e65d..2e1e57e7c 100644--- a/gateway/src/App.tsx+++ b/gateway/src/App.tsx@@ -26,11 +26,11 @@ import AcceptInvitePage from "./pages/onboarding/AcceptInvitePage";import InviteCapture from "./pages/onboarding/InviteCapture";import OnboardingPage from "./pages/onboarding/OnboardingPage";import WorkspacePickerPage from "./pages/onboarding/WorkspacePickerPage";+import OperatorWorkspacesPage from "./pages/operator/OperatorWorkspacesPage";+import OrganizationPage from "./pages/organization/OrganizationPage";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 (diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex b7189f274..d5a27847b 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1224,13 +1224,6 @@ 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;@@ -1239,25 +1232,38 @@ export interface OrganizationMember {created_at: string;}-export interface AuditEvent {+export interface OrganizationAuditEvent {id: string;occurred_at: string;actor_user_id: string | null;+ // Read from the account, so a removed member or the platform operator is+ // named too; null only once the account is gone.+ actor_name: string | null;action: string;target_type: string;target_id: string | null;+ target_name: string | null;details: Record<string, unknown> | null;}+export interface CurrentOrganization {+ id: string;+ slug: string;+ name: string;+ // Null for the platform operator there through operator access alone.+ role: OrganizationRole | null;+}+export interface OperatorWorkspace {id: string;slug: string;name: string;organization_id: string | null;+ organization_name: string | null;}-export async function fetchOrganizations(): Promise<OrganizationSummary[]> {- return jsonRequest<OrganizationSummary[]>("/organizations", "GET");+export async function fetchCurrentOrganization(): Promise<CurrentOrganization> {+ return jsonRequest<CurrentOrganization>("/organizations/current", "GET");}export async function fetchOrganizationWorkspaces(): Promise<TenantMembership[]> {@@ -1288,8 +1294,19 @@ 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");+export const ORGANIZATION_AUDIT_PAGE = 50;++/** One page of the organization's audit log, newest first: the most recent+ * events, or those before `before` (an `occurred_at` from an earlier page). */+export async function fetchOrganizationAuditEvents(+ before: string | null,+): Promise<OrganizationAuditEvent[]> {+ const query = new URLSearchParams({ limit: String(ORGANIZATION_AUDIT_PAGE) });+ if (before !== null) query.set("before", before);+ return jsonRequest<OrganizationAuditEvent[]>(+ `/organizations/current/audit-events?${query}`,+ "GET",+ );}/** Every workspace on the server; the platform operator only. */diff --git a/gateway/src/pages/operator/OperatorWorkspacesPage.tsx b/gateway/src/pages/operator/OperatorWorkspacesPage.tsxindex 34537c587..df347c2c6 100644--- a/gateway/src/pages/operator/OperatorWorkspacesPage.tsx+++ b/gateway/src/pages/operator/OperatorWorkspacesPage.tsx@@ -26,7 +26,13 @@ export default function OperatorWorkspacesPage() {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: "organization_name",+ headerName: "Organization",+ flex: 1,+ minWidth: 160,+ valueGetter: (value, row) => value ?? row.organization_id ?? "None",+ },{field: "actions",headerName: "",diff --git a/gateway/src/pages/organization/OrganizationAuditSection.tsx b/gateway/src/pages/organization/OrganizationAuditSection.tsxindex c0d6347a3..319e73649 100644--- a/gateway/src/pages/organization/OrganizationAuditSection.tsx+++ b/gateway/src/pages/organization/OrganizationAuditSection.tsx@@ -1,14 +1,13 @@-import { Alert, CircularProgress, Stack, Typography } from "@mui/material";+import { Alert, Button, CircularProgress, Stack, Typography } from "@mui/material";import type { GridColDef } from "@mui/x-data-grid";-import { useCallback, useMemo } from "react";+import { useCallback, useEffect, useState } from "react";import DataTable from "../../components/DataTable";import {- type AuditEvent,+ ORGANIZATION_AUDIT_PAGE,+ type OrganizationAuditEvent,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",@@ -17,71 +16,94 @@ const ACTION_LABELS: Record<string, string> = {"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. */+const COLUMNS: GridColDef<OrganizationAuditEvent>[] = [+ {+ 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_name",+ headerName: "Who",+ flex: 1,+ minWidth: 160,+ valueGetter: (value, row) => {+ const who = value ?? row.actor_user_id ?? "Switch";+ return row.details?.platform_access ? `${who} (platform operator)` : who;+ },+ },+ {+ field: "target_name",+ headerName: "Of",+ flex: 1,+ minWidth: 160,+ valueGetter: (value, row) => {+ if (value) return value;+ const name = row.details?.name;+ return typeof name === "string" ? name : row.target_id;+ },+ },+];++/** What changed in the organization as a whole, newest first, a page at a+ * time. 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 [events, setEvents] = useState<OrganizationAuditEvent[]>([]);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);+ // Whether the last page came back full, so there may be older events.+ const [more, setMore] = useState(false);- 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],- );+ const loadPage = useCallback(async (before: string | null) => {+ setLoading(true);+ try {+ const page = await fetchOrganizationAuditEvents(before);+ setEvents((shown) => (before === null ? page : [...shown, ...page]));+ setMore(page.length === ORGANIZATION_AUDIT_PAGE);+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to load");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void loadPage(null);+ }, [loadPage]);return (<Stack spacing={1.5}><Typography variant="h6">Audit log</Typography>{error && <Alert severity="error">{error}</Alert>}- {loading ? (+ {loading && events.length === 0 ? (<CircularProgress />) : (<DataTablerows={events}- columns={columns}+ columns={COLUMNS}height={Math.min(520, 108 + events.length * 52)}pageSize={25}/>)}+ {more && (+ <Button+ sx={{ alignSelf: "flex-start" }}+ disabled={loading}+ onClick={() => loadPage(events[events.length - 1].occurred_at)}+ >+ Load older events+ </Button>+ )}</Stack>);}diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsxindex 453f59724..ae3ebe9fe 100644--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx@@ -44,7 +44,7 @@ export default function OrganizationMembersSection({asOperator: boolean;}) {const load = useCallback(() => fetchOrganizationMembers(), []);- const { data: members, error, loading, refetch } = useLoad(load);+ const { data: members, error, errorStatus, loading, refetch } = useLoad(load);const [actionError, setActionError] = useState<string | null>(null);const [busy, setBusy] = useState<string | null>(null);const { refresh } = useAuth();@@ -132,6 +132,9 @@ export default function OrganizationMembersSection({],[act, busy, selfId],);+ // The operator restores an admin and nothing more: removing a member is+ // refused to them, so there is nothing to offer.+ const shown = asOperator ? columns.filter((c) => c.field !== "actions") : columns;return (<Stack spacing={1.5}>@@ -140,15 +143,20 @@ export default function OrganizationMembersSection({Organization admins administer every workspace in the organization. Someone is removedfrom 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>- ))}+ {asOperator && errorStatus === 403 ? (+ <Alert severity="info">+ As platform operator you can manage this organization's members only while it has no+ admin, to make someone one.+ </Alert>+ ) : (+ error && <Alert severity="error">{error}</Alert>+ )}+ {asOperator && !error && !loading && (+ <Alert severity="warning">+ This organization has no admin. As platform operator you can make one of its members+ an admin; the change is recorded in its audit log, marked as yours.+ </Alert>+ )}{actionError && (<Alert severity="error" onClose={() => setActionError(null)}>{actionError}@@ -159,7 +167,7 @@ export default function OrganizationMembersSection({) : error ? null : (<DataTablerows={(members ?? []).map((m) => ({ ...m, id: m.user_id }))}- columns={columns}+ columns={shown}height={Math.min(520, 108 + (members?.length ?? 0) * 52)}pageSize={25}/>diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsxindex 16abb5f3e..f9f7f6e8f 100644--- a/gateway/src/pages/organization/OrganizationPage.test.tsx+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx@@ -1,5 +1,4 @@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";@@ -7,54 +6,23 @@ 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 ?? "");-}+vi.mock("../../components/DataTable", () => import("../../test/FakeDataTable"));-// 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 {+function session(+ organizationRole: "org_admin" | "member" | null,+ canAdd: boolean,+ isOperator = false,+): Session {const tenant = {id: "t1",slug: "acme",name: "Acme",- role: organizationRole === "org_admin" ? ("admin" as const) : ("member" as const),+ role: organizationRole === "member" ? ("member" as const) : ("admin" as const),organization_role: organizationRole,organization_id: "o1",};return {- user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: false },+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: isOperator },tenant,tenants: [tenant],state: "ready",@@ -64,6 +32,8 @@ function session(organizationRole: "org_admin" | "member", canAdd: boolean): Ses};}+/** Answers each `METHOD /path` from `routes`: a body, or `[status, body]`+ * for a refusal. */function answer(routes: Record<string, unknown>) {const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const path = String(input).replace(/^\/gateway/, "").split("?")[0];@@ -71,12 +41,35 @@ function answer(routes: Record<string, unknown>) {if (!(key in routes)) {return new Response(JSON.stringify({ detail: `unmocked ${key}` }), { status: 404 });}- return new Response(JSON.stringify(routes[key]), { status: 200 });+ const answered = routes[key];+ if (answered instanceof Refusal) {+ return new Response(JSON.stringify({ detail: answered.detail }), {+ status: answered.status,+ });+ }+ return new Response(JSON.stringify(answered), { status: 200 });});vi.stubGlobal("fetch", fetchMock);return fetchMock;}+class Refusal {+ constructor(+ readonly status: number,+ readonly detail: string,+ ) {}+}++function signedInAs(current: Session) {+ const refresh = vi.fn();+ vi.mocked(useAuth).mockReturnValue({+ session: current,+ switchTo: vi.fn(),+ refresh,+ } as unknown as ReturnType<typeof useAuth>);+ return refresh;+}+const workspace = (id: string, name: string) => ({id,slug: id,@@ -93,13 +86,9 @@ describe("OrganizationPage", () => {});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>);+ signedInAs(session("org_admin", true));answer({- "GET /organizations": [{ id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin" }],+ "GET /organizations/current": { 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" },@@ -108,10 +97,12 @@ describe("OrganizationPage", () => {{id: "e1",occurred_at: "2026-01-02",- actor_user_id: "u2",+ actor_user_id: "op",+ actor_name: "Olga",action: "organization.role_changed",target_type: "user",target_id: "u2",+ target_name: "Bob",details: { from: "member", to: "org_admin", platform_access: true },},],@@ -123,17 +114,13 @@ describe("OrganizationPage", () => {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();+ expect(screen.getByText("Olga (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>);+ signedInAs(session("member", false));answer({- "GET /organizations": [{ id: "o1", slug: "acme", name: "Acme Inc", role: "member" }],+ "GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "member" },"GET /organizations/current/workspaces": [workspace("t1", "Acme")],});@@ -145,14 +132,10 @@ describe("OrganizationPage", () => {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>);+ it("adds a workspace, lists it, and refreshes the session", async () => {+ const refresh = signedInAs(session("org_admin", true));const routes: Record<string, unknown> = {- "GET /organizations": [],+ "GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin" },"GET /organizations/current/workspaces": [workspace("t1", "Acme")],"GET /organizations/current/members": [],"GET /organizations/current/audit-events": [],@@ -173,5 +156,48 @@ describe("OrganizationPage", () => {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());+ expect(refresh).toHaveBeenCalled();+ });++ const members = [+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },+ ];+ const operatorRoutes = (membersAnswer: unknown) => ({+ "GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: null },+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],+ "GET /organizations/current/members": membersAnswer,+ });++ it("lets the operator make an admin where there is none, and nothing more", async () => {+ signedInAs(session(null, false, true));+ answer(operatorRoutes(members));++ render(<OrganizationPage />);++ expect(await screen.findByLabelText("Organization role for [email protected]")).toBeTruthy();+ expect(screen.queryByLabelText("Remove [email protected] from the organization")).toBeNull();+ expect(screen.getByText(/This organization has no admin/)).toBeTruthy();+ expect(screen.getByText(/You are here as platform operator/)).toBeTruthy();+ expect(screen.queryByRole("heading", { name: "Audit log" })).toBeNull();+ });++ it("tells the operator why where the organization has an admin", async () => {+ signedInAs(session(null, false, true));+ answer(operatorRoutes(new Refusal(403, "Only an organization admin may do this")));++ render(<OrganizationPage />);++ expect(await screen.findByText(/only while it has no admin/)).toBeTruthy();+ expect(screen.queryByText("Only an organization admin may do this")).toBeNull();+ });++ it("shows the operator a failure as a failure", async () => {+ signedInAs(session(null, false, true));+ answer(operatorRoutes(new Refusal(500, "The database is unavailable")));++ render(<OrganizationPage />);++ expect(await screen.findByText("The database is unavailable")).toBeTruthy();+ expect(screen.queryByText(/only while it has no admin/)).toBeNull();});});diff --git a/gateway/src/pages/organization/OrganizationPage.tsx b/gateway/src/pages/organization/OrganizationPage.tsxindex ba98a0183..6a7fb35a2 100644--- a/gateway/src/pages/organization/OrganizationPage.tsx+++ b/gateway/src/pages/organization/OrganizationPage.tsx@@ -1,7 +1,7 @@import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";import { useCallback } from "react";import { useAuth } from "../../data/AuthContext";-import { fetchOrganizations } from "../../data/api";+import { fetchCurrentOrganization } from "../../data/api";import { administersOrganization } from "../../data/sessionState";import { useLoad } from "../workspace/useLoad";import OrganizationAuditSection from "./OrganizationAuditSection";@@ -13,32 +13,32 @@ import WorkspacesSection from "./WorkspacesSection";* ones the server answers. */export default function OrganizationPage() {const { session } = useAuth();- const load = useCallback(() => fetchOrganizations(), []);- const { data: organizations, error } = useLoad(load);+ const load = useCallback(() => fetchCurrentOrganization(), []);+ const { data: organization, 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="h5">{organization?.name ?? ""}</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."}+ : organization === null+ ? ""+ : organization.role === "member"+ ? "You are a member of this organization."+ : "You are here as platform operator, not as 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}- />+ <WorkspacesSection currentId={tenant.id} canAdd={session.can_add_workspace} />{(isAdmin || session.user.is_operator) && (<OrganizationMembersSection selfId={session.user.id} asOperator={!isAdmin} />)}diff --git a/gateway/src/pages/organization/WorkspacesSection.tsx b/gateway/src/pages/organization/WorkspacesSection.tsxindex 5b2f76cae..09da1028a 100644--- a/gateway/src/pages/organization/WorkspacesSection.tsx+++ b/gateway/src/pages/organization/WorkspacesSection.tsx@@ -34,7 +34,7 @@ interface Props {export default function WorkspacesSection({ currentId, canAdd }: Props) {const load = useCallback(() => fetchOrganizationWorkspaces(), []);const { data: workspaces, error, loading, refetch } = useLoad(load);- const { switchTo } = useAuth();+ const { switchTo, refresh } = useAuth();const [actionError, setActionError] = useState<string | null>(null);const [addOpen, setAddOpen] = useState(false);@@ -102,7 +102,15 @@ export default function WorkspacesSection({ currentId, canAdd }: Props) {pageSize={25}/>)}- <AddWorkspaceDialog open={addOpen} onClose={() => setAddOpen(false)} onAdded={refetch} />+ <AddWorkspaceDialog+ open={addOpen}+ onClose={() => setAddOpen(false)}+ onAdded={async () => {+ await refetch();+ // Adding one may use up the allowance, which the session reports.+ await refresh();+ }}+ /></Stack>);}diff --git a/gateway/src/pages/workspace/MembersSection.test.tsx b/gateway/src/pages/workspace/MembersSection.test.tsxindex 808d1e015..342123b52 100644--- a/gateway/src/pages/workspace/MembersSection.test.tsx+++ b/gateway/src/pages/workspace/MembersSection.test.tsx@@ -1,31 +1,10 @@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>- ),-}));+vi.mock("../../components/DataTable", () => import("../../test/FakeDataTable"));const member = (overrides: Record<string, unknown>) => ({name: "x",@@ -59,6 +38,13 @@ describe("MembersSection", () => {organization_role: "org_admin",via_organization: true,}),+ member({+ user_id: "u4",+ name: "Dee",+ email: "[email protected]",+ role: "owner",+ organization_role: "org_admin",+ }),]),),),@@ -67,6 +53,8 @@ describe("MembersSection", () => {render(<MembersSection tenantId="t1" selfId="u1" canAdmin isOwner />);expect(await screen.findByText("Org Admin, via organization")).toBeTruthy();+ expect(screen.getByText("Owner · Org Admin")).toBeTruthy();+ expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();expect(screen.queryByLabelText("Role for [email protected]")).toBeNull();expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();expect(screen.getByLabelText("Role for [email protected]")).toBeTruthy();diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsxindex fcd4e099a..a0c934e20 100644--- a/gateway/src/pages/workspace/MembersSection.tsx+++ b/gateway/src/pages/workspace/MembersSection.tsx@@ -112,7 +112,11 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:}><Chip- label={row.via_organization ? "Org Admin, via organization" : "Org Admin"}+ label={+ row.via_organization+ ? "Org Admin, via organization"+ : `${titleCase(row.role)} · Org Admin`+ }size="small"color="primary"variant="outlined"diff --git a/gateway/src/pages/workspace/useLoad.ts b/gateway/src/pages/workspace/useLoad.tsindex 0b0dc9f8f..d681495f4 100644--- a/gateway/src/pages/workspace/useLoad.ts+++ b/gateway/src/pages/workspace/useLoad.ts@@ -1,18 +1,24 @@import { useCallback, useEffect, useState } from "react";+import { ApiError } from "../../data/api";/** Load with the error kept: these calls fail for reasons the person should* read (not an admin, workspace gone), not only for being offline. */export function useLoad<T>(load: () => Promise<T>) {const [data, setData] = useState<T | null>(null);const [error, setError] = useState<string | null>(null);+ // The HTTP status of a refusal, so a caller can tell an expected 403 from+ // a failure; null for anything that was not an answer from the server.+ const [errorStatus, setErrorStatus] = useState<number | null>(null);const [loading, setLoading] = useState(true);const refetch = useCallback(async () => {try {setData(await load());setError(null);+ setErrorStatus(null);} catch (err) {setError(err instanceof Error ? err.message : "Failed to load");+ setErrorStatus(err instanceof ApiError ? err.status : null);} finally {setLoading(false);}@@ -22,5 +28,5 @@ export function useLoad<T>(load: () => Promise<T>) {void refetch();}, [refetch]);- return { data, error, loading, refetch };+ return { data, error, errorStatus, loading, refetch };}diff --git a/gateway/src/test/FakeDataTable.tsx b/gateway/src/test/FakeDataTable.tsxnew file mode 100644index 000000000..fcebcdd6b--- /dev/null+++ b/gateway/src/test/FakeDataTable.tsx@@ -0,0 +1,38 @@+import type { GridColDef } from "@mui/x-data-grid";++type Row = Record<string, unknown>;++/** A cell's text as the grid would show it: through `valueGetter`, then+ * `valueFormatter`. */+function cellText(column: GridColDef<Row>, row: Row): 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 ?? "");+}++/** Stands in for `components/DataTable` in tests: the data grid lays rows out+ * from measured sizes, which jsdom does not have, so it renders none. This+ * draws every row's cells plainly, as the grid would show them. */+export default function FakeDataTable({+ rows,+ columns,+}: {+ rows: Row[];+ columns: GridColDef<Row>[];+}) {+ return (+ <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>+ );+}