Files
PaperClipAI/ui/src/components/access/InvitesSection.tsx
T
DottaandPaperclip 582911ba74 fix(access): give Operators default company editing permissions (#15377)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Human company members receive permission grants from their role
preset.
> - Human invitations use the Operator role by default.
> - The old Operator preset only granted task assignment, so ordinary
members could not edit agents or manage connections.
> - This pull request gives Operators company editing and audit access
while keeping join approval and member-permission management separate.
> - Members can configure their agents and accounts without an Owner
role.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The default permission grants for human Operators and the invitation
role description.

**Subsystem affected**

server/ permission presets and invitation authorization, plus ui/
invitation and tool access gates.

**Current behavior**

Operators receive only `tasks:assign` as an explicit default grant.
Agent configuration and managed account setup fail their permission
checks.

**Proposed behavior**

Operators receive agent creation/configuration, skills, environments,
invitations, task assignment, pipelines, connections, tool
management/use, and audit grants. The preset excludes `joins:approve`
and `users:manage_permissions`. Operators can invite Operators and
Viewers. Inviting a role with either excluded power requires that power,
so invitations cannot bypass the restriction.

**Reason and benefit**

Ordinary company members can edit company work and connect accounts
through the existing routes.

**Breaking changes**

The Operator preset grants more permissions. The existing startup and
Cloud sign-in seeding paths can insert these missing grants for existing
Operators. They retain custom grant scopes. Explicit invitation grants
still take precedence. Inviting Admins now requires join approval;
inviting Owners also requires member-permission management. This PR adds
no migration or new backfill path.

Related: #5945 describes missing role grants in another membership entry
point. This PR changes the preset and does not change that endpoint.

## What Changed

- Expanded the Operator preset to 14 company editing, invitation, tool,
and audit grants.
- Kept join approval and member-permission management out of the preset.
- Required those powers when an invitation's selected human role
includes them, preventing Operators from delegating the excluded powers
through Owner/Admin invitations.
- Updated the invitation role copy and the product specifications.
- Allowed active Operators (including legacy Member roles) through the
invite shortcut and advanced tool/profile UI gates. Kept inactive
memberships, Viewers, and other companies excluded; API grants remain
authoritative.
- Added tests for the default Operator grants, both excluded actions,
agent editing, company boundaries, and invitation role authorization.
- Simplified adapter-route test imports so authorization errors and the
error handler use one module graph; retained the upstream
mock-initialization fix.
- Kept Owner/Admin/Viewer presets and explicit invitation grants
unchanged. Added no EE code or database migration.

## Verification

- Permission and invitation tests: 38 passed across access service,
invitation defaults, and invitation creation routes.
- UI access tests: 61 passed across invitation shortcuts, Operator
tool/profile access, and invitation UI.
- Adapter route tests: 15 passed after resolving the upstream test setup
conflict.
- `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates`:
passed on the final branch.
- The initial local `pnpm test:run` general-server batch reported three
tool-access failures and eight upload-helper timeouts. Both complete
affected suites passed in isolation on the final branch: 403 tests. The
initial full local run was not green.
- Both complete tool-access and adapter route suites also passed on an
untouched snapshot of base `88ff98b83`: 387 tests. The earlier tool
failures did not reproduce there.
- [All CI gates
passed](https://github.com/paperclipai/paperclip/actions/runs/37527422346)
for `068be153b9c2a064f2aaccc0627fdf458e73747e`, including the previously
failing serialized adapter lane, general tests, E2E, typecheck, build,
Runner checks, and canary dry run.
- Greptile scored that exact commit 5/5. Superagent passed. Both
invitation review threads are resolved.

## Risks

- Operators gain broad company editing and invitation access by design.
- Existing default seeding can add the new missing grants during startup
or Cloud sign-in. It does not replace existing scopes.
- Company boundaries and the two excluded permission checks still apply.
- An Admin without member-permission management can no longer invite an
Owner. Operators retain invitation access for Operator/Viewer roles and
agent-only invites.
- This PR changes company permissions. Cloud workspace invitation rules
remain separate.

## Model Used

OpenAI Codex, GPT-6. The exact deployment model ID and context window
were not exposed in this session. Used repository inspection, code
editing, shell execution, and test tools.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting a merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-06 15:55:38 -05:00

384 lines
16 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Check, Copy } from "lucide-react";
import { accessApi } from "@/api/access";
import { ApiError } from "@/api/client";
import { Button } from "@/components/ui/button";
import { useCompany } from "@/context/CompanyContext";
import { useToast } from "@/context/ToastContext";
import { Link } from "@/lib/router";
import { queryKeys } from "@/lib/queryKeys";
import { copyTextToClipboard } from "@/lib/clipboard";
import { Badge } from "@/components/ui/badge";
const inviteRoleOptions = [
{
value: "viewer",
label: "Viewer",
description: "Can view organization work and follow along.",
gets: "View-only organization membership.",
},
{
value: "operator",
label: "Operator",
description: "Can edit organization work and invite people.",
gets: "Full editing and audit access. Cannot approve join requests or manage member permissions.",
},
{
value: "admin",
label: "Admin",
description: "Recommended for operators who need to invite people, create agents, and approve joins.",
gets: "Can create agents, invite users, assign tasks, and approve join requests.",
},
{
value: "owner",
label: "Owner",
description: "Full organization access, including membership management.",
gets: "Everything in Admin, plus managing members.",
},
] as const;
const INVITE_HISTORY_PAGE_SIZE = 5;
function isInviteHistoryRow(value: unknown): value is Awaited<ReturnType<typeof accessApi.listInvites>>["invites"][number] {
if (!value || typeof value !== "object") return false;
return "id" in value && "state" in value && "createdAt" in value;
}
/** The Invites tab of the Members page (extracted from the former standalone Invites page). */
export function InvitesSection() {
const { selectedCompanyId } = useCompany();
const { pushToast } = useToast();
const queryClient = useQueryClient();
const [humanRole, setHumanRole] = useState<"owner" | "admin" | "operator" | "viewer">("operator");
const [latestInviteUrl, setLatestInviteUrl] = useState<string | null>(null);
const [latestInviteCopied, setLatestInviteCopied] = useState(false);
const latestInviteInputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
if (!latestInviteCopied) return;
const timeout = window.setTimeout(() => {
setLatestInviteCopied(false);
}, 1600);
return () => window.clearTimeout(timeout);
}, [latestInviteCopied]);
function selectLatestInviteUrl() {
latestInviteInputRef.current?.focus();
latestInviteInputRef.current?.select();
}
async function copyText(text: string, unavailableBody: string, afterFallback?: () => void) {
try {
await copyTextToClipboard(text);
return true;
} catch {
afterFallback?.();
}
pushToast({
title: "Clipboard unavailable",
body: unavailableBody,
tone: "warn",
});
return false;
}
async function copyInviteUrl(url: string) {
return copyText(url, "The invite URL is selected. Copy it manually from the field.", selectLatestInviteUrl);
}
const inviteHistoryQueryKey = queryKeys.access.invites(selectedCompanyId ?? "", "all", INVITE_HISTORY_PAGE_SIZE);
const invitesQuery = useInfiniteQuery({
queryKey: inviteHistoryQueryKey,
queryFn: ({ pageParam }) =>
accessApi.listInvites(selectedCompanyId!, {
limit: INVITE_HISTORY_PAGE_SIZE,
offset: pageParam,
}),
enabled: !!selectedCompanyId,
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextOffset ?? undefined,
});
const inviteHistory = useMemo(
() =>
invitesQuery.data?.pages.flatMap((page) =>
Array.isArray(page?.invites) ? page.invites.filter(isInviteHistoryRow) : [],
) ?? [],
[invitesQuery.data?.pages],
);
const createInviteMutation = useMutation({
mutationFn: () =>
accessApi.createCompanyInvite(selectedCompanyId!, {
allowedJoinTypes: "human",
humanRole,
agentMessage: null,
}),
onSuccess: async (invite) => {
setLatestInviteUrl(invite.inviteUrl);
setLatestInviteCopied(false);
const copied = await copyText(invite.inviteUrl, "Copy the invite URL manually from the field below.");
await queryClient.invalidateQueries({ queryKey: inviteHistoryQueryKey });
pushToast({
title: "Invite created",
body: copied ? "Invite ready below and copied to clipboard." : "Invite ready below.",
tone: "success",
});
},
onError: (error) => {
pushToast({
title: "Failed to create invite",
body: error instanceof Error ? error.message : "Unknown error",
tone: "error",
});
},
});
const revokeMutation = useMutation({
mutationFn: (inviteId: string) => accessApi.revokeInvite(inviteId),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: inviteHistoryQueryKey });
pushToast({ title: "Invite revoked", tone: "success" });
},
onError: (error) => {
pushToast({
title: "Failed to revoke invite",
body: error instanceof Error ? error.message : "Unknown error",
tone: "error",
});
},
});
if (!selectedCompanyId) {
return <div className="text-sm text-muted-foreground">Select an organization to manage invites.</div>;
}
if (invitesQuery.isLoading) {
return <div className="text-sm text-muted-foreground">Loading invites…</div>;
}
if (invitesQuery.error) {
const message =
invitesQuery.error instanceof ApiError && invitesQuery.error.status === 403
? "You do not have permission to manage organization invites."
: invitesQuery.error instanceof Error
? invitesQuery.error.message
: "Failed to load invites.";
return <div className="text-sm text-destructive">{message}</div>;
}
return (
<div className="max-w-6xl space-y-8">
<p className="max-w-3xl text-sm text-muted-foreground">
Invite people to request access to this organization. New invite links are copied to your clipboard when they are
generated.
</p>
<section className="space-y-4 rounded-xl border border-border p-5">
<div className="space-y-1">
<h2 className="text-sm font-semibold">Invite a person</h2>
<p className="text-sm text-muted-foreground">
Generate a human invite link and choose the default access it should request.
</p>
</div>
<fieldset className="space-y-3">
<legend className="text-sm font-medium">Choose a role</legend>
<div className="rounded-xl border border-border">
{inviteRoleOptions.map((option, index) => {
const checked = humanRole === option.value;
return (
<label
key={option.value}
className={`flex cursor-pointer gap-3 px-4 py-4 ${index > 0 ? "border-t border-border" : ""}`}
>
<input
type="radio"
name="invite-role"
value={option.value}
checked={checked}
onChange={() => setHumanRole(option.value)}
className="mt-1 h-4 w-4 border-border text-foreground"
/>
<span className="min-w-0 space-y-1">
<span className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">{option.label}</span>
{option.value === "operator" ? (
<Badge variant="outline" className="border-border text-muted-foreground">
Default
</Badge>
) : null}
</span>
<span className="block max-w-2xl text-sm text-muted-foreground">{option.description}</span>
<span className="block text-sm text-foreground">{option.gets}</span>
</span>
</label>
);
})}
</div>
</fieldset>
<div className="rounded-lg border border-border px-4 py-3 text-sm text-muted-foreground">
Each invite link is single-use. Human invitees get the selected role immediately after sign-in; agent invites still create a join request for approval.
</div>
<div className="flex flex-wrap items-center gap-3">
<Button onClick={() => createInviteMutation.mutate()} disabled={createInviteMutation.isPending}>
{createInviteMutation.isPending ? "Creating…" : "Create invite"}
</Button>
<span className="text-sm text-muted-foreground">Invite history below keeps the audit trail.</span>
</div>
{latestInviteUrl ? (
<div className="space-y-3 rounded-lg border border-border px-4 py-4">
<div className="space-y-1">
<div className="flex items-center justify-between gap-3">
<div className="text-sm font-medium">Latest invite link</div>
{latestInviteCopied ? (
<div className="inline-flex items-center gap-1 text-xs font-medium text-foreground">
<Check className="h-3.5 w-3.5" />
Copied
</div>
) : null}
</div>
<div className="text-sm text-muted-foreground">
This URL includes the current Paperclip domain returned by the server.
</div>
</div>
<label className="block space-y-1">
<span className="sr-only">Latest invite URL</span>
<input
ref={latestInviteInputRef}
readOnly
value={latestInviteUrl}
onFocus={(event) => event.currentTarget.select()}
onClick={(event) => event.currentTarget.select()}
className="w-full rounded-md border border-border bg-muted/60 px-3 py-2 text-sm text-foreground outline-none transition-colors selection:bg-primary selection:text-primary-foreground focus:border-ring"
aria-label="Latest invite URL"
/>
</label>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
variant="outline"
onClick={async () => {
const copied = await copyInviteUrl(latestInviteUrl);
setLatestInviteCopied(copied);
}}
>
<Copy className="h-4 w-4" />
Copy link
</Button>
</div>
</div>
) : null}
</section>
<section className="rounded-xl border border-border">
<div className="flex flex-wrap items-center justify-between gap-4 px-5 py-4">
<div className="space-y-1">
<h2 className="text-sm font-semibold">Invite history</h2>
<p className="text-sm text-muted-foreground">
Review invite status, audience, inviter, and any linked join request.
</p>
</div>
<Link to="/inbox/requests" className="text-sm underline underline-offset-4">
Open join request queue
</Link>
</div>
{inviteHistory.length === 0 ? (
<div className="border-t border-border px-5 py-8 text-sm text-muted-foreground">
No invites have been created for this organization yet.
</div>
) : (
<div className="border-t border-border">
<div className="overflow-x-auto">
<table className="min-w-full text-left text-sm">
<thead>
<tr className="border-b border-border">
<th className="px-5 py-3 font-medium text-muted-foreground">State</th>
<th className="px-5 py-3 font-medium text-muted-foreground">For</th>
<th className="px-5 py-3 font-medium text-muted-foreground">Invited by</th>
<th className="px-5 py-3 font-medium text-muted-foreground">Created</th>
<th className="px-5 py-3 font-medium text-muted-foreground">Join request</th>
<th className="px-5 py-3 text-right font-medium text-muted-foreground">Action</th>
</tr>
</thead>
<tbody>
{inviteHistory.map((invite) => (
<tr key={invite.id} className="border-b border-border last:border-b-0">
<td className="px-5 py-3 align-top">
<Badge variant="outline" className="border-border text-muted-foreground">
{formatInviteState(invite.state)}
</Badge>
</td>
<td className="px-5 py-3 align-top">{formatInviteAudience(invite)}</td>
<td className="px-5 py-3 align-top">
<div>{invite.invitedByUser?.name || invite.invitedByUser?.email || "Unknown inviter"}</div>
{invite.invitedByUser?.email && invite.invitedByUser.name ? (
<div className="text-xs text-muted-foreground">{invite.invitedByUser.email}</div>
) : null}
</td>
<td className="px-5 py-3 align-top text-muted-foreground">
{new Date(invite.createdAt).toLocaleString()}
</td>
<td className="px-5 py-3 align-top">
{invite.relatedJoinRequestId ? (
<Link to="/inbox/requests" className="underline underline-offset-4">
Review request
</Link>
) : (
<span className="text-muted-foreground">—</span>
)}
</td>
<td className="px-5 py-3 text-right align-top">
{invite.state === "active" ? (
<Button
size="sm"
variant="outline"
onClick={() => revokeMutation.mutate(invite.id)}
disabled={revokeMutation.isPending}
>
Revoke
</Button>
) : (
<span className="text-xs text-muted-foreground">Inactive</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{invitesQuery.hasNextPage ? (
<div className="flex justify-center border-t border-border px-5 py-4">
<Button
type="button"
variant="outline"
onClick={() => invitesQuery.fetchNextPage()}
disabled={invitesQuery.isFetchingNextPage}
>
{invitesQuery.isFetchingNextPage ? "Loading more…" : "View more"}
</Button>
</div>
) : null}
</div>
)}
</section>
</div>
);
}
function formatInviteState(state: "active" | "accepted" | "expired" | "revoked") {
return state.charAt(0).toUpperCase() + state.slice(1);
}
function formatInviteAudience(invite: Awaited<ReturnType<typeof accessApi.listInvites>>["invites"][number]) {
if (invite.allowedJoinTypes === "agent") return "Agent";
if (invite.allowedJoinTypes === "both") return invite.humanRole ? `Human or agent · ${invite.humanRole}` : "Human or agent";
return invite.humanRole ?? "Human";
}