Refine company access page layout

This commit is contained in:
Dotta committed 2026-04-10 11:36:07 -05:00
1 parent bf8b5da7c9
commit 1a69dc8d16
2 files changed
+666

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
// @vitest-environment jsdom
import { act } from "react";
import type { AnchorHTMLAttributes } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CompanyAccess } from "./CompanyAccess";
const listMembersMock = vi.hoisted(() => vi.fn());
const listJoinRequestsMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/access", () => ({
accessApi: {
listMembers: (companyId: string) => listMembersMock(companyId),
listJoinRequests: (companyId: string, status: string) => listJoinRequestsMock(companyId, status),
updateMember: vi.fn(),
updateMemberPermissions: vi.fn(),
approveJoinRequest: vi.fn(),
rejectJoinRequest: vi.fn(),
},
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => <a {...props}>{children}</a>,
}));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({
selectedCompanyId: "company-1",
selectedCompany: { id: "company-1", name: "Paperclip" },
}),
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
}));
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: vi.fn() }),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function flushReact() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
describe("CompanyAccess", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
listMembersMock.mockResolvedValue({
members: [
{
id: "member-1",
companyId: "company-1",
principalType: "user",
principalId: "user-1",
status: "active",
membershipRole: "owner",
createdAt: "2026-04-10T00:00:00.000Z",
updatedAt: "2026-04-10T00:00:00.000Z",
user: {
id: "user-1",
email: "codexcoder@paperclip.local",
name: "Codex Coder",
image: null,
},
grants: [],
},
],
access: {
currentUserRole: "owner",
canManageMembers: true,
canInviteUsers: true,
canApproveJoinRequests: true,
},
});
listJoinRequestsMock.mockResolvedValue([
{
id: "join-1",
requestType: "human",
createdAt: "2026-04-10T00:00:00.000Z",
requesterUser: {
id: "user-2",
email: "board@paperclip.local",
name: "Board User",
image: null,
},
requestEmailSnapshot: "board@paperclip.local",
requestingUserId: "user-2",
invite: {
allowedJoinTypes: "human",
humanRole: "operator",
},
},
{
id: "join-2",
requestType: "agent",
createdAt: "2026-04-10T00:00:00.000Z",
agentName: "Codex Worker",
adapterType: "codex_local",
capabilities: "Implements code changes",
invite: {
allowedJoinTypes: "agent",
humanRole: null,
},
},
]);
});
afterEach(() => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("separates humans from agents and removes the summary cards", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<CompanyAccess />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Manage company user memberships");
expect(container.textContent).toContain("Humans");
expect(container.textContent).toContain("Agents");
expect(container.textContent).toContain("Pending human joins");
expect(container.textContent).toContain("Pending agent joins");
expect(container.textContent).toContain("User account");
expect(container.textContent).not.toContain("Active user accounts");
expect(container.textContent).not.toContain("Suspended user accounts");
expect(container.textContent).not.toContain("Pending user joins");
expect((container.textContent ?? "").indexOf("Humans")).toBeLessThan((container.textContent ?? "").indexOf("Agents"));
await act(async () => {
root.unmount();
});
});
});
+510
View File
@@ -0,0 +1,510 @@
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS, PERMISSION_KEYS, type PermissionKey } from "@paperclipai/shared";
import { Bot, ShieldCheck, Users } from "lucide-react";
import { accessApi, type CompanyMember } from "@/api/access";
import { ApiError } from "@/api/client";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
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 permissionLabels: Record<PermissionKey, string> = {
"agents:create": "Create agents",
"users:invite": "Invite humans and agents",
"users:manage_permissions": "Manage members and grants",
"tasks:assign": "Assign tasks",
"tasks:assign_scope": "Assign scoped tasks",
"joins:approve": "Approve join requests",
};
function formatGrantSummary(member: CompanyMember) {
if (member.grants.length === 0) return "No explicit grants";
return member.grants.map((grant) => permissionLabels[grant.permissionKey]).join(", ");
}
export function CompanyAccess() {
const { selectedCompany, selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToast();
const queryClient = useQueryClient();
const [editingMemberId, setEditingMemberId] = useState<string | null>(null);
const [draftRole, setDraftRole] = useState<CompanyMember["membershipRole"]>(null);
const [draftStatus, setDraftStatus] = useState<CompanyMember["status"]>("active");
const [draftGrants, setDraftGrants] = useState<Set<PermissionKey>>(new Set());
useEffect(() => {
setBreadcrumbs([
{ label: selectedCompany?.name ?? "Company", href: "/dashboard" },
{ label: "Settings", href: "/company/settings" },
{ label: "Access" },
]);
}, [selectedCompany?.name, setBreadcrumbs]);
const membersQuery = useQuery({
queryKey: queryKeys.access.companyMembers(selectedCompanyId ?? ""),
queryFn: () => accessApi.listMembers(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const joinRequestsQuery = useQuery({
queryKey: queryKeys.access.joinRequests(selectedCompanyId ?? "", "pending_approval"),
queryFn: () => accessApi.listJoinRequests(selectedCompanyId!, "pending_approval"),
enabled: !!selectedCompanyId && !!membersQuery.data?.access.canApproveJoinRequests,
});
const refreshAccessData = async () => {
if (!selectedCompanyId) return;
await queryClient.invalidateQueries({ queryKey: queryKeys.access.companyMembers(selectedCompanyId) });
await queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId, "pending_approval") });
};
const updateMemberMutation = useMutation({
mutationFn: async (input: { memberId: string; membershipRole: CompanyMember["membershipRole"]; status: CompanyMember["status"]; grants: PermissionKey[] }) => {
await accessApi.updateMember(selectedCompanyId!, input.memberId, {
membershipRole: input.membershipRole,
status: input.status,
});
return accessApi.updateMemberPermissions(selectedCompanyId!, input.memberId, {
grants: input.grants.map((permissionKey) => ({ permissionKey })),
});
},
onSuccess: async () => {
setEditingMemberId(null);
await refreshAccessData();
pushToast({
title: "Member updated",
tone: "success",
});
},
onError: (error) => {
pushToast({
title: "Failed to update member",
body: error instanceof Error ? error.message : "Unknown error",
tone: "error",
});
},
});
const approveJoinRequestMutation = useMutation({
mutationFn: (requestId: string) => accessApi.approveJoinRequest(selectedCompanyId!, requestId),
onSuccess: async () => {
await refreshAccessData();
pushToast({
title: "Join request approved",
tone: "success",
});
},
onError: (error) => {
pushToast({
title: "Failed to approve join request",
body: error instanceof Error ? error.message : "Unknown error",
tone: "error",
});
},
});
const rejectJoinRequestMutation = useMutation({
mutationFn: (requestId: string) => accessApi.rejectJoinRequest(selectedCompanyId!, requestId),
onSuccess: async () => {
await refreshAccessData();
pushToast({
title: "Join request rejected",
tone: "success",
});
},
onError: (error) => {
pushToast({
title: "Failed to reject join request",
body: error instanceof Error ? error.message : "Unknown error",
tone: "error",
});
},
});
const editingMember = useMemo(
() => membersQuery.data?.members.find((member) => member.id === editingMemberId) ?? null,
[editingMemberId, membersQuery.data?.members],
);
useEffect(() => {
if (!editingMember) return;
setDraftRole(editingMember.membershipRole);
setDraftStatus(editingMember.status);
setDraftGrants(new Set(editingMember.grants.map((grant) => grant.permissionKey)));
}, [editingMember]);
if (!selectedCompanyId) {
return <div className="text-sm text-muted-foreground">Select a company to manage access.</div>;
}
if (membersQuery.isLoading) {
return <div className="text-sm text-muted-foreground">Loading company access…</div>;
}
if (membersQuery.error) {
const message =
membersQuery.error instanceof ApiError && membersQuery.error.status === 403
? "You do not have permission to manage company members."
: membersQuery.error instanceof Error
? membersQuery.error.message
: "Failed to load company members.";
return <div className="text-sm text-destructive">{message}</div>;
}
const members = membersQuery.data?.members ?? [];
const access = membersQuery.data?.access;
const pendingHumanJoinRequests =
joinRequestsQuery.data?.filter((request) => request.requestType === "human") ?? [];
const pendingAgentJoinRequests =
joinRequestsQuery.data?.filter((request) => request.requestType === "agent") ?? [];
const joinRequestActionPending =
approveJoinRequestMutation.isPending || rejectJoinRequestMutation.isPending;
return (
<div className="max-w-6xl space-y-8">
<div className="space-y-3">
<div className="flex items-center gap-2">
<ShieldCheck className="h-5 w-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Company Access</h1>
</div>
<p className="max-w-3xl text-sm text-muted-foreground">
Manage company user memberships, membership status, and explicit permission grants for {selectedCompany?.name}.
</p>
</div>
{access && !access.currentUserRole && (
<div className="rounded-xl border border-amber-500/40 px-4 py-3 text-sm text-amber-200">
This account can manage access here through instance-admin privileges, but it does not currently hold an active company membership.
</div>
)}
<section className="space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<h2 className="text-base font-semibold">Humans</h2>
</div>
<p className="max-w-3xl text-sm text-muted-foreground">
Manage human company memberships first. Roles, status, and explicit grants all live here.
</p>
</div>
{access?.canApproveJoinRequests ? (
<Link to="/inbox/requests" className="text-sm text-muted-foreground underline underline-offset-4">
Open join request queue
</Link>
) : null}
</div>
{access?.canApproveJoinRequests && pendingHumanJoinRequests.length > 0 ? (
<div className="space-y-3 rounded-xl border border-border px-4 py-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h3 className="text-sm font-semibold">Pending human joins</h3>
<p className="text-sm text-muted-foreground">
Review human join requests before they become active company members.
</p>
</div>
<Badge variant="outline">{pendingHumanJoinRequests.length} pending</Badge>
</div>
<div className="space-y-3">
{pendingHumanJoinRequests.map((request) => (
<PendingJoinRequestCard
key={request.id}
requestId={request.id}
title={
request.requesterUser?.name ||
request.requestEmailSnapshot ||
request.requestingUserId ||
"Unknown human requester"
}
subtitle={
request.requesterUser?.email ||
request.requestEmailSnapshot ||
request.requestingUserId ||
"No email available"
}
context={
request.invite
? `${request.invite.allowedJoinTypes} join invite${request.invite.humanRole ? ` • default role ${request.invite.humanRole}` : ""}`
: "Invite metadata unavailable"
}
detail={`Submitted ${new Date(request.createdAt).toLocaleString()}`}
approveLabel="Approve human"
rejectLabel="Reject human"
disabled={joinRequestActionPending}
onApprove={() => approveJoinRequestMutation.mutate(request.id)}
onReject={() => rejectJoinRequestMutation.mutate(request.id)}
/>
))}
</div>
</div>
) : null}
<div className="overflow-hidden rounded-xl border border-border">
<div className="grid grid-cols-[minmax(0,1.5fr)_120px_120px_minmax(0,1.2fr)_120px] gap-3 border-b border-border px-4 py-3 text-xs font-medium uppercase tracking-wide text-muted-foreground">
<div>User account</div>
<div>Role</div>
<div>Status</div>
<div>Grants</div>
<div className="text-right">Action</div>
</div>
{members.length === 0 ? (
<div className="px-4 py-8 text-sm text-muted-foreground">No user memberships found for this company yet.</div>
) : (
members.map((member) => (
<div
key={member.id}
className="grid grid-cols-[minmax(0,1.5fr)_120px_120px_minmax(0,1.2fr)_120px] gap-3 border-b border-border px-4 py-3 last:border-b-0"
>
<div className="min-w-0">
<div className="truncate font-medium">{member.user?.name?.trim() || member.user?.email || member.principalId}</div>
<div className="truncate text-xs text-muted-foreground">{member.user?.email || member.principalId}</div>
</div>
<div className="text-sm">
{member.membershipRole
? HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS[member.membershipRole]
: "Unset"}
</div>
<div>
<Badge variant={member.status === "active" ? "secondary" : member.status === "suspended" ? "destructive" : "outline"}>
{member.status.replace("_", " ")}
</Badge>
</div>
<div className="min-w-0 text-sm text-muted-foreground">{formatGrantSummary(member)}</div>
<div className="text-right">
<Button size="sm" variant="outline" onClick={() => setEditingMemberId(member.id)}>
Edit
</Button>
</div>
</div>
))
)}
</div>
</section>
<section className="space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
<Bot className="h-4 w-4 text-muted-foreground" />
<h2 className="text-base font-semibold">Agents</h2>
</div>
<p className="max-w-3xl text-sm text-muted-foreground">
Agent access is handled through invite-driven join requests instead of human memberships.
</p>
</div>
<Link to="/company/settings/invites" className="text-sm text-muted-foreground underline underline-offset-4">
Manage invites
</Link>
</div>
{!access?.canApproveJoinRequests ? (
<div className="rounded-xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground">
Join request review requires company approval permissions.
</div>
) : pendingAgentJoinRequests.length === 0 ? (
<div className="rounded-xl border border-dashed border-border px-4 py-6 text-sm text-muted-foreground">
No pending agent join requests right now.
</div>
) : (
<div className="space-y-3 rounded-xl border border-border px-4 py-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h3 className="text-sm font-semibold">Pending agent joins</h3>
<p className="text-sm text-muted-foreground">
Review pending agents here, then use the full queue for broader history.
</p>
</div>
<Badge variant="outline">{pendingAgentJoinRequests.length} pending</Badge>
</div>
<div className="space-y-3">
{pendingAgentJoinRequests.map((request) => (
<PendingJoinRequestCard
key={request.id}
requestId={request.id}
title={request.agentName || "Unknown agent requester"}
subtitle={request.adapterType || "Adapter not provided"}
context={
request.invite
? `${request.invite.allowedJoinTypes} join invite${request.invite.humanRole ? ` • human role ${request.invite.humanRole}` : ""}`
: "Invite metadata unavailable"
}
detail={request.capabilities || `Submitted ${new Date(request.createdAt).toLocaleString()}`}
detailSecondary={`Submitted ${new Date(request.createdAt).toLocaleString()}`}
approveLabel="Approve agent"
rejectLabel="Reject agent"
disabled={joinRequestActionPending}
onApprove={() => approveJoinRequestMutation.mutate(request.id)}
onReject={() => rejectJoinRequestMutation.mutate(request.id)}
/>
))}
</div>
</div>
)}
</section>
<Dialog open={!!editingMember} onOpenChange={(open) => !open && setEditingMemberId(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit member</DialogTitle>
<DialogDescription>
Update company role, membership status, and explicit grants for {editingMember?.user?.name || editingMember?.user?.email || editingMember?.principalId}.
</DialogDescription>
</DialogHeader>
{editingMember && (
<div className="space-y-5">
<div className="grid gap-4 md:grid-cols-2">
<label className="space-y-2 text-sm">
<span className="font-medium">Company role</span>
<select
className="w-full rounded-md border border-border bg-background px-3 py-2"
value={draftRole ?? ""}
onChange={(event) =>
setDraftRole((event.target.value || null) as CompanyMember["membershipRole"])
}
>
<option value="">Unset</option>
{Object.entries(HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>
<label className="space-y-2 text-sm">
<span className="font-medium">Membership status</span>
<select
className="w-full rounded-md border border-border bg-background px-3 py-2"
value={draftStatus}
onChange={(event) =>
setDraftStatus(event.target.value as CompanyMember["status"])
}
>
<option value="active">Active</option>
<option value="pending">Pending</option>
<option value="suspended">Suspended</option>
</select>
</label>
</div>
<div className="space-y-3">
<div>
<h3 className="text-sm font-medium">Explicit grants</h3>
<p className="text-sm text-muted-foreground">
These permissions are stored separately from the role label. Use them when the member needs exceptions to the default role.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
{PERMISSION_KEYS.map((permissionKey) => (
<label
key={permissionKey}
className="flex items-start gap-3 rounded-lg border border-border px-3 py-2"
>
<Checkbox
checked={draftGrants.has(permissionKey)}
onCheckedChange={(checked) => {
setDraftGrants((current) => {
const next = new Set(current);
if (checked) next.add(permissionKey);
else next.delete(permissionKey);
return next;
});
}}
/>
<span className="space-y-1">
<span className="block text-sm font-medium">{permissionLabels[permissionKey]}</span>
<span className="block text-xs text-muted-foreground">{permissionKey}</span>
</span>
</label>
))}
</div>
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setEditingMemberId(null)}>
Cancel
</Button>
<Button
onClick={() => {
if (!editingMember) return;
updateMemberMutation.mutate({
memberId: editingMember.id,
membershipRole: draftRole,
status: draftStatus,
grants: [...draftGrants],
});
}}
disabled={updateMemberMutation.isPending}
>
{updateMemberMutation.isPending ? "Saving…" : "Save access"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function PendingJoinRequestCard({
title,
subtitle,
context,
detail,
detailSecondary,
approveLabel,
rejectLabel,
disabled,
onApprove,
onReject,
}: {
requestId: string;
title: string;
subtitle: string;
context: string;
detail: string;
detailSecondary?: string;
approveLabel: string;
rejectLabel: string;
disabled: boolean;
onApprove: () => void;
onReject: () => void;
}) {
return (
<div className="rounded-xl border border-border px-4 py-4">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="space-y-2">
<div>
<div className="font-medium">{title}</div>
<div className="text-sm text-muted-foreground">{subtitle}</div>
</div>
<div className="text-sm text-muted-foreground">{context}</div>
<div className="text-sm text-muted-foreground">{detail}</div>
{detailSecondary ? <div className="text-sm text-muted-foreground">{detailSecondary}</div> : null}
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" onClick={onReject} disabled={disabled}>
{rejectLabel}
</Button>
<Button type="button" onClick={onApprove} disabled={disabled}>
{approveLabel}
</Button>
</div>
</div>
</div>
);
}