Files
PaperClipAI/ui/src/pages/CompanyInvites.tsx
T
b9a80dcf22 feat: implement multi-user access and invite flows (#3784)
## Thinking Path

> - Paperclip is the control plane for autonomous AI companies.
> - V1 needs to stay local-first while also supporting shared,
authenticated deployments.
> - Human operators need real identities, company membership, invite
flows, profile surfaces, and company-scoped access controls.
> - Agents and operators also need the existing issue, inbox, workspace,
approval, and plugin flows to keep working under those authenticated
boundaries.
> - This branch accumulated the multi-user implementation, follow-up QA
fixes, workspace/runtime refinements, invite UX improvements,
release-branch conflict resolution, and review hardening.
> - This pull request consolidates that branch onto the current `master`
branch as a single reviewable PR.
> - The benefit is a complete multi-user implementation path with tests
and docs carried forward without dropping existing branch work.

## What Changed

- Added authenticated human-user access surfaces: auth/session routes,
company user directory, profile settings, company access/member
management, join requests, and invite management.
- Added invite creation, invite landing, onboarding, logo/branding,
invite grants, deduped join requests, and authenticated multi-user E2E
coverage.
- Tightened company-scoped and instance-admin authorization across
board, plugin, adapter, access, issue, and workspace routes.
- Added profile-image URL validation hardening, avatar preservation on
name-only profile updates, and join-request uniqueness migration cleanup
for pending human requests.
- Added an atomic member role/status/grants update path so Company
Access saves no longer leave partially updated permissions.
- Improved issue chat, inbox, assignee identity rendering,
sidebar/account/company navigation, workspace routing, and execution
workspace reuse behavior for multi-user operation.
- Added and updated server/UI tests covering auth, invites, membership,
issue workspace inheritance, plugin authz, inbox/chat behavior, and
multi-user flows.
- Merged current `public-gh/master` into this branch, resolved all
conflicts, and verified no `pnpm-lock.yaml` change is included in this
PR diff.

## Verification

- `pnpm exec vitest run server/src/__tests__/issues-service.test.ts
ui/src/components/IssueChatThread.test.tsx ui/src/pages/Inbox.test.tsx`
- `pnpm run preflight:workspace-links && pnpm exec vitest run
server/src/__tests__/plugin-routes-authz.test.ts`
- `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/workspace-runtime-service-authz.test.ts
server/src/__tests__/access-validators.test.ts`
- `pnpm exec vitest run
server/src/__tests__/authz-company-access.test.ts
server/src/__tests__/routines-routes.test.ts
server/src/__tests__/sidebar-preferences-routes.test.ts
server/src/__tests__/approval-routes-idempotency.test.ts
server/src/__tests__/openclaw-invite-prompt-route.test.ts
server/src/__tests__/agent-cross-tenant-authz-routes.test.ts
server/src/__tests__/routines-e2e.test.ts`
- `pnpm exec vitest run server/src/__tests__/auth-routes.test.ts
ui/src/pages/CompanyAccess.test.tsx`
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server
typecheck`
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck`
- `pnpm --filter @paperclipai/ui typecheck`
- `pnpm db:generate`
- `npx playwright test --config tests/e2e/playwright.config.ts --list`
- Confirmed branch has no uncommitted changes and is `0` commits behind
`public-gh/master` before PR creation.
- Confirmed no `pnpm-lock.yaml` change is staged or present in the PR
diff.

## Risks

- High review surface area: this PR contains the accumulated multi-user
branch plus follow-up fixes, so reviewers should focus especially on
company-boundary enforcement and authenticated-vs-local deployment
behavior.
- UI behavior changed across invites, inbox, issue chat, access
settings, and sidebar navigation; no browser screenshots are included in
this branch-consolidation PR.
- Plugin install, upgrade, and lifecycle/config mutations now require
instance-admin access, which is intentional but may change expectations
for non-admin board users.
- A join-request dedupe migration rejects duplicate pending human
requests before creating unique indexes; deployments with unusual
historical duplicates should review the migration behavior.
- Company member role/status/grant saves now use a new combined
endpoint; older separate endpoints remain for compatibility.
- Full production build was not run locally in this heartbeat; CI should
cover the full matrix.

## Model Used

- OpenAI Codex coding agent, GPT-5-based model, CLI/tool-use
environment. Exact deployed model identifier and context window were not
exposed by the runtime.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

Note on screenshots: this is a branch-consolidation PR for an
already-developed multi-user branch, and no browser screenshots were
captured during this heartbeat.

---------

Co-authored-by: dotta <dotta@example.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 09:44:19 -05:00

375 lines
15 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Check, ExternalLink, MailPlus } from "lucide-react";
import { accessApi } from "@/api/access";
import { ApiError } from "@/api/client";
import { Button } from "@/components/ui/button";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useCompany } from "@/context/CompanyContext";
import { useToast } from "@/context/ToastContext";
import { Link } from "@/lib/router";
import { queryKeys } from "@/lib/queryKeys";
const inviteRoleOptions = [
{
value: "viewer",
label: "Viewer",
description: "Can view company work and follow along without operational permissions.",
gets: "No built-in grants.",
},
{
value: "operator",
label: "Operator",
description: "Recommended for people who need to help run work without managing access.",
gets: "Can assign tasks.",
},
{
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 company access, including membership and permission management.",
gets: "Everything in Admin, plus managing members and permission grants.",
},
] 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;
}
export function CompanyInvites() {
const { selectedCompany, selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
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);
useEffect(() => {
if (!latestInviteCopied) return;
const timeout = window.setTimeout(() => {
setLatestInviteCopied(false);
}, 1600);
return () => window.clearTimeout(timeout);
}, [latestInviteCopied]);
async function copyInviteUrl(url: string) {
try {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(url);
return true;
}
} catch {
// Fall through to the unavailable message below.
}
pushToast({
title: "Clipboard unavailable",
body: "Copy the invite URL manually from the field below.",
tone: "warn",
});
return false;
}
useEffect(() => {
setBreadcrumbs([
{ label: selectedCompany?.name ?? "Company", href: "/dashboard" },
{ label: "Settings", href: "/company/settings" },
{ label: "Invites" },
]);
}, [selectedCompany?.name, setBreadcrumbs]);
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 copyInviteUrl(invite.inviteUrl);
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 a company 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 company 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-5xl space-y-8">
<div className="space-y-3">
<div className="flex items-center gap-2">
<MailPlus className="h-5 w-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Company Invites</h1>
</div>
<p className="max-w-3xl text-sm text-muted-foreground">
Create human invite links for company access. New invite links are copied to your clipboard when they are generated.
</p>
</div>
<section className="space-y-4 rounded-xl border border-border p-5">
<div className="space-y-1">
<h2 className="text-sm font-semibold">Create invite</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" ? (
<span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
Default
</span>
) : 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. The first successful use consumes the link and creates or reuses the matching join request before 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>
<button
type="button"
onClick={async () => {
const copied = await copyInviteUrl(latestInviteUrl);
setLatestInviteCopied(copied);
}}
className="w-full rounded-md border border-border bg-muted/60 px-3 py-2 text-left text-sm break-all transition-colors hover:bg-background"
>
{latestInviteUrl}
</button>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" asChild>
<a href={latestInviteUrl} target="_blank" rel="noreferrer">
<ExternalLink className="h-4 w-4" />
Open invite
</a>
</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, role, 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 company 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">Role</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">
<span className="inline-flex rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
{formatInviteState(invite.state)}
</span>
</td>
<td className="px-5 py-3 align-top">{invite.humanRole ?? "—"}</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);
}