@terpjs/react-core 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,655 @@
1
+ // @vitest-environment jsdom
2
+ import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
3
+ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
4
+ import { useEffect } from "react";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import type { ModuleManifest } from "@terpjs/contract";
7
+ import type { ComponentType } from "react";
8
+
9
+ import { withAdminArea } from "../bootstrap";
10
+ import { buildAppRouter } from "../router";
11
+ import { Page } from "../Page";
12
+ import { TerpProvider, useAuth } from "../TerpProvider";
13
+ import { ToastProvider } from "../toast";
14
+
15
+ /**
16
+ * The permission surface end to end: the screen that *explains* the declared model
17
+ * (`/admin/access`) and the panel that *assigns* from it (on a subject's detail screen).
18
+ *
19
+ * Its own harness rather than `admin.test.tsx`'s, for one reason: that fixture answers
20
+ * `/access/model` with no modules at all, which is what every other admin screen needs from it
21
+ * (a role ladder and nothing else). Both surfaces here are entirely about the modules, so they
22
+ * need a model with real ones — and putting that in the shared fixture would make every
23
+ * unrelated admin screen render module strips it has no business rendering.
24
+ */
25
+
26
+ const SUBJECT = "11111111-1111-4111-8111-111111111111";
27
+ const GROUP = "22222222-2222-4222-8222-222222222222";
28
+
29
+ function jsonResponse(body: unknown, status = 200): Response {
30
+ return new Response(JSON.stringify(body), {
31
+ status,
32
+ headers: { "content-type": "application/json" },
33
+ });
34
+ }
35
+
36
+ /** One endpoint of a module, with the outcome the *server* reported for each rung. */
37
+ function endpoint(
38
+ methods: string[],
39
+ label: string | null,
40
+ allowed: Record<string, boolean>,
41
+ ) {
42
+ return {
43
+ path: "/api/v1/notes/",
44
+ methods,
45
+ requirement: "role:viewer",
46
+ extra_permissions: [],
47
+ name: "handler",
48
+ operation: label === null ? null : { id: `notes.${label}`, label },
49
+ by_role: Object.entries(allowed).map(([role, ok]) => ({
50
+ role,
51
+ allowed: ok,
52
+ reason: ok ? "allowed" : "rank",
53
+ })),
54
+ };
55
+ }
56
+
57
+ function accessModel() {
58
+ return {
59
+ // Deliberately out of rank order: the endpoint sorts and the hook sorts again, so a
60
+ // pre-sorted fixture would observe neither, and a ladder rendered out of order destroys the
61
+ // whole legibility of a strip — its point is authority reading left to right.
62
+ roles: [
63
+ { name: "admin", rank: 30 },
64
+ { name: "viewer", rank: 10 },
65
+ { name: "editor", rank: 20 },
66
+ ],
67
+ permissions: [],
68
+ modules: [
69
+ {
70
+ name: "notes",
71
+ prefix: "/api/v1/notes",
72
+ policy: { read: "viewer", write: "editor" },
73
+ permissions: ["notes.delete"],
74
+ access: { assignable: true, label: "Notes", platform_reason: null },
75
+ endpoints: [
76
+ endpoint(["GET"], "View a note", { viewer: true, editor: true, admin: true }),
77
+ endpoint(["POST"], "Write a note", { viewer: false, editor: true, admin: true }),
78
+ endpoint(["DELETE"], "Delete a note", { viewer: false, editor: false, admin: true }),
79
+ ],
80
+ },
81
+ {
82
+ name: "reports",
83
+ prefix: "/api/v1/reports",
84
+ policy: { read: "viewer", write: "editor" },
85
+ permissions: [],
86
+ access: { assignable: true, label: "Reports", platform_reason: null },
87
+ // One route with no declared operation, so the pane has to say the module is not fully
88
+ // explained rather than presenting a partial list as complete.
89
+ endpoints: [endpoint(["GET"], null, { viewer: true, editor: true, admin: true })],
90
+ },
91
+ {
92
+ name: "archive",
93
+ prefix: "/api/v1/archive",
94
+ policy: { read: "viewer", write: "editor" },
95
+ permissions: [],
96
+ access: { assignable: true, label: "Archive", platform_reason: null },
97
+ endpoints: [endpoint(["GET"], "View the archive", { viewer: true, editor: true, admin: true })],
98
+ },
99
+ {
100
+ // Declared, but not assignable — the shape a module has after a release stops
101
+ // accepting per-module roles while rows naming it are still stored.
102
+ name: "legacy",
103
+ prefix: "/api/v1/legacy",
104
+ policy: { read: "viewer", write: "editor" },
105
+ permissions: [],
106
+ access: { assignable: false, label: "Legacy", platform_reason: null },
107
+ endpoints: [],
108
+ },
109
+ {
110
+ name: "retired",
111
+ prefix: "/api/v1/retired",
112
+ policy: { read: "viewer", write: "editor" },
113
+ permissions: [],
114
+ access: { assignable: false, label: "Retired", platform_reason: null },
115
+ endpoints: [],
116
+ },
117
+ {
118
+ name: "access",
119
+ prefix: "/api/v1/access",
120
+ policy: { read: "admin", write: "admin" },
121
+ permissions: [],
122
+ access: {
123
+ assignable: false,
124
+ label: null,
125
+ platform_reason: "administering grants hands out every other authority",
126
+ },
127
+ endpoints: [],
128
+ },
129
+ ],
130
+ };
131
+ }
132
+
133
+ /** The rung names this app declares, by rank. `25` is deliberately absent. */
134
+ const RUNG_NAMES: Record<number, string> = { 10: "viewer", 20: "editor", 30: "admin" };
135
+
136
+ /**
137
+ * The rungs a subject holds directly, as *mutable* state the writes change.
138
+ *
139
+ * Stateful rather than a constant so that a refetch is observable at all: with a stub that
140
+ * answers the same rows forever, a panel that never re-read after writing would look
141
+ * indistinguishable from one that did.
142
+ *
143
+ * `notes` starts at editor, `archive` at rank 25 — a rank the app no longer declares, which
144
+ * the server reports rather than hides, the same choice `terp grant list` makes when it marks
145
+ * a stale grant instead of dropping it.
146
+ */
147
+ function initialDirect(): Map<string, number> {
148
+ return new Map([
149
+ ["notes", 20],
150
+ ["archive", 25],
151
+ // Held in a module that no longer accepts a rung: it has no effect and the only change
152
+ // left is to remove it, which is the whole reason the panel has to show it at all.
153
+ ["legacy", 20],
154
+ ]);
155
+ }
156
+
157
+ /** One held row, with the shape the provenance endpoint reports. */
158
+ function heldRow(module: string, rank: number, via: { id: string; kind: string; name: string | null }) {
159
+ const role = RUNG_NAMES[rank] ?? null;
160
+ return {
161
+ module,
162
+ role_rank: rank,
163
+ role,
164
+ effective: true,
165
+ stale: role === null ? [`this app declares no role at rank ${rank}`] : [],
166
+ via,
167
+ };
168
+ }
169
+
170
+ function subjectAccess(subjectId: string, direct: Map<string, number>) {
171
+ return {
172
+ subject_id: subjectId,
173
+ via: [{ id: subjectId, kind: "self", name: null }],
174
+ permissions: [],
175
+ module_roles: [
176
+ ...[...direct].map(([module, rank]) =>
177
+ heldRow(module, rank, { id: subjectId, kind: "self", name: null }),
178
+ ),
179
+ // Reports comes through a group, so the panel cannot change it — and must still credit it.
180
+ heldRow("reports", 30, { id: GROUP, kind: "group", name: "Finance" }),
181
+ // Orphaned *and* inherited: a rung in a module that accepts none, held by a group. The
182
+ // panel must not offer to clear it here — the row belongs to the group, and the group's
183
+ // own screen is where it is the subject and can be removed.
184
+ heldRow("retired", 20, { id: GROUP, kind: "group", name: "Finance" }),
185
+ ],
186
+ };
187
+ }
188
+
189
+ interface Written {
190
+ method: string;
191
+ path: string;
192
+ body: unknown;
193
+ }
194
+
195
+ /**
196
+ * A gate the test can hold the provenance read behind.
197
+ *
198
+ * Needed because the panel's interesting state is a *window*: between a write resolving and
199
+ * its re-read landing, the rows on screen are the pre-write answer. With a stub that answers
200
+ * on the next microtask that window is real but not observable, and a test that tried to catch
201
+ * it would be a race. Holding every read open makes each step of the state machine a decision
202
+ * the test takes.
203
+ */
204
+ interface ReadGate {
205
+ hold: boolean;
206
+ /** When set, the next held read answers with a failure instead of the rows. */
207
+ fail: boolean;
208
+ waiting: Array<() => void>;
209
+ release: () => void;
210
+ }
211
+
212
+ function makeReadGate(hold: boolean): ReadGate {
213
+ const gate: ReadGate = {
214
+ hold,
215
+ fail: false,
216
+ waiting: [],
217
+ release: () => {
218
+ const pending = gate.waiting.splice(0, gate.waiting.length);
219
+ for (const resume of pending) resume();
220
+ },
221
+ };
222
+ return gate;
223
+ }
224
+
225
+ function stubAccessFetch(written: Written[], direct: Map<string, number>, gate: ReadGate) {
226
+ const fetchMock = vi.fn<typeof fetch>(async (input) => {
227
+ const request = input as Request;
228
+ const url = new URL(request.url);
229
+ const path = url.pathname;
230
+
231
+ if (path.endsWith("/api/v1/auth/login")) {
232
+ return jsonResponse({ access_token: "t", token_type: "bearer" });
233
+ }
234
+ if (path.endsWith("/api/v1/me/")) {
235
+ return jsonResponse({
236
+ id: "a1",
237
+ email: "admin@example.com",
238
+ role_rank: 30,
239
+ role_name: "admin",
240
+ });
241
+ }
242
+ if (path.endsWith("/api/v1/access/model")) {
243
+ return jsonResponse(accessModel());
244
+ }
245
+ if (path.includes("/module-roles/")) {
246
+ const module = path.split("/").pop() ?? "";
247
+ const body = request.method === "PUT" ? await request.clone().json() : null;
248
+ written.push({ method: request.method, path, body });
249
+ if (request.method === "DELETE") {
250
+ direct.delete(module);
251
+ return new Response(null, { status: 204 });
252
+ }
253
+ direct.set(module, (body as { role_rank: number }).role_rank);
254
+ return jsonResponse({
255
+ id: "mr1",
256
+ subject_id: SUBJECT,
257
+ module,
258
+ role_rank: (body as { role_rank: number }).role_rank,
259
+ version: 1,
260
+ created_at: "2026-07-01T10:00:00Z",
261
+ updated_at: "2026-07-01T10:00:00Z",
262
+ });
263
+ }
264
+ if (path.includes("/api/v1/access/subjects/")) {
265
+ if (gate.hold) {
266
+ await new Promise<void>((resume) => gate.waiting.push(resume));
267
+ }
268
+ if (gate.fail) {
269
+ return jsonResponse(
270
+ { code: "internal_error", detail: "the rungs could not be read" },
271
+ 500,
272
+ );
273
+ }
274
+ return jsonResponse(subjectAccess(path.split("/").pop() ?? SUBJECT, direct));
275
+ }
276
+ if (path.endsWith(`/api/v1/users/${SUBJECT}`)) {
277
+ return jsonResponse({
278
+ id: SUBJECT,
279
+ email: "jane.doe@example.com",
280
+ // Globally an editor, which is the floor every strip on this page sits on.
281
+ role: 20,
282
+ is_active: true,
283
+ created_at: "2026-07-01T10:00:00Z",
284
+ updated_at: "2026-07-01T10:00:00Z",
285
+ version: 1,
286
+ });
287
+ }
288
+ if (path.endsWith(`/api/v1/groups/${GROUP}`)) {
289
+ return jsonResponse({
290
+ id: GROUP,
291
+ name: "Finance",
292
+ description: "money",
293
+ member_count: 1,
294
+ version: 1,
295
+ created_at: "2026-07-01T10:00:00Z",
296
+ updated_at: "2026-07-01T10:00:00Z",
297
+ });
298
+ }
299
+ return jsonResponse({ items: [], total: 0, skip: 0, limit: 20 });
300
+ });
301
+ vi.stubGlobal("fetch", fetchMock);
302
+ return fetchMock;
303
+ }
304
+
305
+ function LogInOnMount() {
306
+ const auth = useAuth();
307
+ useEffect(() => {
308
+ void auth.login({ email: "admin@example.com", password: "pw" });
309
+ // eslint-disable-next-line react-hooks/exhaustive-deps
310
+ }, []);
311
+ return null;
312
+ }
313
+
314
+ function renderAt(initialPath: string, { gateReads = false } = {}) {
315
+ const written: Written[] = [];
316
+ const gate = makeReadGate(gateReads);
317
+ const manifests: ModuleManifest[] = [
318
+ { name: "notes", routes: [{ path: "/", view: "NotesList" }], nav: [] },
319
+ ];
320
+ const views: Record<string, ComponentType> = {
321
+ NotesList: () => <Page title="Notes">notes</Page>,
322
+ };
323
+ const direct = initialDirect();
324
+ const merged = withAdminArea(manifests, views, true);
325
+ const router = buildAppRouter(merged.manifests, {
326
+ views: merged.views,
327
+ title: "Terp",
328
+ history: createMemoryHistory({ initialEntries: [initialPath] }),
329
+ });
330
+ stubAccessFetch(written, direct, gate);
331
+ render(
332
+ <TerpProvider baseUrl="https://api.test">
333
+ <ToastProvider>
334
+ <LogInOnMount />
335
+ <RouterProvider router={router} />
336
+ </ToastProvider>
337
+ </TerpProvider>,
338
+ );
339
+ return { written, gate };
340
+ }
341
+
342
+ afterEach(() => {
343
+ cleanup();
344
+ vi.restoreAllMocks();
345
+ window.localStorage.clear();
346
+ });
347
+
348
+ // --- /admin/access: the screen that explains the model ---------------------- //
349
+
350
+ describe("the access screen", () => {
351
+ it("describes each module's ladder without offering a choice", async () => {
352
+ renderAt("/admin/access");
353
+ // A description, not a disabled control: there is nothing on this screen to choose, and a
354
+ // disabled radiogroup would announce three unchecked radio buttons per module.
355
+ await waitFor(() =>
356
+ expect(screen.getByRole("group", { name: "Notes" })).toBeInTheDocument(),
357
+ );
358
+ expect(screen.queryByRole("radiogroup")).not.toBeInTheDocument();
359
+ expect(screen.queryAllByRole("radio")).toEqual([]);
360
+
361
+ // Each rung says what it ADDS over the one below — the only framing in which two rungs can
362
+ // be compared at a glance — split by kind so the destructive half is not buried.
363
+ expect(screen.getByText("View a note")).toBeInTheDocument();
364
+ expect(screen.getByText("Write a note")).toBeInTheDocument();
365
+ expect(screen.getByText("Delete a note")).toBeInTheDocument();
366
+ });
367
+
368
+ it("keeps a module that refuses assignment, and renders the reason as text", async () => {
369
+ renderAt("/admin/access");
370
+ // Filtering it out leaves a question an administrator cannot stop asking. Rendered rather
371
+ // than hovered, for the same reason the delta is on the tile: an explanation you have to
372
+ // discover is not one.
373
+ await waitFor(() =>
374
+ expect(
375
+ screen.getByText("administering grants hands out every other authority"),
376
+ ).toBeInTheDocument(),
377
+ );
378
+ expect(screen.getByText("Never assignable per module")).toBeInTheDocument();
379
+ });
380
+
381
+ it("counts the routes that explained nothing instead of implying the list is complete", async () => {
382
+ renderAt("/admin/access");
383
+ await waitFor(() =>
384
+ expect(
385
+ screen.getByText("1 action(s) in this module have no description yet"),
386
+ ).toBeInTheDocument(),
387
+ );
388
+ });
389
+ });
390
+
391
+ // --- the assignment panel: where the choice has a subject ------------------- //
392
+
393
+ async function openUserPanel() {
394
+ const harness = renderAt(`/admin/users/${SUBJECT}`);
395
+ await waitFor(() =>
396
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).toBeInTheDocument(),
397
+ );
398
+ return harness;
399
+ }
400
+
401
+ function tile(group: string, name: string): HTMLElement {
402
+ const strip = screen.getByRole("radiogroup", { name: group });
403
+ const found = [...strip.querySelectorAll('[role="radio"]')].find(
404
+ (node) => node.textContent?.startsWith(name) === true,
405
+ );
406
+ if (found === undefined) throw new Error(`no ${name} tile in ${group}`);
407
+ return found as HTMLElement;
408
+ }
409
+
410
+ describe("the assignment panel", () => {
411
+ it("offers only the modules that opted in", async () => {
412
+ await openUserPanel();
413
+ // `access` declares that it is never per-module assignable, and offering a control the
414
+ // server would refuse is worse than not offering one. The access screen is where its
415
+ // refusal is explained; this panel simply has no strip for it.
416
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).toBeInTheDocument();
417
+ expect(screen.getByRole("radiogroup", { name: "Reports" })).toBeInTheDocument();
418
+ expect(screen.queryByRole("radiogroup", { name: "access" })).not.toBeInTheDocument();
419
+ });
420
+
421
+ it("preselects the rung held directly and credits an inherited one to its group", async () => {
422
+ await openUserPanel();
423
+ // Two different facts. The strip can only change what this subject holds *directly*; a rung
424
+ // arriving through a group is a fact about the group, and "why can this person do that?" is
425
+ // answered wrongly by a strip that shows only the direct row.
426
+ expect(tile("Notes", "editor")).toHaveAttribute("aria-checked", "true");
427
+ expect(tile("Notes", "admin")).toHaveAttribute("aria-checked", "false");
428
+
429
+ expect(tile("Reports", "No access")).toHaveAttribute("aria-checked", "true");
430
+ expect(screen.getByText("Also admin here, through Finance")).toBeInTheDocument();
431
+ });
432
+
433
+ it("says why a rung at or below the global role would change nothing", async () => {
434
+ await openUserPanel();
435
+ // The guard resolves a module rank as the *higher* of the global rank and the module rung,
436
+ // so assigning `viewer` to an editor stores a row that can never fire. The floor marker is
437
+ // what stops someone doing it and wondering why nothing happened.
438
+ expect(tile("Notes", "editor")).toHaveAttribute("data-floor", "true");
439
+ expect(tile("Notes", "admin")).not.toHaveAttribute("data-floor");
440
+ // One note per strip, tied to the strips actually on screen rather than to a literal: the
441
+ // floor is a property of the subject, so every module it lists has to say it.
442
+ expect(
443
+ screen.getAllByText("editor everywhere already, so anything up to here changes nothing"),
444
+ ).toHaveLength(screen.getAllByRole("radiogroup").length);
445
+ });
446
+
447
+ it("writes a middle rung straight away, addressed by subject and module", async () => {
448
+ const { written } = await openUserPanel();
449
+ fireEvent.click(tile("Reports", "viewer"));
450
+ await waitFor(() => expect(written).toHaveLength(1));
451
+ expect(written[0].method).toBe("PUT");
452
+ expect(written[0].path).toBe(
453
+ `/api/v1/access/subjects/${SUBJECT}/module-roles/reports`,
454
+ );
455
+ // The rank, not the name: the row stores a rank so the ladder stays the app's own
456
+ // (ADR 0022), and the name is what the reader sees.
457
+ expect(written[0].body).toEqual({ role_rank: 10 });
458
+ });
459
+
460
+ it("puts the most privileged rung behind a confirmation", async () => {
461
+ const { written } = await openUserPanel();
462
+ fireEvent.click(tile("Notes", "admin"));
463
+ // Nothing written yet — this is the claim that makes the strip's manual activation
464
+ // load-bearing, since arrowing across the tiles must not fire this either.
465
+ expect(written).toHaveLength(0);
466
+ const dialog = await screen.findByRole("dialog");
467
+ expect(dialog).toHaveTextContent("Give admin in Notes?");
468
+
469
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
470
+ await waitFor(() => expect(written).toHaveLength(1));
471
+ expect(written[0].body).toEqual({ role_rank: 30 });
472
+ });
473
+
474
+ it("takes a rung away through the same strip, behind its own confirmation", async () => {
475
+ const { written } = await openUserPanel();
476
+ // Revoking has to be exactly as reachable as granting, which an option buried in a menu
477
+ // never is — and it is a real tile, so the strip biases downward rather than upward.
478
+ fireEvent.click(tile("Notes", "No access"));
479
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
480
+ "Take away the role in Notes?",
481
+ );
482
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
483
+ await waitFor(() => expect(written).toHaveLength(1));
484
+ expect(written[0].method).toBe("DELETE");
485
+ expect(written[0].path).toBe(`/api/v1/access/subjects/${SUBJECT}/module-roles/notes`);
486
+ });
487
+
488
+ it("writes nothing when the tile already selected is committed again", async () => {
489
+ const { written } = await openUserPanel();
490
+ // A request that stores what is already stored still writes an audit row saying somebody
491
+ // changed something, which is a lie the audit log cannot be allowed to tell.
492
+ fireEvent.click(tile("Notes", "editor"));
493
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
494
+ await new Promise((resolve) => setTimeout(resolve, 0));
495
+ expect(written).toEqual([]);
496
+ });
497
+
498
+ it("marks no floor on a group, because a group has no role of its own", async () => {
499
+ renderAt(`/admin/groups/${GROUP}`);
500
+ await waitFor(() =>
501
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).toBeInTheDocument(),
502
+ );
503
+ // ADR 0074 gives groups permissions rather than roles, so there is no rank under the strip
504
+ // to mark — and a floor drawn from nothing would tell the reader a rung is redundant when
505
+ // it is the only thing granting access at all.
506
+ expect(tile("Notes", "editor")).not.toHaveAttribute("data-floor");
507
+ expect(
508
+ screen.queryByText(/everywhere already, so anything up to here changes nothing/),
509
+ ).not.toBeInTheDocument();
510
+ });
511
+
512
+ it("shows a stale rung as selecting nothing, and still lets it be cleared", async () => {
513
+ const { written } = await openUserPanel();
514
+ // Three states, not two. This row holds rank 25, which the app no longer declares, so the
515
+ // server reports `role: null` — and the strip must not answer with the `no access` tile,
516
+ // because a row that sits there doing nothing is exactly what has to be said out loud.
517
+ expect(tile("Archive", "No access")).toHaveAttribute("aria-checked", "false");
518
+ expect(tile("Archive", "viewer")).toHaveAttribute("aria-checked", "false");
519
+ expect(
520
+ screen.getByText("Held, but has no effect: this app declares no role at rank 25"),
521
+ ).toBeInTheDocument();
522
+
523
+ // And the fix that mattered: collapsing that state into `no access` made committing
524
+ // `no access` look like committing what was already selected, so the one row that most
525
+ // needs removing was the one row the panel could not remove.
526
+ fireEvent.click(tile("Archive", "No access"));
527
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
528
+ "Take away the role in Archive?",
529
+ );
530
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
531
+ await waitFor(() => expect(written).toHaveLength(1));
532
+ expect(written[0].method).toBe("DELETE");
533
+ expect(written[0].path).toBe(`/api/v1/access/subjects/${SUBJECT}/module-roles/archive`);
534
+ });
535
+
536
+ it("re-reads what is held after a write, rather than trusting its own optimism", async () => {
537
+ await openUserPanel();
538
+ // The strip must show what the *server* now says, not what the click intended. A panel that
539
+ // set its own state would agree with itself even when the write was rejected, coerced, or
540
+ // superseded by a rung the same person holds through a group.
541
+ expect(tile("Notes", "editor")).toHaveAttribute("aria-checked", "true");
542
+ fireEvent.click(tile("Notes", "viewer"));
543
+ await waitFor(() =>
544
+ expect(tile("Notes", "viewer")).toHaveAttribute("aria-checked", "true"),
545
+ );
546
+ expect(tile("Notes", "editor")).toHaveAttribute("aria-checked", "false");
547
+ });
548
+
549
+ it("refuses another choice until the re-read it triggered has landed", async () => {
550
+ // The window this closes: `busy` used to clear when the write settled, one round trip
551
+ // before `held` caught up. In between, the strip was fully interactive against the
552
+ // *pre-write* rows — so a second commit was compared with the stale selection and
553
+ // silently dropped as "already selected", leaving the server on the first choice and the
554
+ // reader with no sign their second click had been ignored.
555
+ const { written, gate } = renderAt(`/admin/users/${SUBJECT}`, { gateReads: true });
556
+
557
+ // Nothing is offered before the first read lands: an empty `held` cannot be told apart
558
+ // from "holds nothing", and a strip built on that answer offers the wrong selection.
559
+ await waitFor(() => expect(screen.getByText("Access per module")).toBeInTheDocument());
560
+ expect(screen.queryByRole("radiogroup", { name: "Notes" })).not.toBeInTheDocument();
561
+
562
+ gate.release();
563
+ await waitFor(() =>
564
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).toBeInTheDocument(),
565
+ );
566
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).not.toHaveAttribute(
567
+ "aria-disabled",
568
+ );
569
+ expect(tile("Notes", "editor")).toHaveAttribute("aria-checked", "true");
570
+
571
+ // Commit a middle rung. The write resolves; its re-read is still held.
572
+ fireEvent.click(tile("Notes", "viewer"));
573
+ await waitFor(() => expect(written).toHaveLength(1));
574
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).toHaveAttribute(
575
+ "aria-disabled",
576
+ "true",
577
+ );
578
+
579
+ // A second commit in that window writes nothing — the strip is not a control right now.
580
+ // Before the fix this click reached `onPick`, matched the stale `editor` selection, and
581
+ // was discarded without a request or a word to the reader.
582
+ fireEvent.click(tile("Notes", "editor"));
583
+ expect(written).toHaveLength(1);
584
+
585
+ // Once the re-read lands the strip is a control again, and it shows what the server says.
586
+ gate.release();
587
+ await waitFor(() =>
588
+ expect(tile("Notes", "viewer")).toHaveAttribute("aria-checked", "true"),
589
+ );
590
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).not.toHaveAttribute(
591
+ "aria-disabled",
592
+ );
593
+
594
+ // And the choice the window refused is available again, for real this time.
595
+ fireEvent.click(tile("Notes", "editor"));
596
+ await waitFor(() => expect(written).toHaveLength(2));
597
+ expect(written[1].body).toEqual({ role_rank: 20 });
598
+ });
599
+
600
+ it("says the rungs could not be read, and offers no choice against rows nobody confirmed", async () => {
601
+ // The other half of the settling rule. A read that fails is not a read that landed, so the
602
+ // strip must not become a control on the strength of rows nobody could confirm — offering
603
+ // one is how somebody changes the wrong tier believing it was the right one. The failure is
604
+ // shown rather than only toasted, because a toast is gone by the time it matters.
605
+ const { written, gate } = renderAt(`/admin/users/${SUBJECT}`, { gateReads: true });
606
+ await waitFor(() => expect(screen.getByText("Access per module")).toBeInTheDocument());
607
+
608
+ gate.fail = true;
609
+ gate.release();
610
+
611
+ // Asserted through the alert role rather than by text alone: a hidden node satisfies a
612
+ // text query, so "shown" and "present in the DOM" are two different claims and only the
613
+ // first is the one that matters to somebody reading the screen.
614
+ await waitFor(() =>
615
+ expect(screen.getByRole("alert")).toHaveTextContent("the rungs could not be read"),
616
+ );
617
+ // No strips at all, so there is nothing to click and nothing to misread.
618
+ expect(screen.queryByRole("radiogroup", { name: "Notes" })).not.toBeInTheDocument();
619
+ expect(written).toEqual([]);
620
+ });
621
+
622
+ it("shows a rung held in a module that no longer accepts one, and lets it be cleared", async () => {
623
+ // The strips are filtered to modules that opted in, which is right — offering a rung the
624
+ // server would refuse is worse than offering none. But a rung already *held* in a module
625
+ // that stopped accepting them then had nowhere to appear, and this panel is the only place
626
+ // it could ever be cleared: it outlived the release that made it meaningless, invisible to
627
+ // the one screen that could do anything about it. ADR 0121 says such a row is reported
628
+ // rather than filtered, and the strips alone cannot keep that promise.
629
+ const { written } = await openUserPanel();
630
+
631
+ const notice = screen.getByText(/no longer accepts a role of its own/);
632
+ expect(notice).toHaveTextContent("legacy");
633
+ expect(notice).toHaveTextContent("editor");
634
+ // And no strip for it, because there is no rung it could legally be given.
635
+ expect(screen.queryByRole("radiogroup", { name: "Legacy" })).not.toBeInTheDocument();
636
+
637
+ // Exactly one notice and one action, though two orphaned rungs are held: the other
638
+ // arrives through a group, and that row is the group's to clear on its own screen. The
639
+ // strip makes the same distinction, and a panel that offered it here would be writing a
640
+ // different row than the one it showed.
641
+ expect(screen.getAllByText(/no longer accepts a role of its own/)).toHaveLength(1);
642
+ expect(screen.queryByText(/retired/)).not.toBeInTheDocument();
643
+
644
+ // The one action the declarations still permit is offered, and only that one.
645
+ expect(screen.getAllByRole("button", { name: "Revoke" })).toHaveLength(1);
646
+ fireEvent.click(screen.getByRole("button", { name: "Revoke" }));
647
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
648
+ "Take away the role in legacy?",
649
+ );
650
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
651
+ await waitFor(() => expect(written).toHaveLength(1));
652
+ expect(written[0].method).toBe("DELETE");
653
+ expect(written[0].path).toBe(`/api/v1/access/subjects/${SUBJECT}/module-roles/legacy`);
654
+ });
655
+ });