@terpjs/react-core 0.23.0 → 0.25.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 +2 -2
- package/src/Authorized.test.tsx +22 -0
- package/src/Authorized.tsx +3 -3
- package/src/admin/ModuleAccessPanel.tsx +21 -0
- package/src/admin/access.test.tsx +144 -10
- package/src/admin/admin.test.tsx +62 -5
- package/src/bootstrap.test.tsx +9 -1
- package/src/layoutContract.ts +4 -3
- package/src/realtime-hook.test.tsx +92 -0
- package/src/realtime.test.ts +13 -0
- package/src/realtime.ts +72 -17
- package/src/router.test.tsx +87 -4
- package/src/router.tsx +30 -3
- package/vite.config.ts +16 -9
- package/vitest.setup.ts +25 -18
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@terpjs/react-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.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": {
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@tanstack/react-router": "^1.170.35",
|
|
17
|
-
"@terpjs/contract": "^0.
|
|
17
|
+
"@terpjs/contract": "^0.25.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"react": "^19.0.0",
|
package/src/Authorized.test.tsx
CHANGED
|
@@ -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
|
+
});
|
package/src/Authorized.tsx
CHANGED
|
@@ -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:
|
|
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?:
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
});
|
package/src/admin/admin.test.tsx
CHANGED
|
@@ -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(
|
|
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(
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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");
|
package/src/bootstrap.test.tsx
CHANGED
|
@@ -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
|
}
|
package/src/layoutContract.ts
CHANGED
|
@@ -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
|
|
48
|
-
"the plain Page, which
|
|
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
|
|
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
|
package/src/realtime.test.ts
CHANGED
|
@@ -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
|
});
|
package/src/realtime.ts
CHANGED
|
@@ -36,7 +36,23 @@ interface RealtimePaths {
|
|
|
36
36
|
export interface RealtimeChannelOptions<Message> {
|
|
37
37
|
channel: string;
|
|
38
38
|
transport?: RealtimeTransport;
|
|
39
|
-
/**
|
|
39
|
+
/**
|
|
40
|
+
* Runtime validation for the channel's Pydantic JSON wire payload.
|
|
41
|
+
*
|
|
42
|
+
* THIS FUNCTION IS THE DRIFT BOUNDARY. The authoritative shape is the server's
|
|
43
|
+
* `RealtimeChannel.outbound_model`, which the backend validates every publish against;
|
|
44
|
+
* this guard is hand-written client-side code asserting the same thing. Nothing checks
|
|
45
|
+
* the two against each other, so the realistic way this guard fails is not an attack —
|
|
46
|
+
* the payload's only author is the same deployment's own backend, behind a one-use
|
|
47
|
+
* ticket — but a field added or an enum member widened on the server while the guard
|
|
48
|
+
* still describes the old shape.
|
|
49
|
+
*
|
|
50
|
+
* Because that is the realistic cause, a payload this guard rejects is treated as a
|
|
51
|
+
* MESSAGE failure and not a transport failure: the message is dropped, the rejection is
|
|
52
|
+
* surfaced once on `error` naming this channel, and the transport stays open and keeps
|
|
53
|
+
* delivering. Write the guard narrowly enough to be worth having and wide enough that a
|
|
54
|
+
* server-side addition does not silently blank a screen.
|
|
55
|
+
*/
|
|
40
56
|
validate(value: unknown): value is Message;
|
|
41
57
|
/** Receive every validated message (lastMessage is also retained). */
|
|
42
58
|
onMessage?(message: Message): void;
|
|
@@ -45,8 +61,19 @@ export interface RealtimeChannelOptions<Message> {
|
|
|
45
61
|
}
|
|
46
62
|
|
|
47
63
|
export interface RealtimeChannelState<Message> {
|
|
64
|
+
/**
|
|
65
|
+
* The transport's state. `"error"` means the transport itself failed and a reconnect is
|
|
66
|
+
* scheduled; a message the guard rejected does NOT move this away from `"open"`.
|
|
67
|
+
*/
|
|
48
68
|
status: RealtimeStatus;
|
|
49
69
|
lastMessage: Message | null;
|
|
70
|
+
/**
|
|
71
|
+
* The most recent failure, which is not the same question as `status`. A rejected
|
|
72
|
+
* payload sets this while `status` stays `"open"`: the channel is still delivering, and
|
|
73
|
+
* something it was sent did not match the declared type. Read the pair, not either half
|
|
74
|
+
* — `status === "error"` is the connection's verdict, `error !== null` is the last
|
|
75
|
+
* reason of any kind.
|
|
76
|
+
*/
|
|
50
77
|
error: Error | null;
|
|
51
78
|
/** WebSocket only; throws unless the socket is open. */
|
|
52
79
|
send(message: unknown): void;
|
|
@@ -81,15 +108,20 @@ function transportUrl(
|
|
|
81
108
|
function parseMessage<Message>(
|
|
82
109
|
raw: string,
|
|
83
110
|
validate: (value: unknown) => value is Message,
|
|
111
|
+
channel?: string,
|
|
84
112
|
): Message {
|
|
113
|
+
// The channel is named in the message because the reader of this error is debugging
|
|
114
|
+
// drift between one server-side model and one hand-written guard, and an app may hold
|
|
115
|
+
// several channels at once. Optional so the predicate stays callable on its own.
|
|
116
|
+
const named = channel === undefined ? "Realtime channel" : `Realtime channel "${channel}"`;
|
|
85
117
|
let value: unknown;
|
|
86
118
|
try {
|
|
87
119
|
value = JSON.parse(raw);
|
|
88
120
|
} catch {
|
|
89
|
-
throw new Error(
|
|
121
|
+
throw new Error(`${named} received invalid JSON`);
|
|
90
122
|
}
|
|
91
123
|
if (!validate(value)) {
|
|
92
|
-
throw new Error(
|
|
124
|
+
throw new Error(`${named} received a payload outside its declared type`);
|
|
93
125
|
}
|
|
94
126
|
return value;
|
|
95
127
|
}
|
|
@@ -116,7 +148,7 @@ export function useRealtimeChannel<Message>({
|
|
|
116
148
|
const validateRef = useRef(validate);
|
|
117
149
|
const onMessageRef = useRef(onMessage);
|
|
118
150
|
const closeRef = useRef<() => void>(() => {});
|
|
119
|
-
const
|
|
151
|
+
const messageFailureRef = useRef<(cause: unknown) => void>(() => {});
|
|
120
152
|
validateRef.current = validate;
|
|
121
153
|
onMessageRef.current = onMessage;
|
|
122
154
|
const [status, setStatus] = useState<RealtimeStatus>(
|
|
@@ -128,17 +160,23 @@ export function useRealtimeChannel<Message>({
|
|
|
128
160
|
const receiveRef = useRef((raw: string) => {});
|
|
129
161
|
receiveRef.current = (raw: string) => {
|
|
130
162
|
try {
|
|
131
|
-
const message = parseMessage(raw, validateRef.current);
|
|
163
|
+
const message = parseMessage(raw, validateRef.current, channel);
|
|
132
164
|
setLastMessage(message);
|
|
133
165
|
onMessageRef.current?.(message);
|
|
134
166
|
} catch (cause) {
|
|
135
|
-
|
|
167
|
+
// One message, one failure. The transport is fine — see `messageFailure`.
|
|
168
|
+
messageFailureRef.current(cause);
|
|
136
169
|
}
|
|
137
170
|
};
|
|
138
171
|
|
|
172
|
+
const reportRef = useRef((cause: unknown) => {});
|
|
173
|
+
reportRef.current = (cause: unknown) => {
|
|
174
|
+
setError(cause instanceof Error ? cause : new Error("Realtime channel failed"));
|
|
175
|
+
};
|
|
176
|
+
|
|
139
177
|
const failRef = useRef((cause: unknown) => {});
|
|
140
178
|
failRef.current = (cause: unknown) => {
|
|
141
|
-
|
|
179
|
+
reportRef.current(cause);
|
|
142
180
|
setStatus("error");
|
|
143
181
|
};
|
|
144
182
|
|
|
@@ -174,14 +212,29 @@ export function useRealtimeChannel<Message>({
|
|
|
174
212
|
};
|
|
175
213
|
closeRef.current = stop;
|
|
176
214
|
|
|
177
|
-
|
|
215
|
+
// A payload the guard rejects is a MESSAGE failure, not a transport failure.
|
|
216
|
+
//
|
|
217
|
+
// This used to tear the transport down: `stopped = true`, cancel the retry timer and
|
|
218
|
+
// release the socket, which left the channel dead for the life of the mount — the
|
|
219
|
+
// effect's deps never change on a bad message and the returned state exposes no reopen,
|
|
220
|
+
// so neither shipped subscriber could recover. That is a self-inflicted outage in the
|
|
221
|
+
// one case that actually happens: the payload's only author is the same deployment's
|
|
222
|
+
// own backend behind a one-use ticket, so a guard miss means the hand-written guard has
|
|
223
|
+
// fallen behind the server's model, and every LATER message — including the ones the
|
|
224
|
+
// guard still accepts — was being discarded along with it.
|
|
225
|
+
//
|
|
226
|
+
// So: drop the message, say so once on `error` with the channel named, and keep
|
|
227
|
+
// delivering. Once per connection, because a server whose shape has moved sends the
|
|
228
|
+
// same wrong shape repeatedly and one re-render per message is a second failure on top
|
|
229
|
+
// of the first; a reconnect clears the latch along with the error (`onopen`).
|
|
230
|
+
let rejectedPayloadReported = false;
|
|
231
|
+
const messageFailure = (cause: unknown) => {
|
|
178
232
|
if (!active()) return;
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
failRef.current(cause);
|
|
233
|
+
if (rejectedPayloadReported) return;
|
|
234
|
+
rejectedPayloadReported = true;
|
|
235
|
+
reportRef.current(cause);
|
|
183
236
|
};
|
|
184
|
-
|
|
237
|
+
messageFailureRef.current = messageFailure;
|
|
185
238
|
|
|
186
239
|
if (!enabled) {
|
|
187
240
|
stopped = true;
|
|
@@ -189,8 +242,8 @@ export function useRealtimeChannel<Message>({
|
|
|
189
242
|
return () => {
|
|
190
243
|
cancelled = true;
|
|
191
244
|
if (closeRef.current === stop) closeRef.current = () => {};
|
|
192
|
-
if (
|
|
193
|
-
|
|
245
|
+
if (messageFailureRef.current === messageFailure) {
|
|
246
|
+
messageFailureRef.current = () => {};
|
|
194
247
|
}
|
|
195
248
|
};
|
|
196
249
|
}
|
|
@@ -218,6 +271,7 @@ export function useRealtimeChannel<Message>({
|
|
|
218
271
|
source.onopen = () => {
|
|
219
272
|
if (!active() || source !== connectedSource) return;
|
|
220
273
|
retryAttempt = 0;
|
|
274
|
+
rejectedPayloadReported = false;
|
|
221
275
|
setError(null);
|
|
222
276
|
setStatus("open");
|
|
223
277
|
};
|
|
@@ -236,6 +290,7 @@ export function useRealtimeChannel<Message>({
|
|
|
236
290
|
socket.onopen = () => {
|
|
237
291
|
if (!active() || socket !== connectedSocket) return;
|
|
238
292
|
retryAttempt = 0;
|
|
293
|
+
rejectedPayloadReported = false;
|
|
239
294
|
setError(null);
|
|
240
295
|
setStatus("open");
|
|
241
296
|
};
|
|
@@ -281,8 +336,8 @@ export function useRealtimeChannel<Message>({
|
|
|
281
336
|
cancelRetry();
|
|
282
337
|
releaseTransport("component unmounted");
|
|
283
338
|
if (closeRef.current === stop) closeRef.current = () => {};
|
|
284
|
-
if (
|
|
285
|
-
|
|
339
|
+
if (messageFailureRef.current === messageFailure) {
|
|
340
|
+
messageFailureRef.current = () => {};
|
|
286
341
|
}
|
|
287
342
|
};
|
|
288
343
|
}, [baseUrl, channel, client, enabled, transport]);
|
package/src/router.test.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
2
|
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
|
3
3
|
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
|
4
|
-
import { useEffect, useState } from "react";
|
|
4
|
+
import { Suspense, lazy, useEffect, useState } from "react";
|
|
5
5
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
6
6
|
import type { ModuleManifest } from "@terpjs/contract";
|
|
7
7
|
|
|
@@ -657,9 +657,12 @@ describe("buildAppRouter", () => {
|
|
|
657
657
|
</TerpProvider>,
|
|
658
658
|
);
|
|
659
659
|
|
|
660
|
-
// The bare view mounts, the post-mount check bites, and the screen is torn down.
|
|
661
|
-
|
|
662
|
-
|
|
660
|
+
// The bare view mounts, the post-mount check bites, and the screen is torn down. The
|
|
661
|
+
// timeout clears the guard's grace budget: this is the one test that waits out the whole
|
|
662
|
+
// window, because it is the one asserting the refusal actually arrives.
|
|
663
|
+
await waitFor(
|
|
664
|
+
() => expect(screen.queryByRole("heading", { name: "Bare view" })).not.toBeInTheDocument(),
|
|
665
|
+
{ timeout: 4000 },
|
|
663
666
|
);
|
|
664
667
|
});
|
|
665
668
|
|
|
@@ -702,6 +705,86 @@ describe("buildAppRouter", () => {
|
|
|
702
705
|
);
|
|
703
706
|
});
|
|
704
707
|
|
|
708
|
+
it("accepts a view whose page archetype lands a timer later, not merely a commit later", async () => {
|
|
709
|
+
// The case above frames on the very next commit, which the old one-macrotask window
|
|
710
|
+
// happened to cover on an idle machine and lost on a busy one — this suite's flakiest
|
|
711
|
+
// failure. A view that frames after a *timer* is the same thing without the coin toss:
|
|
712
|
+
// it was refused every time, and it is the ordinary shape of a screen waiting on
|
|
713
|
+
// anything at all before it can draw its frame.
|
|
714
|
+
vi.stubGlobal("fetch", sessionFetch());
|
|
715
|
+
|
|
716
|
+
function TimerFramedView() {
|
|
717
|
+
const [ready, setReady] = useState(false);
|
|
718
|
+
useEffect(() => {
|
|
719
|
+
const timer = setTimeout(() => setReady(true), 25);
|
|
720
|
+
return () => clearTimeout(timer);
|
|
721
|
+
}, []);
|
|
722
|
+
return ready ? <Page title="Late view">late body</Page> : null;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const router = buildAppRouter(
|
|
726
|
+
[{ name: "late", routes: [{ path: "/late", view: "LateView" }], nav: [] }],
|
|
727
|
+
{
|
|
728
|
+
views: { LateView: TimerFramedView },
|
|
729
|
+
title: "Terp",
|
|
730
|
+
history: createMemoryHistory({ initialEntries: ["/late"] }),
|
|
731
|
+
},
|
|
732
|
+
);
|
|
733
|
+
|
|
734
|
+
render(
|
|
735
|
+
<TerpProvider baseUrl="https://api.test">
|
|
736
|
+
<LogInOnMount />
|
|
737
|
+
<RouterProvider router={router} />
|
|
738
|
+
</TerpProvider>,
|
|
739
|
+
);
|
|
740
|
+
|
|
741
|
+
await waitFor(() =>
|
|
742
|
+
expect(screen.getByRole("heading", { name: "Late view" })).toBeInTheDocument(),
|
|
743
|
+
);
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
it("accepts a view whose page archetype arrives with a lazily loaded chunk", async () => {
|
|
747
|
+
// The literal case the grace window's own comment named and did not cover: a code-split
|
|
748
|
+
// screen. `lazy()` resolves over a chunk fetch, so the frame is unreachable within one
|
|
749
|
+
// macrotask by construction — the guard refused every such view, deterministically, and
|
|
750
|
+
// hardest on the slow connections code splitting exists to serve.
|
|
751
|
+
vi.stubGlobal("fetch", sessionFetch());
|
|
752
|
+
|
|
753
|
+
const LazyFramed = lazy(
|
|
754
|
+
() =>
|
|
755
|
+
new Promise<{ default: typeof Page }>((resolve) =>
|
|
756
|
+
setTimeout(() => resolve({ default: Page }), 25),
|
|
757
|
+
),
|
|
758
|
+
);
|
|
759
|
+
function ChunkedView() {
|
|
760
|
+
return (
|
|
761
|
+
<Suspense fallback={null}>
|
|
762
|
+
<LazyFramed title="Late view">late body</LazyFramed>
|
|
763
|
+
</Suspense>
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
const router = buildAppRouter(
|
|
768
|
+
[{ name: "late", routes: [{ path: "/late", view: "LateView" }], nav: [] }],
|
|
769
|
+
{
|
|
770
|
+
views: { LateView: ChunkedView },
|
|
771
|
+
title: "Terp",
|
|
772
|
+
history: createMemoryHistory({ initialEntries: ["/late"] }),
|
|
773
|
+
},
|
|
774
|
+
);
|
|
775
|
+
|
|
776
|
+
render(
|
|
777
|
+
<TerpProvider baseUrl="https://api.test">
|
|
778
|
+
<LogInOnMount />
|
|
779
|
+
<RouterProvider router={router} />
|
|
780
|
+
</TerpProvider>,
|
|
781
|
+
);
|
|
782
|
+
|
|
783
|
+
await waitFor(() =>
|
|
784
|
+
expect(screen.getByRole("heading", { name: "Late view" })).toBeInTheDocument(),
|
|
785
|
+
);
|
|
786
|
+
});
|
|
787
|
+
|
|
705
788
|
it("mounts the built-in profile page; the user menu's Settings opens it", async () => {
|
|
706
789
|
const fetchMock = vi.fn<typeof fetch>(async (input) => {
|
|
707
790
|
const url = (input as Request).url;
|
package/src/router.tsx
CHANGED
|
@@ -55,6 +55,32 @@ export const DEFAULT_ROLE_RANKS: Record<string, number> = {
|
|
|
55
55
|
/** The built-in profile / settings route (an app manifest claiming the path wins). */
|
|
56
56
|
export const PROFILE_PATH = "/profile";
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* How long a routed view may go unframed before the page-archetype guard refuses it.
|
|
60
|
+
*
|
|
61
|
+
* The window used to be one macrotask, and one macrotask does not mean what the guard said it
|
|
62
|
+
* meant. The case the grace exists for — an inner component resolving lazily — is a dynamic
|
|
63
|
+
* `import()`, so the frame lands a *chunk fetch* later and never on the next tick; a view
|
|
64
|
+
* framing on a plain `useEffect` → `setState` → commit can lose the race too, because that
|
|
65
|
+
* commit goes through React's scheduler while the deadline is a timer, and on a loaded machine
|
|
66
|
+
* the timer wins. Both shapes were refused: a correct code-split screen replaced by an error
|
|
67
|
+
* boundary on exactly the slow devices that can least afford it, and a test suite that failed
|
|
68
|
+
* on whichever file the CI runner happened to be busy with.
|
|
69
|
+
*
|
|
70
|
+
* The asymmetry sets the number. Refusing early destroys a working screen in front of a user;
|
|
71
|
+
* refusing late only delays a message a developer reads, and delays it by less than the time it
|
|
72
|
+
* takes to look at what they just broke. So the budget is deliberately generous.
|
|
73
|
+
*
|
|
74
|
+
* It is still a deadline, and the honest limit is that a chunk slower than this is refused. The
|
|
75
|
+
* guard cannot be both fail-closed on an *absent* frame and patient without bound — absence
|
|
76
|
+
* only becomes a fact once something declares the waiting over. Worth knowing while reading
|
|
77
|
+
* that trade: unlike the layout contract, which pairs a lint rule with its runtime check, this
|
|
78
|
+
* control has no build-time half — no lint rule reads the source for it and the Terp Standard
|
|
79
|
+
* catalogs no entry — so this budget is the whole of the judgement, with no second control
|
|
80
|
+
* behind it.
|
|
81
|
+
*/
|
|
82
|
+
const ARCHETYPE_GRACE_MS = 2_000;
|
|
83
|
+
|
|
58
84
|
/**
|
|
59
85
|
* Translate a manifest path into TanStack Router's dialect.
|
|
60
86
|
*
|
|
@@ -561,8 +587,9 @@ export function buildAppRouter(
|
|
|
561
587
|
// The runtime half of the "every routed view is a page archetype" control: Page
|
|
562
588
|
// (composed by OverviewPage / DetailPage / HubPage) marks the render; a routed view
|
|
563
589
|
// that mounted without any archetype in its tree is refused, fail closed. The check
|
|
564
|
-
// waits
|
|
565
|
-
// lazy inner component resolving
|
|
590
|
+
// waits `ARCHETYPE_GRACE_MS` so a view whose archetype lands on a follow-up commit —
|
|
591
|
+
// a lazy inner component resolving, a frame behind one render of state — is not
|
|
592
|
+
// refused spuriously; see that constant for why the budget is as generous as it is.
|
|
566
593
|
const marked = useRef(false);
|
|
567
594
|
const [unframed, setUnframed] = useState(false);
|
|
568
595
|
useEffect(() => {
|
|
@@ -573,7 +600,7 @@ export function buildAppRouter(
|
|
|
573
600
|
if (!marked.current) {
|
|
574
601
|
setUnframed(true);
|
|
575
602
|
}
|
|
576
|
-
},
|
|
603
|
+
}, ARCHETYPE_GRACE_MS);
|
|
577
604
|
return () => clearTimeout(timer);
|
|
578
605
|
}, [allowed]);
|
|
579
606
|
if (unframed && !marked.current) {
|
package/vite.config.ts
CHANGED
|
@@ -18,14 +18,21 @@ export default defineConfig({
|
|
|
18
18
|
// the setup file configured 3s, and a comment that misstates the code it explains is
|
|
19
19
|
// worse than none.
|
|
20
20
|
testTimeout: 15_000,
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
// runs, always one file of eighty-one, each passing on its
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
|
|
21
|
+
// `fileParallelism: false` used to be here, and is deliberately gone. It was added
|
|
22
|
+
// against an intermittent "unable to find element" -- four different fetch-bound
|
|
23
|
+
// assertions across four CI runs, always one file of eighty-one, each passing on its
|
|
24
|
+
// own -- after widening the async budget had already failed to fix it (1s to 3s to 4s,
|
|
25
|
+
// vitest.setup.ts). A serial run did measurably help, which is why it looked like the
|
|
26
|
+
// answer. The actual cause was a structural race in four admin tests: they clicked a
|
|
27
|
+
// submit control that is disabled until an ambient fetch lands, having waited only on
|
|
28
|
+
// the page heading, so jsdom raised no submit event and the click was LOST rather than
|
|
29
|
+
// late. Serialising widened the odds of winning that race; it did not remove it.
|
|
30
|
+
//
|
|
31
|
+
// With the race removed (`enabledSubmitControl`, admin/admin.test.tsx), the suite was
|
|
32
|
+
// re-measured on a four-vCPU machine -- the class of runner the flag was added for --
|
|
33
|
+
// and ran green nine times out of nine in parallel, in ~33s against ~80s serial. So the
|
|
34
|
+
// wall clock is given back. If this suite starts failing intermittently again, do NOT
|
|
35
|
+
// reach for this flag or the async budget first: find out what the failing test is
|
|
36
|
+
// waiting on, and whether the thing it clicks can be clicked yet.
|
|
30
37
|
},
|
|
31
38
|
});
|
package/vitest.setup.ts
CHANGED
|
@@ -7,31 +7,38 @@ import { configure } from "@testing-library/dom";
|
|
|
7
7
|
|
|
8
8
|
// `findBy*` and `waitFor` default to a 1000ms budget, and the component tests spend it on
|
|
9
9
|
// a path that is not a render: a mocked fetch resolving, then the state it sets, then the
|
|
10
|
-
// re-render that finally puts the text on screen. One second
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
10
|
+
// re-render that finally puts the text on screen. One second does not reliably cover that,
|
|
11
|
+
// so the budget is raised. `testTimeout` (vite.config.ts) sits above it, so a matcher that
|
|
12
|
+
// cannot find its element loses first and says which element; equal budgets report an
|
|
13
|
+
// unhelpful "test timed out" instead.
|
|
14
14
|
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
15
|
+
// READ THE HISTORY BELOW AS A TOLERANCE, NOT AS A DIAGNOSIS. This lever was raised twice
|
|
16
|
+
// (1s to 3s to 4s) against an intermittent "unable to find element" — five failures across
|
|
17
|
+
// one day, four different fetch-bound tests, always one file of eighty-one, each passing
|
|
18
|
+
// alone and on a re-run. Neither raise stopped it, and the cause is now known and removed:
|
|
19
|
+
// four admin tests held a structural race. They clicked a submit control that `UserCreate`
|
|
20
|
+
// disables until an ambient access-model fetch has landed AND the effect it feeds has run,
|
|
21
|
+
// having waited on nothing but the page heading — which renders before either. jsdom raises
|
|
22
|
+
// no submit event for a click on a disabled control, so the click was LOST, not late, and
|
|
23
|
+
// the failure surfaced several lines later on whatever was waiting for the POST's result.
|
|
24
|
+
// No budget can close that. Those tests now wait on the control being enabled
|
|
25
|
+
// (`enabledSubmitControl`, admin/admin.test.tsx), and the window itself is pinned by a
|
|
26
|
+
// dedicated test there.
|
|
21
27
|
//
|
|
22
|
-
//
|
|
28
|
+
// Contention is real and is a different thing: it widens the window such a race needs, and
|
|
29
|
+
// a serial run measurably helped (see vite.config.ts). But a test waiting on the wrong
|
|
30
|
+
// thing fails on an idle machine too, only more rarely. So before this lever is reached for
|
|
31
|
+
// a third time: check what the failing test is waiting on, and whether the thing it clicks
|
|
32
|
+
// can even be clicked yet.
|
|
33
|
+
//
|
|
34
|
+
// The budget has a CEILING, and the first attempt at this walked straight into it. A toast
|
|
23
35
|
// auto-dismisses after `DEFAULT_DURATION_MS` (5s, toast.tsx), and several admin tests wait
|
|
24
36
|
// for a field error and then assert the toast SYNCHRONOUSLY. Set the budget to 5s and a
|
|
25
37
|
// wait that takes long enough outlives the toast the next line is about to look for — one
|
|
26
38
|
// flake traded for another, and a worse one, because it looks like a product bug. So the
|
|
27
39
|
// budget sits between the two: comfortably past a fetch and a re-render, comfortably short
|
|
28
|
-
// of a toast's life. `async-budget.test.ts` holds
|
|
29
|
-
//
|
|
30
|
-
// Raised from 3s to 4s on 2026-09-08: 3s was still not enough under CI load. Two
|
|
31
|
-
// consecutive runs failed on two different fetch-bound tests, and main failed a third
|
|
32
|
-
// time in the same window -- always "unable to find element", always one file of
|
|
33
|
-
// eighty-one. 4s keeps a full second below the toast, which is the last of the
|
|
34
|
-
// headroom this lever has: the next move is less contention, not a longer wait.
|
|
40
|
+
// of a toast's life. `async-budget.test.ts` holds the lower end, and
|
|
41
|
+
// `test_frontend_async_budget.py` the ordering across all three files.
|
|
35
42
|
configure({ asyncUtilTimeout: 4_000 });
|
|
36
43
|
|
|
37
44
|
// jsdom's File / Blob / FormData are structurally incompatible with Node's built-in
|