@terpjs/react-core 0.24.0 → 0.27.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terpjs/react-core",
3
- "version": "0.24.0",
3
+ "version": "0.27.0",
4
4
  "type": "module",
5
5
  "description": "Terp React stack core — typed @terpjs/contract client provider, auth session, capability gates, TanStack Router adapter, app shell, page archetypes, DataView and token-styled UI primitives. First frontend stack; see README.md for the component catalog.",
6
6
  "exports": {
@@ -13,8 +13,8 @@
13
13
  "test": "vitest run"
14
14
  },
15
15
  "dependencies": {
16
- "@tanstack/react-router": "^1.170.35",
17
- "@terpjs/contract": "^0.24.0"
16
+ "@tanstack/react-router": "^1.170.38",
17
+ "@terpjs/contract": "^0.27.0"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "react": "^19.0.0",
@@ -26,7 +26,7 @@
26
26
  "@types/react": "^19.3.0",
27
27
  "@types/react-dom": "^19.3.0",
28
28
  "@vitejs/plugin-react": "^6.1.1",
29
- "jsdom": "^30.0.1",
29
+ "jsdom": "^30.1.0",
30
30
  "react": "^19.3.0",
31
31
  "react-dom": "^19.3.0",
32
32
  "typescript": "^5.9.3",
@@ -1,4 +1,5 @@
1
1
  // @vitest-environment jsdom
2
+ import type { TerpPermissionName } from "@terpjs/contract";
2
3
  import { render, screen, waitFor } from "@testing-library/react";
3
4
  import { useEffect } from "react";
4
5
  import { afterEach, describe, expect, it, vi } from "vitest";
@@ -120,3 +121,24 @@ describe("Authorized", () => {
120
121
  await waitFor(() => expect(screen.getByText("n=0 has=false")).toBeInTheDocument());
121
122
  });
122
123
  });
124
+
125
+ // The access vocabulary degrades to `string` in a package that declares none.
126
+ //
127
+ // `@terpjs/contract` is app-agnostic, so `TerpAccessVocabulary` is empty here and
128
+ // `TerpPermissionName` must therefore be plain `string` — otherwise every framework
129
+ // package and every app that has not adopted the narrowing would stop compiling to
130
+ // supply a vocabulary it never declared. That is asserted at the TYPE level, because
131
+ // a runtime assertion cannot see it.
132
+ //
133
+ // The naming matters and is not cosmetic. `lib.dom.d.ts` declares a GLOBAL
134
+ // `PermissionName` (the browser's "geolocation" | "notifications" | …), so a file that
135
+ // used the short name and forgot the import would not fail — it would silently check
136
+ // against the browser's vocabulary and report a union nobody in the app recognises.
137
+ // Writing this found exactly that, which is why the exported name is `Terp`-first.
138
+ it("keeps plain strings for an app that declares no vocabulary", () => {
139
+ const anyName: TerpPermissionName = "whatever.this.app.calls.it";
140
+ type IsWidenedToString = string extends TerpPermissionName ? true : false;
141
+ const widened: IsWidenedToString = true;
142
+ expect(anyName.length).toBeGreaterThan(0);
143
+ expect(widened).toBe(true);
144
+ });
@@ -1,4 +1,4 @@
1
- import type { Action } from "@terpjs/contract";
1
+ import type { Action, TerpPermissionName } from "@terpjs/contract";
2
2
  import type { ReactNode } from "react";
3
3
 
4
4
  import { useAuth } from "./TerpProvider";
@@ -33,7 +33,7 @@ export function usePermissions(): readonly string[] {
33
33
  }
34
34
 
35
35
  /** Whether the current user holds the named permission grant (the UI gate). */
36
- export function useHasPermission(permission: string): boolean {
36
+ export function useHasPermission(permission: TerpPermissionName): boolean {
37
37
  return usePermissions().includes(permission);
38
38
  }
39
39
 
@@ -49,7 +49,7 @@ export interface AuthorizedProps {
49
49
  * `Permission` enforces the permission's role floor **and** the grant, so a UI that
50
50
  * checked only one would disagree with the endpoint in one direction or the other.
51
51
  */
52
- permission?: string;
52
+ permission?: TerpPermissionName;
53
53
  /** Rendered when the user may not perform `action` (default: nothing). */
54
54
  fallback?: ReactNode;
55
55
  }
@@ -269,6 +269,27 @@ export function ModuleAccessPanel({ subjectId, globalRank = null }: ModuleAccess
269
269
  }
270
270
  }
271
271
 
272
+ // An application that declares no assignable module has nothing on this surface anyone
273
+ // can ever act on, and the notice saying so is addressed to whoever writes the
274
+ // `ModuleSpec` — who is not the person reading a subject's detail screen. It is this
275
+ // panel's own rule applied to itself: a module that refuses is not listed, and a section
276
+ // with no modules at all is not drawn either.
277
+ //
278
+ // An orphaned rung is the exception that keeps it alive, and the reason this is not
279
+ // simply `assignable.length === 0`: a row held in a module that stopped accepting one can
280
+ // only ever be cleared here (ADR 0121), so hiding the section on the count of *assignable*
281
+ // modules alone would strand exactly the rows that ADR insists are reported rather than
282
+ // filtered. Both failure legs are excluded too — a panel that could not read its rows has
283
+ // something to say even when it has nothing to offer.
284
+ const nothingToOffer =
285
+ !loading &&
286
+ error === null &&
287
+ heldError === null &&
288
+ settled >= 0 &&
289
+ assignable.length === 0 &&
290
+ orphaned.length === 0;
291
+ if (nothingToOffer) return null;
292
+
272
293
  return (
273
294
  <Stack gap={3}>
274
295
  <h2 data-terp="admin-section-title">{strings.moduleAccessTitle}</h2>
@@ -155,6 +155,11 @@ function initialDirect(): Map<string, number> {
155
155
  }
156
156
 
157
157
  /** One held row, with the shape the provenance endpoint reports. */
158
+ //: The module `accessModel()` declares as "not assignable, rows still stored" — the shape a
159
+ //: module has after a release stops accepting per-module roles. Named once so the fixture and
160
+ //: the stub that builds an orphan out of it cannot drift apart.
161
+ const LEGACY_MODULE = "legacy";
162
+
158
163
  function heldRow(module: string, rank: number, via: { id: string; kind: string; name: string | null }) {
159
164
  const role = RUNG_NAMES[rank] ?? null;
160
165
  return {
@@ -206,7 +211,8 @@ interface ReadGate {
206
211
  /** When set, the next held read answers with a failure instead of the rows. */
207
212
  fail: boolean;
208
213
  waiting: Array<() => void>;
209
- release: () => void;
214
+ /** Resume every read parked on the gate, waiting first for one to be parked. */
215
+ release: () => Promise<void>;
210
216
  }
211
217
 
212
218
  function makeReadGate(hold: boolean): ReadGate {
@@ -214,7 +220,21 @@ function makeReadGate(hold: boolean): ReadGate {
214
220
  hold,
215
221
  fail: false,
216
222
  waiting: [],
217
- release: () => {
223
+ release: async () => {
224
+ // WAIT FOR THE READ TO BE PARKED, DO NOT ASSUME IT ALREADY IS. This used to splice
225
+ // whatever happened to be waiting at that instant, and the tests reach this line after
226
+ // waiting on a heading — which the panel renders without the provenance read having
227
+ // left the gate yet. When it had not, the release resumed nothing and the read that
228
+ // arrived a moment later parked on a gate nobody would open again: the panel then sat
229
+ // in its pre-read state until the matcher timed out, four seconds later, on a state
230
+ // that could no longer arrive. Nothing in the test decided which of those two landed
231
+ // first, so it held on an idle machine and lost on a loaded one — roughly half the
232
+ // time in a full-suite run here, and never once when the file ran alone, which is
233
+ // exactly the shape that gets diagnosed as "CI being flaky".
234
+ if (!gate.hold) {
235
+ return;
236
+ }
237
+ await waitFor(() => expect(gate.waiting.length).toBeGreaterThan(0));
218
238
  const pending = gate.waiting.splice(0, gate.waiting.length);
219
239
  for (const resume of pending) resume();
220
240
  },
@@ -222,7 +242,12 @@ function makeReadGate(hold: boolean): ReadGate {
222
242
  return gate;
223
243
  }
224
244
 
225
- function stubAccessFetch(written: Written[], direct: Map<string, number>, gate: ReadGate) {
245
+ function stubAccessFetch(
246
+ written: Written[],
247
+ direct: Map<string, number>,
248
+ gate: ReadGate,
249
+ { noAssignable = false, keepOrphan = false } = {},
250
+ ) {
226
251
  const fetchMock = vi.fn<typeof fetch>(async (input) => {
227
252
  const request = input as Request;
228
253
  const url = new URL(request.url);
@@ -240,7 +265,20 @@ function stubAccessFetch(written: Written[], direct: Map<string, number>, gate:
240
265
  });
241
266
  }
242
267
  if (path.endsWith("/api/v1/access/model")) {
243
- return jsonResponse(accessModel());
268
+ const model = accessModel();
269
+ // The shape of an application that never opted in: every module declares the default,
270
+ // which is what a `ModuleSpec` with no `access=` produces.
271
+ return jsonResponse(
272
+ noAssignable
273
+ ? {
274
+ ...model,
275
+ modules: model.modules.map((row) => ({
276
+ ...row,
277
+ access: { ...row.access, assignable: false },
278
+ })),
279
+ }
280
+ : model,
281
+ );
244
282
  }
245
283
  if (path.includes("/module-roles/")) {
246
284
  const module = path.split("/").pop() ?? "";
@@ -271,7 +309,25 @@ function stubAccessFetch(written: Written[], direct: Map<string, number>, gate:
271
309
  500,
272
310
  );
273
311
  }
274
- return jsonResponse(subjectAccess(path.split("/").pop() ?? SUBJECT, direct));
312
+ const subject = subjectAccess(path.split("/").pop() ?? SUBJECT, direct);
313
+ // `assignable` is a property of the CURRENT release; a held row is a fact about an
314
+ // earlier one. So "no module accepts a rung today" and "a rung is still stored" are
315
+ // not contradictory — they are exactly the state `legacy` in `accessModel()` is
316
+ // declared to describe, and the only state in which the panel's `orphaned` term does
317
+ // any work. `keepOrphan` is what lets a test stand in it: without it the stub ruled
318
+ // the state out by construction and the ADR 0121 exception had no reachable case.
319
+ if (noAssignable) {
320
+ const orphan = heldRow(LEGACY_MODULE, direct.get(LEGACY_MODULE) ?? 20, {
321
+ id: path.split("/").pop() ?? SUBJECT,
322
+ kind: "self",
323
+ name: null,
324
+ });
325
+ return jsonResponse({
326
+ ...subject,
327
+ module_roles: keepOrphan ? [orphan] : [],
328
+ });
329
+ }
330
+ return jsonResponse(subject);
275
331
  }
276
332
  if (path.endsWith(`/api/v1/users/${SUBJECT}`)) {
277
333
  return jsonResponse({
@@ -311,7 +367,10 @@ function LogInOnMount() {
311
367
  return null;
312
368
  }
313
369
 
314
- function renderAt(initialPath: string, { gateReads = false } = {}) {
370
+ function renderAt(
371
+ initialPath: string,
372
+ { gateReads = false, noAssignable = false, keepOrphan = false } = {},
373
+ ) {
315
374
  const written: Written[] = [];
316
375
  const gate = makeReadGate(gateReads);
317
376
  const manifests: ModuleManifest[] = [
@@ -327,7 +386,7 @@ function renderAt(initialPath: string, { gateReads = false } = {}) {
327
386
  title: "Terp",
328
387
  history: createMemoryHistory({ initialEntries: [initialPath] }),
329
388
  });
330
- stubAccessFetch(written, direct, gate);
389
+ stubAccessFetch(written, direct, gate, { noAssignable, keepOrphan });
331
390
  render(
332
391
  <TerpProvider baseUrl="https://api.test">
333
392
  <ToastProvider>
@@ -559,7 +618,7 @@ describe("the assignment panel", () => {
559
618
  await waitFor(() => expect(screen.getByText("Access per module")).toBeInTheDocument());
560
619
  expect(screen.queryByRole("radiogroup", { name: "Notes" })).not.toBeInTheDocument();
561
620
 
562
- gate.release();
621
+ await gate.release();
563
622
  await waitFor(() =>
564
623
  expect(screen.getByRole("radiogroup", { name: "Notes" })).toBeInTheDocument(),
565
624
  );
@@ -583,7 +642,7 @@ describe("the assignment panel", () => {
583
642
  expect(written).toHaveLength(1);
584
643
 
585
644
  // Once the re-read lands the strip is a control again, and it shows what the server says.
586
- gate.release();
645
+ await gate.release();
587
646
  await waitFor(() =>
588
647
  expect(tile("Notes", "viewer")).toHaveAttribute("aria-checked", "true"),
589
648
  );
@@ -606,7 +665,7 @@ describe("the assignment panel", () => {
606
665
  await waitFor(() => expect(screen.getByText("Access per module")).toBeInTheDocument());
607
666
 
608
667
  gate.fail = true;
609
- gate.release();
668
+ await gate.release();
610
669
 
611
670
  // Asserted through the alert role rather than by text alone: a hidden node satisfies a
612
671
  // text query, so "shown" and "present in the DOM" are two different claims and only the
@@ -619,6 +678,30 @@ describe("the assignment panel", () => {
619
678
  expect(written).toEqual([]);
620
679
  });
621
680
 
681
+ it("settles when the gate is released before the read reaches it", async () => {
682
+ // Pins the gate's own contract, because the two tests above depend on it and neither
683
+ // states it. They release after waiting on a heading the panel renders without the
684
+ // provenance read having left for the gate yet — so "released" and "parked" have no
685
+ // ordering between them, and the losing order is the one nobody wrote a test for.
686
+ //
687
+ // Releasing first is that order, forced. A release that only resumes what happens to be
688
+ // parked at that instant resumes nothing here, and the read that arrives afterwards
689
+ // waits on a gate nobody opens again: the panel holds its pre-read state until the
690
+ // matcher gives up four seconds later, reported as an element that never appeared rather
691
+ // than as the deadlock it is. That is the shape the same two tests hit intermittently on
692
+ // a loaded machine, which is why this one forces it instead of hoping to catch it.
693
+ const { gate } = renderAt(`/admin/users/${SUBJECT}`, { gateReads: true });
694
+ const released = gate.release();
695
+ await waitFor(() => expect(screen.getByText("Access per module")).toBeInTheDocument());
696
+ await released;
697
+
698
+ await waitFor(() =>
699
+ expect(screen.getByRole("radiogroup", { name: "Notes" })).not.toHaveAttribute(
700
+ "aria-disabled",
701
+ ),
702
+ );
703
+ });
704
+
622
705
  it("shows a rung held in a module that no longer accepts one, and lets it be cleared", async () => {
623
706
  // The strips are filtered to modules that opted in, which is right — offering a rung the
624
707
  // server would refuse is worse than offering none. But a rung already *held* in a module
@@ -652,4 +735,55 @@ describe("the assignment panel", () => {
652
735
  expect(written[0].method).toBe("DELETE");
653
736
  expect(written[0].path).toBe(`/api/v1/access/subjects/${SUBJECT}/module-roles/legacy`);
654
737
  });
738
+
739
+ it("draws no section at all when the application declares no assignable module", async () => {
740
+ // The notice this used to render explains a `ModuleSpec` to somebody looking at a person,
741
+ // and no action available on the screen can ever resolve it — a heading, a description and
742
+ // a dead end, on every user and every group, forever. It is the panel's own rule applied
743
+ // to itself: a module that refuses is not listed, so a surface with no modules is not drawn.
744
+ renderAt(`/admin/users/${SUBJECT}`, { noAssignable: true });
745
+
746
+ // Anchored on the page actually arriving, so the absence below is a decision and not a
747
+ // test that outran the render. By role, not by text: the email is the page's heading
748
+ // *and* a row in its detail list, so a bare text query matches twice.
749
+ await waitFor(() =>
750
+ expect(
751
+ screen.getByRole("heading", { name: "jane.doe@example.com" }),
752
+ ).toBeInTheDocument(),
753
+ );
754
+
755
+ // The page arriving is not the panel settling, and the difference is a whole round trip:
756
+ // `UserDetail` renders its heading as soon as `/users/{id}` returns, while the panel hides
757
+ // itself only once `/access/subjects/{id}` comes back and `settled` leaves its -1. Until
758
+ // then it is still drawing the section behind a `LoadingState`, so asserting right after
759
+ // the heading caught the panel mid-read rather than catching it deciding. The anchor above
760
+ // stays, because on its own this `waitFor` would pass at render zero with nothing on screen
761
+ // yet -- the absence has to be reached *after* the page is there, not instead of it.
762
+ await waitFor(() =>
763
+ expect(screen.queryByText("Access per module")).not.toBeInTheDocument(),
764
+ );
765
+ expect(
766
+ screen.queryByText(/no module in this application accepts a role of its own/i),
767
+ ).not.toBeInTheDocument();
768
+ });
769
+
770
+ it("keeps the section when nothing is assignable but a stale rung is still held", async () => {
771
+ // The exception that stops the rule above from being `assignable.length === 0`: this panel
772
+ // is the only place an orphaned row can be cleared, so hiding on the count of assignable
773
+ // modules alone would strand exactly the rows ADR 0121 insists are reported.
774
+ //
775
+ // It has to be driven with `noAssignable`, or it asserts nothing. Against the default
776
+ // fixture three modules ARE assignable, so `nothingToOffer` is already false on the
777
+ // `assignable.length === 0` term and the `orphaned.length === 0` term this test exists
778
+ // for never decides anything — drop that term from the condition and the test stays
779
+ // green. Checked the other way too: with the term removed, this now fails.
780
+ renderAt(`/admin/users/${SUBJECT}`, { noAssignable: true, keepOrphan: true });
781
+
782
+ // Awaited on the ORPHAN, not on the heading: with nothing assignable there is no strip
783
+ // to wait for, and the heading is drawn by the loading state too — so anchoring on it
784
+ // would assert against a spinner one round trip before the subject read lands.
785
+ expect(await screen.findByText(/no longer accepts a role of its own/)).toBeInTheDocument();
786
+ expect(screen.getByText("Access per module")).toBeInTheDocument();
787
+ expect(screen.getAllByRole("button", { name: "Revoke" })).toHaveLength(1);
788
+ });
655
789
  });
@@ -25,6 +25,7 @@ afterEach(() => {
25
25
  cleanup();
26
26
  vi.restoreAllMocks();
27
27
  window.localStorage.clear();
28
+ heldAccessModel = null;
28
29
  });
29
30
 
30
31
  // --- withAdminArea: the injection rules ------------------------------------- //
@@ -152,6 +153,13 @@ function LogInOnMount() {
152
153
 
153
154
  const emptyPage = { items: [], total: 0, skip: 0, limit: 1 };
154
155
 
156
+ /**
157
+ * Held open, the access-model response does not land. Set by the one test that needs the
158
+ * role ladder to still be in flight while it looks at the form, so the window in which the
159
+ * submit control is disabled is a fact rather than a timing accident. Cleared in `afterEach`.
160
+ */
161
+ let heldAccessModel: Promise<void> | null = null;
162
+
155
163
  function stubAdminFetch() {
156
164
  const fetchMock = vi.fn<typeof fetch>(async (input) => {
157
165
  const request = input as Request;
@@ -169,6 +177,7 @@ function stubAdminFetch() {
169
177
  });
170
178
  }
171
179
  if (path.endsWith("/api/v1/access/model")) {
180
+ if (heldAccessModel) await heldAccessModel;
172
181
  // The admin screens read the role ladder from the access model rather than from three
173
182
  // literals in `roles.ts`, so the mock has to answer it. Declaring a fourth rung here is
174
183
  // deliberate: it is what proves the screens render the ladder the *app* declares, which
@@ -429,6 +438,28 @@ function renderAdminApp(
429
438
  return { fetchMock, router };
430
439
  }
431
440
 
441
+ /**
442
+ * The create form's submit control, waited on until it is actually clickable.
443
+ *
444
+ * `UserCreate` gates the only control that reaches the POST on
445
+ * `creating || ladderLoading || role === ""`, and `role` is still `""` in the commit where
446
+ * `ladderLoading` first clears — the effect that picks the ladder's lowest rung runs after
447
+ * it. So the button is disabled for one commit longer than the access-model fetch takes,
448
+ * while the page heading renders before either. Awaiting the heading and then clicking
449
+ * submits nothing at all: jsdom raises no submit event for a click on a disabled control,
450
+ * and the test then fails several lines later on whatever was waiting for the POST's
451
+ * result, as "unable to find element" pointing at the wrong line.
452
+ *
453
+ * A control disabled on an ambient async load has to give a test something deterministic
454
+ * to wait on. This is that thing, and it is the condition that actually gates the click
455
+ * rather than a proxy for it.
456
+ */
457
+ async function enabledSubmitControl(): Promise<HTMLElement> {
458
+ const control = await screen.findByRole("button", { name: "Provision user" });
459
+ await waitFor(() => expect(control).toBeEnabled());
460
+ return control;
461
+ }
462
+
432
463
  describe("the packaged admin area", () => {
433
464
  it("serves the hub at /admin with cards into users, groups and audit", async () => {
434
465
  renderAdminApp("/admin");
@@ -477,6 +508,29 @@ describe("the packaged admin area", () => {
477
508
  expect(screen.getByRole("navigation", { name: "Breadcrumb" })).toHaveTextContent("Users");
478
509
  });
479
510
 
511
+ it("keeps the create form's submit control disabled until the declared ladder arrives", async () => {
512
+ // The pin under `enabledSubmitControl`, and the reason the four submitting tests below
513
+ // cannot go back to awaiting the heading. With the ladder held in flight, the heading is
514
+ // up and the only control that reaches the POST is disabled — so a click there raises no
515
+ // submit event at all in jsdom, and the test would fail much later, on whatever was
516
+ // waiting for the POST's result and with a message naming that instead. This holds the
517
+ // window itself: disabled while the ladder is outstanding, enabled once it lands. It
518
+ // does not hold which of the two gates (`ladderLoading`, `role === ""`) is doing it —
519
+ // either one alone produces the window, and both have to go for the race to.
520
+ let releaseLadder: () => void = () => {};
521
+ heldAccessModel = new Promise<void>((resolve) => {
522
+ releaseLadder = resolve;
523
+ });
524
+ renderAdminApp("/admin/users/new");
525
+
526
+ await screen.findByRole("heading", { level: 1, name: "Provision user" });
527
+ const submit = screen.getByRole("button", { name: "Provision user" });
528
+ expect(submit).toBeDisabled();
529
+
530
+ releaseLadder();
531
+ await waitFor(() => expect(submit).toBeEnabled());
532
+ });
533
+
480
534
  it("provisions a user on a dedicated create page and redirects to its detail", async () => {
481
535
  const { fetchMock } = renderAdminApp("/admin/users");
482
536
  await screen.findByRole("heading", { level: 1, name: "Users" });
@@ -496,7 +550,7 @@ describe("the packaged admin area", () => {
496
550
  target: { value: "new.account@example.com" },
497
551
  });
498
552
  fireEvent.change(screen.getByLabelText("Password"), { target: { value: "strong-password" } });
499
- fireEvent.click(screen.getByRole("button", { name: "Provision user" }));
553
+ fireEvent.click(await enabledSubmitControl());
500
554
 
501
555
  await screen.findByRole("heading", { level: 1, name: "new.account@example.com" });
502
556
  expect(fetchMock.mock.calls.some(([input]) => {
@@ -581,7 +635,7 @@ describe("the packaged admin area", () => {
581
635
 
582
636
  fireEvent.change(screen.getByLabelText("Email"), { target: { value: "taken@example.com" } });
583
637
  fireEvent.change(screen.getByLabelText("Password"), { target: { value: "strong-password" } });
584
- fireEvent.click(screen.getByRole("button", { name: "Provision user" }));
638
+ fireEvent.click(await enabledSubmitControl());
585
639
 
586
640
  const shown = await screen.findByText("Email address is already registered");
587
641
  expect(shown.getAttribute("data-terp")).toBe("field-error");
@@ -596,7 +650,10 @@ describe("the packaged admin area", () => {
596
650
  const { fetchMock } = renderAdminApp("/admin/users/u1");
597
651
  await screen.findByRole("heading", { level: 1, name: "jane.doe@example.com" });
598
652
  fireEvent.click(screen.getByRole("button", { name: "More actions" }));
599
- fireEvent.click(screen.getByRole("menuitem", { name: "Make viewer" }));
653
+ // Waited on, not reached for: the rung this item offers comes from the access model, so
654
+ // the menu opens empty of it until that fetch lands. Same race as `enabledSubmitControl`
655
+ // guards, one screen over.
656
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Make viewer" }));
600
657
  expect(screen.getByRole("dialog", { name: "Make viewer" })).toBeInTheDocument();
601
658
  expect(fetchMock.mock.calls.some(([input]) => (input as Request).method === "PATCH")).toBe(false);
602
659
 
@@ -698,7 +755,7 @@ describe("the packaged admin area", () => {
698
755
  target: { value: "new.account@example.com" },
699
756
  });
700
757
  fireEvent.change(screen.getByLabelText("Password"), { target: { value: "strong-password" } });
701
- fireEvent.click(screen.getByRole("button", { name: "Provision user" }));
758
+ fireEvent.click(await enabledSubmitControl());
702
759
 
703
760
  expect(
704
761
  await screen.findByText("organization_id: Not allowed for this tenant"),
@@ -734,7 +791,7 @@ describe("the packaged admin area", () => {
734
791
 
735
792
  fireEvent.change(screen.getByLabelText("Email"), { target: { value: "taken@example.com" } });
736
793
  fireEvent.change(screen.getByLabelText("Password"), { target: { value: "strong-password" } });
737
- fireEvent.click(screen.getByRole("button", { name: "Provision user" }));
794
+ fireEvent.click(await enabledSubmitControl());
738
795
 
739
796
  const shown = await screen.findByText("Email address is already registered");
740
797
  expect(shown.getAttribute("data-terp")).toBe("field-error");
@@ -143,6 +143,14 @@ describe("renderTerpApp", () => {
143
143
  //
144
144
  // Mutation: delete `layout: options.layout` from the buildAppRouter call, and this stops
145
145
  // throwing.
146
+ //
147
+ // `"bespoke"` is the value used here on purpose, and the assertion covers the whole
148
+ // message rather than only the rejection. The word appears in the contract's own
149
+ // description and in its violation text, where it reads as though it might name a
150
+ // second contract; it does not, and ADR 0079 records why (a contract is declared once
151
+ // for the whole app and is per-archetype slot specs, so an unconstrained one would be
152
+ // a second spelling of declaring none). An author who reads it as a value should be
153
+ // told what the values ARE, not only that this is not one.
146
154
  const root = document.createElement("div");
147
155
  document.body.appendChild(root);
148
156
  try {
@@ -153,7 +161,7 @@ describe("renderTerpApp", () => {
153
161
  layout: { contract: "bespoke" },
154
162
  rootElement: root,
155
163
  }),
156
- ).toThrow(/Unknown layout contract "bespoke"/);
164
+ ).toThrow(/Unknown layout contract "bespoke"; known contracts: standard\./);
157
165
  } finally {
158
166
  root.remove();
159
167
  }
@@ -44,8 +44,8 @@ export const LAYOUT_CONTRACTS: Readonly<Record<string, LayoutContractSpec>> = {
44
44
  "sections and no Field at the top level, so the body is always a container rather " +
45
45
  "than a loose run of controls; a settings body is Card sections and holds no " +
46
46
  "collection; and a split " +
47
- "body is two SplitPanes and nothing else. A bespoke screen composes " +
48
- "the plain Page, which the contract deliberately leaves unconstrained.",
47
+ "body is two SplitPanes and nothing else. A screen that needs no contract " +
48
+ "composes the plain Page, which this contract deliberately leaves unconstrained.",
49
49
  slots: {
50
50
  HubPage: {
51
51
  components: { HubCard: "hubcard" },
@@ -133,7 +133,8 @@ export function slotViolationMessage(
133
133
  return (
134
134
  `Layout contract "${contractId}": the ${slotOwner} body slot accepts only ` +
135
135
  `${allowed.join(" / ")}; found ${found}. Compose the body from those react-core ` +
136
- "components (recipe: terp guide layouts), move bespoke content to a plain Page, " +
136
+ "components (recipe: terp guide layouts), move content that needs no contract to a " +
137
+ "plain Page, " +
137
138
  "or opt out on this line with a justified // terp-allow-layout-contract: <reason> " +
138
139
  "marker (counted by the escape-hatch budget)."
139
140
  );
@@ -172,6 +172,98 @@ describe("useRealtimeChannel lifecycle", () => {
172
172
  expect(result.current.lastMessage).toEqual({ sequence: 2, text: "fresh" });
173
173
  });
174
174
 
175
+ it("drops a payload the guard rejects and keeps delivering on the same transport", async () => {
176
+ // The channel used to die here. A rejected payload ran a TRANSPORT teardown — stopped,
177
+ // retry cancelled, source released — and because the effect's deps never change on a
178
+ // bad message and the returned state exposes no reopen, the channel stayed dead for the
179
+ // life of the mount. The realistic cause of a rejection is drift between the server's
180
+ // own model and this hand-written guard, so that traded one unusable message for every
181
+ // later message, including the ones the guard still accepts.
182
+ mocks.post.mockResolvedValue({
183
+ data: {
184
+ ticket: "ticket-one",
185
+ expires_in: 30,
186
+ channel: "system.notices",
187
+ transport: "sse",
188
+ },
189
+ });
190
+ vi.stubGlobal("EventSource", EventSourceDouble);
191
+
192
+ const seen: Notice[] = [];
193
+ const { result } = renderHook(() =>
194
+ useRealtimeChannel({
195
+ channel: "system.notices",
196
+ validate: isNotice,
197
+ onMessage: (notice) => seen.push(notice),
198
+ }),
199
+ );
200
+ await act(async () => {
201
+ await Promise.resolve();
202
+ });
203
+ const source = EventSourceDouble.instances[0];
204
+ act(() => source.onopen?.(new Event("open")));
205
+ expect(result.current.status).toBe("open");
206
+
207
+ act(() =>
208
+ source.onmessage?.(new MessageEvent("message", { data: '{"sequence":"one"}' })),
209
+ );
210
+ // Said out loud, once, naming the channel — and the transport is untouched.
211
+ expect(result.current.error?.message).toContain("system.notices");
212
+ expect(result.current.status).toBe("open");
213
+ expect(source.closed).toBe(false);
214
+ expect(result.current.lastMessage).toBeNull();
215
+ expect(seen).toEqual([]);
216
+
217
+ // And the next message the guard DOES accept still arrives, which is the whole point.
218
+ act(() =>
219
+ source.onmessage?.(
220
+ new MessageEvent("message", { data: '{"sequence":2,"text":"fresh"}' }),
221
+ ),
222
+ );
223
+ expect(result.current.lastMessage).toEqual({ sequence: 2, text: "fresh" });
224
+ expect(seen).toEqual([{ sequence: 2, text: "fresh" }]);
225
+ expect(mocks.post).toHaveBeenCalledTimes(1);
226
+ });
227
+
228
+ it("reports a rejected payload once per connection, not once per message", async () => {
229
+ // A server whose shape has moved sends the same wrong shape repeatedly. Re-rendering
230
+ // every subscriber on each one is a second failure stacked on the first, so the report
231
+ // latches — and unlatches when a reconnect actually opens, since that is a new
232
+ // connection and may carry a different answer.
233
+ mocks.post.mockResolvedValue({
234
+ data: {
235
+ ticket: "ticket-one",
236
+ expires_in: 30,
237
+ channel: "system.notices",
238
+ transport: "sse",
239
+ },
240
+ });
241
+ vi.stubGlobal("EventSource", EventSourceDouble);
242
+
243
+ const { result } = renderHook(() =>
244
+ useRealtimeChannel({ channel: "system.notices", validate: isNotice }),
245
+ );
246
+ await act(async () => {
247
+ await Promise.resolve();
248
+ });
249
+ const source = EventSourceDouble.instances[0];
250
+ act(() => source.onopen?.(new Event("open")));
251
+
252
+ act(() => source.onmessage?.(new MessageEvent("message", { data: "not json" })));
253
+ const first = result.current.error;
254
+ expect(first).not.toBeNull();
255
+
256
+ act(() =>
257
+ source.onmessage?.(new MessageEvent("message", { data: '{"sequence":"two"}' })),
258
+ );
259
+ expect(result.current.error).toBe(first);
260
+
261
+ act(() => source.onopen?.(new Event("open")));
262
+ expect(result.current.error).toBeNull();
263
+ act(() => source.onmessage?.(new MessageEvent("message", { data: "not json" })));
264
+ expect(result.current.error).not.toBeNull();
265
+ });
266
+
175
267
  it("remints after a remote WebSocket close until the caller closes", async () => {
176
268
  vi.useFakeTimers();
177
269
  mocks.post
@@ -38,6 +38,19 @@ describe("realtime transport contract", () => {
38
38
  );
39
39
  });
40
40
 
41
+ it("names the channel in a rejection, because the reader is diagnosing drift", () => {
42
+ // The guard is hand-written against a model the server owns, so the realistic cause of
43
+ // a rejection is that one of the two moved. An app may hold several channels at once,
44
+ // and "a payload outside its declared type" with no channel in it does not say which
45
+ // guard to go and read.
46
+ expect(() => parseMessage('{"sequence":"one"}', isNotice, "system.notices")).toThrow(
47
+ /Realtime channel "system\.notices" received a payload outside its declared type/,
48
+ );
49
+ expect(() => parseMessage("not json", isNotice, "system.notices")).toThrow(
50
+ /Realtime channel "system\.notices" received invalid JSON/,
51
+ );
52
+ });
53
+
41
54
  it("exports the sanctioned hook", () => {
42
55
  expect(typeof useRealtimeChannel).toBe("function");
43
56
  });