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

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
@@ -1,19 +1,21 @@
1
1
  import { useCallback, useEffect, useId, useRef, useState } from 'react';
2
- import { Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';
2
+ import { Loader2, UsersRound, X } from 'lucide-react';
3
3
  import { PageShell } from '../../../shared/components/PageShell';
4
4
  import { DEFAULT_BRANCH } from '@bevel-software/platform-shared';
5
5
  import { useAdmin } from '../state/admin.context';
6
6
  import {
7
7
  addMember,
8
- createRole,
9
- deleteRole,
8
+ assignGroup,
9
+ convertRoleToGroup,
10
10
  fetchRoles,
11
11
  removeMember,
12
- renameRole,
13
12
  RolesApiError,
13
+ unassignGroup,
14
14
  type RoleRosterEntry,
15
15
  } from '../services/roles.api';
16
16
  import { suggestPrincipals } from '../../access/api';
17
+ import { EMAIL_RE, isGroupPrefixed } from '../../../lib/email';
18
+ import { useExclusiveRunner, type ExclusiveRunner } from '../hooks/useExclusiveRunner';
17
19
 
18
20
  /** The default-branch workspace id — roles are managed there (admin status derives from it). */
19
21
  // A function, not a constant: the branch model arrives from `/api/config`
@@ -21,29 +23,6 @@ import { suggestPrincipals } from '../../access/api';
21
23
  // string that exists before it.
22
24
  const rolesWorkspaceId = () => encodeURIComponent(DEFAULT_BRANCH);
23
25
 
24
- const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
25
-
26
- // Mirror of the backend's canonicalRoleName (access-control.service.ts) so an
27
- // optimistic create can compute the same canonical the server will assign,
28
- // keeping the placeholder card's identity stable until the roster reconciles.
29
- function canonicalRoleName(name: string): string {
30
- return name.trim().toLowerCase().replace(/\s+/g, ' ');
31
- }
32
-
33
- // Advisory client-side validation for a new role name. Mirrors the backend
34
- // invariants so the user gets instant feedback; the server still has final say.
35
- function validateNewRoleName(name: string): string | null {
36
- const trimmed = name.trim();
37
- if (!trimmed) return 'Enter a role name.';
38
- const lower = trimmed.toLowerCase();
39
- if (lower === 'deny' || lower === 'everyone') {
40
- return `"${trimmed}" is a reserved name.`;
41
- }
42
- if (/[:#<>]/.test(trimmed)) return 'A role name can’t contain : # < >.';
43
- if (trimmed.startsWith('-')) return 'A role name can’t start with "-".';
44
- return null;
45
- }
46
-
47
26
  function errMessage(err: unknown, fallback: string): string {
48
27
  if (err instanceof Error) return err.message;
49
28
  return fallback;
@@ -58,10 +37,6 @@ function initials(value: string): string {
58
37
  return name.slice(0, 2).toUpperCase();
59
38
  }
60
39
 
61
- interface DeleteTarget {
62
- role: RoleRosterEntry;
63
- }
64
-
65
40
  interface SelfRemoveTarget {
66
41
  canonical: string;
67
42
  email: string;
@@ -72,6 +47,13 @@ interface SelfRemoveTarget {
72
47
  * persistent toolbar). Admin-gated: non-admins get a clear "Admins only"
73
48
  * state instead of the roster (the backend enforces the same gate on every
74
49
  * roles endpoint — this is presentation, not the security boundary).
50
+ *
51
+ * MEMBERSHIP ONLY. Roles are app-defined capabilities: the product decides
52
+ * which roles exist, so there is deliberately no create / rename / delete
53
+ * here (the backend routes are gone too). What an admin edits is who HOLDS
54
+ * each role — individual emails, and group assignments on roles whose
55
+ * capability allows it. Legacy pre-split people-set roles remain
56
+ * membership-editable, with "Convert to group" as their migration path.
75
57
  */
76
58
  export function AdminRolesPage() {
77
59
  const { isAdmin } = useAdmin();
@@ -79,22 +61,16 @@ export function AdminRolesPage() {
79
61
  const [loading, setLoading] = useState(true);
80
62
  const [error, setError] = useState<string | null>(null);
81
63
 
82
- // Optimistic list reshaping. A pending create appends a placeholder card; a
83
- // pending delete hides the card by canonical. Both reconcile against the
84
- // authoritative roster each mutation returns (or roll back on error).
85
- const [pendingCreates, setPendingCreates] = useState<RoleRosterEntry[]>([]);
86
- const [pendingDeletes, setPendingDeletes] = useState<Set<string>>(new Set());
87
- // Delete errors, keyed by canonical. Owned here (not on the card) because a
88
- // delete optimistically unmounts the card before the commit settles; on
89
- // failure the card is restored as a NEW instance, so a card-local setError
90
- // would land on the unmounted one and vanish. Parent-owned, it survives the
91
- // hide→restore cycle and reaches the restored card by canonical.
92
- const [deleteErrors, setDeleteErrors] = useState<Record<string, string>>({});
93
-
94
64
  // Bump on every load so a stale in-flight response never overwrites the
95
- // current roster.
65
+ // current roster. (The initial fetch does NOT go through the exclusive
66
+ // runner, so — unlike the Groups page — a mutation response can still race
67
+ // it; the bump in applyRoster is what drops the superseded load.)
96
68
  const requestId = useRef(0);
97
69
 
70
+ // All roster mutations queue through here — see useExclusiveRunner. The
71
+ // per-card busy/optimistic UX is untouched; only the requests serialize.
72
+ const runExclusive = useExclusiveRunner();
73
+
98
74
  // Load the roster on mount (and again if admin status resolves later —
99
75
  // AdminProvider fetches admin status asynchronously, so `isAdmin` can flip
100
76
  // to true after the first render). All setState happens in the async
@@ -123,12 +99,7 @@ export function AdminRolesPage() {
123
99
  };
124
100
  }, [isAdmin]);
125
101
 
126
- // Each mutation returns the fresh roster — set it directly (refetch-only) and
127
- // reconcile the optimistic sets in the same update, while the authoritative
128
- // rows are in hand: drop a pending create once its real card appears, and a
129
- // pending delete once the card is actually gone. Doing this here (rather than
130
- // in a roster-watching effect) avoids effect-driven cascading setState — and
131
- // a placeholder double-listing, or a no-op/failed delete hiding a card.
102
+ // Each mutation returns the fresh roster — set it directly (refetch-only).
132
103
  const applyRoster = useCallback((rows: RoleRosterEntry[]) => {
133
104
  // Bump so any in-flight load() result is dropped in favour of this fresher
134
105
  // mutation response.
@@ -140,118 +111,42 @@ export function AdminRolesPage() {
140
111
  // stuck spinning, or showing a stale load error under fresh rows.
141
112
  setLoading(false);
142
113
  setError(null);
143
- const present = new Set(rows.map((r) => r.canonical));
144
- setPendingCreates((prev) => {
145
- if (prev.length === 0) return prev;
146
- const next = prev.filter((c) => !present.has(c.canonical));
147
- return next.length === prev.length ? prev : next;
148
- });
149
- setPendingDeletes((prev) => {
150
- if (prev.size === 0) return prev;
151
- const next = new Set([...prev].filter((c) => present.has(c)));
152
- return next.size === prev.size ? prev : next;
153
- });
154
114
  }, []);
155
115
 
156
- // Optimistic create: show a placeholder card immediately, fire the commit in
157
- // the background, reconcile (or roll back the placeholder on error).
158
- const createOptimistic = useCallback(
159
- async (displayName: string): Promise<string | null> => {
160
- const canonical = canonicalRoleName(displayName);
161
- // No client-side duplicate guard: a reserved/duplicate name is left to the
162
- // server, which rolls the placeholder back and surfaces its precise error.
163
- const placeholder: RoleRosterEntry = {
164
- canonical,
165
- displayName: displayName.trim(),
166
- members: [],
167
- isAdmin: false,
168
- referencedBy: [],
169
- };
170
- setPendingCreates((prev) => [...prev, placeholder]);
171
- try {
172
- const rows = await createRole(displayName.trim());
173
- applyRoster(rows);
174
- return null;
175
- } catch (err) {
176
- setPendingCreates((prev) => prev.filter((c) => c.canonical !== canonical));
177
- return errMessage(err, 'Failed to create role');
178
- }
179
- },
180
- [applyRoster],
181
- );
182
-
183
- // Optimistic delete: hide the card immediately, fire the commit, reconcile
184
- // (or roll back the hide on error).
185
- const deleteOptimistic = useCallback(
186
- async (canonical: string): Promise<void> => {
187
- setPendingDeletes((prev) => new Set(prev).add(canonical));
188
- // Clear any stale error from a previous failed attempt on this role.
189
- setDeleteErrors((prev) => {
190
- if (!(canonical in prev)) return prev;
191
- const rest = { ...prev };
192
- delete rest[canonical];
193
- return rest;
194
- });
195
- try {
196
- const rows = await deleteRole(canonical);
197
- applyRoster(rows);
198
- } catch (err) {
199
- // Roll back the optimistic hide and record the error against the
200
- // restored card by canonical (it may be a fresh instance by now).
201
- setPendingDeletes((prev) => {
202
- const next = new Set(prev);
203
- next.delete(canonical);
204
- return next;
205
- });
206
- setDeleteErrors((prev) => ({ ...prev, [canonical]: errMessage(err, 'Failed to delete role') }));
207
- }
208
- },
209
- [applyRoster],
210
- );
211
-
212
- // The list the user sees = authoritative roster minus optimistically-deleted,
213
- // plus optimistically-created placeholders not yet reflected by the server.
214
- const rosterCanonicals = new Set(roster.map((r) => r.canonical));
215
- const visibleRoster = [
216
- ...roster.filter((r) => !pendingDeletes.has(r.canonical)),
217
- ...pendingCreates.filter((c) => !rosterCanonicals.has(c.canonical)),
218
- ];
219
-
220
116
  if (!isAdmin) {
221
117
  return (
222
118
  <PageShell title="Roles & Members">
223
119
  <div className="text-sm text-ink-muted">
224
- Admins only. Ask an admin if you need a role or membership changed.
120
+ Admins only. Ask an admin if you need a membership changed.
225
121
  </div>
226
122
  </PageShell>
227
123
  );
228
124
  }
229
125
 
230
126
  return (
231
- <PageShell
232
- title="Roles & Members"
233
-
234
- actions={<NewRoleControl onCreate={createOptimistic} />}
235
- >
127
+ <PageShell title="Roles & Members">
128
+ <p className="mb-3 text-xs text-ink-muted leading-snug">
129
+ Roles are defined by the app — what each one unlocks is fixed. Manage
130
+ who holds them: add people by email, or assign a group.
131
+ </p>
236
132
  {loading && roster.length === 0 ? (
237
133
  <div className="flex items-center gap-2 p-2 text-sm text-ink-muted">
238
134
  <Loader2 size={14} className="animate-spin" /> Loading…
239
135
  </div>
240
136
  ) : error ? (
241
- <div className="p-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded">
137
+ <div className="p-3 text-sm text-danger bg-danger-soft border border-danger/30 rounded-sm">
242
138
  {error}
243
139
  </div>
244
- ) : visibleRoster.length === 0 ? (
245
- <div className="p-2 text-sm text-ink-muted">No roles yet.</div>
140
+ ) : roster.length === 0 ? (
141
+ <div className="p-2 text-sm text-ink-muted">No roles.</div>
246
142
  ) : (
247
143
  <div className="flex flex-col gap-3">
248
- {visibleRoster.map((role) => (
144
+ {roster.map((role) => (
249
145
  <RoleCard
250
146
  key={role.canonical}
251
147
  role={role}
252
148
  onApply={applyRoster}
253
- onDelete={deleteOptimistic}
254
- deleteError={deleteErrors[role.canonical] ?? null}
149
+ runExclusive={runExclusive}
255
150
  />
256
151
  ))}
257
152
  </div>
@@ -260,118 +155,21 @@ export function AdminRolesPage() {
260
155
  );
261
156
  }
262
157
 
263
- function NewRoleControl({
264
- onCreate,
265
- }: {
266
- onCreate: (displayName: string) => Promise<string | null>;
267
- }) {
268
- const [open, setOpen] = useState(false);
269
- const [name, setName] = useState('');
270
- const [error, setError] = useState<string | null>(null);
271
-
272
- const reset = () => {
273
- setOpen(false);
274
- setName('');
275
- setError(null);
276
- };
277
-
278
- const submit = async () => {
279
- const clientError = validateNewRoleName(name);
280
- if (clientError) {
281
- setError(clientError);
282
- return;
283
- }
284
- // Optimistic: the placeholder card appears immediately, so close the form
285
- // right away. The commit runs in the background; a server rejection surfaces
286
- // as an inline error (re-opening the form with the typed name preserved).
287
- const typed = name.trim();
288
- reset();
289
- const err = await onCreate(typed);
290
- if (err) {
291
- setOpen(true);
292
- setName(typed);
293
- setError(err);
294
- }
295
- };
296
-
297
- if (!open) {
298
- return (
299
- <button
300
- type="button"
301
- onClick={() => setOpen(true)}
302
- className="px-3 py-1.5 text-xs rounded border border-line hover:bg-hover flex items-center gap-1.5"
303
- >
304
- <Plus size={12} /> New role
305
- </button>
306
- );
307
- }
308
-
309
- return (
310
- <div className="flex flex-col items-end gap-1">
311
- <div className="flex items-center gap-1.5">
312
- <input
313
- autoFocus
314
- value={name}
315
- onChange={(e) => setName(e.target.value)}
316
- onKeyDown={(e) => {
317
- if (e.key === 'Enter') submit();
318
- if (e.key === 'Escape') reset();
319
- }}
320
- placeholder="Role name"
321
- className="text-xs px-2 py-1 border border-line rounded focus:outline-none focus:border-accent w-48 max-w-full min-w-0"
322
- aria-label="New role name"
323
- />
324
- <button
325
- type="button"
326
- onClick={submit}
327
- className="px-2 py-1 text-xs rounded bg-accent hover:bg-accent-hover text-white disabled:opacity-50 flex items-center gap-1"
328
- >
329
- Add
330
- </button>
331
- <button
332
- type="button"
333
- onClick={reset}
334
- className="p-1 rounded hover:bg-hover text-ink-muted"
335
- aria-label="Cancel"
336
- >
337
- <X size={14} />
338
- </button>
339
- </div>
340
- {error && (
341
- <div className="text-xs text-red-700 bg-red-50 border border-red-200 rounded px-2 py-1">
342
- {error}
343
- </div>
344
- )}
345
- </div>
346
- );
347
- }
348
-
349
158
  function RoleCard({
350
159
  role,
351
160
  onApply,
352
- onDelete,
353
- deleteError,
161
+ runExclusive,
354
162
  }: {
355
163
  role: RoleRosterEntry;
356
164
  onApply: (rows: RoleRosterEntry[]) => void;
357
- onDelete: (canonical: string) => Promise<void>;
358
- // Delete error for this role, owned by the parent so it survives the
359
- // optimistic hide→restore cycle (the card may remount in between).
360
- deleteError: string | null;
165
+ // Page-level mutation queue — every card's mutations share it.
166
+ runExclusive: ExclusiveRunner;
361
167
  }) {
362
168
  const [error, setError] = useState<string | null>(null);
363
169
  const [busy, setBusy] = useState(false);
364
170
 
365
- // Rename inline-edit state.
366
- const [renaming, setRenaming] = useState(false);
367
- const [renameValue, setRenameValue] = useState(role.displayName);
368
- // A rename commit is in flight. Other row mutations capture `role.canonical`,
369
- // which changes once an identity-changing rename reconciles, so we block them
370
- // until the rename settles to avoid requests against the stale canonical.
371
- const [renamePending, setRenamePending] = useState(false);
372
-
373
171
  // Add-member input + people autocomplete (same suggest source as Manage
374
- // Access, scoped to people/emails — a role's members are emails, not plugins).
172
+ // Access, scoped to people/emails — a role's members are emails).
375
173
  const [memberEmail, setMemberEmail] = useState('');
376
174
  const [suggestions, setSuggestions] = useState<{ name: string; email: string }[]>([]);
377
175
  const [showSuggest, setShowSuggest] = useState(false);
@@ -384,10 +182,6 @@ function RoleCard({
384
182
  // server confirms. Reconciled (dropped) once they appear in the authoritative
385
183
  // roster, or rolled back on error.
386
184
  const [pendingAdds, setPendingAdds] = useState<string[]>([]);
387
- // Optimistic rename: the new display name shown immediately while the rename
388
- // commit is in flight. Cleared once the authoritative roster reflects it (or
389
- // rolled back on error).
390
- const [optimisticName, setOptimisticName] = useState<string | null>(null);
391
185
 
392
186
  useEffect(() => {
393
187
  const q = memberEmail.trim();
@@ -409,7 +203,7 @@ function RoleCard({
409
203
  ...role.members.map((m) => m.toLowerCase()),
410
204
  ...pendingAdds.map((e) => e.toLowerCase()),
411
205
  ]);
412
- setSuggestions(res.people.filter((p) => !existing.has(p.email.toLowerCase())));
206
+ setSuggestions((res.people ?? []).filter((p) => !existing.has(p.email.toLowerCase())));
413
207
  })
414
208
  .catch(() => {
415
209
  if (myReq === suggestReq.current) setSuggestions([]);
@@ -419,12 +213,12 @@ function RoleCard({
419
213
  }, [memberEmail, role.members, pendingAdds]);
420
214
 
421
215
  // Dialogs.
422
- const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null);
423
216
  const [selfRemove, setSelfRemove] = useState<SelfRemoveTarget | null>(null);
217
+ const [convertOpen, setConvertOpen] = useState(false);
218
+
219
+ // Assign-group input (roles with a group-assignable capability only).
220
+ const [groupName, setGroupName] = useState('');
424
221
 
425
- // Name shown in the UI = optimistic rename target while a rename is in flight,
426
- // else the authoritative display name.
427
- const displayName = optimisticName ?? role.displayName;
428
222
  // Members shown in the UI = server members minus any optimistically-removed,
429
223
  // plus any optimistically-added not yet reflected in the server roster.
430
224
  const serverMembers = role.members.filter((m) => !pendingRemovals.has(m.toLowerCase()));
@@ -453,19 +247,12 @@ function RoleCard({
453
247
  });
454
248
  }, [role.members]);
455
249
 
456
- // Clear the optimistic rename once the authoritative roster reflects it.
457
- useEffect(() => {
458
- if (optimisticName !== null && role.displayName === optimisticName) {
459
- setOptimisticName(null);
460
- }
461
- }, [role.displayName, optimisticName]);
462
-
463
250
  const run = useCallback(
464
251
  async (fn: () => Promise<RoleRosterEntry[]>) => {
465
252
  setBusy(true);
466
253
  setError(null);
467
254
  try {
468
- const rows = await fn();
255
+ const rows = await runExclusive(fn);
469
256
  onApply(rows);
470
257
  return true;
471
258
  } catch (err) {
@@ -475,38 +262,20 @@ function RoleCard({
475
262
  setBusy(false);
476
263
  }
477
264
  },
478
- [onApply],
265
+ [onApply, runExclusive],
479
266
  );
480
267
 
481
- const submitRename = async () => {
482
- const next = renameValue.trim();
483
- if (next === role.displayName) {
484
- setRenaming(false);
485
- return;
486
- }
487
- // Optimistic: show the new name and close the editor immediately. The rename
488
- // commit runs in the background; the authoritative roster reconciles it (or
489
- // we roll back on error). Not gated on `busy` — same posture as removal.
490
- setError(null);
491
- setOptimisticName(next);
492
- setRenaming(false);
493
- setRenamePending(true);
494
- try {
495
- const rows = await renameRole(role.canonical, next);
496
- onApply(rows);
497
- } catch (err) {
498
- setOptimisticName(null); // roll back the optimistic label
499
- setError(errMessage(err, 'Failed to rename role'));
500
- } finally {
501
- setRenamePending(false);
502
- }
503
- };
504
-
505
268
  const submitAddMember = async (override?: string) => {
506
- // A rename is reconciling — `role.canonical` is about to change, so don't
507
- // fire mutations against the stale one.
508
- if (renamePending) return;
509
269
  const email = (override ?? memberEmail).trim();
270
+ // Mirror the backend's refusal of `group:`-prefixed member values with an
271
+ // inline hint (a `group:lee@x.io` would pass the email regex server-side
272
+ // check order matters — see roles-edit.addMember).
273
+ if (isGroupPrefixed(email)) {
274
+ setError(
275
+ 'Members are emails — to give this role to a group, use the group assignment instead.',
276
+ );
277
+ return;
278
+ }
510
279
  if (!EMAIL_RE.test(email)) {
511
280
  setError('Enter a valid email address.');
512
281
  return;
@@ -532,7 +301,7 @@ function RoleCard({
532
301
  setShowSuggest(false);
533
302
  setSuggestions([]);
534
303
  try {
535
- const rows = await addMember(role.canonical, email);
304
+ const rows = await runExclusive(() => addMember(role.canonical, email));
536
305
  onApply(rows);
537
306
  } catch (err) {
538
307
  // Roll back the optimistic chip so it disappears.
@@ -542,7 +311,6 @@ function RoleCard({
542
311
  };
543
312
 
544
313
  const handleRemoveMember = async (email: string) => {
545
- if (renamePending) return;
546
314
  setError(null);
547
315
  const lower = email.toLowerCase();
548
316
  // If this chip is an optimistic add not yet on the server, just drop it from
@@ -560,7 +328,7 @@ function RoleCard({
560
328
  // chip just disappears, which is the whole point of optimism.
561
329
  setPendingRemovals((s) => new Set(s).add(email.toLowerCase()));
562
330
  try {
563
- const rows = await removeMember(role.canonical, email);
331
+ const rows = await runExclusive(() => removeMember(role.canonical, email));
564
332
  onApply(rows); // authoritative roster replaces local members
565
333
  } catch (err) {
566
334
  // Roll back the optimistic hide so the chip returns.
@@ -572,6 +340,9 @@ function RoleCard({
572
340
  if (err instanceof RolesApiError && err.status === 409 && err.kind === 'self-admin-removal') {
573
341
  setSelfRemove({ canonical: role.canonical, email });
574
342
  } else {
343
+ // The Admin ≥1-direct-email invariant (and any other refusal) arrives
344
+ // as a typed 422 whose message IS the explanation — render it inline
345
+ // on the card, verbatim, never a generic failure.
575
346
  setError(errMessage(err, 'Failed to remove member'));
576
347
  }
577
348
  }
@@ -585,104 +356,77 @@ function RoleCard({
585
356
  if (ok) setSelfRemove(null);
586
357
  };
587
358
 
588
- const confirmDelete = async () => {
589
- if (renamePending) return;
590
- // Optimistic: close the dialog and let the card vanish immediately. The
591
- // commit runs in the background; on failure the parent rolls back the hide
592
- // and records the error (keyed by canonical), which arrives via deleteError
593
- // — so it survives even if this card instance was unmounted in between.
594
- setDeleteTarget(null);
595
- await onDelete(role.canonical);
359
+ const submitAssignGroup = async () => {
360
+ const group = groupName.trim();
361
+ if (!group) {
362
+ setError('Enter a group name.');
363
+ return;
364
+ }
365
+ // Not optimistic: unlike a member email, a group name may simply not exist
366
+ // and the server's 404/422 is the interesting outcome — a chip that appears
367
+ // then vanishes would just look like a glitch.
368
+ const ok = await run(() => assignGroup(role.canonical, group));
369
+ if (ok) setGroupName('');
370
+ };
371
+
372
+ const handleRemoveGroup = async (group: string) => {
373
+ await run(() => unassignGroup(role.canonical, group));
374
+ };
375
+
376
+ const confirmConvert = async () => {
377
+ // On success the role leaves the roster (it lives in the groups file now);
378
+ // on refusal `run` records the backend's message, shown on the card.
379
+ await run(() => convertRoleToGroup(role.canonical));
380
+ setConvertOpen(false);
596
381
  };
597
382
 
383
+ // Group assignment follows the roster payload: the registry decides which
384
+ // capability roles may be assigned to groups (Admin included — the backend's
385
+ // parse-time invariant keeps at least one direct email member on Admin, so
386
+ // a group can never be its only membership). Legacy people-set roles get
387
+ // "Convert to group" instead of assignments.
388
+ const groupAssignable = role.capability !== null && role.capability.groupAssignable;
389
+ // ...but a role can already CARRY assignments it isn't allowed to receive
390
+ // here (a hand-edited roles.yaml, or grants made before this gating). Those
391
+ // must stay visible — with their remove controls — or there is no UI left to
392
+ // unassign them, and convertRoleToGroup refuses until they're gone.
393
+ const showGroupsSection = groupAssignable || role.groups.length > 0;
394
+
598
395
  return (
599
396
  <div className="border border-line rounded-lg p-4">
600
397
  <div className="flex items-start gap-3">
601
398
  <div className="flex-1 min-w-0">
602
- {renaming ? (
603
- <div className="flex items-center gap-1.5">
604
- <input
605
- autoFocus
606
- value={renameValue}
607
- onChange={(e) => setRenameValue(e.target.value)}
608
- onKeyDown={(e) => {
609
- if (e.key === 'Enter') submitRename();
610
- if (e.key === 'Escape') {
611
- setRenameValue(role.displayName);
612
- setRenaming(false);
613
- }
614
- }}
615
- disabled={busy}
616
- className="text-base font-semibold px-2 py-1 border border-line rounded focus:outline-none focus:border-accent min-w-0"
617
- aria-label="Role name"
618
- />
619
- <button
620
- type="button"
621
- onClick={submitRename}
622
- disabled={busy}
623
- className="p-1 rounded hover:bg-hover text-ink-muted disabled:opacity-50 shrink-0"
624
- aria-label="Save name"
625
- >
626
- {busy ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}
627
- </button>
628
- <button
629
- type="button"
630
- onClick={() => {
631
- setRenameValue(role.displayName);
632
- setRenaming(false);
633
- }}
634
- disabled={busy}
635
- className="p-1 rounded hover:bg-hover text-ink-muted shrink-0"
636
- aria-label="Cancel rename"
637
- >
638
- <X size={14} />
639
- </button>
640
- </div>
641
- ) : (
642
- <div className="flex items-center gap-2">
643
- <h2 className="text-base font-semibold text-ink truncate">
644
- {displayName}
645
- </h2>
646
- {role.isAdmin && (
647
- <span className="text-[10px] uppercase tracking-wide text-ink-muted border border-line rounded px-1.5 py-0.5">
648
- Required
649
- </span>
650
- )}
651
- </div>
652
- )}
653
- </div>
654
-
655
- {!renaming && (
656
- <div className="flex items-center gap-1 shrink-0">
657
- <button
658
- type="button"
659
- onClick={() => {
660
- setRenameValue(role.displayName);
661
- setRenaming(true);
662
- }}
663
- disabled={busy || renamePending}
664
- className="p-1.5 rounded hover:bg-hover text-ink-muted disabled:opacity-50"
665
- title="Rename"
666
- aria-label="Rename role"
667
- >
668
- <Pencil size={14} />
669
- </button>
670
- {!role.isAdmin && (
671
- <button
672
- type="button"
673
- onClick={() => setDeleteTarget({ role })}
674
- disabled={busy || renamePending}
675
- className="p-1.5 rounded hover:bg-red-50 text-red-600 disabled:opacity-50"
676
- title="Delete role"
677
- aria-label="Delete role"
678
- >
679
- <Trash2 size={14} />
680
- </button>
399
+ <div className="flex items-center gap-2">
400
+ <h2 className="text-base font-semibold text-ink truncate">
401
+ {role.displayName}
402
+ </h2>
403
+ {role.isAdmin && (
404
+ <span className="text-[10px] uppercase tracking-wide text-ink-muted border border-line rounded-sm px-1.5 py-0.5">
405
+ Required
406
+ </span>
681
407
  )}
682
408
  </div>
409
+ </div>
410
+
411
+ {role.capability === null && !role.isAdmin && (
412
+ <button
413
+ type="button"
414
+ onClick={() => setConvertOpen(true)}
415
+ disabled={busy}
416
+ className="shrink-0 px-2 py-1 text-xs rounded-sm border border-line hover:bg-hover text-ink-muted disabled:opacity-50"
417
+ title="Convert this people-set role into a group"
418
+ >
419
+ Convert to group
420
+ </button>
683
421
  )}
684
422
  </div>
685
423
 
424
+ {/* What the role DOES. Absent on legacy people-set roles — those get the
425
+ Convert action instead. */}
426
+ {role.capability && (
427
+ <p className="mt-1 text-xs text-ink-muted">{role.capability.description}</p>
428
+ )}
429
+
686
430
  {/* Member chips — optimistically hides members pending removal. */}
687
431
  <div className="mt-3 flex flex-wrap gap-2">
688
432
  {visibleMembers.length === 0 ? (
@@ -702,11 +446,11 @@ function RoleCard({
702
446
  <button
703
447
  type="button"
704
448
  onClick={() => handleRemoveMember(email)}
705
- disabled={busy || renamePending || isLastAdminMember}
706
- className="shrink-0 rounded-full p-0.5 text-ink-faint hover:text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:hover:text-ink-faint disabled:hover:bg-transparent"
449
+ disabled={busy || isLastAdminMember}
450
+ className="shrink-0 rounded-full p-0.5 text-ink-faint hover:text-danger hover:bg-danger-soft disabled:cursor-not-allowed disabled:hover:text-ink-faint disabled:hover:bg-transparent"
707
451
  title={
708
452
  isLastAdminMember
709
- ? 'Admin must keep at least one member'
453
+ ? 'Admin must keep at least one direct email member'
710
454
  : 'Remove member'
711
455
  }
712
456
  aria-label={`Remove ${email}`}
@@ -740,13 +484,13 @@ function RoleCard({
740
484
  if (e.key === 'Escape') setShowSuggest(false);
741
485
  }}
742
486
  placeholder="Add member by email"
743
- disabled={busy || renamePending}
744
- className="text-xs px-2 py-1 border border-line rounded focus:outline-none focus:border-accent w-full min-w-0"
487
+ disabled={busy}
488
+ className="text-xs px-2 py-1 border border-line rounded-sm focus:outline-none focus:border-accent w-full min-w-0"
745
489
  aria-label="Member email"
746
490
  autoComplete="off"
747
491
  />
748
492
  {showSuggest && suggestions.length > 0 && (
749
- <ul className="absolute z-10 mt-1 w-full sm:w-72 max-w-full max-h-56 overflow-auto bg-white border border-line rounded shadow-lg py-1">
493
+ <ul className="absolute z-10 mt-1 w-full sm:w-72 max-w-full max-h-56 overflow-auto bg-white border border-line rounded-lg shadow-lg py-1">
750
494
  {suggestions.map((p) => (
751
495
  <li key={p.email}>
752
496
  <button
@@ -772,47 +516,95 @@ function RoleCard({
772
516
  <button
773
517
  type="button"
774
518
  onClick={() => submitAddMember()}
775
- disabled={busy || renamePending}
776
- className="shrink-0 px-3 py-1 text-xs rounded border border-line hover:bg-hover disabled:opacity-50 flex items-center gap-1"
519
+ disabled={busy}
520
+ className="shrink-0 px-3 py-1 text-xs rounded-sm border border-line hover:bg-hover disabled:opacity-50 flex items-center gap-1"
777
521
  >
778
522
  {busy && <Loader2 size={12} className="animate-spin" />}
779
523
  Add
780
524
  </button>
781
525
  </div>
782
526
 
783
- {(error ?? deleteError) && (
784
- <div className="mt-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
785
- {error ?? deleteError}
527
+ {/* Group assignments — everyone in an assigned group holds the role.
528
+ The section shows whenever there is something to see: assignments the
529
+ role already carries (even a legacy/opted-out role — hiding them
530
+ would leave no way to unassign, dead-ending Convert), or a
531
+ group-assignable capability. The ADD control is stricter: only
532
+ group-assignable capability roles may gain assignments here. */}
533
+ {showGroupsSection && (
534
+ <div className="mt-3 pt-3 border-t border-line">
535
+ <div className="text-label uppercase text-ink-faint mb-1.5">
536
+ Assigned groups
537
+ </div>
538
+ <div className="flex flex-wrap gap-2">
539
+ {role.groups.length === 0 ? (
540
+ <span className="text-xs text-ink-faint">No groups assigned.</span>
541
+ ) : (
542
+ role.groups.map((group) => (
543
+ <span
544
+ key={group}
545
+ className="inline-flex max-w-full items-center gap-1.5 px-1.5 py-1 bg-sunken border border-line rounded-full text-xs text-ink"
546
+ >
547
+ <UsersRound size={12} className="shrink-0 text-ink-muted" />
548
+ <span className="min-w-0 truncate max-w-[14rem]">{group}</span>
549
+ <button
550
+ type="button"
551
+ onClick={() => handleRemoveGroup(group)}
552
+ disabled={busy}
553
+ className="shrink-0 rounded-full p-0.5 text-ink-faint hover:text-danger hover:bg-danger-soft disabled:opacity-50"
554
+ title="Unassign group"
555
+ aria-label={`Remove group ${group}`}
556
+ >
557
+ <X size={12} />
558
+ </button>
559
+ </span>
560
+ ))
561
+ )}
562
+ </div>
563
+ {groupAssignable && (
564
+ <div className="mt-2 flex items-center gap-1.5">
565
+ <input
566
+ value={groupName}
567
+ onChange={(e) => setGroupName(e.target.value)}
568
+ onKeyDown={(e) => {
569
+ if (e.key === 'Enter') submitAssignGroup();
570
+ }}
571
+ placeholder="Assign group by name"
572
+ disabled={busy}
573
+ className="text-xs px-2 py-1 border border-line rounded-sm focus:outline-none focus:border-accent flex-1 min-w-0 max-w-[16rem]"
574
+ aria-label="Assign group"
575
+ autoComplete="off"
576
+ />
577
+ <button
578
+ type="button"
579
+ onClick={submitAssignGroup}
580
+ disabled={busy}
581
+ className="shrink-0 px-3 py-1 text-xs rounded-sm border border-line hover:bg-hover disabled:opacity-50"
582
+ >
583
+ Assign
584
+ </button>
585
+ </div>
586
+ )}
587
+ </div>
588
+ )}
589
+
590
+ {error && (
591
+ <div className="mt-3 text-sm text-danger bg-danger-soft border border-danger/30 rounded-sm px-3 py-2">
592
+ {error}
786
593
  </div>
787
594
  )}
788
595
 
789
- {deleteTarget && (
596
+ {convertOpen && (
790
597
  <ConfirmDialog
791
- title={`Delete "${deleteTarget.role.displayName}"?`}
792
- confirmLabel="Delete role"
793
- danger
598
+ title={`Convert "${role.displayName}" to a group?`}
599
+ confirmLabel="Convert"
794
600
  busy={busy}
795
- onCancel={() => setDeleteTarget(null)}
796
- onConfirm={confirmDelete}
601
+ onCancel={() => setConvertOpen(false)}
602
+ onConfirm={confirmConvert}
797
603
  >
798
- {deleteTarget.role.referencedBy.length > 0 ? (
799
- <>
800
- <p className="text-sm text-ink">
801
- {deleteTarget.role.referencedBy.length} access rule
802
- {deleteTarget.role.referencedBy.length === 1 ? '' : 's'} will be
803
- ignored after deletion:
804
- </p>
805
- <ul className="mt-2 max-h-40 overflow-auto text-xs text-ink-muted space-y-0.5">
806
- {deleteTarget.role.referencedBy.map((ref, i) => (
807
- <li key={`${ref.path}:${ref.verb}:${i}`} className="truncate">
808
- {ref.verb} · {ref.path}
809
- </li>
810
- ))}
811
- </ul>
812
- </>
813
- ) : (
814
- <p className="text-sm text-ink">This role has no access rules.</p>
815
- )}
604
+ <p className="text-sm text-ink">
605
+ Grants keep working — the name stays; it just becomes a group. Manage its
606
+ members on the Groups page afterwards.
607
+ </p>
816
608
  </ConfirmDialog>
817
609
  )}
818
610
 
@@ -927,7 +719,7 @@ function ConfirmDialog({
927
719
  type="button"
928
720
  onClick={onCancel}
929
721
  disabled={busy}
930
- className="px-3 py-1.5 text-xs rounded border border-line hover:bg-hover disabled:opacity-50"
722
+ className="px-3 py-1.5 text-xs rounded-sm border border-line hover:bg-hover disabled:opacity-50"
931
723
  >
932
724
  Cancel
933
725
  </button>
@@ -935,8 +727,8 @@ function ConfirmDialog({
935
727
  type="button"
936
728
  onClick={onConfirm}
937
729
  disabled={busy}
938
- className={`px-3 py-1.5 text-xs rounded text-white disabled:opacity-50 flex items-center gap-1 ${
939
- danger ? 'bg-red-600 hover:bg-red-700' : 'bg-accent hover:bg-accent-hover'
730
+ className={`px-3 py-1.5 text-xs rounded-sm text-white disabled:opacity-50 flex items-center gap-1 ${
731
+ danger ? 'bg-danger hover:bg-danger/90' : 'bg-accent hover:bg-accent-hover'
940
732
  }`}
941
733
  >
942
734
  {busy && <Loader2 size={12} className="animate-spin" />}