AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(web): rebuild the role dialog around view/edit permissions and people (#15698)
lina-alomari014b7401a789
diff --git a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md b/brain/knowledge/platform-editions-ee/ee-projects-rbac.mdindex a693d30db66..ff4d35ffd19 100644--- a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md+++ b/brain/knowledge/platform-editions-ee/ee-projects-rbac.md@@ -24,7 +24,7 @@ Note it lives under `ee/authentication/`, not `ee/projects/`, which is where mos### Gotchas- **`rbacMiddleware` only covers HTTP routes. Websocket events bypass it.** A socket is authorized once at connect, against the project it claims in the handshake. After that, every resource id arriving in an event payload is just whatever the client typed, and nothing re-checks it. So a socket handler must look the resource up scoped to the connection's project and check the permission itself. Getting this wrong is how `LOCK_RESOURCE` and `JOIN_PRESENCE` shipped letting any member lock, and read the editors of, another project's flows and tables (SRE-218). `collaborative-resource.ts` has the shape to copy.-- **A new `Permission` needs a row in the role dialog, or custom roles can never grant it.** The toggle list is a hardcoded array, `initialPermissions` in `packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsx`, and the dialog is a plain `.map()` over it. Default-role grants are hardcoded separately in `access-control-list.ts`, so a permission added there but not here is invisible: ADMIN/EDITOR/VIEWER have it, custom roles cannot be given it, and the feature's tab just never appears for those members. This has already shipped twice — Variables + Knowledge Base (GIT-1751), then Agents. Nothing catches the drift: CI neither typechecks nor unit-tests `web`, so add the row in the same PR as the enum entry.+- **A new `Permission` needs a row in the role grid, or custom roles can never grant it.** The resource-to-permission mapping is a hardcoded array, `groups()` in `packages/web/src/features/members/lib/role-permissions.ts` (it lived inline in `project-role-dialog.tsx` as `initialPermissions` until the Roles & access rebuild), and the grid is a plain `.map()` over it. Default-role grants are hardcoded separately in `access-control-list.ts`, so a permission added there but not here is invisible: ADMIN/EDITOR/VIEWER have it, custom roles cannot be given it, and the feature's tab just never appears for those members. This has already shipped three times — Variables + Knowledge Base (GIT-1751), then Agents, and `PUBLISH_SENSITIVE_FLOW_ACCESS` is missing right now: the grid is **29 of the 30 `Permission` values**, which is why its counter reads "N of 29", and flow-approval rights stay Admin-only. `packages/web/test/features/members/lib/role-permissions.test.ts` now catches the drift — it asserts `PUBLISH_SENSITIVE_FLOW_ACCESS` is the *only* `Permission` absent from the grid, so adding an enum value without a row fails that test.- **The release diff and the release apply have to share one rule, or a field becomes either invisible or permanently dirty.** `flowDiffService` decides whether a flow changed by comparing a `normalize()`d copy of each side, and `projectStateHelper.updateFlowInProject` decides what actually gets written — two places, and for connection auth they disagreed both ways. `normalize()` blanked `input.auth` before comparing, so re-pointing a step at a different connection and changing nothing else was reported `flowsUnchanged` and never applied, while the connection the release created sat unreferenced at status `MISSING`; and when some other edit did make the diff fire, the apply unconditionally restored the destination's old auth on top of the incoming one (`f196530db6`, Jul 2024 secret preservation that predates externalId placeholders). Patching the two sites separately is the trap: it leaves a destination-has-auth / incoming-has-none step reporting changed on **every** apply forever, because the diff and the apply then hold different ideas of what unchanged means. The fix (GIT-1764) is one exported `mergeDestinationAuth` that both call, so the diff compares the merged incoming version — exactly what apply is about to write. Any future field with "keep the destination's value" semantics wants the same shape. Worth knowing while reading this code: `flowStructureUtil.transferFlow` deep-clones before the callback runs, so mutating `step` inside it never touches the caller's state; connection references persist as the literal `{{connections['<externalId>']}}`, identical in both projects, which is why comparing them across instances is meaningful at all; and `flowVersionService` recomputes `connectionIds` via `extractConnectionIds` on every mutation, so the version tracks the new reference without anyone updating it by hand.- **Piece filtering** now via **piece sets** — `project.pieceSetId` (nullable FK, SET NULL). When `managePiecesEnabled`, new EE projects get the Default set on create; unassigned resolves to Default at filter time. This supersedes the legacy project-plan allow/block list.- **Worker routing**: `workerGroupId` (bare label, `^[a-z0-9_-]+$`) gated by `workerGroupsEnabled`. When set, the project's `EXECUTE_FLOW`/`EXECUTE_WEBHOOK` jobs route to `project-<label>-jobs`; other job types unaffected. Set via `POST /v1/projects/:id`; `GET /v1/projects/worker-groups` (platform-admin) lists online project-scope workers, 402 when flag off.diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex ba015defbce..282f00ec960 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -739,6 +739,42 @@"Single Sign On": "Single Sign On","Project Roles": "Project Roles","Roles & Access": "Roles & Access",+ "Could not delete the role. Try again.": "Could not delete the role. Try again.",+ "Built in — platform roles can't be added or changed.": "Built in — platform roles can't be added or changed.",+ "permissionsCount": "{granted} of {total} permissions",+ "Nobody has this role yet": "Nobody has this role yet",+ "People get it when they are added to a project with this role.": "People get it when they are added to a project with this role.",+ "nameAlreadyTaken": "A role called {name} already exists on this platform. Pick another name.",+ "Could not save the role. Try again.": "Could not save the role. Try again.",+ "Connections & releases": "Connections & releases",+ "People": "People",+ "Flow status": "Flow status",+ "Knowledge base": "Knowledge base",+ "MCP servers": "MCP servers",+ "Alerts": "Alerts",+ "App connections": "App connections",+ "Project releases": "Project releases",+ "Project members": "Project members",+ "Invitations": "Invitations",+ "Project settings": "Project settings",+ "No view-only level": "No view-only level",+ "Read-only — open the menu to edit this role.": "Read-only — open the menu to edit this role.",+ "View {resource}": "View {resource}",+ "Edit {resource}": "Edit {resource}",+ "Based on": "Based on",+ "Nothing": "Nothing",+ "Viewer": "Viewer",+ "Editor": "Editor",+ "grantedCount": "{granted} of {total} granted",+ "Create role": "Create role",+ "Delete role": "Delete role",+ "Edit permissions": "Edit permissions",+ "Built-in roles can't be changed": "Built-in roles can't be changed",+ "Tick to add a permission, untick to take it away.": "Tick to add a permission, untick to take it away.",+ "Role name": "Role name",+ "showingFirstPeople": "{count, plural, =1 {Showing the first person} other {Showing the first # people}}",+ "A role is set per project, so the same person can have a different role elsewhere. To change someone's role, open that project.": "A role is set per project, so the same person can have a different role elsewhere. To change someone's role, open that project.",+ "people": "people","Full access": "Full access","Build, publish, and manage flows": "Build, publish, and manage flows","View only": "View only",@@ -748,7 +784,6 @@"Platform roles": "Platform roles","New role": "New role","Built in": "Built in",- "Press a row to open the role. Press the people count to see who has it. Edit and delete live inside the role, so the list stays quiet.": "Press a row to open the role. Press the people count to see who has it. Edit and delete live inside the role, so the list stays quiet.","Everyone has exactly one. To change someone's, open": "Everyone has exactly one. To change someone's, open","Every project as Admin, plus this console": "Every project as Admin, plus this console","Every project as Editor, no console": "Every project as Editor, no console",@@ -1373,19 +1408,11 @@"New Role": "New Role","Contact sales to unlock custom roles": "Contact sales to unlock custom roles","Define custom roles and permissions to control what your team members can access and modify": "Define custom roles and permissions to control what your team members can access and modify",- "Create Role": "Create Role",- "View Role: {name}": "View Role: {name}",- "Edit Role: {name}": "Edit Role: {name}",- "Define a custom role with specific permissions for project members.": "Define a custom role with specific permissions for project members.",- "Review and manage permissions for this role.": "Review and manage permissions for this role.","Role Name": "Role Name","None": "None",- "View the users assigned to this role": "View the users assigned to this role","No users found": "No users found",- "Start by assigning users to this role": "Start by assigning users to this role","No project roles yet. Create one to get started.": "No project roles yet. Create one to get started.","Custom": "Custom",- "Delete Role": "Delete Role","Deleting this role will remove {count} project member(s) and all associated invitations.": "Deleting this role will remove {count} project member(s) and all associated invitations.","Project Role": "Project Role","New Secret Manager Connection": "New Secret Manager Connection",diff --git a/packages/web/src/app/components/centered-page.tsx b/packages/web/src/app/components/centered-page.tsxindex 7df71a9609a..a8c5d9ffee7 100644--- a/packages/web/src/app/components/centered-page.tsx+++ b/packages/web/src/app/components/centered-page.tsx@@ -4,6 +4,8 @@ import { ScrollArea } from '@/components/ui/scroll-area';import { Separator } from '@/components/ui/separator';import { cn } from '@/lib/utils';+const GUTTER = 'w-full px-4 sm:px-6';+export const CenteredPage = ({title,description,@@ -11,6 +13,7 @@ export const CenteredPage = ({footer,children,widthClassName = 'max-w-[40rem]',+ className,}: {title?: string;description?: React.ReactNode;@@ -18,6 +21,7 @@ export const CenteredPage = ({footer?: React.ReactNode;children: React.ReactNode;widthClassName?: string;+ className?: string;}) => {const header =title === undefined && !description && !actions ? null : (@@ -39,31 +43,35 @@ export const CenteredPage = ({if (!footer) {return (- <div className={cn('w-full mx-auto py-6', widthClassName)}>- {header}- {children}+ <div className={cn(GUTTER, 'py-6', className)}>+ <div className={cn('w-full mx-auto', widthClassName)}>+ {header}+ {children}+ </div></div>);}return (<div className="flex flex-col h-full min-h-0">- <div className={cn('w-full mx-auto pt-6 shrink-0', widthClassName)}>- {header}+ <div className={cn(GUTTER, 'pt-6 shrink-0')}>+ <div className={cn('w-full mx-auto', widthClassName)}>{header}</div></div><ScrollArea className="flex-1 min-h-0">- <div className={cn('w-full mx-auto pb-6', widthClassName)}>- {children}+ <div className={cn(GUTTER, 'pb-6')}>+ <div className={cn('w-full mx-auto', widthClassName)}>{children}</div></div></ScrollArea><div className="shrink-0 border-t bg-background">- <div- className={cn(- 'w-full mx-auto py-3 flex justify-end gap-2',- widthClassName,- )}- >- {footer}+ <div className={cn(GUTTER, 'py-3')}>+ <div+ className={cn(+ 'w-full mx-auto flex justify-end gap-2',+ widthClassName,+ )}+ >+ {footer}+ </div></div></div></div>diff --git a/packages/web/src/app/routes/platform/security/project-role/index.tsx b/packages/web/src/app/routes/platform/security/project-role/index.tsxindex 784e0fa9f15..b03d6b863da 100644--- a/packages/web/src/app/routes/platform/security/project-role/index.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/index.tsx@@ -21,6 +21,7 @@ const ProjectRolePage = () => {title={t('Roles & Access')}description={t('What new members get, and what each role can do.')}widthClassName="max-w-4xl"+ className="min-h-full bg-muted/50 dark:bg-background"><RolesCardprojectRoles={roles}diff --git a/packages/web/src/app/routes/platform/security/project-role/permission-grid.tsx b/packages/web/src/app/routes/platform/security/project-role/permission-grid.tsxnew file mode 100644index 00000000000..d9a637e8b0c--- /dev/null+++ b/packages/web/src/app/routes/platform/security/project-role/permission-grid.tsx@@ -0,0 +1,159 @@+import { t } from 'i18next';++import { Checkbox } from '@/components/ui/checkbox';+import {+ PermissionColumn,+ PermissionGroup,+ PermissionRow,+ rolePermissionModel,+} from '@/features/members/lib/role-permissions';+import { cn } from '@/lib/utils';++export function PermissionGrid({+ permissions,+ changedRowKeys,+ readOnly,+ onPermissionsChange,+}: PermissionGridProps) {+ const groups = rolePermissionModel.groups();+ const granted = new Set(permissions);++ const toggle = ({ row, column, checked }: ToggleParams) => {+ onPermissionsChange(+ rolePermissionModel.toggleBox({ permissions, row, column, checked }),+ );+ };++ const renderColumn = (+ columnGroups: PermissionGroup[],+ className?: string,+ headerClassName?: string,+ ) => (+ <div className={cn('flex flex-col', className)}>+ <ColumnHeader className={headerClassName} />+ {columnGroups.map((group) => (+ <div key={group.key} className="flex flex-col">+ <p className="flex items-center gap-2 pt-3 pb-1 text-xss font-medium uppercase tracking-wider text-muted-foreground">+ <span className="size-1.5 shrink-0" />+ {group.label}+ </p>+ {group.rows.map((row) => (+ <div key={row.key} className="flex items-center gap-2 py-2">+ <span+ className={cn(+ 'size-1.5 shrink-0 rounded-full',+ changedRowKeys?.includes(row.key)+ ? 'bg-primary'+ : 'bg-transparent',+ )}+ />+ <span className="flex min-w-0 flex-1 items-baseline gap-2 text-sm">+ <span className="truncate">{row.label}</span>+ </span>+ <Box+ permission={row.view}+ checked={Boolean(row.view && granted.has(row.view))}+ disabled={readOnly || row.viewAlwaysOn}+ label={t('View {resource}', { resource: row.label })}+ onCheckedChange={(checked) =>+ toggle({ row, column: 'view', checked })+ }+ />+ <Box+ permission={row.edit}+ checked={Boolean(row.edit && granted.has(row.edit))}+ disabled={readOnly}+ label={t('Edit {resource}', { resource: row.label })}+ onCheckedChange={(checked) =>+ toggle({ row, column: 'edit', checked })+ }+ />+ </div>+ ))}+ </div>+ ))}+ </div>+ );++ return (+ <div className="grid grid-cols-1 gap-x-8 @min-[38rem]:grid-cols-2">+ {renderColumn(groups.filter((group) => group.key === 'build'))}+ {renderColumn(+ groups.filter((group) => group.key !== 'build'),+ '@min-[38rem]:border-l @min-[38rem]:border-border/60 @min-[38rem]:pl-8',+ 'hidden @min-[38rem]:flex',+ )}+ </div>+ );+}++function ColumnHeader({ className }: { className?: string }) {+ return (+ <div+ className={cn(+ 'flex items-center gap-2 border-b border-border/60 pb-1',+ className,+ )}+ >+ <span className="size-1.5 shrink-0" />+ <span className="flex-1" />+ <span className="w-12 shrink-0 text-center text-xss font-medium uppercase tracking-wider text-muted-foreground">+ {t('View')}+ </span>+ <span className="w-12 shrink-0 text-center text-xss font-medium uppercase tracking-wider text-muted-foreground">+ {t('Edit')}+ </span>+ </div>+ );+}++function Box({+ permission,+ checked,+ disabled,+ label,+ onCheckedChange,+}: BoxProps) {+ return (+ <span className="flex w-12 shrink-0 justify-center">+ {permission ? (+ <Checkbox+ checked={checked}+ disabled={disabled}+ aria-label={label}+ onCheckedChange={(value) => onCheckedChange(value === true)}+ />+ ) : (+ <span+ role="img"+ aria-label={t('No view-only level')}+ title={t('No view-only level')}+ className="text-xs text-muted-foreground"+ >+ —+ </span>+ )}+ </span>+ );+}++type ToggleParams = {+ row: PermissionRow;+ column: PermissionColumn;+ checked: boolean;+};++type BoxProps = {+ permission?: string;+ checked: boolean;+ disabled?: boolean;+ label: string;+ onCheckedChange: (checked: boolean) => void;+};++type PermissionGridProps = {+ permissions: string[];+ changedRowKeys?: string[];+ readOnly: boolean;+ onPermissionsChange: (permissions: string[]) => void;+};diff --git a/packages/web/src/app/routes/platform/security/project-role/platform-roles-list.tsx b/packages/web/src/app/routes/platform/security/project-role/platform-roles-list.tsxindex a5921bdbcd5..b870d24b200 100644--- a/packages/web/src/app/routes/platform/security/project-role/platform-roles-list.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/platform-roles-list.tsx@@ -25,10 +25,15 @@ export function PlatformRolesList() {personalProjectsEnabled: platform.autoCreatePersonalProjects,}).map((platformRole) => (- <Item key={platformRole.role} variant="outline" size="sm">- <RoleAvatar name={platformRole.label} />- <ItemContent>- <ItemTitle>+ <Item+ key={platformRole.role}+ variant="outline"+ size="sm"+ className="flex-nowrap bg-background dark:bg-muted/50"+ >+ <RoleAvatar name={platformRole.label} tone={platformRole.tone} />+ <ItemContent className="min-w-0">+ <ItemTitle className="min-w-0 max-w-full flex-wrap">{platformRole.label}<Badgevariant="accent"diff --git a/packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsx b/packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsxindex 7373b22f950..963ee06878d 100644--- a/packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsx@@ -1,136 +1,51 @@-import { Permission, ProjectRole, RoleType } from '@activepieces/core-utils';+import { ErrorCode, ProjectRole, RoleType } from '@activepieces/core-utils';import { t } from 'i18next';-import { Trash } from 'lucide-react';-import { useState, ReactNode } from 'react';+import { MoreHorizontal, Pencil, Trash, X } from 'lucide-react';+import { ReactNode, useState } from 'react';import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';+import EditableText from '@/components/custom/editable-text';+import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import {Dialog,+ DialogClose,DialogContent,DialogDescription,- DialogHeader,DialogTitle,DialogTrigger,} from '@/components/ui/dialog';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Input } from '@/components/ui/input';import { ScrollArea } from '@/components/ui/scroll-area';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { roleCopy } from '@/features/members/lib/role-copy';+import {+ ROLE_BASES,+ RoleBase,+ rolePermissionModel,+} from '@/features/members/lib/role-permissions';import { projectRoleMutations } from '@/features/platform-admin';+import { api } from '@/lib/api';+import { cn } from '@/lib/utils';-const initialPermissions = [- {- name: 'Project',- description: 'Project settings and configuration',- read: [Permission.READ_PROJECT],- write: [Permission.READ_PROJECT, Permission.WRITE_PROJECT],- disableNone: true,- },- {- name: 'Flows',- description: 'Read and write flows',- read: [Permission.READ_FLOW],- write: [Permission.READ_FLOW, Permission.WRITE_FLOW],- disableNone: true,- },- {- name: 'Flow Status',- description: 'Update flow status',- disableRead: true,- read: [],- write: [Permission.UPDATE_FLOW_STATUS],- },- {- name: 'App Connections',- description: 'Read and write app connections',- read: [Permission.READ_APP_CONNECTION],- write: [Permission.READ_APP_CONNECTION, Permission.WRITE_APP_CONNECTION],- },- {- name: 'Runs',- description: 'Read and write runs',- read: [Permission.READ_RUN],- write: [Permission.READ_RUN, Permission.WRITE_RUN],- },- {- name: 'Alerts',- description: 'Read and write alerts',- read: [Permission.READ_ALERT],- write: [Permission.READ_ALERT, Permission.WRITE_ALERT],- },- {- name: 'Folders',- description: 'Read and write folders',- read: [Permission.READ_FOLDER],- write: [Permission.READ_FOLDER, Permission.WRITE_FOLDER],- },- {- name: 'Project Members',- description: 'Read and write project members',- read: [Permission.READ_PROJECT_MEMBER],- write: [Permission.READ_PROJECT_MEMBER, Permission.WRITE_PROJECT_MEMBER],- },- {- name: 'Invitations',- description: 'Read and write invitations',- read: [Permission.READ_INVITATION],- write: [Permission.READ_INVITATION, Permission.WRITE_INVITATION],- },- {- name: 'Project Releases',- description: 'Read and write project releases',- read: [Permission.READ_PROJECT_RELEASE],- write: [Permission.READ_PROJECT_RELEASE, Permission.WRITE_PROJECT_RELEASE],- },- {- name: 'Tables',- description: 'Read and write tables',- read: [Permission.READ_TABLE],- write: [Permission.READ_TABLE, Permission.WRITE_TABLE],- },- {- name: 'MCP',- description: 'Read and write MCP',- read: [Permission.READ_MCP],- write: [Permission.READ_MCP, Permission.WRITE_MCP],- },- {- name: 'Variables',- description: 'Read and write project variables',- read: [Permission.READ_VARIABLE],- write: [Permission.READ_VARIABLE, Permission.WRITE_VARIABLE],- },- {- name: 'Knowledge Base',- description: 'Read and write knowledge base',- read: [Permission.READ_KNOWLEDGE_BASE],- write: [Permission.READ_KNOWLEDGE_BASE, Permission.WRITE_KNOWLEDGE_BASE],- },- {- name: 'Agents',- description: 'Read and write agents',- read: [Permission.READ_AGENT],- write: [Permission.READ_AGENT, Permission.WRITE_AGENT],- },-];-interface ProjectRoleDialogProps {- mode: 'create' | 'edit';- projectRole?: ProjectRole;- platformId: string;- onSave: () => void;- children?: ReactNode;- disabled?: boolean;- open?: boolean;- onOpenChange?: (open: boolean) => void;-}+import { PermissionGrid } from './permission-grid';+import { RoleAvatar } from './role-avatar';+import { RolePeopleTab } from './role-people-tab';export const ProjectRoleDialog = ({mode,projectRole,onSave,children,- disabled = false,open,onOpenChange,+ initialTab = 'permissions',}: ProjectRoleDialogProps) => {const [uncontrolledOpen, setUncontrolledOpen] = useState(false);const isOpen = open ?? uncontrolledOpen;@@ -140,236 +55,435 @@ export const ProjectRoleDialog = ({}onOpenChange?.(nextOpen);};- const [roleName, setRoleName] = useState(projectRole?.name || '');- const [permissions, setPermissions] = useState<string[]>(() => {- if (!projectRole?.permissions) {- // Set default Read permissions for any permission with disableNone- const defaultPermissions = new Set<string>();- initialPermissions.forEach((permission) => {- if (permission.disableNone) {- permission.read.forEach((p) => defaultPermissions.add(p));- }- });- return Array.from(defaultPermissions);- }- return projectRole.permissions;- });- const { mutate } = projectRoleMutations.useUpsertProjectRole({- onSave: () => {- setIsOpen(false);- onSave();- },- });- const { mutate: deleteProjectRole } =- projectRoleMutations.useDeleteProjectRole({- onSuccess: () => {- setIsOpen(false);- onSave();- },- });- const handlePermissionChange = (permission: string, level: string) => {- const currentPermission = initialPermissions.find(- (p) => p.name === permission,- );- const updatedPermissions = new Set(permissions);+ return (+ <Dialog open={isOpen} onOpenChange={setIsOpen}>+ {children && <DialogTrigger asChild>{children}</DialogTrigger>}+ <DialogContent+ showCloseButton={false}+ className="@container flex h-[min(39rem,88dvh)] w-[calc(100vw-2rem)] max-w-4xl flex-col gap-0 overflow-hidden p-0"+ >+ <RoleDialogBody+ key={isOpen ? `${projectRole?.id ?? 'new'}-open` : 'closed'}+ mode={mode}+ projectRole={projectRole}+ initialTab={initialTab}+ onClose={() => setIsOpen(false)}+ onSaved={() => {+ setIsOpen(false);+ onSave();+ }}+ />+ </DialogContent>+ </Dialog>+ );+};- if (currentPermission?.disableNone) {- currentPermission.read.forEach((p) => updatedPermissions.delete(p));- currentPermission.write.forEach((p) => updatedPermissions.delete(p));+function RoleDialogBody({+ mode,+ projectRole,+ initialTab,+ onClose,+ onSaved,+}: RoleDialogBodyProps) {+ const isCreate = mode === 'create';+ const isBuiltIn = projectRole?.type === RoleType.DEFAULT;- if (level === 'Read') {- currentPermission.read.forEach((p) => updatedPermissions.add(p));- } else if (level === 'Write') {- currentPermission.write.forEach((p) => updatedPermissions.add(p));- }- } else {- if (level === 'None') {- currentPermission?.read.forEach((p) => updatedPermissions.delete(p));- currentPermission?.write.forEach((p) => updatedPermissions.delete(p));- } else if (level === 'Read') {- currentPermission?.write.forEach((p) => updatedPermissions.delete(p));- currentPermission?.read.forEach((p) => updatedPermissions.add(p));- } else if (level === 'Write') {- currentPermission?.write.forEach((p) => updatedPermissions.add(p));- }- }- setPermissions(Array.from(updatedPermissions));- };+ const [base, setBase] = useState<RoleBase>('Viewer');+ const [name, setName] = useState(projectRole?.name ?? '');+ const [permissions, setPermissions] = useState<string[]>(+ projectRole?.permissions ??+ rolePermissionModel.basePermissions({ base: 'Viewer' }),+ );+ const [isRenaming, setIsRenaming] = useState(false);+ const [isEditingPermissions, setIsEditingPermissions] = useState(false);+ const [tab, setTab] = useState<RoleDialogTab>(initialTab);+ const [saveError, setSaveError] = useState<string | null>(null);- const getButtonVariant = (permission: string, level: string) => {- const currentPermission = initialPermissions.find(- (p) => p.name === permission,- );- const writePermissions = new Set(currentPermission?.write || []);- const readPermissions = new Set(currentPermission?.read || []);- const currentPermissionsSet = new Set(permissions);+ const { mutate: upsertRole, isPending: isSaving } =+ projectRoleMutations.useUpsertProjectRole({+ onSave: onSaved,+ onError: (error) =>+ setSaveError(+ isDuplicateNameError(error)+ ? t('nameAlreadyTaken', { name: name.trim() })+ : t('Could not save the role. Try again.'),+ ),+ });+ const { mutateAsync: deleteRole } = projectRoleMutations.useDeleteProjectRole(+ {+ onSuccess: onSaved,+ },+ );- const hasWritePermissions =- writePermissions.size > 0 &&- [...writePermissions].every((p) => currentPermissionsSet.has(p));+ const granted = rolePermissionModel.grantedBoxes({ permissions });+ const total = rolePermissionModel.totalBoxes();+ const isDirty =+ name.trim() !== projectRole?.name ||+ !samePermissions(permissions, projectRole?.permissions ?? []);+ const showsActions =+ isCreate || isDirty || (isEditingPermissions && tab === 'permissions');+ const canSubmit =+ name.trim().length > 0 && !isSaving && (isCreate || isDirty);+ const footerNote =+ saveError ??+ footerNoteFor({+ isCreate,+ isRenaming,+ isBuiltIn,+ isEditingPermissions,+ tab,+ });- const hasReadPermissions =- readPermissions.size > 0 &&- [...readPermissions].every((p) => currentPermissionsSet.has(p)) &&- !hasWritePermissions;+ const cancelEdit = () => {+ setName(projectRole?.name ?? '');+ setPermissions(projectRole?.permissions ?? []);+ setIsRenaming(false);+ setIsEditingPermissions(false);+ setSaveError(null);+ };- if (level === 'Write' && hasWritePermissions) {- return 'default';- } else if (level === 'Read' && hasReadPermissions) {- return 'default';- } else if (- level === 'None' &&- !hasReadPermissions &&- !hasWritePermissions- ) {- return 'default';- }- return 'ghost';+ const changeBase = (nextBase: RoleBase) => {+ setBase(nextBase);+ setPermissions(rolePermissionModel.basePermissions({ base: nextBase }));};- const handleSubmit = () => {- if (!disabled) {- mutate({- mode,- roleId: projectRole?.id,- name: roleName,- permissions,- type: RoleType.CUSTOM,- });- }++ const submit = () => {+ setSaveError(null);+ upsertRole({+ mode,+ roleId: projectRole?.id,+ name: name.trim(),+ permissions,+ type: RoleType.CUSTOM,+ });};+ const counter = (+ <span className="hidden shrink-0 text-sm tabular-nums text-muted-foreground @min-[24rem]:inline">+ {t('grantedCount', { granted, total })}+ </span>+ );+return (- <Dialog open={isOpen} onOpenChange={setIsOpen}>- {children && <DialogTrigger asChild>{children}</DialogTrigger>}- <DialogContent className="w-full max-w-3xl">- <DialogHeader>- <DialogTitle>- {mode === 'create'- ? t('Create Role')- : projectRole?.type === RoleType.DEFAULT- ? t('View Role: {name}', { name: projectRole?.name })- : t('Edit Role: {name}', { name: projectRole?.name })}- </DialogTitle>- <DialogDescription>- {mode === 'create'- ? t(- 'Define a custom role with specific permissions for project members.',- )- : t('Review and manage permissions for this role.')}+ <>+ <header className="flex shrink-0 items-center gap-3 border-b px-6 py-4">+ {!isCreate && projectRole && (+ <RoleAvatar+ name={projectRole.name}+ tone={roleCopy.projectRoleTone(projectRole.name)}+ />+ )}+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ {isCreate && (+ <p className="text-xss font-medium uppercase tracking-wider text-muted-foreground">+ {t('New role')}+ </p>+ )}+ {isCreate ? (+ <>+ <DialogTitle className="sr-only">{t('New role')}</DialogTitle>+ <Input+ autoFocus+ value={name}+ onChange={(event) => {+ setName(event.target.value);+ setSaveError(null);+ }}+ placeholder={t('Role name')}+ className="h-9 max-w-xs"+ />+ </>+ ) : (+ <DialogTitle className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-lg">+ <span className="flex min-w-0 items-center gap-1.5">+ <EditableText+ value={name}+ readonly={isBuiltIn}+ isEditing={isRenaming}+ setIsEditing={setIsRenaming}+ onValueChange={(next) => {+ setName(next);+ setSaveError(null);+ }}+ tooltipContent={isBuiltIn ? '' : t('Rename role')}+ className={cn(+ 'min-w-0 rounded-sm px-1 py-0.5',+ !isBuiltIn &&+ !isRenaming &&+ 'cursor-text hover:bg-muted hover:text-foreground/80',+ isRenaming &&+ 'border border-ring bg-background ring-[1px] ring-ring/50',+ )}+ />+ {!isBuiltIn && !isRenaming && (+ <Pencil+ aria-hidden+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ )}+ </span>+ <Badge+ variant={isBuiltIn ? 'accent' : 'inverted'}+ className="shrink-0 text-xss uppercase tracking-wider"+ >+ {isBuiltIn ? t('Built in') : t('Custom')}+ </Badge>+ </DialogTitle>+ )}+ <DialogDescription className="sr-only">+ {isBuiltIn+ ? t("Built-in roles can't be changed")+ : t('Tick to add a permission, untick to take it away.')}</DialogDescription>- </DialogHeader>- <div className="grid space-y-4 mt-4">- <div>- <span className="text-sm font-medium text-foreground">- {t('Name')}- </span>- <Input- value={roleName}- onChange={(e) => setRoleName(e.target.value)}- required- id="name"- type="text"- placeholder={t('Role Name')}- className="rounded-sm mt-2"- disabled={disabled}- />- </div>- <div>- <span className="text-sm font-medium text-foreground">- {t('Permissions')}- </span>- <div className="overflow-y-auto p-2 rounded-md">- <ScrollArea className="h-[55vh] pr-4">- <div className="grid grid-cols-2 gap-x-6">- {initialPermissions.map((permission) => (- <div- key={permission.name}- className="flex flex-col justify-between py-3 border-b last:border-b-0"- >- <div className="flex flex-row items-center justify-between gap-2">- <span className="font-semibold text-sm text-foreground">- {permission.name}- </span>- <div className="flex bg-accent rounded-sm">- {!permission.disableNone && (- <Button- className="h-9 px-4"- variant={getButtonVariant(- permission.name,- 'None',- )}- onClick={() =>- handlePermissionChange(permission.name, 'None')- }- disabled={disabled}- >- {t('None')}- </Button>- )}- {!permission.disableRead && (- <Button- className="h-9 px-4"- variant={getButtonVariant(- permission.name,- 'Read',- )}- onClick={() =>- handlePermissionChange(permission.name, 'Read')- }- disabled={disabled}- >- {t('Read')}- </Button>- )}- <Button- className="h-9 px-4"- variant={getButtonVariant(permission.name, 'Write')}- onClick={() =>- handlePermissionChange(permission.name, 'Write')- }- disabled={disabled}- >- {t('Write')}- </Button>- </div>- </div>- <span className="text-xs text-muted-foreground mt-1">- {permission.description}- </span>- </div>- ))}- </div>- </ScrollArea>- </div>- </div>- {!disabled && (- <div className="flex items-center justify-between gap-2">- {mode === 'edit' && projectRole && (+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {!isCreate && !isBuiltIn && projectRole && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="size-8 shrink-0 p-0"+ >+ <MoreHorizontal className="size-4" />+ <span className="sr-only">{t('More')}</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onSelect={() => {+ setIsEditingPermissions(true);+ setTab('permissions');+ }}+ disabled={isEditingPermissions}+ >+ <Pencil className="size-4" />+ {t('Edit permissions')}+ </DropdownMenuItem><ConfirmationDeleteDialogisDanger={true}- title={t('Delete Role')}+ title={t('Delete role')}message={t('Deleting this role will remove {count} project member(s) and all associated invitations.',{ count: projectRole.userCount },)}entityName={`${t('Project Role')} ${projectRole.name}`}- buttonText={t('Delete Role')}- mutationFn={async () => deleteProjectRole(projectRole.name)}+ buttonText={t('Delete role')}+ mutationFn={async () => {+ await deleteRole(projectRole.name);+ }}>- <Button variant="ghost" className="text-destructive">+ <DropdownMenuItem+ variant="destructive"+ onSelect={(event) => event.preventDefault()}+ ><Trash className="size-4" />- {t('Delete Role')}- </Button>+ {t('Delete role')}+ </DropdownMenuItem></ConfirmationDeleteDialog>- )}- <Button onClick={handleSubmit} className="ml-auto">- {mode === 'create' ? t('Create') : t('Save')}- </Button>- </div>+ </DropdownMenuContent>+ </DropdownMenu>)}+ <DialogClose asChild>+ <Button variant="ghost" size="sm" className="size-8 shrink-0 p-0">+ <X className="size-4" />+ <span className="sr-only">{t('Close')}</span>+ </Button>+ </DialogClose></div>- </DialogContent>- </Dialog>+ </header>++ {isCreate ? (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-3 px-6 pt-4 pb-3">+ <div className="flex items-center gap-3">+ <span className="text-sm text-muted-foreground">+ {t('Based on')}+ </span>+ <div className="inline-flex items-center rounded-md bg-muted p-1">+ {ROLE_BASES.map((roleBase) => (+ <Button+ key={roleBase}+ type="button"+ size="sm"+ variant="ghost"+ className={cn(+ 'h-7 rounded-sm px-3 text-muted-foreground',+ base === roleBase &&+ 'bg-background text-foreground shadow-xs hover:bg-background',+ )}+ onClick={() => changeBase(roleBase)}+ >+ {t(roleBase)}+ </Button>+ ))}+ </div>+ </div>+ {counter}+ </div>+ <ScrollArea className="min-h-0 flex-1">+ <div className="px-6 pb-4">+ <PermissionGrid+ permissions={permissions}+ readOnly={false}+ changedRowKeys={rolePermissionModel.changedRowKeys({+ permissions,+ base,+ })}+ onPermissionsChange={setPermissions}+ />+ </div>+ </ScrollArea>+ </div>+ ) : (+ <Tabs+ value={tab}+ onValueChange={(value) =>+ setTab(value === 'people' ? 'people' : 'permissions')+ }+ className="flex min-h-0 flex-1 flex-col gap-0"+ >+ <div className="flex shrink-0 items-center justify-between gap-4 border-b px-6">+ <TabsList variant="outline" className="gap-6">+ <TabsTrigger+ variant="outline"+ value="permissions"+ className="px-0 py-3"+ >+ {t('Permissions')}+ </TabsTrigger>+ <TabsTrigger+ variant="outline"+ value="people"+ className="gap-2 px-0 py-3"+ >+ {t('People')}+ <span className="tabular-nums text-muted-foreground">+ {projectRole?.userCount ?? 0}+ </span>+ </TabsTrigger>+ </TabsList>+ {tab === 'permissions' && counter}+ </div>+ <TabsContent+ value="permissions"+ className="mt-0 flex min-h-0 flex-1 flex-col"+ >+ <ScrollArea className="min-h-0 flex-1">+ <div className="px-6 pt-4 pb-4">+ <PermissionGrid+ permissions={permissions}+ readOnly={!isEditingPermissions}+ onPermissionsChange={setPermissions}+ />+ </div>+ </ScrollArea>+ </TabsContent>+ <TabsContent value="people" className="mt-0 min-h-0 flex-1">+ {projectRole && <RolePeopleTab projectRole={projectRole} />}+ </TabsContent>+ </Tabs>+ )}++ <footer className="flex min-h-15 shrink-0 flex-wrap items-center justify-end gap-x-6 gap-y-2 border-t px-6 py-3">+ {footerNote ? (+ <p+ role={saveError ? 'alert' : undefined}+ className={cn(+ 'min-w-0 basis-full text-xs sm:flex-1 sm:basis-auto',+ saveError+ ? 'font-medium text-destructive'+ : 'text-muted-foreground',+ )}+ >+ {footerNote}+ </p>+ ) : (+ <span className="hidden sm:block sm:flex-1" />+ )}+ {showsActions && (+ <div className="flex shrink-0 items-center gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={isCreate ? onClose : cancelEdit}+ >+ {t('Cancel')}+ </Button>+ <Button type="button" disabled={!canSubmit} onClick={submit}>+ {isCreate ? t('Create role') : t('Save changes')}+ </Button>+ </div>+ )}+ </footer>+ </>+ );+}++function footerNoteFor({+ isCreate,+ isRenaming,+ isBuiltIn,+ isEditingPermissions,+ tab,+}: FooterNoteParams): string | null {+ if (isCreate || isRenaming) {+ return null;+ }+ if (tab === 'people') {+ return t(+ "A role is set per project, so the same person can have a different role elsewhere. To change someone's role, open that project.",+ );+ }+ if (isBuiltIn) {+ return t("Built-in roles can't be changed");+ }+ if (isEditingPermissions) {+ return null;+ }+ return t('Read-only — open the menu to edit this role.');+}++function isDuplicateNameError(error: unknown): boolean {+ return (+ api.isApError(error, ErrorCode.VALIDATION) ||+ api.isApError(error, ErrorCode.ENTITY_NOT_FOUND));+}++function samePermissions(left: string[], right: string[]): boolean {+ if (left.length !== right.length) {+ return false;+ }+ const rightSet = new Set(right);+ return left.every((permission) => rightSet.has(permission));+}++type FooterNoteParams = {+ isCreate: boolean;+ isRenaming: boolean;+ isBuiltIn: boolean;+ isEditingPermissions: boolean;+ tab: RoleDialogTab;+};++type RoleDialogTab = 'permissions' | 'people';++type RoleDialogBodyProps = {+ mode: 'create' | 'edit';+ projectRole?: ProjectRole;+ initialTab: RoleDialogTab;+ onClose: () => void;+ onSaved: () => void;+};++type ProjectRoleDialogProps = {+ mode: 'create' | 'edit';+ projectRole?: ProjectRole;+ onSave: () => void;+ children?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ initialTab?: RoleDialogTab;};diff --git a/packages/web/src/app/routes/platform/security/project-role/project-role-users-table.tsx b/packages/web/src/app/routes/platform/security/project-role/project-role-users-table.tsxdeleted file mode 100644index c5eb5245f81..00000000000--- a/packages/web/src/app/routes/platform/security/project-role/project-role-users-table.tsx+++ /dev/null@@ -1,105 +0,0 @@-import { ProjectRole } from '@activepieces/core-utils';-import { ProjectMemberWithUser } from '@activepieces/shared';-import { t } from 'i18next';-import { Loader2, Users } from 'lucide-react';-import { Link } from 'react-router-dom';--import { UserAvatar } from '@/components/custom/user-avatar';-import {- Item,- ItemContent,- ItemDescription,- ItemTitle,-} from '@/components/ui/item';-import {- Sheet,- SheetContent,- SheetDescription,- SheetHeader,- SheetTitle,-} from '@/components/ui/sheet';-import { VirtualizedScrollArea } from '@/components/ui/virtualized-scroll-area';-import { projectRoleQueries } from '@/features/platform-admin';--export const ProjectRoleUsersSheet = ({- projectRole,- isOpen,- onOpenChange,-}: ProjectRoleUsersSheetProps) => {- const { data, isLoading } = projectRoleQueries.useProjectRoleMembers(- projectRole?.id,- isOpen && projectRole !== null,- );-- const users = data?.data ?? [];-- return (- <Sheet open={isOpen} onOpenChange={onOpenChange}>- <SheetContent className="w-[600px] sm:max-w-[600px] flex flex-col p-0">- <SheetHeader className="px-6 py-4 border-b shrink-0">- <SheetTitle className="text-base">- {projectRole?.name} {t('Role')} {t('Users')}- </SheetTitle>- <SheetDescription>- {t('View the users assigned to this role')}- </SheetDescription>- </SheetHeader>- <div className="flex-1 overflow-hidden">- {isLoading ? (- <div className="flex items-center justify-center h-full">- <Loader2 className="size-8 animate-spin text-muted-foreground" />- </div>- ) : users.length === 0 ? (- <div className="flex flex-col items-center justify-center h-full gap-2 text-muted-foreground">- <Users className="size-14" />- <p className="text-sm font-medium">{t('No users found')}</p>- <p className="text-xs">- {t('Start by assigning users to this role')}- </p>- </div>- ) : (- <VirtualizedScrollArea- items={users}- estimateSize={() => 64}- getItemKey={(index) => users[index].id}- renderItem={(member) => renderUserItem(member)}- />- )}- </div>- </SheetContent>- </Sheet>- );-};--function renderUserItem(member: ProjectMemberWithUser) {- const { user, project } = member;- const fullName = `${user.firstName} ${user.lastName}`.trim();-- return (- <Item size="sm">- <UserAvatar- name={fullName}- email={user.email}- imageUrl={user.imageUrl}- size={36}- disableTooltip- />- <ItemContent>- <ItemTitle>{fullName}</ItemTitle>- <ItemDescription>- {user.email}- {' · '}- <Link to={`/projects/${project.id}/settings/team`}>- {project.displayName}- </Link>- </ItemDescription>- </ItemContent>- </Item>- );-}--type ProjectRoleUsersSheetProps = {- projectRole: ProjectRole | null;- isOpen: boolean;- onOpenChange: (open: boolean) => void;-};diff --git a/packages/web/src/app/routes/platform/security/project-role/project-roles-list.tsx b/packages/web/src/app/routes/platform/security/project-role/project-roles-list.tsxindex 70a2ce64ef5..a49495fc7ba 100644--- a/packages/web/src/app/routes/platform/security/project-role/project-roles-list.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/project-roles-list.tsx@@ -5,6 +5,7 @@ import { ChevronRight, Shield } from 'lucide-react';import { useState } from 'react';import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';import { Badge } from '@/components/ui/badge';import {Item,@@ -15,10 +16,8 @@ import {} from '@/components/ui/item';import { SkeletonList } from '@/components/ui/skeleton';import { roleCopy } from '@/features/members/lib/role-copy';-import { platformHooks } from '@/hooks/platform-hooks';import { ProjectRoleDialog } from './project-role-dialog';-import { ProjectRoleUsersSheet } from './project-role-users-table';import { RoleAvatar } from './role-avatar';export function ProjectRolesList({@@ -27,9 +26,7 @@ export function ProjectRolesList({isError,refetch,}: ProjectRolesListProps) {- const { platform } = platformHooks.useCurrentPlatform();- const [openedRole, setOpenedRole] = useState<ProjectRole | null>(null);- const [peopleRole, setPeopleRole] = useState<ProjectRole | null>(null);+ const [opened, setOpened] = useState<OpenedRole | null>(null);if (isLoading) {return <SkeletonList numberOfItems={3} className="w-full h-[60px]" />;@@ -39,7 +36,9 @@ export function ProjectRolesList({return <DataFetchErrorState entity={t('roles')} onRetry={refetch} />;}- const roles = projectRoles?.data ?? [];+ const roles = roleCopy.sortProjectRoles({+ roles: projectRoles?.data ?? [],+ });if (roles.length === 0) {return (@@ -56,91 +55,91 @@ export function ProjectRolesList({<div className="flex flex-col gap-3"><ItemGroup className="gap-2">{roles.map((role) => {- const description = roleCopy.projectRoleDescription(role.name);+ const description = roleCopy.projectRoleSummary({+ name: role.name,+ permissions: role.permissions,+ });return (<Itemkey={role.id}variant="outline"size="sm"- className="relative cursor-pointer hover:bg-accent/50 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50"+ className="relative flex-nowrap cursor-pointer bg-background hover:bg-accent/50 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-muted/50">- <RoleAvatar name={role.name} />- <ItemContent>- <ItemTitle>+ <RoleAvatar+ name={role.name}+ tone={roleCopy.projectRoleTone(role.name)}+ />+ <ItemContent className="min-w-0">+ <ItemTitle className="min-w-0 max-w-full"><buttontype="button"- className="text-left after:absolute after:inset-0 after:content-[''] focus-visible:outline-none"- onClick={() => setOpenedRole(role)}+ className="min-w-0 text-left after:absolute after:inset-0 after:content-['']"+ onClick={() => setOpened({ role, tab: 'permissions' })}>- {role.name}+ <TextWithTooltip tooltipMessage={role.name}>+ <span className="block truncate">{role.name}</span>+ </TextWithTooltip></button><Badgevariant={role.type === RoleType.DEFAULT ? 'accent' : 'inverted'}- className="text-xss uppercase tracking-wider"+ className="shrink-0 text-xss uppercase tracking-wider">{role.type === RoleType.DEFAULT? t('Built in'): t('Custom')}</Badge></ItemTitle>- <ItemDescription>- {description}- {description && !isNil(role.userCount) && ' · '}- {!isNil(role.userCount) && (- <button- type="button"- className="relative z-10 text-primary underline-offset-4 hover:underline"- onClick={() => setPeopleRole(role)}- >- {t('rolePeopleCount', { count: role.userCount })}- </button>- )}- </ItemDescription>+ <ItemDescription>{description}</ItemDescription></ItemContent>+ {!isNil(role.userCount) &&+ (role.userCount === 0 ? (+ <span className="shrink-0 text-sm tabular-nums text-muted-foreground">+ {t('rolePeopleCount', { count: 0 })}+ </span>+ ) : (+ <button+ type="button"+ className="relative z-10 shrink-0 text-sm tabular-nums text-primary underline-offset-4 hover:underline"+ onClick={() => setOpened({ role, tab: 'people' })}+ >+ {t('rolePeopleCount', { count: role.userCount })}+ </button>+ ))}<ChevronRight className="size-4 shrink-0 text-muted-foreground" /></Item>);})}</ItemGroup>- <p className="text-xs text-muted-foreground">- {t(- 'Press a row to open the role. Press the people count to see who has it. Edit and delete live inside the role, so the list stays quiet.',- )}- </p>- {openedRole && (+ {opened && (<ProjectRoleDialog- key={openedRole.id}+ key={`${opened.role.id}-${opened.tab}`}mode="edit"- projectRole={openedRole}- platformId={platform.id}+ projectRole={opened.role}+ initialTab={opened.tab}open={true}onOpenChange={(open) => {if (!open) {- setOpenedRole(null);+ setOpened(null);}}}onSave={() => {- setOpenedRole(null);+ setOpened(null);refetch();}}- disabled={openedRole.type === RoleType.DEFAULT}/>)}- <ProjectRoleUsersSheet- projectRole={peopleRole}- isOpen={peopleRole !== null}- onOpenChange={(open) => {- if (!open) {- setPeopleRole(null);- }- }}- /></div>);}+type OpenedRole = {+ role: ProjectRole;+ tab: 'permissions' | 'people';+};+type ProjectRolesListProps = {projectRoles: SeekPage<ProjectRole> | undefined;isLoading: boolean;diff --git a/packages/web/src/app/routes/platform/security/project-role/role-avatar.tsx b/packages/web/src/app/routes/platform/security/project-role/role-avatar.tsxindex 64f56522be7..1255fe09049 100644--- a/packages/web/src/app/routes/platform/security/project-role/role-avatar.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/role-avatar.tsx@@ -1,19 +1,31 @@-import { ItemMedia } from '@/components/ui/item';+import { RoleTone } from '@/features/members/lib/role-copy';import { cn } from '@/lib/utils';-export function RoleAvatar({ name, className }: RoleAvatarProps) {+const toneClasses: Record<RoleTone, string> = {+ brand: 'bg-primary/10 text-primary',+ info: 'bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300',+ neutral: 'bg-muted text-muted-foreground',+ custom:+ 'bg-warning-50 text-warning-700 dark:bg-warning-950 dark:text-warning-300',+};++export function RoleAvatar({ name, tone, className }: RoleAvatarProps) {return (- <ItemMedia- variant="icon"- className={cn('text-sm font-medium text-muted-foreground', className)}+ <spanaria-hidden+ className={cn(+ 'flex size-9 shrink-0 items-center justify-center rounded-lg text-base font-medium leading-none',+ toneClasses[tone],+ className,+ )}>{name.trim().charAt(0).toUpperCase()}- </ItemMedia>+ </span>);}type RoleAvatarProps = {name: string;+ tone: RoleTone;className?: string;};diff --git a/packages/web/src/app/routes/platform/security/project-role/role-people-tab.tsx b/packages/web/src/app/routes/platform/security/project-role/role-people-tab.tsxnew file mode 100644index 00000000000..be71df53db1--- /dev/null+++ b/packages/web/src/app/routes/platform/security/project-role/role-people-tab.tsx@@ -0,0 +1,146 @@+import { ProjectRole } from '@activepieces/core-utils';+import { ProjectMemberWithUser } from '@activepieces/shared';+import { t } from 'i18next';+import { ArrowUpRight, Loader2, Users } from 'lucide-react';+import { Link } from 'react-router-dom';++import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';+import { UserAvatar } from '@/components/custom/user-avatar';+import { Button } from '@/components/ui/button';+import { ScrollArea } from '@/components/ui/scroll-area';+import { projectRoleQueries } from '@/features/platform-admin';+import { cn } from '@/lib/utils';++export function RolePeopleTab({ projectRole }: RolePeopleTabProps) {+ const {+ data,+ isLoading,+ isError,+ refetch,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = projectRoleQueries.useProjectRoleMembers(projectRole.id, true);++ if (isLoading) {+ return (+ <div className="flex h-full items-center justify-center">+ <Loader2 className="size-6 animate-spin text-muted-foreground" />+ </div>+ );+ }++ if (isError) {+ return (+ <div className="flex h-full items-center justify-center px-6">+ <DataFetchErrorState entity={t('people')} onRetry={refetch} />+ </div>+ );+ }++ const members = data?.pages.flatMap((page) => page.data) ?? [];++ if (members.length === 0) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-muted-foreground">+ <Users className="size-10" />+ <p className="text-sm font-medium">{t('Nobody has this role yet')}</p>+ <p className="text-xs">+ {t('People get it when they are added to a project with this role.')}+ </p>+ </div>+ );+ }++ return (+ <div className="flex h-full flex-col pt-4">+ {hasNextPage && (+ <p className="shrink-0 px-6 pb-3 text-sm text-muted-foreground">+ {t('showingFirstPeople', { count: members.length })}+ </p>+ )}+ <div className={cn(PEOPLE_COLUMNS, 'shrink-0 border-b px-6 pb-2')}>+ <span className="text-xss font-medium uppercase tracking-wider text-muted-foreground">+ {t('Name')}+ </span>+ <span className="hidden text-xss font-medium uppercase tracking-wider text-muted-foreground @min-[36rem]:block">+ {t('Email')}+ </span>+ <span className="text-xss font-medium uppercase tracking-wider text-muted-foreground">+ {t('Project')}+ </span>+ </div>+ <ScrollArea className="min-h-0 flex-1">+ <div className="px-6">+ {members.map((member) => (+ <PersonRow key={member.id} member={member} />+ ))}+ {hasNextPage && (+ <div className="flex justify-center py-3">+ <Button+ variant="outline"+ size="sm"+ disabled={isFetchingNextPage}+ onClick={() => fetchNextPage()}+ >+ {isFetchingNextPage && (+ <Loader2 className="size-4 animate-spin" />+ )}+ {t('Load more')}+ </Button>+ </div>+ )}+ </div>+ </ScrollArea>+ </div>+ );+}++function PersonRow({ member }: { member: ProjectMemberWithUser }) {+ const fullName = `${member.user.firstName} ${member.user.lastName}`.trim();+ return (+ <div+ className={cn(+ PEOPLE_COLUMNS,+ 'border-b border-border/60 py-2 last:border-b-0',+ )}+ >+ <span className="flex min-w-0 items-center gap-2">+ <UserAvatar+ name={fullName}+ email={member.user.email}+ imageUrl={member.user.imageUrl}+ size={24}+ disableTooltip+ />+ <TextWithTooltip tooltipMessage={fullName}>+ <span className="min-w-0 truncate text-sm">{fullName}</span>+ </TextWithTooltip>+ </span>+ <span className="hidden min-w-0 @min-[36rem]:block">+ <TextWithTooltip tooltipMessage={member.user.email}>+ <span className="block min-w-0 truncate text-sm text-muted-foreground">+ {member.user.email}+ </span>+ </TextWithTooltip>+ </span>+ <Link+ to={`/projects/${member.project.id}/settings/team`}+ className="flex min-w-0 items-center gap-1 text-sm text-primary underline-offset-4 hover:underline"+ >+ <TextWithTooltip tooltipMessage={member.project.displayName}>+ <span className="min-w-0 truncate">{member.project.displayName}</span>+ </TextWithTooltip>+ <ArrowUpRight className="size-3.5 shrink-0" />+ </Link>+ </div>+ );+}++const PEOPLE_COLUMNS =+ 'grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] items-center gap-x-6 @min-[36rem]:grid-cols-[minmax(0,1.1fr)_minmax(0,1.3fr)_minmax(0,1fr)]';++type RolePeopleTabProps = {+ projectRole: ProjectRole;+};diff --git a/packages/web/src/app/routes/platform/security/project-role/roles-card.tsx b/packages/web/src/app/routes/platform/security/project-role/roles-card.tsxindex 2d8b35bae59..03e79741d5f 100644--- a/packages/web/src/app/routes/platform/security/project-role/roles-card.tsx+++ b/packages/web/src/app/routes/platform/security/project-role/roles-card.tsx@@ -44,11 +44,7 @@ export function RolesCard({</TooltipContent></Tooltip>) : (- <ProjectRoleDialog- mode="create"- onSave={() => refetch()}- platformId={platform.id}- >+ <ProjectRoleDialog mode="create" onSave={() => refetch()}><AnimatedIconButton icon={PlusIcon} iconSize={16} size="sm">{t('New role')}</AnimatedIconButton>@@ -59,7 +55,7 @@ export function RolesCard({<section className="flex flex-col gap-4"><div className="flex flex-col gap-1"><h2 className="text-base font-medium">{t('Roles')}</h2>- <p className="text-sm text-muted-foreground">+ <p className="max-w-2xl text-sm text-muted-foreground">{t('Two kinds. A platform role is one per person and decides console access and which projects they see. A project role is chosen per project and decides what they can do inside it.',)}@@ -69,7 +65,7 @@ export function RolesCard({value={activeTab}onValueChange={(value) => setActiveTab(toRolesTab(value))}>- <div className="flex items-center justify-between gap-4">+ <div className="flex flex-wrap items-center justify-between gap-3"><TabsList><TabsTrigger value="project" className="gap-2">{t('Project roles')}@@ -86,7 +82,13 @@ export function RolesCard({</span></TabsTrigger></TabsList>- {activeTab === 'project' && newRoleButton}+ {activeTab === 'project' ? (+ newRoleButton+ ) : (+ <p className="text-xs text-muted-foreground">+ {t("Built in \u2014 platform roles can't be added or changed.")}+ </p>+ )}</div><TabsContent value="project"><ProjectRolesListdiff --git a/packages/web/src/features/members/components/project-role-select.tsx b/packages/web/src/features/members/components/project-role-select.tsxindex ea7483600a9..5ccfc4ad101 100644--- a/packages/web/src/features/members/components/project-role-select.tsx+++ b/packages/web/src/features/members/components/project-role-select.tsx@@ -1,5 +1,3 @@-import { isNil } from '@activepieces/core-utils';-import { useQuery } from '@tanstack/react-query';import { t } from 'i18next';import { useEffect } from 'react';import { UseFormReturn } from 'react-hook-form';@@ -7,7 +5,7 @@ import { UseFormReturn } from 'react-hook-form';import { FormField, FormItem, FormMessage } from '@/components/ui/form';import { Label } from '@/components/ui/label';import { RoleSelector } from '@/features/members/components/role-selector';-import { projectRoleApi } from '@/features/platform-admin/api/project-role-api';+import { projectRoleQueries } from '@/features/platform-admin';import { platformHooks } from '@/hooks/platform-hooks';type ProjectRoleSelectProps = {@@ -17,13 +15,8 @@ type ProjectRoleSelectProps = {export const ProjectRoleSelect = ({ form }: ProjectRoleSelectProps) => {const { platform } = platformHooks.useCurrentPlatform();- const { data: rolesData, isPending: rolesLoading } = useQuery({- queryKey: ['project-roles'],- queryFn: () => projectRoleApi.list(),- enabled:- !isNil(platform.plan.projectRolesEnabled) &&- platform.plan.projectRolesEnabled,- });+ const { data: rolesData, isLoading: rolesLoading } =+ projectRoleQueries.useProjectRoles(platform.plan.projectRolesEnabled);const roles = rolesData?.data ?? [];const defaultProjectRole =diff --git a/packages/web/src/features/members/components/role-selector.tsx b/packages/web/src/features/members/components/role-selector.tsxindex 387d426a2aa..37de5d5e7b9 100644--- a/packages/web/src/features/members/components/role-selector.tsx+++ b/packages/web/src/features/members/components/role-selector.tsx@@ -13,17 +13,13 @@ import {import { roleCopy } from '@/features/members/lib/role-copy';import { platformHooks } from '@/hooks/platform-hooks';-export const getProjectRoleDescription = (roleName: string): string => {- return roleCopy.projectRoleDescription(roleName) ?? '';-};-interface RoleSelectorProps {type: 'platform' | 'project';value: string;onValueChange: (value: string) => void;disabled?: boolean;placeholder?: string;- roles?: Array<{ name: string }>;+ roles?: Array<{ name: string; permissions: string[] }>;isLoading?: boolean;isAssigningRole?: boolean;}@@ -60,7 +56,10 @@ export const RoleSelector = ({: roles.map((role) => ({value: role.name,label: role.name,- description: getProjectRoleDescription(role.name),+ description: roleCopy.projectRoleSummary({+ name: role.name,+ permissions: role.permissions,+ }),}));const selectedRole = options.find((r) => r.value === value);diff --git a/packages/web/src/features/members/lib/role-copy.ts b/packages/web/src/features/members/lib/role-copy.tsindex 4e68285bc46..00cfb2c3be0 100644--- a/packages/web/src/features/members/lib/role-copy.ts+++ b/packages/web/src/features/members/lib/role-copy.ts@@ -2,6 +2,8 @@ import { ProjectRole, RoleType } from '@activepieces/core-utils';import { DefaultProjectRole, PlatformRole } from '@activepieces/shared';import { t } from 'i18next';+import { rolePermissionModel } from './role-permissions';+const BUILT_IN_ORDER: string[] = [DefaultProjectRole.ADMIN,DefaultProjectRole.EDITOR,@@ -21,6 +23,17 @@ function projectRoleDescription(roleName: string): string | null {}}+function projectRoleSummary({+ name,+ permissions,+}: ProjectRoleSummaryParams): string {+ const granted = rolePermissionModel.grantedBoxes({ permissions });+ const total = rolePermissionModel.totalBoxes();+ const count = t('permissionsCount', { granted, total });+ const description = projectRoleDescription(name);+ return description ? `${description} \u00b7 ${count}` : count;+}+function projectRoleTone(roleName: string): RoleTone {switch (roleName) {case DefaultProjectRole.ADMIN:@@ -89,6 +102,7 @@ function builtInRank(role: ProjectRole): number {export const roleCopy = {projectRoleDescription,+ projectRoleSummary,projectRoleTone,platformRoles,sortProjectRoles,@@ -107,3 +121,8 @@ export type PlatformRoleSummary = {type PlatformRolesParams = {personalProjectsEnabled: boolean;};++type ProjectRoleSummaryParams = {+ name: string;+ permissions: string[];+};diff --git a/packages/web/src/features/members/lib/role-permissions.ts b/packages/web/src/features/members/lib/role-permissions.tsnew file mode 100644index 00000000000..c1a488ccddf--- /dev/null+++ b/packages/web/src/features/members/lib/role-permissions.ts@@ -0,0 +1,251 @@+import { Permission } from '@activepieces/core-utils';+import { DefaultProjectRole, rolePermissions } from '@activepieces/shared';+import { t } from 'i18next';++function groups(): PermissionGroup[] {+ return [+ {+ key: 'build',+ label: t('Build'),+ rows: [+ {+ key: 'flows',+ label: t('Flows'),+ view: Permission.READ_FLOW,+ edit: Permission.WRITE_FLOW,+ viewAlwaysOn: true,+ },+ {+ key: 'flow-status',+ label: t('Flow status'),+ edit: Permission.UPDATE_FLOW_STATUS,+ },+ {+ key: 'folders',+ label: t('Folders'),+ view: Permission.READ_FOLDER,+ edit: Permission.WRITE_FOLDER,+ },+ {+ key: 'tables',+ label: t('Tables'),+ view: Permission.READ_TABLE,+ edit: Permission.WRITE_TABLE,+ },+ {+ key: 'agents',+ label: t('Agents'),+ view: Permission.READ_AGENT,+ edit: Permission.WRITE_AGENT,+ },+ {+ key: 'knowledge-base',+ label: t('Knowledge base'),+ view: Permission.READ_KNOWLEDGE_BASE,+ edit: Permission.WRITE_KNOWLEDGE_BASE,+ },+ {+ key: 'variables',+ label: t('Variables'),+ view: Permission.READ_VARIABLE,+ edit: Permission.WRITE_VARIABLE,+ },+ {+ key: 'mcp-servers',+ label: t('MCP servers'),+ view: Permission.READ_MCP,+ edit: Permission.WRITE_MCP,+ },+ ],+ },+ {+ key: 'run',+ label: t('Run'),+ rows: [+ {+ key: 'runs',+ label: t('Runs'),+ view: Permission.READ_RUN,+ edit: Permission.WRITE_RUN,+ },+ {+ key: 'alerts',+ label: t('Alerts'),+ view: Permission.READ_ALERT,+ edit: Permission.WRITE_ALERT,+ },+ ],+ },+ {+ key: 'connections-releases',+ label: t('Connections & releases'),+ rows: [+ {+ key: 'app-connections',+ label: t('App connections'),+ view: Permission.READ_APP_CONNECTION,+ edit: Permission.WRITE_APP_CONNECTION,+ },+ {+ key: 'project-releases',+ label: t('Project releases'),+ view: Permission.READ_PROJECT_RELEASE,+ edit: Permission.WRITE_PROJECT_RELEASE,+ },+ ],+ },+ {+ key: 'people',+ label: t('People'),+ rows: [+ {+ key: 'project-members',+ label: t('Project members'),+ view: Permission.READ_PROJECT_MEMBER,+ edit: Permission.WRITE_PROJECT_MEMBER,+ },+ {+ key: 'invitations',+ label: t('Invitations'),+ view: Permission.READ_INVITATION,+ edit: Permission.WRITE_INVITATION,+ },+ ],+ },+ {+ key: 'project',+ label: t('Project'),+ rows: [+ {+ key: 'project-settings',+ label: t('Project settings'),+ view: Permission.READ_PROJECT,+ edit: Permission.WRITE_PROJECT,+ viewAlwaysOn: true,+ },+ ],+ },+ ];+}++function allRows(): PermissionRow[] {+ return groups().flatMap((group) => group.rows);+}++function totalBoxes(): number {+ return allRows().reduce(+ (total, row) => total + (row.view ? 1 : 0) + (row.edit ? 1 : 0),+ 0,+ );+}++function grantedBoxes({ permissions }: { permissions: string[] }): number {+ const granted = new Set(permissions);+ return allRows().reduce((total, row) => {+ const viewGranted = row.view && granted.has(row.view) ? 1 : 0;+ const editGranted = row.edit && granted.has(row.edit) ? 1 : 0;+ return total + viewGranted + editGranted;+ }, 0);+}++function alwaysOnPermissions(): string[] {+ return allRows().flatMap((row) =>+ row.viewAlwaysOn && row.view ? [row.view] : [],+ );+}++function basePermissions({ base }: { base: RoleBase }): string[] {+ switch (base) {+ case 'Viewer':+ return [...rolePermissions[DefaultProjectRole.VIEWER]];+ case 'Editor':+ return [...rolePermissions[DefaultProjectRole.EDITOR]];+ default:+ return alwaysOnPermissions();+ }+}++function toggleBox({+ permissions,+ row,+ column,+ checked,+}: ToggleBoxParams): string[] {+ const next = new Set(permissions);+ if (column === 'edit' && row.edit) {+ if (checked) {+ next.add(row.edit);+ if (row.view) {+ next.add(row.view);+ }+ } else {+ next.delete(row.edit);+ }+ }+ if (column === 'view' && row.view && !row.viewAlwaysOn) {+ if (checked) {+ next.add(row.view);+ } else {+ next.delete(row.view);+ if (row.edit) {+ next.delete(row.edit);+ }+ }+ }+ return Array.from(next);+}++function changedRowKeys({+ permissions,+ base,+}: {+ permissions: string[];+ base: RoleBase;+}): string[] {+ const current = new Set(permissions);+ const original = new Set(basePermissions({ base }));+ return allRows()+ .filter((row) =>+ [row.view, row.edit].some(+ (permission) =>+ permission && current.has(permission) !== original.has(permission),+ ),+ )+ .map((row) => row.key);+}++export const rolePermissionModel = {+ groups,+ totalBoxes,+ grantedBoxes,+ basePermissions,+ toggleBox,+ changedRowKeys,+};++export const ROLE_BASES: RoleBase[] = ['Nothing', 'Viewer', 'Editor'];++export type RoleBase = 'Nothing' | 'Viewer' | 'Editor';++export type PermissionColumn = 'view' | 'edit';++export type PermissionRow = {+ key: string;+ label: string;+ view?: Permission;+ edit?: Permission;+ viewAlwaysOn?: boolean;+};++export type PermissionGroup = {+ key: string;+ label: string;+ rows: PermissionRow[];+};++type ToggleBoxParams = {+ permissions: string[];+ row: PermissionRow;+ column: PermissionColumn;+ checked: boolean;+};diff --git a/packages/web/src/features/platform-admin/hooks/project-role-hooks.ts b/packages/web/src/features/platform-admin/hooks/project-role-hooks.tsindex 3acdfb74c2a..f7569999182 100644--- a/packages/web/src/features/platform-admin/hooks/project-role-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/project-role-hooks.ts@@ -1,9 +1,11 @@-import { useMutation, useQuery } from '@tanstack/react-query';+import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';import { t } from 'i18next';import { toast } from 'sonner';import { projectRoleApi } from '../api/project-role-api';+const PROJECT_ROLE_MEMBERS_PAGE_SIZE = 100;+export const projectRoleKeys = {all: ['project-roles'] as const,members: (roleId: string) => ['users-with-project-roles', roleId] as const,@@ -17,19 +19,21 @@ export const projectRoleQueries = {enabled,}),useProjectRoleMembers: (roleId: string | undefined, enabled: boolean) =>- useQuery({+ useInfiniteQuery({queryKey: projectRoleKeys.members(roleId ?? ''),- queryFn: () =>+ queryFn: ({ pageParam }) =>projectRoleApi.listProjectMembers(roleId!, {- cursor: undefined,- limit: 10,+ cursor: pageParam,+ limit: PROJECT_ROLE_MEMBERS_PAGE_SIZE,}),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (lastPage) => lastPage.next ?? undefined,enabled: enabled && !!roleId,}),};export const projectRoleMutations = {- useUpsertProjectRole: ({ onSave }: { onSave: () => void }) => {+ useUpsertProjectRole: ({ onSave, onError }: UpsertProjectRoleHandlers) => {return useMutation({mutationFn: async ({mode,@@ -49,7 +53,11 @@ export const projectRoleMutations = {}},onSuccess: onSave,- onError: () => {+ onError: (error) => {+ if (onError) {+ onError(error);+ return;+ }toast.error(t('Role name already exists'), {duration: 3000,});@@ -66,10 +74,20 @@ export const projectRoleMutations = {duration: 3000,});},+ onError: () => {+ toast.error(t('Could not delete the role. Try again.'), {+ duration: 5000,+ });+ },});},};+type UpsertProjectRoleHandlers = {+ onSave: () => void;+ onError?: (error: unknown) => void;+};+type UpsertProjectRoleParams = {mode: 'create' | 'edit';roleId?: string;diff --git a/packages/web/test/features/members/lib/role-permissions.test.ts b/packages/web/test/features/members/lib/role-permissions.test.tsnew file mode 100644index 00000000000..e28ce66d080--- /dev/null+++ b/packages/web/test/features/members/lib/role-permissions.test.ts@@ -0,0 +1,232 @@+import { Permission } from '@activepieces/core-utils';+import { DefaultProjectRole, rolePermissions } from '@activepieces/shared';+import { describe, expect, it, vi } from 'vitest';++import {+ PermissionRow,+ rolePermissionModel,+} from '@/features/members/lib/role-permissions';++vi.mock('i18next', () => ({ t: (key: string) => key }));++const rows = (): PermissionRow[] =>+ rolePermissionModel.groups().flatMap((group) => group.rows);++const row = (key: string): PermissionRow => {+ const found = rows().find((candidate) => candidate.key === key);+ if (!found) {+ throw new Error(`no row for ${key}`);+ }+ return found;+};++const EXPECTED_MAPPING: [string, Permission | undefined, Permission | undefined][] =+ [+ ['flows', Permission.READ_FLOW, Permission.WRITE_FLOW],+ ['flow-status', undefined, Permission.UPDATE_FLOW_STATUS],+ ['folders', Permission.READ_FOLDER, Permission.WRITE_FOLDER],+ ['tables', Permission.READ_TABLE, Permission.WRITE_TABLE],+ ['agents', Permission.READ_AGENT, Permission.WRITE_AGENT],+ [+ 'knowledge-base',+ Permission.READ_KNOWLEDGE_BASE,+ Permission.WRITE_KNOWLEDGE_BASE,+ ],+ ['variables', Permission.READ_VARIABLE, Permission.WRITE_VARIABLE],+ ['mcp-servers', Permission.READ_MCP, Permission.WRITE_MCP],+ ['runs', Permission.READ_RUN, Permission.WRITE_RUN],+ ['alerts', Permission.READ_ALERT, Permission.WRITE_ALERT],+ [+ 'app-connections',+ Permission.READ_APP_CONNECTION,+ Permission.WRITE_APP_CONNECTION,+ ],+ [+ 'project-releases',+ Permission.READ_PROJECT_RELEASE,+ Permission.WRITE_PROJECT_RELEASE,+ ],+ [+ 'project-members',+ Permission.READ_PROJECT_MEMBER,+ Permission.WRITE_PROJECT_MEMBER,+ ],+ ['invitations', Permission.READ_INVITATION, Permission.WRITE_INVITATION],+ ['project-settings', Permission.READ_PROJECT, Permission.WRITE_PROJECT],+ ];++describe('the permission grid mapping', () => {+ it.each(EXPECTED_MAPPING)(+ '%s maps to the right view and edit permissions',+ (key, view, edit) => {+ expect(row(key).view).toBe(view);+ expect(row(key).edit).toBe(edit);+ },+ );++ it('lists every row exactly once, in the expected order', () => {+ expect(rows().map((candidate) => candidate.key)).toEqual(+ EXPECTED_MAPPING.map(([key]) => key),+ );+ });++ it('covers every Permission except the one deliberately left out', () => {+ const inGrid = new Set(+ rows().flatMap((candidate) =>+ [candidate.view, candidate.edit].filter(Boolean),+ ),+ );+ const missing = Object.values(Permission).filter(+ (permission) => !inGrid.has(permission),+ );+ expect(missing).toEqual([Permission.PUBLISH_SENSITIVE_FLOW_ACCESS]);+ });++ it('has 29 boxes, which is what the counter promises', () => {+ expect(rolePermissionModel.totalBoxes()).toBe(29);+ });++ it('keeps view permanently on only where a role cannot function without it', () => {+ expect(+ rows()+ .filter((candidate) => candidate.viewAlwaysOn)+ .map((candidate) => candidate.key),+ ).toEqual(['flows', 'project-settings']);+ });+});++describe('the built-in bases', () => {+ it.each([+ ['Nothing' as const, [Permission.READ_FLOW, Permission.READ_PROJECT], 2],+ ['Viewer' as const, rolePermissions[DefaultProjectRole.VIEWER], 12],+ ['Editor' as const, rolePermissions[DefaultProjectRole.EDITOR], 24],+ ])('%s seeds the stored set and counts %i', (base, expected, count) => {+ const permissions = rolePermissionModel.basePermissions({ base });+ expect(new Set(permissions)).toEqual(new Set(expected));+ expect(rolePermissionModel.grantedBoxes({ permissions })).toBe(count);+ });++ it('never counts a permission the grid does not show', () => {+ const adminBoxes = rolePermissionModel.grantedBoxes({+ permissions: rolePermissions[DefaultProjectRole.ADMIN],+ });+ expect(rolePermissions[DefaultProjectRole.ADMIN]).toContain(+ Permission.PUBLISH_SENSITIVE_FLOW_ACCESS,+ );+ expect(adminBoxes).toBe(rolePermissionModel.totalBoxes());+ });+});++describe('toggling a box', () => {+ it('turns view on with edit, because write without read is not a state the API has', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [],+ row: row('tables'),+ column: 'edit',+ checked: true,+ });+ expect(new Set(permissions)).toEqual(+ new Set([Permission.READ_TABLE, Permission.WRITE_TABLE]),+ );+ });++ it('clears edit when view goes off', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [Permission.READ_TABLE, Permission.WRITE_TABLE],+ row: row('tables'),+ column: 'view',+ checked: false,+ });+ expect(permissions).toEqual([]);+ });++ it('leaves edit alone when only edit goes off', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [Permission.READ_TABLE, Permission.WRITE_TABLE],+ row: row('tables'),+ column: 'edit',+ checked: false,+ });+ expect(permissions).toEqual([Permission.READ_TABLE]);+ });++ it('refuses to take away a view that is always on', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [Permission.READ_FLOW],+ row: row('flows'),+ column: 'view',+ checked: false,+ });+ expect(permissions).toEqual([Permission.READ_FLOW]);+ });++ it('ignores a view toggle on a row that has no view box', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [],+ row: row('flow-status'),+ column: 'view',+ checked: true,+ });+ expect(permissions).toEqual([]);+ });++ it('reaches exactly the three states the old None/Read/Write control offered', () => {+ const tables = row('tables');+ const none = rolePermissionModel.toggleBox({+ permissions: [Permission.READ_TABLE, Permission.WRITE_TABLE],+ row: tables,+ column: 'view',+ checked: false,+ });+ const read = rolePermissionModel.toggleBox({+ permissions: none,+ row: tables,+ column: 'view',+ checked: true,+ });+ const write = rolePermissionModel.toggleBox({+ permissions: read,+ row: tables,+ column: 'edit',+ checked: true,+ });+ expect([new Set(none), new Set(read), new Set(write)]).toEqual([+ new Set([]),+ new Set([Permission.READ_TABLE]),+ new Set([Permission.READ_TABLE, Permission.WRITE_TABLE]),+ ]);+ });+});++describe('marking what changed against a base', () => {+ it('finds nothing when the set is the base', () => {+ expect(+ rolePermissionModel.changedRowKeys({+ permissions: rolePermissionModel.basePermissions({ base: 'Viewer' }),+ base: 'Viewer',+ }),+ ).toEqual([]);+ });++ it('names the rows that differ, added or taken away', () => {+ const viewer = rolePermissionModel.basePermissions({ base: 'Viewer' });+ const withAlerts = rolePermissionModel.toggleBox({+ permissions: viewer,+ row: row('alerts'),+ column: 'view',+ checked: true,+ });+ const withoutTables = rolePermissionModel.toggleBox({+ permissions: withAlerts,+ row: row('tables'),+ column: 'view',+ checked: false,+ });+ expect(+ rolePermissionModel.changedRowKeys({+ permissions: withoutTables,+ base: 'Viewer',+ }),+ ).toEqual(['tables', 'alerts']);+ });+});