@bevel-software/platform-core-frontend 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +25 -0
  4. package/src/lib/email.ts +25 -0
  5. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +1 -1
  6. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +280 -4
  7. package/src/modules/access/api.ts +47 -13
  8. package/src/modules/access/components/ManageAccessDialog.tsx +119 -49
  9. package/src/modules/admin/__tests__/AdminRolesPage.capabilities.test.tsx +281 -0
  10. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +4 -4
  11. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +438 -0
  12. package/src/modules/admin/components/AdminRolesPage.tsx +203 -411
  13. package/src/modules/admin/components/DirectoryGroupsPage.tsx +610 -0
  14. package/src/modules/admin/hooks/useExclusiveRunner.ts +27 -0
  15. package/src/modules/admin/services/groups.api.ts +151 -0
  16. package/src/modules/admin/services/roles.api.ts +57 -31
  17. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +42 -3
  18. package/src/modules/library/__tests__/PluginPage.test.tsx +29 -0
  19. package/src/modules/library/__tests__/ToolPage.test.tsx +22 -0
  20. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +90 -0
  21. package/src/modules/library/components/LibraryPage.tsx +2 -2
  22. package/src/modules/library/components/PersonalPluginPage.tsx +2 -2
  23. package/src/modules/library/components/PluginPage.tsx +2 -2
  24. package/src/modules/library/components/tool-page/ToolPage.tsx +7 -1
  25. package/src/modules/library/routes/LibraryRoutes.tsx +6 -4
  26. package/src/modules/library/routes/WorkspaceItemRoute.tsx +33 -5
  27. package/src/modules/library/routes/library-paths.ts +30 -0
  28. package/src/modules/onboarding/__tests__/onboarding.test.tsx +63 -17
  29. package/src/modules/onboarding/agent-clients.ts +21 -7
  30. package/src/modules/onboarding/components/WelcomePage.tsx +1 -1
  31. package/src/modules/settings/settings-nav-items.tsx +9 -1
  32. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +135 -20
  33. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +113 -14
  34. package/src/shared/mcp/__tests__/connect-snippets.test.ts +66 -0
  35. package/src/shared/mcp/connect-snippets.ts +76 -0
  36. package/src/shared/mcp/index.ts +3 -0
@@ -25,6 +25,7 @@ import {
25
25
  revokeAccess,
26
26
  suggestPrincipals,
27
27
  asInheritedError,
28
+ type AccessEligible,
28
29
  type AccessResponse,
29
30
  type GrantVerb,
30
31
  type GrantSource,
@@ -32,6 +33,7 @@ import {
32
33
  type Principal,
33
34
  type SuggestResponse,
34
35
  } from '../api';
36
+ import { EMAIL_RE } from '../../../lib/email';
35
37
 
36
38
  interface Props {
37
39
  entry: FileTreeEntry;
@@ -42,8 +44,8 @@ interface Props {
42
44
  * it edits the branch the user is looking at.
43
45
  *
44
46
  * The Library is the other case: its surfaces describe the DEFAULT branch
45
- * regardless of which branch happens to be open, so a plugin's access edit
46
- * has to be pinned to it. Without this the same click would splice
47
+ * regardless of which branch happens to be open, so a Library item's access
48
+ * edit has to be pinned to it. Without this the same click would splice
47
49
  * `access.md` on whatever branch the context last had open — a rule written
48
50
  * into a draft nobody merges, silently doing nothing.
49
51
  */
@@ -76,7 +78,12 @@ interface PrincipalRow {
76
78
  label: string;
77
79
  sub?: string;
78
80
  verbs: VerbSet;
79
- isRole: boolean;
81
+ /**
82
+ * What the row is: a person, a ROLE (app-defined capability), or a GROUP
83
+ * (grant audience). Decides the badge ("Role" vs "Group") and which
84
+ * principal kind mutations round-trip with.
85
+ */
86
+ kind: 'user' | 'role' | 'group';
80
87
  isYou: boolean;
81
88
  /** The principal to send on grant / revoke. */
82
89
  principal: Principal;
@@ -146,6 +153,33 @@ function folderPath(accessMdPath: string): string {
146
153
  return dir === '' ? 'the root folder' : dir;
147
154
  }
148
155
 
156
+ /**
157
+ * A principal's row/chip identity. Kind is PART of it: a group and a role
158
+ * sharing a name are DIFFERENT principals server-side (bare token vs
159
+ * `role/<name>`), so they key — and chip — separately (`g:` vs `r:`). One
160
+ * name picked as both is two chips, and each grants its own kind.
161
+ */
162
+ function principalKey(p: Principal): string {
163
+ return p.kind === 'role'
164
+ ? `r:${p.role.toLowerCase()}`
165
+ : p.kind === 'group'
166
+ ? `g:${p.group.toLowerCase()}`
167
+ : `u:${p.email.toLowerCase()}`;
168
+ }
169
+
170
+ /**
171
+ * Look a row/principal key up in a response's `sources` map. Group rows key
172
+ * as `g:<name>`; an older server still keys groups under `r:<name>`, so a
173
+ * miss on `g:` falls back to the shared legacy key (version skew only — a
174
+ * current server emits `g:` for groups).
175
+ */
176
+ function lookupSources(
177
+ sources: AccessResponse['sources'] | undefined,
178
+ key: string,
179
+ ): GrantSources | undefined {
180
+ return sources?.[key] ?? (key.startsWith('g:') ? sources?.[`r:${key.slice(2)}`] : undefined);
181
+ }
182
+
149
183
  /** The distinct ancestor `access.md` path(s) named across a per-verb sources map. */
150
184
  function ancestorsFromSources(sources: GrantSources | undefined): string[] {
151
185
  if (!sources) return [];
@@ -188,8 +222,6 @@ function avatarTone(seed: string): { bg: string; fg: string } {
188
222
  return AVATAR_TONES[Math.abs(h) % AVATAR_TONES.length];
189
223
  }
190
224
 
191
- const EMAIL_RE = /^[^<>\s@]+@[^<>\s@]+\.[^<>\s@]+$/;
192
-
193
225
  /** Human noun for a verb, used in the verb-scoped confirmation copy. */
194
226
  const VERB_NOUN: Record<GrantVerb, string> = {
195
227
  owner: 'owner',
@@ -214,7 +246,7 @@ const ROLE_TO_KEY: Record<Role, keyof VerbSet> = {
214
246
  'Can download': 'download',
215
247
  };
216
248
 
217
- /** The built-in `everyone` plugin — grantable as public READ only (see backend). */
249
+ /** The built-in `everyone` role — grantable as public READ only (see backend). */
218
250
  function isEveryoneRole(p: Principal): boolean {
219
251
  return p.kind === 'role' && p.role.trim().toLowerCase() === 'everyone';
220
252
  }
@@ -362,7 +394,7 @@ function AnchoredMenu({
362
394
  /**
363
395
  * Google-Drive-style "Manage access" sheet. Reads the resolved access for a KB
364
396
  * path and lets anyone who can write the path's access config share it: add one
365
- * or more people/plugins as chips and grant them a shared verb (Owner / Can edit /
397
+ * or more people/groups/roles as chips and grant them a shared verb (Owner / Can edit /
366
398
  * Can read / Can download). Each existing grantee's verbs are editable inline via
367
399
  * a multi-select checklist (independent verbs); toggling a box grants or revokes
368
400
  * that single verb. Grants/revokes write the folder's `access.md` (folder target)
@@ -492,16 +524,28 @@ export function ManageAccessDialog({
492
524
  // so an owner legitimately shows owner+write+read checked; download is its own
493
525
  // axis (owner folds in, write does not), sourced from `downloaders`.
494
526
  const rows = new Map<string, PrincipalRow>();
495
- const touchRole = (role: string): PrincipalRow => {
496
- const key = `r:${role.toLowerCase()}`;
527
+ // Kinded collective list for one eligible set. Older servers omit
528
+ // `principals` (version skew) — fall back to the name-only `roles`,
529
+ // treating everything as a role (the pre-groups display).
530
+ const collectivesOf = (list: AccessEligible): { name: string; kind: 'role' | 'group' }[] =>
531
+ list.principals ?? list.roles.map((name) => ({ name, kind: 'role' as const }));
532
+ const touchCollective = (c: { name: string; kind: 'role' | 'group' }): PrincipalRow => {
533
+ // Rows are keyed by KIND + name (`g:`/`r:`) — the backend treats a bare
534
+ // `Product` (group) and `role/Product` (role) as DIFFERENT principals,
535
+ // so a group and a role sharing a name are two rows, each mutating its
536
+ // own grant. Collapsing them to one row silently pointed every edit at
537
+ // the group and hid the role's grant entirely.
538
+ const key =
539
+ c.kind === 'group' ? `g:${c.name.toLowerCase()}` : `r:${c.name.toLowerCase()}`;
497
540
  let row = rows.get(key);
498
541
  if (!row) {
499
542
  row = {
500
543
  key,
501
- label: role,
502
- isRole: true,
544
+ label: c.name,
545
+ kind: c.kind,
503
546
  isYou: false,
504
- principal: { kind: 'role', role },
547
+ principal:
548
+ c.kind === 'group' ? { kind: 'group', group: c.name } : { kind: 'role', role: c.name },
505
549
  verbs: { owner: false, write: false, read: false, download: false },
506
550
  manage: 'direct',
507
551
  ancestors: [],
@@ -522,7 +566,7 @@ export function ManageAccessDialog({
522
566
  // would otherwise render the same email twice, burning a row of the
523
567
  // scarce width on a duplicate.
524
568
  sub: label.toLowerCase() === u.email.toLowerCase() ? undefined : u.email,
525
- isRole: false,
569
+ kind: 'user',
526
570
  isYou: u.email.toLowerCase() === myEmail,
527
571
  principal: { kind: 'user', email: u.email, displayName: u.name || u.email },
528
572
  verbs: { owner: false, write: false, read: false, download: false },
@@ -534,23 +578,24 @@ export function ManageAccessDialog({
534
578
  return row;
535
579
  };
536
580
 
537
- for (const r of data.owners.roles) touchRole(r).verbs.owner = true;
581
+ for (const c of collectivesOf(data.owners)) touchCollective(c).verbs.owner = true;
538
582
  for (const u of data.owners.users) touchUser(u).verbs.owner = true;
539
- for (const r of data.eligible.roles) touchRole(r).verbs.write = true;
583
+ for (const c of collectivesOf(data.eligible)) touchCollective(c).verbs.write = true;
540
584
  for (const u of data.eligible.users) touchUser(u).verbs.write = true;
541
585
  // Read membership is per-principal only for a restricted node. When
542
586
  // `restricted` is false, read is `everyone` and the reader lists are empty.
543
587
  if (data.readers.restricted) {
544
- for (const r of data.readers.roles) touchRole(r).verbs.read = true;
588
+ for (const c of collectivesOf(data.readers)) touchCollective(c).verbs.read = true;
545
589
  for (const u of data.readers.users) touchUser(u).verbs.read = true;
546
590
  }
547
- for (const r of data.downloaders.roles) touchRole(r).verbs.download = true;
591
+ for (const c of collectivesOf(data.downloaders)) touchCollective(c).verbs.download = true;
548
592
  for (const u of data.downloaders.users) touchUser(u).verbs.download = true;
549
593
 
550
594
  // Attach each row's per-verb source + manageability (direct / inherited /
551
- // external) from the resolver's `sources` map, keyed by the same row key.
595
+ // external) from the resolver's `sources` map, keyed by the same row key
596
+ // (with the `g:` → `r:` version-skew fallback for group rows).
552
597
  for (const row of rows.values()) {
553
- row.sources = data.sources?.[row.key];
598
+ row.sources = lookupSources(data.sources, row.key);
554
599
  const { manage, ancestors } = classifyManage(row.sources);
555
600
  row.manage = manage;
556
601
  row.ancestors = ancestors;
@@ -569,7 +614,7 @@ export function ManageAccessDialog({
569
614
  );
570
615
 
571
616
  /**
572
- * The inherited rows, ONE PLUGIN PER GRANTING FOLDER — the prototype's shape
617
+ * The inherited rows, ONE SECTION PER GRANTING FOLDER — the prototype's shape
573
618
  * (proto:3637-3649) and, more to the point, its reasoning:
574
619
  *
575
620
  * "Inheritance, said as a sentence instead of labelled as a concept.
@@ -626,18 +671,23 @@ export function ManageAccessDialog({
626
671
  const canManage = !!data?.canWrite;
627
672
 
628
673
  // Resolve the CURRENT typed query into a principal to append as a chip: an
629
- // exact plugin match or a free-typed email. (Suggestion clicks append directly.)
674
+ // exact group/role match or a free-typed email. (Suggestion clicks append
675
+ // directly.) Group first — bare grant tokens resolve group-first, so a name
676
+ // shared by both defaults to the audience concept; the role stays reachable
677
+ // via its own suggestion row.
630
678
  const addPending: Principal | null = useMemo(() => {
631
679
  const q = query.trim();
632
680
  if (!q) return null;
633
- const pluginHit = suggest?.plugins.find((g) => g.toLowerCase() === q.toLowerCase());
634
- if (pluginHit) return { kind: 'role', role: pluginHit };
681
+ const groupHit = suggest?.groups?.find((g) => g.toLowerCase() === q.toLowerCase());
682
+ if (groupHit) return { kind: 'group', group: groupHit };
683
+ const roleHit = suggest?.roles?.find((g) => g.toLowerCase() === q.toLowerCase());
684
+ if (roleHit) return { kind: 'role', role: roleHit };
635
685
  if (EMAIL_RE.test(q)) return { kind: 'user', email: q, displayName: q.split('@')[0] };
636
686
  return null;
637
687
  }, [query, suggest]);
638
688
 
639
- const principalKey = (p: Principal): string =>
640
- p.kind === 'role' ? `r:${p.role.toLowerCase()}` : `u:${p.email.toLowerCase()}`;
689
+ const principalLabel = (p: Principal): string =>
690
+ p.kind === 'role' ? p.role : p.kind === 'group' ? p.group : p.displayName || p.email;
641
691
 
642
692
  const addChip = useCallback((p: Principal) => {
643
693
  setPickedChips((chips) =>
@@ -687,7 +737,7 @@ export function ManageAccessDialog({
687
737
  const failures: string[] = [];
688
738
  try {
689
739
  for (const principal of pickedChips) {
690
- const label = principal.kind === 'role' ? principal.role : principal.email;
740
+ const label = principalLabel(principal);
691
741
  // `everyone` is public-read only — the backend rejects any other verb for
692
742
  // it, so clamp here to avoid a guaranteed failure when a higher verb is
693
743
  // also selected for the other chips.
@@ -767,8 +817,8 @@ export function ManageAccessDialog({
767
817
 
768
818
  // Toggle a single verb on an existing grantee: check → grant that verb, uncheck
769
819
  // → revoke just that verb. The server's fresh view is authoritative (we never
770
- // flip optimistically); a refused revoke (e.g. last-owner) surfaces its message
771
- // and we re-sync.
820
+ // flip optimistically); a refused revoke (e.g. lock contention) surfaces its
821
+ // message and we re-sync.
772
822
  const doToggleVerb = useCallback(
773
823
  async (principal: Principal, role: Role, currentlyOn: boolean) => {
774
824
  if (!workspaceId || repoRelative === null) return;
@@ -797,15 +847,16 @@ export function ManageAccessDialog({
797
847
  // so one uncheck finishes the job instead of a half-removal (the direct
798
848
  // bit gone, the inherited bit silently remaining and the box re-checking).
799
849
  if (currentlyOn) {
800
- const key = principal.kind === 'role'
801
- ? `r:${principal.role.toLowerCase()}`
802
- : `u:${principal.email.toLowerCase()}`;
803
- const stillForVerb = res.sources?.[key]?.[grantVerb] ?? [];
850
+ const key = principalKey(principal);
851
+ const stillForVerb = lookupSources(res.sources, key)?.[grantVerb] ?? [];
804
852
  const ancestors = ancestorsFromSources({ [grantVerb]: stillForVerb });
805
853
  if (ancestors.length > 0) {
806
- const label =
807
- principal.kind === 'role' ? principal.role : principal.displayName || principal.email;
808
- setConfirmRemove({ principal, label, ancestors, verb: grantVerb });
854
+ setConfirmRemove({
855
+ principal,
856
+ label: principalLabel(principal),
857
+ ancestors,
858
+ verb: grantVerb,
859
+ });
809
860
  }
810
861
  }
811
862
  } catch (err) {
@@ -815,8 +866,7 @@ export function ManageAccessDialog({
815
866
  // "Remove from parent?" flow a Remove uses, instead of a raw error toast.
816
867
  const inherited = asInheritedError(err);
817
868
  if (inherited) {
818
- const label =
819
- principal.kind === 'role' ? principal.role : principal.displayName || principal.email;
869
+ const label = principalLabel(principal);
820
870
  // Scope the confirmation to the single verb the user unchecked, so
821
871
  // "Restrict just this file" / "Remove from parent" act on THAT verb
822
872
  // only and leave the principal's other (e.g. direct download) verbs.
@@ -865,7 +915,7 @@ export function ManageAccessDialog({
865
915
  // finish the job instead of leaving a row that reappears as inherited (a
866
916
  // silent half-removal). We read the just-revoked row's post-revoke sources
867
917
  // straight from the response, so it reflects the real current tree.
868
- const ancestors = ancestorsFromSources(res.sources?.[row.key]);
918
+ const ancestors = ancestorsFromSources(lookupSources(res.sources, row.key));
869
919
  if (ancestors.length > 0) {
870
920
  setConfirmRemove({ principal: row.principal, label: row.label, ancestors });
871
921
  }
@@ -966,7 +1016,7 @@ export function ManageAccessDialog({
966
1016
  // squeezing the name to zero width — which left the `Role` badge sitting
967
1017
  // on top of the "via …" label and pushed Remove off the panel's edge.
968
1018
  <div key={p.key} className="flex flex-wrap items-center gap-x-3 gap-y-1 py-2">
969
- {p.isRole ? (
1019
+ {p.kind !== 'user' ? (
970
1020
  <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-sunken text-detail font-bold text-ink-muted">
971
1021
  {initials(p.label)}
972
1022
  </span>
@@ -982,9 +1032,11 @@ export function ManageAccessDialog({
982
1032
  <div className="flex min-w-0 items-center gap-1.5">
983
1033
  <span className="truncate text-ui font-medium text-ink">{p.label}</span>
984
1034
  {p.isYou && <span className="shrink-0 text-ui text-ink-faint">(you)</span>}
985
- {p.isRole && (
1035
+ {p.kind !== 'user' && (
1036
+ // The same chip vocabulary as the suggest menu's trailing tags:
1037
+ // a role is a capability, a group is an audience — badge which.
986
1038
  <Badge tone="outline" size="xs" className="shrink-0 uppercase">
987
- Role
1039
+ {p.kind === 'group' ? 'Group' : 'Role'}
988
1040
  </Badge>
989
1041
  )}
990
1042
  </div>
@@ -1008,8 +1060,8 @@ export function ManageAccessDialog({
1008
1060
  </Button>
1009
1061
  </div>
1010
1062
  ) : canManage && p.manage === 'external' ? (
1011
- // No file-backed grant to remove here — managed elsewhere (a plugin's
1012
- // membership, the everyone policy, or admin rescue).
1063
+ // No file-backed grant to remove here — managed elsewhere (a role or
1064
+ // group's membership, the everyone policy, or admin rescue).
1013
1065
  <span
1014
1066
  className="ml-auto shrink-0 text-detail text-ink-faint"
1015
1067
  title="Granted via a role or policy. Manage it there"
@@ -1115,7 +1167,7 @@ export function ManageAccessDialog({
1115
1167
  treatment as the primitive, wrapped so the chips can wrap. */}
1116
1168
  <div className="flex w-full flex-wrap items-center gap-1.5 rounded-md border border-line-strong bg-surface px-2 py-1 focus-within:border-transparent focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-accent">
1117
1169
  {pickedChips.map((c) => {
1118
- const label = c.kind === 'role' ? c.role : c.displayName || c.email;
1170
+ const label = principalLabel(c);
1119
1171
  return (
1120
1172
  <span
1121
1173
  key={principalKey(c)}
@@ -1142,13 +1194,31 @@ export function ManageAccessDialog({
1142
1194
  addChip(addPending);
1143
1195
  }
1144
1196
  }}
1145
- placeholder={pickedChips.length ? '' : 'Add people or roles…'}
1197
+ placeholder={pickedChips.length ? '' : 'Add people, groups, or roles…'}
1146
1198
  className="min-w-32 flex-1 bg-transparent px-1 py-1 text-ui text-ink placeholder:text-ink-faint focus:outline-none"
1147
1199
  />
1148
1200
  </div>
1149
- {query.trim() && suggest && (suggest.plugins.length > 0 || suggest.people.length > 0) && (
1201
+ {/* Defensive `?? []` on every field: a suggest response missing
1202
+ `roles` or `groups` (version skew) must degrade to an empty
1203
+ section, never a crash. Groups lead — they are the audience
1204
+ concept grants are meant for; roles remain grantable below. */}
1205
+ {query.trim() && suggest && ((suggest.groups?.length ?? 0) > 0 || (suggest.roles?.length ?? 0) > 0 || (suggest.people?.length ?? 0) > 0) && (
1150
1206
  <AnchoredMenu width="anchor" align="left" className="max-h-56 overflow-auto">
1151
- {suggest.plugins.map((g) => (
1207
+ {(suggest.groups ?? []).map((g) => (
1208
+ <MenuItem
1209
+ key={`grp:${g}`}
1210
+ onClick={() => addChip({ kind: 'group', group: g })}
1211
+ trailing={
1212
+ <span className="text-label uppercase text-ink-faint">group</span>
1213
+ }
1214
+ >
1215
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-sunken text-label font-bold text-ink-muted">
1216
+ {initials(g)}
1217
+ </span>
1218
+ <span className="min-w-0 flex-1 truncate">{g}</span>
1219
+ </MenuItem>
1220
+ ))}
1221
+ {(suggest.roles ?? []).map((g) => (
1152
1222
  <MenuItem
1153
1223
  key={`g:${g}`}
1154
1224
  onClick={() => addChip({ kind: 'role', role: g })}
@@ -1162,7 +1232,7 @@ export function ManageAccessDialog({
1162
1232
  <span className="min-w-0 flex-1 truncate">{g}</span>
1163
1233
  </MenuItem>
1164
1234
  ))}
1165
- {suggest.people.map((p) => {
1235
+ {(suggest.people ?? []).map((p) => {
1166
1236
  const tone = avatarTone(p.name || p.email);
1167
1237
  return (
1168
1238
  <MenuItem
@@ -1250,7 +1320,7 @@ export function ManageAccessDialog({
1250
1320
  </div>
1251
1321
  {query.trim() && !addPending && !suggest?.peopleWithheld && (
1252
1322
  <p className="mt-1.5 text-detail text-ink-muted">
1253
- Type a full email to add someone, or pick a role from the list.
1323
+ Type a full email to add someone, or pick a group or role from the list.
1254
1324
  </p>
1255
1325
  )}
1256
1326
  {pickedChips.some(isEveryoneRole) && (
@@ -0,0 +1,281 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, waitFor, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { AdminRolesPage } from '../components/AdminRolesPage';
5
+ import { AdminContext } from '../state/admin.context';
6
+ import {
7
+ addMember,
8
+ assignGroup,
9
+ convertRoleToGroup,
10
+ fetchRoles,
11
+ removeMember,
12
+ RolesApiError,
13
+ unassignGroup,
14
+ type RoleRosterEntry,
15
+ } from '../services/roles.api';
16
+
17
+ vi.mock('../services/roles.api', async (importOriginal) => {
18
+ const actual = await importOriginal<typeof import('../services/roles.api')>();
19
+ return {
20
+ ...actual,
21
+ fetchRoles: vi.fn(),
22
+ addMember: vi.fn(),
23
+ removeMember: vi.fn(),
24
+ assignGroup: vi.fn(),
25
+ unassignGroup: vi.fn(),
26
+ convertRoleToGroup: vi.fn(),
27
+ };
28
+ });
29
+ vi.mock('../../access/api', async (importOriginal) => {
30
+ const actual = await importOriginal<typeof import('../../access/api')>();
31
+ return { ...actual, suggestPrincipals: vi.fn() };
32
+ });
33
+ import { suggestPrincipals } from '../../access/api';
34
+
35
+ // Matches the real registry: Admin IS group-assignable — the backend's
36
+ // parse-time invariant (≥1 direct email member) is what keeps a directory
37
+ // outage from ever locking the deployment out, not a UI refusal.
38
+ const ADMIN: RoleRosterEntry = {
39
+ canonical: 'admin',
40
+ displayName: 'Admin',
41
+ members: ['root@example.com'],
42
+ groups: [],
43
+ capability: { description: 'Full administrative access.', groupAssignable: true },
44
+ isAdmin: true,
45
+ referencedBy: [],
46
+ };
47
+
48
+ // A capability role whose registry entry opts out of group assignment.
49
+ const OPTED_OUT: RoleRosterEntry = {
50
+ canonical: 'auditor',
51
+ displayName: 'Auditor',
52
+ members: [],
53
+ groups: [],
54
+ capability: { description: 'Read-only audit access.', groupAssignable: false },
55
+ isAdmin: false,
56
+ referencedBy: [],
57
+ };
58
+
59
+ const EDITOR: RoleRosterEntry = {
60
+ canonical: 'editor',
61
+ displayName: 'Editor',
62
+ members: [],
63
+ groups: ['engineering'],
64
+ capability: { description: 'Can edit everything.', groupAssignable: true },
65
+ isAdmin: false,
66
+ referencedBy: [],
67
+ };
68
+
69
+ // A legacy people-set role: no capability behind it — gets the Convert action.
70
+ const LEGACY: RoleRosterEntry = {
71
+ canonical: 'product',
72
+ displayName: 'Product',
73
+ members: ['pat@example.com'],
74
+ groups: [],
75
+ capability: null,
76
+ isAdmin: false,
77
+ referencedBy: [],
78
+ };
79
+
80
+ function renderPage() {
81
+ return render(
82
+ <AdminContext.Provider
83
+ value={{
84
+ isAdmin: true,
85
+ unreadCount: 0,
86
+ lastSeen: null,
87
+ markSeen: () => {},
88
+ refresh: () => {},
89
+ rolesConfigCorrupted: false,
90
+ rolesConfigErrors: [],
91
+ runRolesRecovery: async () => {},
92
+ }}
93
+ >
94
+ <AdminRolesPage />
95
+ </AdminContext.Provider>,
96
+ );
97
+ }
98
+
99
+ /** The card that owns a role heading — scopes queries to one role's row. */
100
+ async function findCard(name: string): Promise<HTMLElement> {
101
+ const heading = await screen.findByRole('heading', { name });
102
+ return heading.closest('div.rounded-lg') as HTMLElement;
103
+ }
104
+
105
+ const ALL = [ADMIN, OPTED_OUT, EDITOR, LEGACY];
106
+
107
+ beforeEach(() => {
108
+ vi.mocked(suggestPrincipals)
109
+ .mockReset()
110
+ .mockResolvedValue({ roles: [], groups: [], people: [], peopleWithheld: false });
111
+ vi.mocked(fetchRoles).mockReset().mockResolvedValue(ALL);
112
+ vi.mocked(addMember).mockReset().mockResolvedValue(ALL);
113
+ vi.mocked(removeMember).mockReset().mockResolvedValue(ALL);
114
+ vi.mocked(assignGroup).mockReset().mockResolvedValue(ALL);
115
+ vi.mocked(unassignGroup).mockReset().mockResolvedValue(ALL);
116
+ vi.mocked(convertRoleToGroup).mockReset().mockResolvedValue([ADMIN, OPTED_OUT, EDITOR]);
117
+ });
118
+
119
+ describe('AdminRolesPage: capabilities, groups, and legacy conversion', () => {
120
+ it('renders the capability description under a role that has one', async () => {
121
+ renderPage();
122
+ expect(await screen.findByText('Full administrative access.')).toBeInTheDocument();
123
+ expect(screen.getByText('Can edit everything.')).toBeInTheDocument();
124
+ });
125
+
126
+ it('group assignment follows the roster payload: Admin (assignable) gets the control, an opted-out role does not', async () => {
127
+ renderPage();
128
+ // Admin: the registry says groupAssignable — the UI offers assignment
129
+ // (the ≥1-direct-email invariant is the backend's guard, not a UI ban)
130
+ // but NEVER a Convert action (it is a capability role).
131
+ const adminCard = within(await findCard('Admin'));
132
+ expect(adminCard.getByRole('textbox', { name: 'Assign group' })).toBeInTheDocument();
133
+ expect(
134
+ adminCard.queryByRole('button', { name: 'Convert to group' }),
135
+ ).not.toBeInTheDocument();
136
+ // Opted out in the registry: no assignment UI, no Convert either.
137
+ const optedOutCard = within(await findCard('Auditor'));
138
+ expect(optedOutCard.queryByRole('textbox', { name: 'Assign group' })).not.toBeInTheDocument();
139
+ expect(optedOutCard.queryByText('Assigned groups')).not.toBeInTheDocument();
140
+ expect(
141
+ optedOutCard.queryByRole('button', { name: 'Convert to group' }),
142
+ ).not.toBeInTheDocument();
143
+ });
144
+
145
+ it('renders group chips and assigns a group through the endpoint', async () => {
146
+ renderPage();
147
+ const editorCard = within(await findCard('Editor'));
148
+ expect(editorCard.getByText('engineering')).toBeInTheDocument();
149
+
150
+ await userEvent.type(editorCard.getByRole('textbox', { name: 'Assign group' }), 'design');
151
+ await userEvent.click(editorCard.getByRole('button', { name: 'Assign' }));
152
+ await waitFor(() => expect(assignGroup).toHaveBeenCalledWith('editor', 'design'));
153
+ });
154
+
155
+ it('removes a group chip through the endpoint', async () => {
156
+ renderPage();
157
+ const editorCard = within(await findCard('Editor'));
158
+ await userEvent.click(editorCard.getByRole('button', { name: 'Remove group engineering' }));
159
+ await waitFor(() => expect(unassignGroup).toHaveBeenCalledWith('editor', 'engineering'));
160
+ });
161
+
162
+ it('a legacy role WITHOUT assignments gets Convert and no assigned-groups section', async () => {
163
+ renderPage();
164
+ const legacyCard = within(await findCard('Product'));
165
+ expect(legacyCard.getByRole('button', { name: 'Convert to group' })).toBeInTheDocument();
166
+ // Nothing assigned and nothing assignable — no section at all. Offering
167
+ // the assign input here would dead-end the Convert path (a group-assigned
168
+ // role can't be converted).
169
+ expect(legacyCard.queryByText('Assigned groups')).not.toBeInTheDocument();
170
+ expect(legacyCard.queryByRole('textbox', { name: 'Assign group' })).not.toBeInTheDocument();
171
+ });
172
+
173
+ it('a legacy role WITH assignments keeps the chips and remove control — but no add input', async () => {
174
+ // A legacy role can already carry assignments (hand-edited roles.yaml, or
175
+ // assigned before the gating existed). convertRoleToGroup refuses until
176
+ // they're removed, so the unassign controls MUST stay reachable.
177
+ const legacyAssigned: RoleRosterEntry = { ...LEGACY, groups: ['engineering'] };
178
+ vi.mocked(fetchRoles).mockResolvedValue([ADMIN, EDITOR, legacyAssigned]);
179
+ renderPage();
180
+ const legacyCard = within(await findCard('Product'));
181
+ expect(legacyCard.getByText('Assigned groups')).toBeInTheDocument();
182
+ expect(legacyCard.getByText('engineering')).toBeInTheDocument();
183
+ // The add input stays hidden — only removal is offered on a legacy role.
184
+ expect(legacyCard.queryByRole('textbox', { name: 'Assign group' })).not.toBeInTheDocument();
185
+ expect(legacyCard.queryByRole('button', { name: 'Assign' })).not.toBeInTheDocument();
186
+ // The remove control works and hits the endpoint.
187
+ await userEvent.click(legacyCard.getByRole('button', { name: 'Remove group engineering' }));
188
+ await waitFor(() => expect(unassignGroup).toHaveBeenCalledWith('product', 'engineering'));
189
+ });
190
+
191
+ it('legacy role converts only after an explicit confirm, refreshing from the response', async () => {
192
+ renderPage();
193
+ const legacyCard = within(await findCard('Product'));
194
+ await userEvent.click(legacyCard.getByRole('button', { name: 'Convert to group' }));
195
+ expect(convertRoleToGroup).not.toHaveBeenCalled();
196
+
197
+ const dialog = within(screen.getByRole('dialog'));
198
+ expect(dialog.getByText(/Grants keep working/)).toBeInTheDocument();
199
+ await userEvent.click(dialog.getByRole('button', { name: 'Convert' }));
200
+ await waitFor(() => expect(convertRoleToGroup).toHaveBeenCalledWith('product'));
201
+ // The response no longer contains the role — its card is gone.
202
+ await waitFor(() =>
203
+ expect(screen.queryByRole('heading', { name: 'Product' })).not.toBeInTheDocument(),
204
+ );
205
+ });
206
+
207
+ it('a convert refusal surfaces the backend message on the card', async () => {
208
+ vi.mocked(convertRoleToGroup).mockRejectedValue(
209
+ new Error('A group named "product" already exists.'),
210
+ );
211
+ renderPage();
212
+ const card = await findCard('Product');
213
+ await userEvent.click(within(card).getByRole('button', { name: 'Convert to group' }));
214
+ await userEvent.click(
215
+ within(screen.getByRole('dialog')).getByRole('button', { name: 'Convert' }),
216
+ );
217
+ expect(
218
+ await within(card).findByText('A group named "product" already exists.'),
219
+ ).toBeInTheDocument();
220
+ });
221
+
222
+ it('non-Admin roles with a capability do not offer Convert', async () => {
223
+ renderPage();
224
+ const editorCard = within(await findCard('Editor'));
225
+ expect(
226
+ editorCard.queryByRole('button', { name: 'Convert to group' }),
227
+ ).not.toBeInTheDocument();
228
+ });
229
+ });
230
+
231
+ describe('AdminRolesPage: membership-only surface', () => {
232
+ it('offers NO create / rename / delete affordances — roles are app-defined', async () => {
233
+ renderPage();
234
+ await screen.findByRole('heading', { name: 'Admin' });
235
+ // Roles cannot be minted, rebranded, or retired from the UI (the backend
236
+ // routes are gone too): no New-role control, no rename pencil, no trash.
237
+ expect(screen.queryByRole('button', { name: /new role/i })).not.toBeInTheDocument();
238
+ expect(screen.queryByRole('textbox', { name: /new role name/i })).not.toBeInTheDocument();
239
+ expect(screen.queryByRole('button', { name: /rename role/i })).not.toBeInTheDocument();
240
+ expect(screen.queryByRole('button', { name: /delete role/i })).not.toBeInTheDocument();
241
+ // What remains is membership: member emails and (where assignable) groups.
242
+ const adminCard = within(await findCard('Admin'));
243
+ expect(adminCard.getByRole('textbox', { name: 'Member email' })).toBeInTheDocument();
244
+ });
245
+
246
+ it('the Admin ≥1-direct-email 422 renders the backend message inline on the card', async () => {
247
+ // Two direct members, so the client-side last-member disable does not
248
+ // trip — the backend is the authority (e.g. a concurrent edit already
249
+ // removed the other member) and answers 422 with the invariant message.
250
+ const adminTwo: RoleRosterEntry = {
251
+ ...ADMIN,
252
+ members: ['root@example.com', 'second@example.com'],
253
+ };
254
+ vi.mocked(fetchRoles).mockResolvedValue([adminTwo, EDITOR]);
255
+ const invariant =
256
+ 'The Admin role must keep at least one direct email member — group references alone are not enough.';
257
+ vi.mocked(removeMember).mockRejectedValue(new RolesApiError(invariant, 422));
258
+
259
+ renderPage();
260
+ const adminCard = within(await findCard('Admin'));
261
+ await userEvent.click(adminCard.getByRole('button', { name: 'Remove second@example.com' }));
262
+ // The exact backend message, inline on the card — not a generic failure.
263
+ expect(await adminCard.findByText(invariant)).toBeInTheDocument();
264
+ // The optimistic hide rolled back: the member chip is visible again.
265
+ expect(adminCard.getByText('second@example.com')).toBeInTheDocument();
266
+ });
267
+
268
+ it("a 'group:'-prefixed member value gets the inline hint and no request", async () => {
269
+ renderPage();
270
+ const editorCard = within(await findCard('Editor'));
271
+ await userEvent.type(
272
+ editorCard.getByRole('textbox', { name: 'Member email' }),
273
+ 'group:engineering',
274
+ );
275
+ await userEvent.click(editorCard.getByRole('button', { name: 'Add' }));
276
+ expect(
277
+ await editorCard.findByText(/Members are emails — to give this role to a group/),
278
+ ).toBeInTheDocument();
279
+ expect(addMember).not.toHaveBeenCalled();
280
+ });
281
+ });