Skip to content

The open-source app everyone uses to manage agents at work

fix(access): give Operators default company editing permissions (#15377)

Dotta582911ba7435
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index 0d7715e854..3ea52f845f 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -584,6 +584,18 @@ conversation lifecycles, and protection against replaying superseded requests.
- Board has full read/write across all companies in deployment
- Every board mutation writes to `activity_log`
+Human invitations default to the Operator role. Its default grants allow agent
+creation and configuration, skill editing, environment management, invitations,
+task assignment, pipeline editing, connection and tool management/use, and tool
+and agent-action audit views. Operators do not receive `joins:approve` or
+`users:manage_permissions`. Explicit invitation grants remain authoritative.
+Creating a human invitation also requires any of these two membership powers
+included in its selected role. Operators can invite Operators and Viewers;
+inviting an Admin requires join approval, and inviting an Owner also requires
+member-permission management.
+This preset change adds no database migration; existing role-default seeding
+continues to insert missing grants without replacing custom scopes.
+
## 9.2 Agent Auth
- Bearer API key mapped to one agent and company
diff --git a/doc/SPEC.md b/doc/SPEC.md
index 5b949cc70f..0a300c3737 100644
--- a/doc/SPEC.md
+++ b/doc/SPEC.md
@@ -21,6 +21,12 @@ A Company is a first-order object. One Paperclip instance runs multiple Companie
Every Company has a **Board** that governs high-impact decisions. The Board is the human oversight layer.
+Human invitations default to Operator, with company editing, invitations,
+connections, tools, environments, pipelines, and audit views available by
+default. Join approval and member-permission management remain separate grants.
+An inviter must hold these membership grants to invite a role that includes them.
+See [human Operator defaults](SPEC-implementation.md#91-board-auth).
+
**V1: Single human Board.** One human operator.
#### Board Approval Gates (V1)
diff --git a/server/src/__tests__/access-service.test.ts b/server/src/__tests__/access-service.test.ts
index 3482a5784b..2d81dba8bc 100644
--- a/server/src/__tests__/access-service.test.ts
+++ b/server/src/__tests__/access-service.test.ts
@@ -879,7 +879,7 @@ describeEmbeddedPostgres("access service", () => {
.toHaveLength(1);
});
- it("allows owner and admin role-default grants to manage environments", async () => {
+ it("allows owner, admin, and operator role-default grants to manage environments", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const access = accessService(db);
const roles = ["admin", "operator", "viewer"] as const;
@@ -919,10 +919,50 @@ describeEmbeddedPostgres("access service", () => {
await expect(access.canUser(company.id, owner.principalId, "environments:manage")).resolves.toBe(true);
await expect(access.canUser(company.id, admin.principalId, "environments:manage")).resolves.toBe(true);
- await expect(access.canUser(company.id, operator.principalId, "environments:manage")).resolves.toBe(false);
+ await expect(access.canUser(company.id, operator.principalId, "environments:manage")).resolves.toBe(true);
await expect(access.canUser(company.id, viewer.principalId, "environments:manage")).resolves.toBe(false);
});
+ it("allows default operators to edit agents and company work without administering membership", async () => {
+ const { company, owner } = await createCompanyWithOwner(db);
+ const access = accessService(db);
+ const operator = await access.ensureMembership(company.id, "user", `operator-${randomUUID()}`, "operator");
+ const agent = await db.insert(agents).values({
+ companyId: company.id,
+ name: "Operator-editable agent",
+ role: "engineer",
+ adapterType: "process",
+ adapterConfig: {},
+ }).returning().then((rows) => rows[0]!);
+ await access.setPrincipalGrants(
+ company.id,
+ "user",
+ operator.principalId,
+ grantsForHumanRole("operator"),
+ owner.principalId,
+ );
+
+ for (const permissionKey of [
+ "agents:create", "agents:configure", "skills:create", "environments:manage",
+ "users:invite", "tasks:assign", "pipelines:write", "tools:manage_connections",
+ "tools:manage_profiles", "tools:manage_runtime", "tools:use", "tools:admin",
+ "tools:view_audit", "audit:view_agent_actions",
+ ] as const) {
+ await expect(access.canUser(company.id, operator.principalId, permissionKey)).resolves.toBe(true);
+ }
+ for (const permissionKey of ["joins:approve", "users:manage_permissions"] as const) {
+ await expect(access.canUser(company.id, operator.principalId, permissionKey)).resolves.toBe(false);
+ }
+ await expect(access.decide({
+ actor: { type: "board", userId: operator.principalId, source: "session" },
+ action: "agent_config:update",
+ resource: { type: "agent", companyId: company.id, agentId: agent.id },
+ })).resolves.toMatchObject({ allowed: true, reason: "allow_direct_change" });
+
+ const otherCompany = await createCompanyWithOwner(db);
+ await expect(access.canUser(otherCompany.company.id, operator.principalId, "agents:configure")).resolves.toBe(false);
+ });
+
it("backfills pre-upgrade human memberships with missing role grants without replacing custom grants", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const scopedEnvironmentGrant = { environmentId: "env-1" };
diff --git a/server/src/__tests__/adapter-routes.test.ts b/server/src/__tests__/adapter-routes.test.ts
index 73828da47c..3fc3c55bd2 100644
--- a/server/src/__tests__/adapter-routes.test.ts
+++ b/server/src/__tests__/adapter-routes.test.ts
@@ -55,9 +55,6 @@ function registerModuleMocks() {
vi.doMock("node:child_process", async () => vi.importActual("node:child_process"));
vi.doMock("../adapters/plugin-loader.js", () => mockPluginLoader);
vi.doMock("../services/adapter-plugin-store.js", () => mockAdapterPluginStore);
- vi.doMock("../routes/adapters.js", async () => vi.importActual("../routes/adapters.js"));
- vi.doMock("../routes/authz.js", async () => vi.importActual("../routes/authz.js"));
- vi.doMock("../middleware/index.js", async () => vi.importActual("../middleware/index.js"));
}
function resetAdapterMocks() {
@@ -104,11 +101,9 @@ describe("adapter routes", () => {
beforeAll(async () => {
registerModuleMocks();
resetAdapterMocks();
- const [registry, routes, middleware] = await Promise.all([
- vi.importActual<typeof import("../adapters/registry.js")>("../adapters/registry.js"),
- import("../routes/adapters.js"),
- import("../middleware/index.js"),
- ]);
+ const registry = await import("../adapters/registry.js");
+ const routes = await import("../routes/adapters.js");
+ const middleware = await import("../middleware/index.js");
registerServerAdapter = registry.registerServerAdapter;
unregisterServerAdapter = registry.unregisterServerAdapter;
findServerAdapter = registry.findServerAdapter;
diff --git a/server/src/__tests__/invite-create-route.test.ts b/server/src/__tests__/invite-create-route.test.ts
index 4ceedd3856..27372692df 100644
--- a/server/src/__tests__/invite-create-route.test.ts
+++ b/server/src/__tests__/invite-create-route.test.ts
@@ -3,12 +3,14 @@ import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const logActivityMock = vi.fn();
+const canUserMock = vi.fn();
+const insertMock = vi.fn();
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => ({
isInstanceAdmin: vi.fn(),
- canUser: vi.fn(),
+ canUser: (...args: unknown[]) => canUserMock(...args),
hasPermission: vi.fn(),
}),
agentService: () => ({
@@ -44,6 +46,7 @@ function createDbStub() {
return {
insert() {
+ insertMock();
return {
values() {
return {
@@ -75,7 +78,7 @@ function createDbStub() {
};
}
-async function createApp() {
+async function createApp(source: "local_implicit" | "session" = "local_implicit") {
const [{ accessRoutes }, { errorHandler }] = await Promise.all([
import("../routes/access.js"),
import("../middleware/index.js"),
@@ -85,9 +88,10 @@ async function createApp() {
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
- source: "local_implicit",
- userId: null,
+ source,
+ userId: source === "session" ? "inviter-1" : null,
companyIds: ["company-1"],
+ memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }],
};
next();
});
@@ -114,6 +118,9 @@ describe("POST /companies/:companyId/invites", () => {
registerModuleMocks();
vi.clearAllMocks();
logActivityMock.mockReset();
+ canUserMock.mockReset();
+ insertMock.mockReset();
+ canUserMock.mockImplementation(async (_companyId, _userId, permissionKey) => permissionKey === "users:invite");
});
it("returns an absolute invite URL using the request base URL", async () => {
@@ -133,4 +140,67 @@ describe("POST /companies/:companyId/invites", () => {
expect(res.body.invitePath).toMatch(/^\/invite\/pcp_invite_/);
expect(res.body.inviteUrl).toMatch(/^https:\/\/paperclip\.example\/invite\/pcp_invite_/);
});
+
+ it.each(["operator", "viewer"])("allows Operators to invite %s members", async (humanRole) => {
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "human", humanRole });
+
+ expect(res.status).toBe(201);
+ expect(insertMock).toHaveBeenCalledOnce();
+ });
+
+ it("allows the default Operator role for mixed human and agent invitations", async () => {
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "both" });
+
+ expect(res.status).toBe(201);
+ expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
+ expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
+ });
+
+ it("does not require human membership permissions for agent-only invitations", async () => {
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "agent", humanRole: "owner" });
+
+ expect(res.status).toBe(201);
+ expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
+ expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
+ });
+
+ it.each(["admin", "owner"])("prevents Operators from inviting %s members", async (humanRole) => {
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "human", humanRole });
+
+ expect(res.status).toBe(403);
+ expect(insertMock).not.toHaveBeenCalled();
+ expect(logActivityMock).not.toHaveBeenCalled();
+ });
+
+ it("requires member-permission management to invite Owners even when join approval is allowed", async () => {
+ canUserMock.mockImplementation(async (_companyId, _userId, permissionKey) =>
+ permissionKey === "users:invite" || permissionKey === "joins:approve",
+ );
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "human", humanRole: "owner" });
+
+ expect(res.status).toBe(403);
+ expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
+ expect(insertMock).not.toHaveBeenCalled();
+ });
+
+ it("allows Owner invitations when both membership permissions are granted", async () => {
+ canUserMock.mockResolvedValue(true);
+ const res = await request(await createApp("session"))
+ .post("/api/companies/company-1/invites")
+ .send({ allowedJoinTypes: "human", humanRole: "owner" });
+
+ expect(res.status).toBe(201);
+ expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
+ expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
+ });
});
diff --git a/server/src/__tests__/invite-join-grants.test.ts b/server/src/__tests__/invite-join-grants.test.ts
index 9c10d2d636..63c614e66d 100644
--- a/server/src/__tests__/invite-join-grants.test.ts
+++ b/server/src/__tests__/invite-join-grants.test.ts
@@ -98,6 +98,25 @@ describe("human invite roles", () => {
]);
});
+ it("maps operator to company editing grants without join approval or member permissions", () => {
+ expect(grantsForHumanRole("operator")).toEqual([
+ { permissionKey: "agents:create", scope: null },
+ { permissionKey: "agents:configure", scope: null },
+ { permissionKey: "skills:create", scope: null },
+ { permissionKey: "environments:manage", scope: null },
+ { permissionKey: "users:invite", scope: null },
+ { permissionKey: "tasks:assign", scope: null },
+ { permissionKey: "pipelines:write", scope: null },
+ { permissionKey: "tools:manage_connections", scope: null },
+ { permissionKey: "tools:manage_profiles", scope: null },
+ { permissionKey: "tools:manage_runtime", scope: null },
+ { permissionKey: "tools:use", scope: null },
+ { permissionKey: "tools:admin", scope: null },
+ { permissionKey: "tools:view_audit", scope: null },
+ { permissionKey: "audit:view_agent_actions", scope: null },
+ ]);
+ });
+
it("defaults legacy or missing roles to operator", () => {
expect(normalizeHumanRole("member")).toBe("operator");
expect(resolveHumanInviteRole(null)).toBe("operator");
@@ -114,9 +133,7 @@ describe("human invite roles", () => {
});
it("falls back to role grants when human invite defaults omit explicit grants", () => {
- expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual([
- { permissionKey: "tasks:assign", scope: null },
- ]);
+ expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual(grantsForHumanRole("operator"));
});
it("preserves explicit human invite grants", () => {
diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts
index 3aaa1df32e..460cd3c3dd 100644
--- a/server/src/routes/access.ts
+++ b/server/src/routes/access.ts
@@ -3073,6 +3073,15 @@ export function accessRoutes(
input.allowedJoinTypes === "agent"
? null
: input.humanRole ?? "operator";
+ if (effectiveHumanRole) {
+ // An invitation must not delegate the membership powers its creator lacks.
+ const roleGrants = grantsForHumanRole(effectiveHumanRole);
+ for (const permissionKey of ["joins:approve", "users:manage_permissions"] as const) {
+ if (roleGrants.some((grant) => grant.permissionKey === permissionKey)) {
+ await assertCompanyPermission(input.req, input.companyId, permissionKey);
+ }
+ }
+ }
const insertValues = {
companyId: input.companyId,
inviteType: "company_join" as const,
diff --git a/server/src/services/company-member-roles.ts b/server/src/services/company-member-roles.ts
index 2a9d781734..d67ddbc90e 100644
--- a/server/src/services/company-member-roles.ts
+++ b/server/src/services/company-member-roles.ts
@@ -55,7 +55,22 @@ export function grantsForHumanRole(
{ permissionKey: "tools:admin", scope: null },
];
case "operator":
- return [{ permissionKey: "tasks:assign", scope: null }];
+ return [
+ { permissionKey: "agents:create", scope: null },
+ { permissionKey: "agents:configure", scope: null },
+ { permissionKey: "skills:create", scope: null },
+ { permissionKey: "environments:manage", scope: null },
+ { permissionKey: "users:invite", scope: null },
+ { permissionKey: "tasks:assign", scope: null },
+ { permissionKey: "pipelines:write", scope: null },
+ { permissionKey: "tools:manage_connections", scope: null },
+ { permissionKey: "tools:manage_profiles", scope: null },
+ { permissionKey: "tools:manage_runtime", scope: null },
+ { permissionKey: "tools:use", scope: null },
+ { permissionKey: "tools:admin", scope: null },
+ { permissionKey: "tools:view_audit", scope: null },
+ { permissionKey: "audit:view_agent_actions", scope: null },
+ ];
case "viewer":
return [];
}
diff --git a/ui/src/components/SidebarAccountMenu.production.tsx b/ui/src/components/SidebarAccountMenu.production.tsx
index e0549e56fe..c085b62117 100644
--- a/ui/src/components/SidebarAccountMenu.production.tsx
+++ b/ui/src/components/SidebarAccountMenu.production.tsx
@@ -131,8 +131,8 @@ export function SidebarAccountMenu({
// fallback there because it drives a different invitation flow.
const cloudInviteUrl = useCloudInviteUrl();
// Self-hosted invites need the `users:invite` grant. Offer the shortcut only
- // to boards that hold it (company owner/admin, instance admins, local
- // boards) so a plain member is never sent to a permission error.
+ // to boards with role-default access (company owner/admin/operator,
+ // instance admins, local boards). The server checks the actual grants.
const canInviteMembers = useCanInviteCompanyMembers(!isCloud);
const inviteHref = isCloud ? cloudInviteUrl : canInviteMembers ? INVITES_PATH : null;
const showInvite =
diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsx
index 008102b1f5..897065b603 100644
--- a/ui/src/components/SidebarAccountMenu.test.tsx
+++ b/ui/src/components/SidebarAccountMenu.test.tsx
@@ -144,7 +144,7 @@ describe("SidebarAccountMenu", () => {
});
mockAuthApi.signOut.mockResolvedValue({ success: true, redirectTo: "/cloud/logout" });
// Default to a company owner: the self-hosted Invite shortcut needs the
- // `users:invite` grant, which owners and admins hold.
+ // `users:invite` grant, which owners, admins, and operators hold by default.
mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("owner"));
});
@@ -665,9 +665,8 @@ describe("SidebarAccountMenu", () => {
status: "ok",
deploymentMode: "authenticated",
});
- // Operators and viewers lack `users:invite`; the Invites tab would only
- // show them a permission error, so the menu must not offer it.
- mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("operator"));
+ // Viewers lack `users:invite`; the menu must not offer the shortcut.
+ mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("viewer"));
await act(async () => {
root.render(
@@ -697,6 +696,7 @@ describe("SidebarAccountMenu", () => {
["instance admin", boardAccess("viewer", { isInstanceAdmin: true })],
["local board", boardAccess("viewer", { source: "local_implicit" })],
["company admin", boardAccess("admin")],
+ ["company operator", boardAccess("operator")],
])("offers the self-hosted invite shortcut to a %s", async (_label, access) => {
const root = createRoot(container);
const queryClient = new QueryClient({
diff --git a/ui/src/components/SidebarAccountMenu.tsx b/ui/src/components/SidebarAccountMenu.tsx
index f40959aa70..b87beea361 100644
--- a/ui/src/components/SidebarAccountMenu.tsx
+++ b/ui/src/components/SidebarAccountMenu.tsx
@@ -130,8 +130,8 @@ export function SidebarAccountMenu({
// fallback there because it drives a different invitation flow.
const cloudInviteUrl = useCloudInviteUrl();
// Self-hosted invites need the `users:invite` grant. Offer the shortcut only
- // to boards that hold it (company owner/admin, instance admins, local
- // boards) so a plain member is never sent to a permission error.
+ // to boards with role-default access (company owner/admin/operator,
+ // instance admins, local boards). The server checks the actual grants.
const canInviteMembers = useCanInviteCompanyMembers(!isCloud);
const inviteHref = isCloud ? cloudInviteUrl : canInviteMembers ? INVITES_PATH : null;
const showInvite =
diff --git a/ui/src/components/access/InvitesSection.tsx b/ui/src/components/access/InvitesSection.tsx
index db6f22c76e..6416952ec7 100644
--- a/ui/src/components/access/InvitesSection.tsx
+++ b/ui/src/components/access/InvitesSection.tsx
@@ -21,8 +21,8 @@ const inviteRoleOptions = [
{
value: "operator",
label: "Operator",
- description: "Recommended for people who need to help run work without managing access.",
- gets: "Can assign tasks.",
+ description: "Can edit organization work and invite people.",
+ gets: "Full editing and audit access. Cannot approve join requests or manage member permissions.",
},
{
value: "admin",
diff --git a/ui/src/hooks/useCompanyInviteAccess.test.ts b/ui/src/hooks/useCompanyInviteAccess.test.ts
index 1939426a12..2a81b568e6 100644
--- a/ui/src/hooks/useCompanyInviteAccess.test.ts
+++ b/ui/src/hooks/useCompanyInviteAccess.test.ts
@@ -27,14 +27,14 @@ describe("canInviteCompanyMembers", () => {
expect(canInviteCompanyMembers(null, snapshot({ isInstanceAdmin: true }))).toBe(true);
});
- it.each(["owner", "admin"] as const)("passes an active company %s", (membershipRole) => {
+ it.each(["owner", "admin", "operator", "member"] as const)("passes an active company %s", (membershipRole) => {
const access = snapshot({
memberships: [{ companyId: "company-1", membershipRole, status: "active" }],
});
expect(canInviteCompanyMembers("company-1", access)).toBe(true);
});
- it.each(["operator", "viewer", "member", null] as const)("rejects a company %s", (membershipRole) => {
+ it.each(["viewer", null] as const)("rejects a company %s", (membershipRole) => {
const access = snapshot({
memberships: [{ companyId: "company-1", membershipRole, status: "active" }],
});
diff --git a/ui/src/hooks/useCompanyInviteAccess.ts b/ui/src/hooks/useCompanyInviteAccess.ts
index 7eec8933fc..53b1f1cb50 100644
--- a/ui/src/hooks/useCompanyInviteAccess.ts
+++ b/ui/src/hooks/useCompanyInviteAccess.ts
@@ -9,8 +9,9 @@ import { useOptionalCompany } from "@/context/CompanyContext";
*
* Mirrors the other client-side role gates (`ToolsAdminGate`, the run
* ledger): local implicit boards and instance admins always pass; otherwise
- * the active company membership must be owner or admin, the roles that carry
- * the `users:invite` grant. Resolves to false while the snapshot is unknown.
+ * the active company membership must be owner, admin, or operator, the roles
+ * that carry the default `users:invite` grant. Legacy members normalize to
+ * operator. Resolves to false while the snapshot is unknown.
* The server stays authoritative; this only decides whether to offer a
* shortcut that would otherwise end in a permission error.
*/
@@ -24,7 +25,10 @@ export function canInviteCompanyMembers(
const membership = boardAccess.memberships?.find(
(item) => item.companyId === companyId && item.status === "active",
);
- return membership?.membershipRole === "owner" || membership?.membershipRole === "admin";
+ return membership?.membershipRole === "owner" ||
+ membership?.membershipRole === "admin" ||
+ membership?.membershipRole === "operator" ||
+ membership?.membershipRole === "member";
}
/**
diff --git a/ui/src/pages/InviteUxLab.tsx b/ui/src/pages/InviteUxLab.tsx
index 9856eafb23..2737a1d05b 100644
--- a/ui/src/pages/InviteUxLab.tsx
+++ b/ui/src/pages/InviteUxLab.tsx
@@ -33,8 +33,8 @@ const inviteRoleOptions = [
{
value: "operator",
label: "Operator",
- description: "Recommended for people who need to help run work without managing access.",
- gets: "Can assign tasks.",
+ description: "Can edit organization work and invite people.",
+ gets: "Full editing and audit access. Cannot approve join requests or manage member permissions.",
},
{
value: "admin",
diff --git a/ui/src/pages/tools/AdvancedToolsRoute.tsx b/ui/src/pages/tools/AdvancedToolsRoute.tsx
index 5659a0d1ba..31acdcb8b3 100644
--- a/ui/src/pages/tools/AdvancedToolsRoute.tsx
+++ b/ui/src/pages/tools/AdvancedToolsRoute.tsx
@@ -8,10 +8,10 @@ import { ToolsAccess } from "./ToolsAccess";
/**
* Admin gate for the Advanced door (PAP-10862, plan D8). The developer surface
- * lives under `/apps/advanced` and is reserved for administrators (`tools:admin`
- * on the server). This is a best-effort UX gate — the server is authoritative —
- * derived from the caller's board access: instance admins and company
- * owners/admins pass. Non-admins get a friendly explanation rather than a 403.
+ * lives under `/apps/advanced` and requires `tools:admin` on the server.
+ * This is a best-effort UX gate derived from role defaults: local boards,
+ * instance admins, and active company owners/admins/operators pass.
+ * The server is authoritative.
*/
export function AdvancedToolsRoute() {
const { selectedCompanyId } = useCompany();
@@ -26,22 +26,25 @@ export function AdvancedToolsRoute() {
}
const data = boardAccess.data;
- const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId);
- const isAdmin =
+ const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId && m.status === "active");
+ const canManageTools =
+ data?.source === "local_implicit" ||
Boolean(data?.isInstanceAdmin) ||
membership?.membershipRole === "owner" ||
- membership?.membershipRole === "admin";
+ membership?.membershipRole === "admin" ||
+ membership?.membershipRole === "operator" ||
+ membership?.membershipRole === "member";
- if (!isAdmin) {
+ if (!canManageTools) {
return (
<div className="mx-auto max-w-xl py-10">
<div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-6">
<div className="flex items-center gap-2 text-foreground">
<ShieldAlert className="h-5 w-5 text-muted-foreground" />
- <h1 className="text-lg font-semibold">Advanced setup is for administrators</h1>
+ <h1 className="text-lg font-semibold">Advanced setup requires editing access</h1>
</div>
<p className="text-sm text-muted-foreground">
- This area lets administrators wire up tools that aren't in the gallery. Ask an administrator if you
+ This area lets company editors wire up tools that aren't in the gallery. Ask a company editor if you
need a new app connected, or head back to{" "}
<Link to="/apps" className="font-medium text-primary hover:underline">
your apps
diff --git a/ui/src/pages/tools/ToolRoleAccess.test.tsx b/ui/src/pages/tools/ToolRoleAccess.test.tsx
new file mode 100644
index 0000000000..a0e362c7da
--- /dev/null
+++ b/ui/src/pages/tools/ToolRoleAccess.test.tsx
@@ -0,0 +1,84 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CurrentBoardAccess } from "@/api/access";
+import { AdvancedToolsRoute } from "./AdvancedToolsRoute";
+import { ToolsAdminGate } from "./profiles/ToolsAdminGate";
+
+const accessState = vi.hoisted(() => ({ data: undefined as CurrentBoardAccess | undefined }));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: () => ({ data: accessState.data, isLoading: false }),
+}));
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({ selectedCompanyId: "company-1" }),
+}));
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to }: { children: React.ReactNode; to: string }) => <a href={to}>{children}</a>,
+}));
+vi.mock("./ToolsAccess", () => ({
+ ToolsAccess: () => <div>Advanced tool setup</div>,
+}));
+
+function snapshot(role: "owner" | "admin" | "operator" | "member" | "viewer"): CurrentBoardAccess {
+ return {
+ user: { id: "user-1", email: "[email protected]", name: "Editor", image: null },
+ userId: "user-1",
+ isInstanceAdmin: false,
+ companyIds: ["company-1"],
+ memberships: [{ companyId: "company-1", membershipRole: role, status: "active" }],
+ source: "session",
+ keyId: null,
+ };
+}
+
+describe.each([
+ ["advanced tool setup", <AdvancedToolsRoute />, "Advanced tool setup"],
+ ["access profiles", <ToolsAdminGate>Profile editor</ToolsAdminGate>, "Profile editor"],
+] as const)("%s role access", (_label, content, editorText) => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ accessState.data = undefined;
+ });
+
+ afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ });
+
+ function render(access: CurrentBoardAccess | undefined) {
+ accessState.data = access;
+ flushSync(() => root.render(content));
+ }
+
+ it.each(["owner", "admin", "operator", "member"] as const)("allows active %s defaults", (role) => {
+ render(snapshot(role));
+ expect(container.textContent).toContain(editorText);
+ });
+
+ it("allows local boards and instance admins without company membership", () => {
+ render({ ...snapshot("viewer"), memberships: [], source: "local_implicit" });
+ expect(container.textContent).toContain(editorText);
+ render({ ...snapshot("viewer"), memberships: [], isInstanceAdmin: true });
+ expect(container.textContent).toContain(editorText);
+ });
+
+ it("rejects viewers, inactive memberships, and members of another company", () => {
+ render(snapshot("viewer"));
+ expect(container.textContent).not.toContain(editorText);
+ const operator = snapshot("operator");
+ render({ ...operator, memberships: [{ ...operator.memberships![0]!, status: "suspended" }] });
+ expect(container.textContent).not.toContain(editorText);
+ render({ ...operator, memberships: [{ ...operator.memberships![0]!, companyId: "company-2" }] });
+ expect(container.textContent).not.toContain(editorText);
+ render(undefined);
+ expect(container.textContent).not.toContain(editorText);
+ });
+});
diff --git a/ui/src/pages/tools/profiles/ToolsAdminGate.tsx b/ui/src/pages/tools/profiles/ToolsAdminGate.tsx
index 5f43cc2bbd..4febb728b0 100644
--- a/ui/src/pages/tools/profiles/ToolsAdminGate.tsx
+++ b/ui/src/pages/tools/profiles/ToolsAdminGate.tsx
@@ -8,9 +8,9 @@ import { useCompany } from "@/context/CompanyContext";
/**
* Best-effort admin gate for the access-profiles surface, mirroring
- * `AdvancedToolsRoute` (PAP-10862, plan D8). Instance admins and company
- * owners/admins pass; the server stays authoritative. Shared so the profiles
- * index and the create wizard guard identically.
+ * `AdvancedToolsRoute` (PAP-10862, plan D8). Local boards, instance admins,
+ * and active company owners/admins/operators pass; the server stays
+ * authoritative. Shared so the profiles index and create wizard guard identically.
*/
export function ToolsAdminGate({ children }: { children: ReactNode }) {
const { selectedCompanyId } = useCompany();
@@ -25,22 +25,25 @@ export function ToolsAdminGate({ children }: { children: ReactNode }) {
}
const data = boardAccess.data;
- const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId);
- const isAdmin =
+ const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId && m.status === "active");
+ const canManageTools =
+ data?.source === "local_implicit" ||
Boolean(data?.isInstanceAdmin) ||
membership?.membershipRole === "owner" ||
- membership?.membershipRole === "admin";
+ membership?.membershipRole === "admin" ||
+ membership?.membershipRole === "operator" ||
+ membership?.membershipRole === "member";
- if (!isAdmin) {
+ if (!canManageTools) {
return (
<div className="mx-auto max-w-xl py-10">
<div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-6">
<div className="flex items-center gap-2 text-foreground">
<ShieldAlert className="h-5 w-5 text-muted-foreground" />
- <h1 className="text-lg font-semibold">Access profiles are for administrators</h1>
+ <h1 className="text-lg font-semibold">Access profiles require editing access</h1>
</div>
<p className="text-sm text-muted-foreground">
- Access profiles decide which tools your agents can use. Ask an administrator to set these up, or
+ Access profiles decide which tools your agents can use. Ask a company editor to set these up, or
head back to{" "}
<Link to="/apps" className="font-medium text-primary hover:underline">
your apps