File size: 71,868 Bytes
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
1f123e1
 
cfd4ac1
1f123e1
 
 
cfd4ac1
3998487
1f123e1
aa1490a
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
1f123e1
3998487
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
1f123e1
 
affe37f
1f123e1
 
affe37f
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
1f123e1
 
 
 
 
c72f0a1
1f123e1
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
affe37f
cfd4ac1
 
 
 
affe37f
cfd4ac1
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
c72f0a1
cfd4ac1
 
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
1f123e1
 
 
 
3998487
1f123e1
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
1f123e1
3998487
 
affe37f
3998487
 
 
affe37f
3998487
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
cfd4ac1
 
 
affe37f
cfd4ac1
 
 
 
3998487
1f123e1
 
3998487
 
 
 
 
 
c72f0a1
3998487
affe37f
3998487
 
 
c72f0a1
 
3998487
 
 
 
 
 
 
 
 
 
 
 
affe37f
3998487
c72f0a1
1f123e1
 
 
 
 
 
 
 
 
affe37f
 
 
1f123e1
 
affe37f
1f123e1
 
 
 
 
affe37f
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
c72f0a1
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
1f123e1
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
c72f0a1
1f123e1
 
c72f0a1
 
 
 
 
 
 
1f123e1
 
c72f0a1
 
 
 
1f123e1
 
c72f0a1
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
1f123e1
 
 
 
 
 
 
 
 
c72f0a1
1f123e1
3998487
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
1f123e1
 
 
 
 
 
 
 
 
 
 
3998487
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
c72f0a1
affe37f
c72f0a1
 
 
 
affe37f
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
3998487
1f123e1
 
 
3998487
 
 
 
 
1f123e1
cfd4ac1
3998487
1f123e1
 
 
 
 
 
 
 
 
cfd4ac1
1f123e1
 
 
 
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
// ---------------------------------------------------------------------------
// settings / PermsEditor.tsx β€” THE USER PAGE. (wave 15 R9: the permission
// editor Β· wave 17 R7: everything else about the account, merged in.)
//
// "Manage users β†’ click a user β†’ the modal body BECOMES that user's page." A
// full-pane takeover, not a drawer beside the list and not a third dialog: the
// thing being edited is a whole account, and giving it a room of its own is
// what makes room for a filter builder and a field list per module without
// either being a 200px scroll-box.
//
// ⚠ WHY THE FILE NAME NO LONGER DESCRIBES THE FILE. Wave 17's R7, verbatim:
// *"Edit and clicking a user name should just be the EXACT same opening of a
// full page so its not confusing."* Before it there were two doors β€” the name
// opened this page, "Edit" unfolded a card at the BOTTOM of the accounts list β€”
// and which one an admin needed depended on a distinction only the code cared
// about (who the account IS vs what it may SEE). Both jobs live here now. The
// export keeps its name because renaming it would ripple through the shell, the
// gate's module list and the render smoke for no user-visible gain β€” the same
// trade R12 made for `SettingsModal`.
//
// β›” EVERY CONTROL HERE IS A COURTESY. `/admin/*` is refused to a member at the
// server, fail-closed, and the wall that acts on what this page writes is
// `core/perm_scope.permits()` β€” which re-validates the whole record. Nothing on
// this page is a permission check; this page is where an admin SAYS what the
// wall should be.
//
// THE PANELS ARE THE GRID'S OWN (contract C-KIT). Not lookalikes β€” the same
// `FilterBuilderPanel` and `FieldsHidePanel` the toolbar mounts, from
// `filter-kit/`, which is the entire reason that extraction happened before this
// file existed. An admin writing "customers where dba is Fisch" uses the control
// they already know, and there is one condition grammar in the product rather
// than two that drift within a wave.
//
// ⚠ WHAT THIS EDITOR CANNOT OFFER, AND WHY IT IS RIGHT THAT IT DOES NOT:
//   Β· **Cohort conditions** β€” cohorts are a user's own workspace objects and an
//     admin editing someone else's account holds no list of them. The prop is
//     absent, so the affordance is absent (never present-and-inert).
//   Β· **Choice lists the grid discovers from ROWS** β€” this page has loaded none.
//     β›” WAVE 33 (D-76) CORRECTS THIS PARAGRAPH: it used to end "so only Odoo
//     lifecycle columns come up bare", and that was FALSE. `stock_bucket` and
//     `category` are product `select` columns that declare no options either, and
//     `stock_bucket` is the exact column wave 26 item 24 was about β€” the same
//     empty dropdown, one surface over, under a comment saying it could not
//     happen here. The fix is at the SOURCE and it is server-side:
//     `routes_admin::_server_side_vocabularies` now ships `stock_bucket`'s labels
//     on the field itself (imported from `modules/inventory.COVERAGE_LABELS`, not
//     restated), so the panel's ordinary `choiceOptions` fallback finds them and
//     this file needs no new prop. TWO remain bare ON PURPOSE and are named
//     rather than left to look handled: `category` is an OPEN vocabulary read
//     off Odoo and has no closed list to declare. ⭐ `odoo_status` was the second
//     one and is now FIXED AT ITS PROPER HOME β€” lane E declared
//     `options: ['Active','Archived']` on the grid contract itself, so the grid
//     gets it for free too. `platform/verify_perm_scope.py::section_tenant_derived`
//     reds when a NEW bare choice column appears AND when this list goes stale in
//     the other direction, which is how that change was noticed at all.
// Both are C-KIT's documented absences, restated here because a reader of this
// file will meet them as "why is that dropdown empty".
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
// ⭐ W37-T05 β€” the shared in-flight label; see `ui/Busy.tsx` for why it is a component.
import { Busy } from "../ui/Busy";
// ⭐ The per-database list is ONE component, shared with `manage-agent` (owner
// item 10: "the same exact layout"). The filter/hide panels are mounted THERE
// now, which is why `filter-kit` is no longer imported here.
import { ModulePermsList } from "./ModulePermsList";
// ⭐ W40-T14 (owner instruction 7) β€” the row's accordion became a ROOM. The list above offers a
// checkbox and one way in; this is what the way in opens.
import { DatabasePermsPane } from "./DatabasePermsPane";
// C4: this lane's own stylesheet. `index.css` is B's and nothing here touches it.
import "./perms.css";
import {
  getConnectorGrants,
  getUserPerms,
  patchUser,
  putConnectorGrants,
  putUserPerms,
  setPassword,
} from "./settingsApi";
import type { AdminUser, ConnectorKind } from "./settingsApi";
import type { PermsModule, PermsPayload, PermsRecord } from "./permsModel";
import {
  accessSaveRefusal,
  accessSummary,
  isDirty,
  normalizeMetrics,
  parsePermsPayload,
  setAccess,
  setFilter,
  setHidden,
  setMetrics,
  toPutBody,
  toggleHidden,
} from "./permsModel";

type Load =
  | { phase: "loading" }
  | { phase: "error"; message: string }
  | { phase: "ready"; payload: PermsPayload };

/** What the confirm step is asking about. `null` = nothing is being confirmed. */
type Ask = null | { kind: "save" } | { kind: "discard" };

function showRefusal(text: string) {
  window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}

// A permissions PUT replaces the block. Unedited stored values must survive the editor's parsed view.
function retainedPermsBody(stored: Record<string, unknown>, payload: PermsPayload, saved: PermsRecord, draft: PermsRecord) {
  const normalized = toPutBody(payload, draft).perms;
  const perms: Record<string, unknown> = { ...stored };
  for (const module of payload.modules) {
    const key = module.key;
    if (!Object.prototype.hasOwnProperty.call(stored, key)) {
      perms[key] = normalized[key];
      continue;
    }
    const changes: Record<string, unknown> = {};
    for (const field of ["access", "filter", "hiddenFields", "metrics"] as const) {
      if (JSON.stringify(saved[key]?.[field]) !== JSON.stringify(draft[key]?.[field])) {
        changes[field] = normalized[key][field];
      }
    }
    if (Object.keys(changes).length) {
      perms[key] = { ...(stored[key] as Record<string, unknown>), ...changes };
    }
  }
  return { perms: perms as PermsRecord };
}

const MEMBER_PAGE_SIZE = 20;
const databaseGroup = (module: PermsModule) =>
  module.key === "customer_data" || module.key === "product_data" || module.key.startsWith("ut_odoo_")
    ? "Odoo" : "Workspace";

// --- C-PERMCOPY IS GONE (W47-T19, owner instruction 11) ----------------------
//
// Owner, verbatim: *"Delete the 'Copy this account access to' button, its not
// needed"*. Asked directly on 2026-08-30 whether the door should merely MOVE to
// the bottom bar (instruction 11 names it twice, once as a move and once as a
// deletion), the owner ruled: delete it entirely, the button AND the modal it
// opened. So the whole contract's client half went with it β€” the pick/confirm
// dialog, the per-target prepare, the write loop, and the `permsModel` helpers
// that only it called are no longer imported here. `permsModel` keeps
// `copyTargetRecord`/`copyDropped` and their gates; nothing in the UI reaches
// them now, which is a deliberate deletion rather than a seam left dangling.

export function PermsEditor({
  user,
  userOptions,
  onBack,
  onSaved,
}: {
  /**
   * ⚠ THE WHOLE RECORD, not a username and a display name (wave 17 R7). The
   * page edits the account as well as its access, so it needs `role` and
   * `active` β€” and taking the record rather than five scalars means one place
   * (the pane's `reload`) refreshes everything after a write.
   */
  user: AdminUser;
  /** The people a `user`-typed field may name, for the condition builder. Real
   *  accounts, never invented: an admin filtering on an owner who does not exist
   *  writes a rule that matches nothing and looks like it should match.
   *  ⚠ DISPLAY NAMES β€” the cells hold names. Not the copy targets below. */
  userOptions?: string[];
  /** β›” ACCEPTED AND IGNORED SINCE WAVE 47 (W47-T19, owner instruction 11). It fed
   *  C-PERMCOPY's "Apply this access to…" door, which the owner ruled deleted
   *  outright on 2026-08-30 β€” the button and the modal both. The MEMBER stays on
   *  this interface deliberately: `settings/SettingsModal.tsx` and
   *  `pages/_test/render.test.tsx` still pass it, and neither is this ticket's to
   *  edit, so removing it would red `tsc` in files the change does not own. It is
   *  read nowhere below; the next writer removing it must clear both call sites in
   *  the same change. */
  copyTargets?: readonly AdminUser[];
  onBack: () => void;
  /** "The server took a write" β€” the list behind this page reloads. It does NOT
   *  close the page (R7: one page, several things to save on it). */
  /** ⭐ W37-T05 β€” `back` is OPTIONAL and defaults to staying put. Only the permissions write,
   *  the page's terminal action, passes `true`. An optional second argument rather than a second
   *  callback because every one of the four call sites below already reads as "I saved something";
   *  a `onSavedAndClose` beside `onSaved` is two names for one event, and the next writer picks the
   *  wrong one. */
  onSaved: (message: string, back?: boolean) => void;
}) {
  const displayName = user.name || user.username;
  const username = user.username;

  const [load, setLoad] = useState<Load>({ phase: "loading" });
  /** The record as the SERVER holds it β€” the baseline `isDirty` compares to. */
  const [saved, setSaved] = useState<PermsRecord>({});
  const [draft, setDraft] = useState<PermsRecord>({});
  const [stored, setStored] = useState<Record<string, unknown>>({});
  const [readAttempt, setReadAttempt] = useState(0);
  const [databaseQuery, setDatabaseQuery] = useState("");
  const [group, setGroup] = useState("all");
  const [databasePage, setDatabasePage] = useState(0);
  const [ask, setAsk] = useState<Ask>(null);
  const [busy, setBusy] = useState(false);
  /** What just happened, said ON THIS PAGE. The pane's own notice renders in the
   *  accounts LIST, which the admin is no longer sent back to on save β€” so
   *  without this a successful write would land in an empty room. */
  const [said, setSaid] = useState("");
  /**
   * ⭐⭐ W40-T14 (owner instruction 7) β€” WHICH DATABASE'S RULE IS OPEN, or `null` for the account
   * page. A KEY rather than the module object: the module list is re-derived from the payload on
   * every load, and a held object would be a stale second copy of a row the page can no longer
   * find. Resolving the key against `payload.modules` below is also what makes a stale key
   * harmless β€” it falls back to the account page instead of drawing an empty room.
   *
   * ⚠ IT DOES NOT FORK THE DRAFT. The pane edits the SAME `draft`, so leaving it loses nothing
   * and there is exactly one thing on this page that "Save access" commits.
   */
  const [editing, setEditing] = useState<string | null>(null);
  // ⚠ The disclosure state MOVED to `ModulePermsList` with the list itself: it is
  // a property of that list and of nothing else, and leaving a copy here would be
  // a second source of truth for which row is open, in the one room that renders
  // two of those lists.

  // --- the account half (R7, moved here from the accounts list's `EditUser`) --
  const [name, setName] = useState(user.name ?? "");
  const [role, setRole] = useState(user.role ?? "user");
  const [pw, setPw] = useState("");

  /**
   * ⭐⭐ W54-T47 / R4 / contract C4 β€” THE THIRD AXIS. Owner, verbatim: *"Under Settings, an Admin
   * should grant a user access to add connectors, so access becomes Database / Module /
   * Connector."*
   *
   * β›” IT IS ITS OWN STATE RATHER THAN A THIRD GROUP OF `draft`, because it is not a registry key.
   * `payload.modules` are databases and surfaces the perms record governs; a connector is a
   * CREDENTIAL KIND out of `core/keychain.py::ENTRY_TYPES`, carried by its own route so the perms
   * PUT body stays exactly the whole-record replace `permsModel.toPutBody` builds. Folding it in
   * would have made every existing perms leg negotiate a key that is not a module.
   *
   * ⚠ `kinds` EMPTY IS ALSO THE FAILURE STATE, deliberately. A server that cannot answer, or one
   * that predates this route, leaves the list empty and the section renders NO HEADING at all,
   * which is the same rule the Database and Module groups already follow: a group with no members
   * is not a labelled empty room.
   */
  const [connKinds, setConnKinds] = useState<ConnectorKind[]>([]);
  /** The grants as the SERVER holds them, and the draft beside it. Same pairing, same reason, as
   *  `saved` / `draft` above: without the baseline there is nothing for "unsaved" to mean. */
  const [connSaved, setConnSaved] = useState<string[]>([]);
  const [connDraft, setConnDraft] = useState<string[]>([]);
  const requestScope = useRef<AbortController | null>(null);
  const actionGeneration = useRef(0);

  useLayoutEffect(() => {
    // Each identity owns an irreversible token, captured before each request.
    const scope = new AbortController();
    requestScope.current = scope;
    const invalidate = () => { scope.abort(); setPw(""); };
    window.addEventListener(UNAUTHORIZED_EVENT, invalidate);
    window.addEventListener("aios:signed-out", invalidate);
    return () => {
      scope.abort();
      window.removeEventListener(UNAUTHORIZED_EVENT, invalidate);
      window.removeEventListener("aios:signed-out", invalidate);
    };
  }, [username]);

  useLayoutEffect(() => {
    actionGeneration.current += 1;
    setBusy(false);
  }, [username, readAttempt]);

  useEffect(() => {
    let dead = false;
    const request = requestScope.current?.signal;
    setLoad({ phase: "loading" });
    void getUserPerms(username).then((r) => {
      if (dead || !request || request.aborted) return;
      if (!r.ok) {
        setLoad({ phase: "error", message: r.message });
        return;
      }
      const payload = parsePermsPayload(r.data);
      if (!payload) {
        // An unreadable payload is NOT an empty one. Rendering "no modules"
        // here would invite an admin to save a record that grants nothing,
        // over a record they never saw.
        setLoad({
          phase: "error",
          message: "The permission record could not be read. Close and try again.",
        });
        return;
      }
      setSaved(payload.entries);
      setDraft(payload.entries);
      const record = r.data as { stored_perms?: unknown; perms?: unknown };
      const raw = record.stored_perms ?? record.perms;
      setStored(raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {});
      setLoad({ phase: "ready", payload });
    });
    return () => {
      dead = true;
    };
  }, [username, readAttempt]);

  /**
   * ⭐ W54-T47 β€” THE CONNECTOR AXIS IS READ ON ITS OWN WIRE, AND A FAILURE HERE IS SILENT.
   *
   * β›” IT MUST NOT BE ABLE TO BREAK THE PAGE. The perms GET above puts the whole editor into an
   * error state when it cannot be read, and rightly: an admin must never be invited to save a
   * record they were not shown. This one is the opposite case. The grants it fetches are the ONLY
   * thing it can affect, absence of a grant is the ordinary state of every account in the product,
   * and the wall is on the server either way. So a refusal leaves `connKinds` empty, the section
   * renders nothing, and Database and Module keep working exactly as they did.
   */
  useEffect(() => {
    let dead = false;
    const request = requestScope.current?.signal;
    setConnKinds([]);
    setConnSaved([]);
    setConnDraft([]);
    void getConnectorGrants(username).then((r) => {
      if (dead || !request || request.aborted || !r.ok) return;
      const granted = Array.isArray(r.data?.granted) ? r.data.granted.map(String) : [];
      setConnKinds(Array.isArray(r.data?.kinds) ? r.data.kinds : []);
      setConnSaved(granted);
      setConnDraft(granted);
    });
    return () => {
      dead = true;
    };
  }, [username]);

  const payload = load.phase === "ready" ? load.payload : null;
  /**
   * ⭐ W40-T14 β€” the drill-in RESOLVED, which is the only form the render is allowed to trust.
   * `editing` alone can name a module this deployment no longer declares (a payload reload, an
   * orphaned key), and a pane drawn from that would be a room with no fields, no filter and no
   * title. Resolving to `null` sends the reader back to the account page instead.
   *
   * ⚠ IT ALSO CANNOT RESOLVE BEFORE THE RECORD LOADS, and that is load-bearing: `payload` is
   * null while the GET is in flight, so no checkbox of this pane's can paint over an unloaded
   * record β€” the property `pages/_test/render.test.tsx` pins.
   */
  const editModule = editing ? payload?.modules.find((m) => m.key === editing) ?? null : null;
  /**
   * ⭐⭐ W40-T15 (owner instruction 8) β€” THE TWO KINDS OF THING THIS PAGE GOVERNS, split in the
   * CLIENT. Owner, verbatim: *"put 'Agents' and 'Assistants' access under a 'Module' section, so
   * Database-level access has its own 'Database' section."* A `surface` module is an app SURFACE
   * (Assistant, Agents) and everything else is a database; the flag is the server's own, parsed
   * by `permsModel.parsePermsPayload` from `modules[].surface`.
   *
   * β›” THE SERVER ORDER IS PRESERVED INSIDE EACH GROUP AND NOTHING IS SORTED. The order comes
   * from `core/perms.py::tenant_governable_modules` (customer_data, product_data, analyst,
   * automation, then `ut_*`), which today puts the two surfaces BETWEEN the Odoo topics and the
   * user databases. A filter keeps relative order, so grouping is the whole change: re-sorting
   * here would make this page disagree with every other reading of the same list.
   */
  const databases = payload ? payload.modules.filter((m) => !m.surface) : [];
  const surfaces = payload ? payload.modules.filter((m) => m.surface) : [];
  const groups = [...new Set(databases.map(databaseGroup))];
  const filteredDatabases = databases.filter((module) =>
    (group === "all" || databaseGroup(module) === group) &&
    module.label.toLocaleLowerCase().includes(databaseQuery.trim().toLocaleLowerCase()));
  const pageCount = Math.max(1, Math.ceil(filteredDatabases.length / MEMBER_PAGE_SIZE));
  const page = Math.min(databasePage, pageCount - 1);
  const pageStart = page * MEMBER_PAGE_SIZE;
  const pageDatabases = filteredDatabases.slice(pageStart, pageStart + MEMBER_PAGE_SIZE);
  const dirty = payload ? isDirty(payload, saved, draft) : false;
  /**
   * ⚠ `payload.isAdmin` ALONE GOES STALE THE MOMENT THIS PAGE CAN CHANGE THE
   * ROLE β€” which is new in wave 17. It is a snapshot taken by the perms GET on
   * mount; promote the account to Admin from the card above and that GET is not
   * repeated, so the "these rules are inert" banner would stay hidden over an
   * account whose rules had just become inert. `user.role` is the fresher
   * truth: the accounts list reloads after every write here, and the record
   * comes back with it. Both are read, because either can be the newer one β€”
   * and the failure this prevents is an admin restricting an administrator and
   * walking away believing they did, which is the exact misreading the banner
   * exists to stop.
   *
   * ⚠ NOT the local `role` state: that is the DRAFT, and an unsaved role change
   * has not made anything inert yet.
   */
  const subjectIsAdmin = user.role === "admin" || payload?.isAdmin === true;
  /**
   * ⚠ THE GUARD HAD TO WIDEN WITH THE PAGE. `dirty` describes the PERMISSION
   * draft only, and it was the whole story while this file was only a
   * permission editor. Merge the account form in and Escape would throw away a
   * half-typed display name or a role change with no prompt and no undo β€”
   * exactly the failure the capture-phase listener below exists to prevent,
   * arriving through a second door.
   *
   * ⚠ A TYPED PASSWORD IS DELIBERATELY NOT COUNTED. It is a one-shot field with
   * its own button, retyped in seconds, and prompting "discard changes?" because
   * a password box has characters in it trains people to click through the
   * prompt β€” which weakens the guard for the edits that actually cost something.
   */
  const accountDirty =
    name.trim() !== (user.name ?? "").trim() || role !== (user.role ?? "user");
  /**
   * ⭐ W54-T47 β€” the Connector axis's own baseline comparison. Compared as SORTED text rather than
   * by reference or length: the checkbox writes a new array on every click, so identity says
   * nothing, and two lists of the same size can hold different kinds.
   */
  const connKey = (list: string[]) => [...list].sort().join("\u0000");
  const connDirty = connKey(connDraft) !== connKey(connSaved);
  const anyDirty = dirty || accountDirty || connDirty;
  /**
   * ⭐⭐ W47-T19 (owner instruction 11) β€” WHAT THE ONE SAVE SAYS IT SAVES. With the two buttons
   * merged there is a single control committing two different kinds of work, and a fixed label
   * would be wrong half the time: "Save access" over a renamed account, or "Save account" over a
   * pure permission edit. So it names the wider of the two whenever the account form is part of
   * the write, and the narrower one when only the rules changed.
   *
   * ⚠ THE CONFIRM'S BUTTON READS THIS SAME VALUE, which is the point of holding it once: the
   * control the admin clicks and the control they confirm with can never disagree about what is
   * being written.
   *
   * β›” BOTH SPELLINGS ARE PINNED BY `verify_ui.py`, and neither is free to be reworded here.
   * "Save account" is what the render smoke reads to prove wave 17's R7 (the account form, with
   * its save, is on THIS page and not behind a second door), and its blanking is that check's
   * negative control. "Save access" is the label whose in-flight component
   * `saves_show_they_are_working`'s own NC strips to prove leg 1 can still fire. Changing either
   * word means changing the gate that pins it, in the same commit, on purpose.
   */
  /** ⚠ W54-T47 β€” the Connector axis counts as ACCESS, which is what the owner called it. Widening
   *  the first operand rather than adding a third word keeps both pinned spellings intact. */
  const saveLabel = (dirty || connDirty) && !accountDirty ? "Save access" : "Save account";

  const goBack = useCallback(() => {
    if (anyDirty) setAsk({ kind: "discard" });
    else onBack();
  }, [anyDirty, onBack]);

  /**
   * ⭐ W40-T14 β€” LEAVING THE DRILL-IN, as ONE function. The Back control in the pane and the
   * Escape key both call this, because a keyboard and a pointer disagreeing about where "back"
   * goes is the whole class of bug an arbitrated Escape handler exists to prevent.
   *
   * β›” IT ASKS NOTHING, unlike `goBack`. The pane edits the same draft as the page under it, so
   * nothing is discarded by returning β€” a "discard changes?" prompt here would be warning about
   * a loss that is not happening, which is exactly how a real prompt gets clicked through.
   * Stable (`[]`), so the once-bound capture listener below can call it.
   */
  const leaveEditing = useCallback(() => setEditing(null), []);

  // ⚠ CAPTURE PHASE, ON PURPOSE. The settings modal binds its own window
  // `keydown` and closes the WHOLE dialog on Escape β€” which, on this page,
  // would throw away an admin's unsaved edits with no prompt and no undo. A
  // capture-phase listener on the same target runs before that bubble-phase
  // one, so `stopPropagation()` here actually stops it.
  const dirtyRef = useRef(anyDirty);
  dirtyRef.current = anyDirty;
  const askRef = useRef(ask);
  askRef.current = ask;
  // ⭐ W40-T14 β€” the FOURTH state Escape arbitrates. It tracks the RESOLVED drill-in, not the raw
  // key: a stale key draws nothing, so Escape must not act as though a room were open over one.
  const editingRef = useRef(false);
  editingRef.current = editModule !== null;
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== "Escape") return;
      // ⭐ W47-T19 β€” the copy dialog was the innermost thing Escape used to arbitrate and it is
      // deleted, so the confirm below is the innermost thing left. Nothing else about this
      // arbitration changed, and the order of the three survivors is still load-bearing.
      if (askRef.current) {
        e.stopPropagation();
        setAsk(null);
        return;
      }
      // β›”β›” W40-T14 β€” THE DRILL-IN OUTRANKS `dirty`, AND THE ORDER IS THE WHOLE POINT. The pane
      // edits the same draft as the page beneath it, so leaving it discards nothing; falling
      // through to the `discard` question would ask about a data loss that is not happening, on
      // the one keystroke a reader presses to back out of a room. Escape here does exactly what
      // the pane's Back control does, through the same function.
      if (editingRef.current) {
        e.stopPropagation();
        leaveEditing();
        return;
      }
      if (dirtyRef.current) {
        e.stopPropagation();
        setAsk({ kind: "discard" });
      }
    };
    window.addEventListener("keydown", onKey, true);
    return () => window.removeEventListener("keydown", onKey, true);
    // ⚠ STILL BOUND ONCE. `leaveEditing` is `useCallback(..., [])`, so its identity never
    // changes and naming it here re-binds nothing; every state the handler reads still comes
    // through a ref for exactly that reason.
  }, [leaveEditing]);

  // ⚠ THE CONFIRM MUST BE BROUGHT INTO VIEW, and this is not polish. Its scrim
  // is scoped to THIS PANE rather than the viewport (a second full-screen scrim
  // over a dialog that already has one reads as the application losing its
  // place) β€” but the pane grows with the module list while `.set-body` is what
  // scrolls, so a card centred in the PANE can sit hundreds of pixels above the
  // visible area. The admin clicks Save at the bottom of a long page and
  // nothing appears to happen. One module fits today; the second one does not.
  const confirmRef = useRef<HTMLDivElement | null>(null);
  useEffect(() => {
    if (!ask) return;
    confirmRef.current?.scrollIntoView({ block: "center" });
    // Focus follows the question, so Enter answers it and a screen reader is
    // taken to the alert rather than left where the pointer was.
    confirmRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
  }, [ask]);

  /**
   * ⭐⭐ W47-T19 (owner instruction 11) β€” ONE SAVE, BOTH HALVES, IN THE ORDER A FAILURE CAN BE
   * REASONED ABOUT. Owner, verbatim: *"we should merge 'Save access' and 'Save account' and move
   * those buttons at the bottom of the navigation."* So the page's two writes became one action:
   * the account PATCH first, the permission PUT second, one success message.
   *
   * β›” THE ACCOUNT HALF GOES FIRST AND A FAILURE THERE STOPS THE WHOLE ACTION. The two writes
   * cannot be one transaction β€” they are two routes β€” so the order decides what a half-failure
   * leaves behind. Patching first means a refused PATCH writes nothing at all; doing it the other
   * way round would leave the access committed under a role the admin believed they had changed,
   * which is the one combination that misleads about who may see what.
   *
   * ⚠ THE ACCESS HALF IS SKIPPED WHEN THE RECORD NEVER LOADED, and that is not a shortcut: with
   * `payload` null there is no baseline to build a whole-tree PUT from, and `dirty` is false by
   * construction, so the only thing that can be dirty is the account form. Saving it anyway is
   * what keeps the display name, role and deactivate usable while the perms GET is failing β€”
   * the capability wave 17's R7 moved onto this page.
   */
  const save = useCallback(async () => {
    const request = requestScope.current?.signal;
    if (!request || request.aborted) return;
    const generation = actionGeneration.current;
    setBusy(true);
    if (accountDirty) {
      const a = await patchUser(username, { name, role });
      if (request.aborted || generation !== actionGeneration.current) return;
      if (!a.ok) {
        setBusy(false);
        setAsk(null);
        showRefusal(a.message);
        return;
      }
    }
    /**
     * ⭐ W54-T47 β€” THE CONNECTOR AXIS COMMITS HERE, BETWEEN THE TWO, AND THAT POSITION IS THE
     * ARGUMENT ABOVE APPLIED ONCE MORE.
     *
     * β›” AFTER THE ACCOUNT PATCH, because promoting the account to Admin makes every rule below
     * inert and a refused PATCH must still write nothing at all.
     * β›” BEFORE the `!payload` early return, because this grant does not live in the perms record
     * and has its own route: a failing perms GET must not take the Connector axis down with it,
     * for the same reason it does not take Deactivate down with it.
     * β›” AND A FAILURE STOPS THE ACTION rather than being swallowed. This is a permission write;
     * a half-save that reports success is how somebody comes to believe they revoked a connector
     * they did not.
     */
    if (connDirty) {
      const g = await putConnectorGrants(username, connDraft);
      if (request.aborted || generation !== actionGeneration.current) return;
      if (!g.ok) {
        setBusy(false);
        setAsk(null);
        showRefusal(g.message);
        return;
      }
      setConnSaved(connDraft);
    }
    if (!payload) {
      setBusy(false);
      setAsk(null);
      const msg = `Saved ${username}.`;
      setSaid(msg);
      // Stays on the page: the access half is still unread, so this is not the terminal action.
      onSaved(msg);
      return;
    }
    const body = retainedPermsBody(stored, payload, saved, draft);
    const r = await putUserPerms(username, body);
    if (request.aborted || generation !== actionGeneration.current) return;
    setBusy(false);
    setAsk(null);
    if (r.ok) {
      setSaved(draft);
      setStored(body.perms);
      const msg = accountDirty
        ? `Saved ${username} and their access.`
        : `Saved access for ${username}.`;
      setSaid(msg);
      // ⭐ W37-T05 β€” the second argument = TAKE THE ADMIN BACK TO THE LIST. Only this write passes
      // it, and that is the whole reconciliation with wave 17's R7: that ruling removed the return
      // BECAUSE "a page with several things to save should not eject you after the first". It was
      // right, and it stays right β€” `applyAccount` below still leaves you where you are. What
      // changed is that the owner named THIS save, which is the page's terminal action: with the
      // account and the access committed together there is nothing else on the pane to do.
      onSaved(msg, true);
    } else {
      showRefusal(accessSaveRefusal(r.message));
    }
  }, [payload, stored, saved, draft, username, onSaved, accountDirty, name, role, connDirty, connDraft]);

  /** The account half's write. ⚠ THE PATCH STILL CARRIES NO `bus` (R1), and
   *  that is load-bearing rather than tidy: with the picker gone this form
   *  cannot edit the field, so a PATCH that still sent it would be a client
   *  echoing back a value it only read β€” and once the migration converts `bus`
   *  into a permanent filter and clears the field, that echo would RESURRECT
   *  it. A form writes what it edits and nothing else. */
  const applyAccount = useCallback(
    (patch: Parameters<typeof patchUser>[1], said: string) => {
      const request = requestScope.current?.signal;
      if (!request || request.aborted) return;
      const generation = actionGeneration.current;
      setBusy(true);
      void patchUser(username, patch).then((r) => {
        if (request.aborted || generation !== actionGeneration.current) return;
        setBusy(false);
        if (r.ok) {
          setSaid(said);
          onSaved(said);
        } else {
          showRefusal(r.message);
        }
      });
    },
    [username, onSaved]
  );

  /**
   * ⭐ W40-T14 β€” WHO THIS PAGE IS ABOUT, plus whatever just happened, held ONCE. Both returns
   * below render it: the account page and the per-database room are the same room with a
   * different body, and a second copy of this markup is how the two come to disagree about which
   * account the reader is looking at (the `ModulePermsList` extraction, one level up).
   */
  const head = (
    <div className="set-member-header">
      {/* ⭐⭐ W40-T15 (owner instruction 9) β€” THE WAY OUT AND THE PAGE TITLE STOPPED SHARING A
          LINE. Owner, verbatim: *"'Back to accounts' with the username to its right is ugly, make
          it sleeker."* They were three unequal things on one `space-between`-free flex row β€” an
          exit, a person, and two status chips β€” so the eye met a button first and the name of the
          account it had just opened second, at the same weight.
          Now the exit is page chrome on its own line, quiet the way `.shell-newfolder` is quiet
          (muted ink, wash on hover, no border), and the identity is the page TITLE underneath it
          with the chips beside the name exactly as before.
          β›” THE LITERAL "Back to accounts" IS PINNED TWICE: `pages/_test/render.test.tsx` asserts
          the way out paints before the record arrives, and `verify_ui.py`'s compiled control
          `perms-editor-loses-its-way-out-while-loading` blanks this very string and demands that
          leg go red. It stays one JSX text node, and the chevron is a sibling of it. */}
      <button type="button" className="set-perm-back" onClick={goBack}>
        {/* The chevron `DatabasePermsPane` already draws, at the same geometry: extending the
            house vocabulary rather than importing a second icon language (`DESIGN.md` Β§4). */}
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false">
          <path
            d="M9.5 4 5.5 8l4 4"
            stroke="currentColor"
            strokeWidth={1.3}
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
        Back to accounts
      </button>
      <div className="set-perm-ident">
        <div className="set-perm-nameline">
          <h3 className="set-h set-perm-title">{displayName}</h3>
          {/* ⚠ THE CHIPS STAY BESIDE THE NAME, and the reason index.css records for it still
              holds: pushed to the far end they read as a status of the DIALOG rather than of the
              person. All that changed is which line the name sits on. */}
          <span className={role === "admin" ? "set-chip set-chip--admin" : "set-chip"}>
            {role === "admin" ? "Admin" : "Member"}
          </span>
          {user.active ? null : <span className="set-chip set-chip--off">Deactivated</span>}
        </div>
        <span className="set-username">{username}</span>
      </div>

      {said ? <p className="set-notice" role="status">{said}</p> : null}
    </div>
  );

  /**
   * ⭐ W40-T15 (owner instruction 8) β€” ONE MOUNT OF `ModulePermsList`, CALLED TWICE. The page now
   * draws a "Database" list and a "Module" list, and the ticket asks for both to get the same
   * handlers, the same `onEdit`, the same `onMetrics` and the same `userOptions`. Two literal
   * copies of that ten-prop element would be the `ManageAgentPane` mistake this component was
   * extracted to prevent, one file down: the copies drift, and each reads correct on its own.
   *
   * β›” `onMetrics=` STAYS ON ONE LINE WITH ITS CLOSING BRACE. `verify_ui.py`'s
   * `metrics_toggle_has_a_mount_site` NC deletes every `\n\s*onMetrics=\{[^\n]*\}` from this file
   * and requires the check to go RED; split the prop across lines and the mutation matches
   * nothing, the NC no-ops, and the gate fails on a control that tested nothing.
   *
   * ⭐ ONE RENDERER FOR BOTH ROOMS (owner item 10: *"manage agent too since its the same exact
   * layout"*). The list used to be ~70 lines of JSX in the render below; it is
   * `settings/ModulePermsList.tsx`, and `manage-agent/ManageAgentPane` mounts the SAME component.
   * Nothing about the list is duplicated, so nothing about it can drift.
   *
   * β›”β›” `onMetrics` ABOVE IS THE LINE W38-T19 SHIPPED WITHOUT, AND EVERY GATE WAS GREEN OVER ITS
   * ABSENCE. The capability was complete on both sides β€” `perm_scope.may_metrics`, four gated
   * read doors, `_clean_perms`'s fourth entry field, `parseEntry`/`toPutBody`, and the checkbox
   * itself in `ModulePermsList` β€” with 39 new gate checks across `api_scopes`, `web_login` and
   * `web_ui`. What did not exist was this prop, so the component's own
   * `{on && !schemaless && onMetrics}` render gate never fired and the toggle the `done-when`
   * names had NO MOUNT SITE anywhere in the product. Found by wave-38 QA on the deployed build,
   * by opening the screen and looking.
   * ⭐ THE PROP IS OPTIONAL AND THAT IS PRECISELY WHAT LET IT SHIP: `tsc` cannot name a call site
   * that forgot an optional prop. It STAYS optional because `manage-agent` legitimately does not
   * want it (an agent's reads never open a grid door, so the rule would be stored and never
   * applied) β€” so what pins this line is `verify_ui.py`'s `metrics_toggle_has_a_mount_site`, not
   * the type system.
   * ⭐⭐ W40-T14 MOVED THE MOUNT SITE AND W40-T16 RETIRED IT. Owner instruction 7 put the blanket
   * Metrics toggle inside the database's own pane, so `onEdit` here also suppresses the row's
   * copy of the box (`!drilled` in `ModulePermsList`); owner instruction 13 then folded that
   * blanket box into the pane's Hide-fields list, one checkbox per metric, and the pane's control
   * is deleted. β›” SO `onMetrics` ABOVE NOW FEEDS A BRANCH THAT NEVER RENDERS, and the other
   * caller does not render it either β€” `manage-agent/ManageAgentPane.tsx` passes exactly
   * `modules, entries, onAccess, onFilter, onToggleHidden, onSetHidden, userOptions, emptyNote`
   * and no `onMetrics` (measured, not assumed). Nothing in the UI writes `PermsEntry.metrics` any
   * more, which is instruction 13 replacing a blanket control rather than keeping it beside its
   * replacement; the boolean lives on as a legacy value that `hiddenSetFor` honours on read.
   * ⚠ THE LINE STAYS because it keeps the seam and its two gate controls exercised β€” see the
   * note on the box itself in `ModulePermsList.tsx`, where the cost of keeping it is spelled out.
   * β›” THE CHECK MOVED WITH THE CONTROL, TWICE. `verify_ui.py::metrics_toggle_has_a_mount_site`
   * grew clauses over `DatabasePermsPane.tsx` in W40-T14 because clauses 3 and 4 would have
   * stayed GREEN over a pane that dropped the checkbox; W40-T16 replaced those clauses with ones
   * over the PER-METRIC ROWS that took its place, so the check still has a live subject rather
   * than going green on a deletion.
   * ⚠ AND THE WHOLE BLOCK IS A DOC COMMENT ON THE HELPER, NEVER A JSX COMMENT BETWEEN THE
   * ATTRIBUTES: a JSX comment in an attribute list TYPE-CHECKS under the app's own tsc and then
   * EMITS a bare `...` into the props object, invalid JS that only the render smoke catches.
   */
  /**
   * ⭐⭐ W40-T16 β€” EVERY HIDDEN-FIELD WRITE GOES THROUGH HERE FIRST, and this composition is the
   * ONE spelling of it rather than four hand-copies. Four callbacks write `hiddenFields` (the
   * list's toggle and set-all, the pane's toggle and set-all); a copy that forgot the wrapper
   * would be a DOOR LEFT BEHIND β€” one route by which a record keeps its blanket `metrics: false`
   * while the other three convert it, which is the class of bug this file's own history is full
   * of. `verify_ui.py::metrics_toggle_has_a_mount_site` refuses a raw-draft hidden write here for
   * exactly that reason.
   *
   * β›” WHY A WRITE NEEDS NORMALISING AT ALL: `hiddenSetFor` paints every metric row hidden while
   * the blanket revocation stands, so without this the row could never be made visible again β€”
   * unticking it writes the key, the union re-hides it, and the blanket has no control left to
   * lift it. `normalizeMetrics` converts the blanket into the explicit per-metric list, LOSSLESSLY
   * (the union preserves what it meant), at the moment the admin is already deciding.
   *
   * ⚠ THE FIELD LIST COMES FROM `payload`, NOT FROM THE CALLER'S SUBSET. `accessList` is invoked
   * twice, over `databases` and over `surfaces`; resolving against the whole declared list is
   * what keeps one answer for "which fields does this database have" no matter which section the
   * click came from. An unknown key yields an empty list, which makes this a no-op rather than a
   * guess.
   */
  const metricNormalized = (d: PermsRecord, key: string): PermsRecord =>
    normalizeMetrics(d, key, payload?.modules.find((m) => m.key === key)?.fields ?? []);

  const accessList = (mods: PermsModule[], emptyNote?: string) => (
    <ModulePermsList
      modules={mods}
      entries={draft}
      onAccess={(key, on) => setDraft((d) => setAccess(d, key, on))}
      onFilter={(key, next) => setDraft((d) => setFilter(d, key, next))}
      onToggleHidden={(key, fk) => setDraft((d) => toggleHidden(metricNormalized(d, key), key, fk))}
      onSetHidden={(key, keys) => setDraft((d) => setHidden(metricNormalized(d, key), key, keys))}
      onMetrics={(key, on) => setDraft((d) => setMetrics(d, key, on))}
      onEdit={(key) => setEditing(key)}
      userOptions={userOptions}
      emptyNote={emptyNote}
    />
  );

  /**
   * ⭐⭐ W40-T14 (owner instruction 7) β€” THE DRILL-IN IS A FULL-PANE TAKEOVER, not a panel beside
   * the list: *"Edit opens the whole database's Fields and Filters to toggle, with a Back button
   * to return."* So the account card, the notices, the Access section, the module list and the
   * bottom actions are all REPLACED while it is open, and the reader has one thing to read.
   *
   * ⚠ IT CANNOT OPEN OVER AN UNLOADED RECORD: `editModule` resolves against `payload.modules`,
   * which is null until the GET answers.
   *
   * ⭐⭐ W40-T16 (OWNER INSTRUCTION 13) β€” THE PANE NO LONGER TAKES `onMetrics`, AND THE MISSING
   * PROP BELOW IS THE TICKET RATHER THAN AN OVERSIGHT. The blanket box ("Metric fields (lookback
   * measures over this database)") is folded into that pane's Hide-fields list as one checkbox
   * per metric, so `DatabasePermsPane` stopped declaring the prop and passing it would not
   * compile. `setMetrics` is still imported and still wired β€” by `accessList` above, to the ROW's
   * box, which `manage-agent/ManageAgentPane.tsx` still needs and which has no Hide-fields list
   * of metric rows to be folded into.
   */
  if (editModule) {
    return (
      <div className="set-pane set-perms set-member">
        {head}
        <DatabasePermsPane
          module={editModule}
          entries={draft}
          onBack={leaveEditing}
          onFilter={(next) => setDraft((d) => setFilter(d, editModule.key, next))}
          onToggleHidden={(fk) =>
            setDraft((d) => toggleHidden(metricNormalized(d, editModule.key), editModule.key, fk))}
          onSetHidden={(keys) =>
            setDraft((d) => setHidden(metricNormalized(d, editModule.key), editModule.key, keys))}
          userOptions={userOptions}
          /**
           * ⭐⭐ W46-T34 β€” THE METRIC CENSUS FOR THIS DATABASE, AND THIS LINE IS WHAT MAKES THE
           * PANE'S `none` AND `unavailable` BRANCHES REACHABLE AT ALL. The server has published
           * `metrics_by_module` since the ticket's first half; nothing read it, so the pane could
           * only ever see its own field-count fallback and the two branches were dead code with
           * every gate green ([[a-built-validated-wall-can-have-no-caller]]).
           *
           * ⚠ `undefined` FOR A DATABASE THE SERVER DID NOT REPORT ON, and that is the correct
           * absence rather than a gap. `parsePermsPayload` keeps the map SPARSE: an older server,
           * or an entry whose `status` is not one of the three, leaves no key here, and the pane
           * then falls back to counting its own metric rows β€” the one reading that refuses to
           * call an empty list "none". Substituting a zero census here would print the confident
           * wrong sentence for exactly the case nobody could answer.
           */
          metrics={payload?.metricsByModule?.[editModule.key]}
        />
      </div>
    );
  }

  return (
    <div className="set-pane set-perms set-member">
      {head}

      <label className="set-member-master">
        <span>Account active</span>
        <input type="checkbox" role="switch" checked={user.active} disabled={busy || anyDirty}
          title={anyDirty ? "Save or discard changes first." : undefined}
          aria-label={user.active ? "Deactivate account" : "Reactivate account"}
          onChange={() => applyAccount({ active: !user.active }, `${user.active ? "Deactivated" : "Reactivated"} ${username}.`)} />
      </label>

      {load.phase === "loading" ? (
        <div className="set-skeleton" role="status" aria-label="Loading access" aria-busy="true">
          <span className="set-skeleton-line" aria-hidden="true" />
          <span className="set-skeleton-line" aria-hidden="true" />
          <span className="set-skeleton-line" aria-hidden="true" />
        </div>
      ) : null}
      {load.phase === "error" ? <div className="set-error" role="alert">
        <span title={load.message}>Could not load this account's access.</span>
        <button type="button" className="set-secondary" onClick={() => setReadAttempt((attempt) => attempt + 1)}>Retry</button>
      </div> : null}

      {payload ? (
        <>
          {/* β›”β›” W40-T14 (owner instruction 7: *"Remove the ugly administrator note."*) β€” THE
              `subjectIsAdmin` BANNER IS DELETED, NOT SHORTENED. `DESIGN.md` Β§4, "never
              over-explain": the app does not narrate itself. That paragraph was STANDING
              narration β€” it said the same three sentences on every admin account, every visit,
              about a fact the header already states: the role chip beside the name reads "Admin",
              and the Role select in the card above is the control that changes it. A shorter
              paragraph in its place would be the same defect in fewer words.
              ⚠ `subjectIsAdmin` SURVIVES: the `!payload.migrated` notice below still reads it,
              and that one is a conditional warning about THIS record rather than standing prose.

              C-PERM amendment 4 β€” an un-migrated record still runs under the
              PREVIOUS wall, so its empty perms mean "not written yet", not "no
              access". Saying so is the difference between an admin reading this
              page correctly and one who thinks the account is locked out. */}
          {!payload.migrated && !subjectIsAdmin ? (
            <p className="set-notice set-perm-banner" role="status">
              This account still uses the previous access model, so the rules below
              are not in force yet. Saving moves it to the per-module model, so set
              every module deliberately before you do.
            </p>
          ) : null}

          {/* A whole-record replace drops what it does not name. An admin should
              learn that here, not from a support ticket about a filter that
              vanished. */}
          {/* R252 keeps undeclared entries in the stored block on every save. */}

          {/* ⭐⭐ W47-T19 (owner instruction 11) β€” THE SECOND SAVE IS GONE FROM THIS HEADING, AND
              SO IS THE COPY DOOR. Owner, verbatim: *"We have two 'Save access' under Manage User,
              one in the middle of the navigation and one at the bottom. Delete the one in the
              middle."* W40-T15 offered the same command at both ends of the section on purpose;
              the owner has now read that as one button too many, and the bottom bar is where every
              button on this pane lives.
              ⚠ THE `.set-perm-sectend` WRAPPER WENT WITH THEM. It existed only to keep those two
              trailing controls to ONE flex child of `.set-perm-sect` (which is `space-between` and
              lives in index.css, not this lane's file); with nothing to group it would be an empty
              span holding a heading away from an edge.
              ⚠ `role="group"` STAYS, and its reason narrowed rather than expired: the section is
              still one named region, named by its own heading through `aria-labelledby` so there is
              one copy of the word "Access" and it cannot drift. */}
          <div className="set-member-access" role="group" aria-labelledby="set-access-h">
            <div className="set-perm-sect">
              <h4 className="set-h4" id="set-access-h">Access</h4>
            </div>

            {/* ⭐ W40-T14 β€” WHAT THIS ACCOUNT CAN SEE, and nothing else. `DESIGN.md` Β§4 "never
                over-explain": the three clauses that used to follow were a feature tour of the
                controls sitting directly underneath, restated on every visit. The sentence that
                stays is STATE β€” it changes as the draft changes, and it is the one line here a
                reader cannot get by looking. */}
            <p className="set-help set-perm-intro">{accessSummary(payload, draft)}.</p>

            {/* ⭐ W47-T19 β€” the "copying is unavailable while there are unsaved changes" line went
                with the copy door it explained. A sentence about a control the page no longer
                offers is worse than no sentence. */}

            {/* ⭐⭐ W40-T15 (owner instruction 8) β€” TWO ROOMS, AND NEITHER OF THEM IS EMPTY.
                β›” A GROUP WITH NO MEMBERS RENDERS NO HEADING, which is the whole reason this is a
                branch rather than two unconditional blocks: a tenant with no `ut_*` databases and
                no surfaces would otherwise read as two labelled empty rooms, which says the
                deployment lost something rather than that it never had it.
                ⚠ AND THE "governs NOTHING at all" MESSAGE STAYS REACHABLE. When there is not one
                module of either kind, one HEADLESS list is rendered so `ModulePermsList`'s own
                empty branch still speaks β€” the note belongs to the list, and a heading over it
                would be labelling an absence. */}
            {payload.modules.length === 0
              ? accessList([], "This deployment declares no modules that can be restricted.")
              : (
                  <>
                    {surfaces.length ? (
                      <>
                        <h5 className="set-h4 set-perm-group">Module</h5>
                        {accessList(surfaces)}
                      </>
                    ) : null}
                    {databases.length ? (
                      <>
                        <h5 className="set-h4 set-perm-group">Database</h5>
                        <div className="set-member-filters">
                          <label className="set-member-search">
                            <span className="set-label">Search databases</span>
                            <input type="search" className="set-input" value={databaseQuery}
                              onChange={(event) => { setDatabaseQuery(event.target.value); setDatabasePage(0); }} />
                          </label>
                          <label>
                            <span className="set-label">Group</span>
                            <select className="pg-select" value={group}
                              onChange={(event) => { setGroup(event.target.value); setDatabasePage(0); }}>
                              <option value="all">All databases</option>
                              {groups.map((name) => <option key={name} value={name}>{name}</option>)}
                            </select>
                          </label>
                        </div>
                        {[...new Set(pageDatabases.map(databaseGroup))].map((name) => (
                          <div className="set-member-database-group" key={name}>
                            <h6 className="set-member-group-name">{name}</h6>
                            {accessList(pageDatabases.filter((module) => databaseGroup(module) === name))}
                          </div>
                        ))}
                        {filteredDatabases.length === 0 ? <p className="set-help">No databases match.</p> : null}
                        <nav className="set-member-pager" aria-label="Database pages">
                          <span aria-live="polite">{filteredDatabases.length ? pageStart + 1 : 0} to {Math.min(pageStart + MEMBER_PAGE_SIZE, filteredDatabases.length)} of {filteredDatabases.length}</span>
                          <button type="button" className="set-secondary" disabled={page === 0} onClick={() => setDatabasePage(0)}>First</button>
                          <button type="button" className="set-secondary" disabled={page === 0} onClick={() => setDatabasePage(page - 1)}>Previous</button>
                          <span>Page {page + 1} of {pageCount}</span>
                          <button type="button" className="set-secondary" disabled={page === pageCount - 1} onClick={() => setDatabasePage(page + 1)}>Next</button>
                          <button type="button" className="set-secondary" disabled={page === pageCount - 1} onClick={() => setDatabasePage(pageCount - 1)}>Last</button>
                        </nav>
                      </>
                    ) : null}
                  </>
                )}

            {/* ⭐⭐ W54-T47 / R4 / contract C4 β€” THE THIRD ROOM. Owner, verbatim: *"Under
                Settings, an Admin should grant a user access to add connectors, so access becomes
                Database / Module / Connector. This allows many connectors per tenant … depending
                on the admin's configuration per user."*

                β›” IT SITS OUTSIDE THE `payload.modules.length` TERNARY ABOVE, and that is not a
                layout choice. A connector is not a registry module, so a deployment that governs
                no databases at all can still have an administrator deciding who may wire up
                Shopify; nesting this inside that branch would have made the new axis disappear
                for exactly the tenant with the least already set up.

                β›” A GROUP WITH NO MEMBERS RENDERS NO HEADING, the same rule the two groups above
                follow and the same reason: an empty labelled room says the deployment lost
                something rather than that it never had it. An older server, or one whose route
                refused, leaves `connKinds` empty and nothing paints.

                ⚠ A CHECKBOX PER KIND AND NO `ModulePermsList`. That component's furniture is a
                filter, a field list and a drill-in room; a connector has none of the three, and
                borrowing the card would have promised three controls that cannot exist. The card
                idiom is shared, the list component is not. */}
            {connKinds.length ? (
              <>
                <h5 className="set-h4 set-perm-group">Connector</h5>
                {/* ⚠ THE SECOND SENTENCE IS THE ONE A READER CANNOT GET BY LOOKING, and it is
                    what stops an admin reading an empty list as a lockout: no grant is the
                    ordinary state and it takes nothing away. */}
                <p className="set-help set-perm-intro">
                  Ticked connectors are the ones this account can add for the whole workspace.
                  Everyone can already add their own personal connections, so leaving these clear
                  takes nothing away.
                </p>
                {connKinds.map((k) => {
                  const on = connDraft.includes(k.key);
                  return (
                    <section className="set-card set-perm-mod" key={k.key}>
                      <div className="set-perm-modhead">
                        <label className="set-check set-perm-toggle">
                          <input
                            type="checkbox"
                            checked={on}
                            onChange={(e) =>
                              setConnDraft((cur) =>
                                e.target.checked
                                  ? [...cur, k.key]
                                  : cur.filter((x) => x !== k.key)
                              )
                            }
                          />
                          <span className="set-perm-modname">{k.label}</span>
                        </label>
                        {/* ⚠ Wrapped for the reason `ModulePermsList` wraps its own trailing
                            controls: `.set-perm-modhead` is `space-between` and lives in
                            `index.css`, which this lane does not own. One flex child in, one out. */}
                        <span className="set-perm-headend">
                          {k.tenantWide ? (
                            <span className="set-perm-sum">
                              Every database in this workspace reads through it
                            </span>
                          ) : null}
                        </span>
                      </div>
                    </section>
                  );
                })}
              </>
            ) : null}

          </div>
        </>
      ) : null}

      {/* ── the account (R7) ─────────────────────────────────────────────── */}
      <section className="set-card">
        <h4 className="set-h4">Account</h4>
        <div className="set-grid2">
          <div className="set-field">
            <label className="set-label" htmlFor="set-name">Display name</label>
            <input
              id="set-name"
              className="set-input"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div className="set-field">
            <label className="set-label" htmlFor="set-role">Role</label>
            <select
              id="set-role"
              className="pg-select"
              value={role}
              onChange={(e) => setRole(e.target.value)}
            >
              <option value="user">Member</option>
              <option value="admin">Admin</option>
            </select>
          </div>
        </div>
        {/* An admin bypasses every rule below. Changing the role here therefore
            changes whether this whole page means anything, and saying so at the
            control beats discovering it from an access page that does nothing. */}
        {role === "admin" && (user.role ?? "user") !== "admin" ? (
          <p className="set-help">
            Saving this makes the account an administrator, which bypasses every
            access rule set below.
          </p>
        ) : null}
        {/* ⭐⭐ W47-T19 (owner instruction 11) β€” THIS CARD HAS NO BUTTONS OF ITS OWN ANY MORE.
            "Save account" and "Deactivate account" moved to the one action bar at the bottom of
            the page, which is where the owner asked for every button on this pane to live. The
            card is now what it describes: the account's fields. The password control below stays
            HERE on purpose and is not part of that merge β€” it is a one-shot field with its own
            immediate consequence, not a pending edit the bottom bar could commit. */}

        {/* ⭐⭐ W40-T15 (owner instruction 9) β€” ONE DELIBERATE GROUP, READ TOP TO BOTTOM. Owner,
            verbatim: *"move the 'This signs <email> out everywhere immediately.' notice one line
            below. The reset password control is misplaced."*

            β›” WHAT WAS WRONG WITH THE TWO-COLUMN GRID IT REPLACES, and it is not taste. The
            field sat in column one and the button in column two under a sentence, so the three
            parts of ONE action were split across a column boundary: the reader met the
            consequence before the control that causes it, and the button lined up with a
            sentence rather than with the box it acts on. The old note here defended the grid on
            the grounds that it made the password box the same width as the display-name box β€”
            true, and the wrong thing to optimise, because the two boxes are not the same kind of
            thing and never wanted the same row.
            Now: label, box and button share ONE line and one baseline (`DESIGN.md` Β§4, "controls
            in a row share height and baseline"), and the consequence sits a line under them,
            which is both the owner's move and the order a person acts in.
            ⚠ IT IS STILL THE SAME `.set-danger` BLOCK under the same red hairline. No new card:
            a destructive-ish action inside the Account card is one containment layer, and a
            second box around it would be the card-in-card `DESIGN.md` Β§4 forbids. */}
        <div className="set-danger set-pw-group">
          <div className="set-pw-row">
            <div className="set-field set-pw-field">
              <label className="set-label" htmlFor="set-pw">Set a new password</label>
              <input
                id="set-pw"
                className="set-input"
                type="password"
                value={pw}
                autoComplete="new-password"
                onChange={(e) => setPw(e.target.value)}
              />
            </div>
            <button
              type="button"
              className="set-secondary"
              disabled={busy || pw.length === 0}
              onClick={() => {
                const request = requestScope.current?.signal;
                if (!request || request.aborted) return;
                const generation = actionGeneration.current;
                void setPassword(username, pw).then((r) => {
                  if (request.aborted || generation !== actionGeneration.current) return;
                  if (r.ok) {
                    setPw("");
                    setSaid(`Password reset; ${username} was signed out.`);
                  } else {
                    showRefusal(r.message);
                  }
                });
              }}
            >
              <Busy busy={busy} idle="Reset password" doing="Resetting" />
            </button>
          </div>
          {/* Still said plainly BEFORE the click, only now under the control rather than over
              it. Resetting a password bumps the session epoch, which signs the person out of
              every device they are using, and an admin should not discover that from a support
              ticket.
              ⚠ `.set-pw-note` EXISTS BECAUSE THE OLD SPACING WAS UPSIDE DOWN: index.css puts
              `margin: 0 0 7px` on `.set-pw-side .set-help`, a gap UNDER a sentence that used to
              be first. That rule is lane I's and is not edited; the wrapper it keyed off is gone
              from this markup, so it matches nothing here and the new class sets the gap ABOVE
              the sentence where this arrangement wants it. */}
          <p className="set-help set-pw-note">
            This signs {username} out everywhere immediately.
          </p>
        </div>
      </section>

      {/* ⭐⭐ W47-T19 (owner instruction 11) β€” ONE BAR, AT THE BOTTOM, FOR EVERY BUTTON ON THIS
          PAGE. Owner, verbatim: *"we should merge 'Save access' and 'Save account' and move those
          buttons at the bottom of the navigation. Deactivate this account and apply access to
          button should live at the bottom of the navigation too."* Three action groups became
          this one: the Account card's pair, the mid-section save, and the old bottom row.

          β›” IT SITS OUTSIDE THE `{payload ? … : null}` BLOCK, AND THAT IS NOT A LAYOUT DETAIL. The
          account half of this page is served by the `AdminUser` the accounts list already holds
          and renders before the permission GET answers (wave 17 R7); the access half does not.
          Put this bar inside the payload gate and a failing or slow perms read would take
          Deactivate away with it β€” the one control an admin reaches for when an account is
          misbehaving, and R7 deleted the other door to it. `save()` handles the same case on the
          write side by skipping the access half when there is no record to build a PUT from.

          ⚠ THE ORDER IS THE OWNER'S: the primary first, then the account-level action, then the
          way out, then what is outstanding. */}
      <div className="set-actions set-perm-actions">
        <button
          type="button"
          className="set-primary"
          disabled={busy || load.phase === "loading" || !anyDirty}
          title="Saves the account details and the access rules together."
          onClick={() => setAsk({ kind: "save" })}
        >
          <Busy busy={busy} idle={saveLabel} doing="Saving" />
        </button>
        {/* ⚠ NOT PART OF THE MERGE, AND DELIBERATELY STILL ITS OWN WRITE. Deactivating is not a
            pending edit sitting in a form: it is an immediate, reversible switch on the account,
            so it keeps `applyAccount` and leaves the admin where they are. Merging it into the
            Save would mean a role change and a deactivation could only ever ship together. */}
        <button
          type="button"
          className="set-secondary"
          disabled={busy}
          onClick={() =>
            applyAccount(
              { active: !user.active },
              `${user.active ? "Deactivated" : "Reactivated"} ${username}.`
            )
          }
        >
          <Busy busy={busy} idle={user.active ? "Deactivate account" : "Reactivate account"}
                doing={user.active ? "Deactivating" : "Reactivating"} />
        </button>
        <button type="button" className="set-secondary" disabled={busy} onClick={goBack}>
          Cancel
        </button>
        {anyDirty ? <span className="set-help set-perm-dirty">Unsaved changes</span> : null}
      </div>

      {ask ? (
        <div className="set-confirm-wrap">
          <div
            ref={confirmRef}
            className="set-confirm"
            role="alertdialog"
            aria-modal="true"
            aria-label={ask.kind === "save" ? "Confirm these changes" : "Discard changes"}
          >
            {ask.kind === "save" ? (
              <>
                {/* ⭐ W47-T19 β€” THE QUESTION COVERS BOTH HALVES NOW, and it names which ones are
                    in the write through the same `unsavedWords` the discard question uses. One
                    Save commits the account form and the access rules together, so a confirm
                    that only asked about access would be understating what the click does. */}
                <h4 className="set-h4">Save these changes for {displayName}?</h4>
                <p className="set-help">
                  {unsavedWords(dirty || connDirty, accountDirty)} are written now, and a change to access takes
                  effect the next time they load a page. {accessSummaryLine(payload, draft)}
                </p>
              </>
            ) : (
              <>
                <h4 className="set-h4">Discard these changes?</h4>
                {/* ⚠ IT NAMES WHICH ONES. The page holds two kinds of unsaved
                    work now, and "your changes" over a form the reader cannot
                    see behind the scrim is a question they cannot answer. */}
                <p className="set-help">
                  {unsavedWords(dirty || connDirty, accountDirty)} for {displayName} stay as they were.
                </p>
              </>
            )}
            <div className="set-actions">
              {/* ⭐ W47-T19 β€” THREE BRANCH-OWNED BUTTONS RATHER THAN ONE BUTTON WITH THREE
                  TERNARIES INSIDE IT. Each branch renders the whole control, so the label, the
                  in-flight words and the handler travel together and a reader sees one complete
                  button per answer. The save branches read `saveLabel`, so this dialog says
                  exactly what the bar behind it said.
                  β›” AND IT IS WHAT KEEPS `verify_ui.py`'s NC t05-bare ABLE TO FIRE: that control
                  strips the `<Busy>` element off the "Save access" spelling and requires the check
                  to go red. Fold these back into one `<button>` and the surviving `<Busy>` in the
                  other branch hides the stripped one from the check, which then passes over a bare
                  label and the negative control silently tests nothing. */}
              {ask.kind !== "save" ? (
                <button
                  type="button"
                  className="set-primary"
                  disabled={busy}
                  onClick={() => {
                    setAsk(null);
                    onBack();
                  }}
                >
                  <Busy busy={busy} idle="Discard" doing="Discarding" />
                </button>
              ) : saveLabel === "Save access" ? (
                <button
                  type="button"
                  className="set-primary"
                  disabled={busy}
                  onClick={() => void save()}
                >
                  <Busy busy={busy} idle="Save access" doing="Saving" />
                </button>
              ) : (
                <button
                  type="button"
                  className="set-primary"
                  disabled={busy}
                  onClick={() => void save()}
                >
                  <Busy busy={busy} idle="Save account" doing="Saving" />
                </button>
              )}
              <button
                type="button"
                className="set-secondary"
                disabled={busy}
                onClick={() => setAsk(null)}
              >
                Keep editing
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

/** The confirm's one-line restatement. Deliberately the SAME sentence the pane
 *  header shows: a confirm that summarises differently from the page behind it
 *  is asking the reader to reconcile two descriptions under time pressure. */
function accessSummaryLine(payload: PermsPayload | null, draft: PermsRecord): string {
  const s = accessSummary(payload, draft);
  return s ? `${s} after this change.` : "";
}

/** Which kinds of unsaved work the discard question is about. Exported-shaped
 *  as a pure function so it reads once and cannot drift between the two places
 *  a reader meets it. */
function unsavedWords(permsDirty: boolean, accountDirty: boolean): string {
  if (permsDirty && accountDirty) return "The account details and access rules";
  if (accountDirty) return "The account details";
  return "The access rules";
}