Files
Ekklesia/surfaces/shell/tests/displays-settings.test.tsx
T
ekklesiaandClaude Opus 5.5 300d9eab51
CI / verify (pull_request) Successful in 1m12s
CI / infrastructure-smoke (pull_request) Successful in 45s
CI / package-release (pull_request) Successful in 50s
CI / migration-smoke (pull_request) Successful in 2m34s
CI / image-build (pull_request) Successful in 1m8s
CI / deploy-smoke (same-origin) (pull_request) Successful in 51s
CI / package-publication (pull_request) Successful in 57s
CI / deploy-smoke (split) (pull_request) Successful in 3m52s
Pair displays at the platform's own /display/setup, with or without modules
Displays are platform-owned, but a screen could only start pairing on a
module's display page: every pairing request named a module, so an
installation with no module that uses displays could not set one up.

- /display/setup is the platform's own display page, served whenever
  the deployment has device support, whatever is installed. It pairs a
  platform display with no module. Once paired, it opens the module it
  is set to show; with none set, it shows its name and waits, rechecking
  so it stays alive and notices revocation. "setup" is now a reserved
  module id.
- Migration core:0009_platform_display_pairing lets a pairing request
  name no module. It relaxes module_id and permission_id and adds a
  both-or-neither check. It is additive and destroys nothing.
- POST /api/v1/device-pairing/requests accepts {} for a platform
  display. Approval accepts an optional moduleId, so the administrator
  can choose an installed display module and the device gets that
  module's declared permission. A module display's own request can't be
  redirected.
- GET /api/v1/device-pairing/self lets a paired device describe itself:
  its name and the module displays it may show. It renews the device's
  cookie.
- GET /api/v1/devices/setup is replaced by
  GET /api/v1/devices/display-modules: the modules a display can be set
  to show.
- Settings -> Displays always offers the /display/setup address, Copy
  setup link and Add display. Add display has an optional "Show on this
  screen" choice, and each paired display says what it shows.
- /display/<module-id> is unchanged, so released Signage 0.1.5 works as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 16:43:02 -05:00

404 lines
16 KiB
TypeScript

import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DisplaysSettingsPage } from "../src/browser/DisplaysSettingsPage.js";
declare global {
// eslint-disable-next-line no-var
var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
}
/**
* Settings → Displays (ADR 0064): the device surface that used to sit in the sidebar, moved into
* Settings — the paired displays, a deliberate Add display flow, and revocation in a product dialog.
*/
const apiBaseUrl = "https://ekklesia.example.test";
const NOW = new Date("2026-10-15T12:00:00.000Z");
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
});
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { "content-type": "application/json" },
status,
});
}
interface ServerOptions {
readonly devices?: unknown[];
readonly denied?: boolean;
/** What `GET /api/v1/devices/display-modules` answers: the installed display modules (by
* default Signage), none, or a failure. */
readonly modules?: unknown[] | "fails";
}
/** A screen that asked from Signage's own display page. */
const MODULE_CODE = "123456";
/** A screen that asked from the platform's `/display/setup`, with no module (ADR 0065). */
const PLATFORM_CODE = "654321";
function server(options: ServerOptions = {}) {
let devices: unknown[] = options.devices ?? [
{
createdAt: "2026-10-01T09:00:00.000Z",
id: "device-1",
lastSeenAt: "2026-10-15T11:50:00.000Z",
name: "Foyer TV",
permissions: [],
revoked: false,
},
];
const requests: { path: string; body: unknown }[] = [];
const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const path = new URL(String(input)).pathname;
const body = init?.body === undefined ? undefined : JSON.parse(String(init.body));
requests.push({ body, path });
if (path === "/api/v1/devices/display-modules") {
if (options.modules === "fails") {
return json({ code: "DEVICE_LOOKUP_UNAVAILABLE" }, 503);
}
return json({
modules: options.modules ?? [
{ moduleId: "signage", name: "Signage", permissionId: "signage.display" },
],
});
}
if (path === "/api/v1/devices") {
return options.denied ? json({ code: "AUTHORIZATION_DENIED" }, 403) : json({ devices });
}
if (path === "/api/v1/devices/device-1/revoke") {
devices = devices.map((device) => ({ ...(device as object), revoked: true }));
return new Response(null, { status: 204 });
}
if (path === "/api/v1/device-pairing/lookups") {
const code = (body as { code: string }).code;
if (code !== MODULE_CODE && code !== PLATFORM_CODE) {
return json({ code: "DEVICE_PAIRING_NOT_FOUND" }, 404);
}
const module = code === MODULE_CODE;
return json({
expiresAt: "2026-10-15T12:10:00.000Z",
moduleId: module ? "signage" : null,
permissionId: module ? "signage.display" : null,
requestedAt: "2026-10-15T11:59:00.000Z",
});
}
if (path === "/api/v1/device-pairing/approvals") {
const approval = body as { code: string; deviceName: string; moduleId?: string };
const shows = approval.code === MODULE_CODE ? "signage" : approval.moduleId;
devices = [
...devices,
{
createdAt: "2026-10-15T12:00:00.000Z",
id: "device-2",
name: approval.deviceName,
permissions: shows === "signage" ? ["signage.display"] : [],
revoked: false,
},
];
return json({
moduleId: shows ?? null,
permissionId: shows === undefined ? null : `${shows}.display`,
});
}
return json({ code: "NOT_FOUND" }, 404);
}) as unknown as typeof globalThis.fetch;
return { fetch, requests };
}
function query(testId: string): HTMLElement | null {
return container.querySelector(`[data-testid="${testId}"]`);
}
function required(testId: string): HTMLElement {
const element = query(testId);
if (!element) {
throw new Error(`missing ${testId}`);
}
return element;
}
async function settle(): Promise<void> {
for (let index = 0; index < 6; index += 1) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
async function click(testId: string): Promise<void> {
await act(async () => {
required(testId).click();
await settle();
});
}
async function type(testId: string, value: string): Promise<void> {
const input = required(testId) as HTMLInputElement;
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
async function choose(testId: string, value: string): Promise<void> {
const select = required(testId) as HTMLSelectElement;
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set;
setter?.call(select, value);
select.dispatchEvent(new Event("change", { bubbles: true }));
});
}
async function submit(testId: string): Promise<void> {
const form = (required(testId) as HTMLButtonElement).form;
await act(async () => {
form?.requestSubmit();
await settle();
});
}
async function renderPage(options: ServerOptions = {}) {
const platform = server(options);
await act(async () => {
root.render(
<DisplaysSettingsPage
back={{ href: "/settings", label: "Back to Settings", onBack: () => undefined }}
config={{ apiBaseUrl, fetch: platform.fetch }}
moduleName={(moduleId) => (moduleId === "signage" ? "Signage" : undefined)}
now={() => NOW}
/>,
);
await settle();
});
return platform;
}
describe("Settings → Displays", () => {
it("lists the paired displays with what is known about each, and takes no focus", async () => {
const before = document.activeElement;
await renderPage();
const card = required("device-device-1");
expect(card.textContent).toContain("Foyer TV");
expect(card.textContent).toContain("Paired");
expect(card.textContent).toContain("Last seen within the last hour");
expect(card.textContent).toContain("Not showing a module yet");
expect(container.querySelector("h1")?.textContent).toBe("Displays");
// How to set up a new screen comes first, in one place: the platform's own setup page on the
// API origin, then Add display right under it, with the step-by-step version folded away.
const setup = required("display-setup");
expect(setup.textContent).toContain("Open this address on the new screen");
expect(required("display-setup-url").textContent).toBe(`${apiBaseUrl}/display/setup`);
expect(setup.contains(required("add-display"))).toBe(true);
const steps = required("display-setup-steps");
expect(steps.tagName).toBe("DETAILS");
expect((steps as HTMLDetailsElement).open).toBe(false);
expect(steps.querySelector("summary")?.textContent).toBe("Step-by-step instructions");
expect(steps.textContent).toContain("six-digit pairing code");
// Not a second Add display up in the header.
expect(container.querySelectorAll('[data-testid="add-display"]')).toHaveLength(1);
// No pairing form until someone asks for one, and nothing grabbed focus.
expect(container.querySelector("input")).toBeNull();
expect(document.activeElement).toBe(before);
});
it("says when nothing is paired yet, and when the list is not this person's to see", async () => {
await renderPage({ devices: [] });
expect(required("device-list-empty").textContent).toContain("No displays are paired yet");
await act(async () => root.unmount());
root = createRoot(container);
await renderPage({ denied: true });
expect(container.textContent).toContain("Displays aren't available to you");
expect(query("add-display")).toBeNull();
});
it("pairs a display through a deliberate Add display flow, focusing each next step", async () => {
const platform = await renderPage();
await click("add-display");
const dialog = required("add-display-dialog");
expect(dialog.getAttribute("role")).toBe("dialog");
// Typing the code is now plainly the next thing to do, so the field has focus.
expect(document.activeElement).toBe(required("device-pairing-code-input"));
await type("device-pairing-code-input", "999999");
await submit("device-pairing-lookup");
expect(required("device-pairing-error").textContent).toContain("not waiting for approval");
await type("device-pairing-code-input", MODULE_CODE);
await submit("device-pairing-lookup");
// A screen that asked from a module's own display already shows that module: no choice.
expect(required("device-pairing-found").textContent).toContain("Signage");
expect(query("device-pairing-shows")).toBeNull();
expect(document.activeElement).toBe(required("device-pairing-name"));
await type("device-pairing-name", "Sanctuary left");
await submit("device-pairing-approve");
expect(query("add-display-dialog")).toBeNull();
expect(
platform.requests.find((r) => r.path === "/api/v1/device-pairing/approvals")?.body,
).toEqual({ code: MODULE_CODE, deviceName: "Sanctuary left" });
// The new display appears without a page refresh, and the page says so.
expect(required("device-device-2").textContent).toContain("Sanctuary left");
expect(required("device-pairing-success").textContent).toContain(
"Sanctuary left is paired and shows Signage.",
);
expect(required("device-device-2").textContent).toContain("Shows Signage");
// Focus is back on the control that opened the flow.
expect(document.activeElement).toBe(required("add-display"));
});
it("closes the Add display flow on Cancel without pairing anything", async () => {
const platform = await renderPage();
await click("add-display");
await click("add-display-cancel");
expect(query("add-display-dialog")).toBeNull();
expect(platform.requests.map((r) => r.path).sort()).toEqual([
"/api/v1/devices",
"/api/v1/devices/display-modules",
]);
expect(document.activeElement).toBe(required("add-display"));
});
});
describe("setting up a new screen (ADR 0065)", () => {
it("copies the platform setup address, and says so when the browser cannot", async () => {
const writeText = vi.fn(async () => undefined);
Object.defineProperty(window.navigator, "clipboard", {
configurable: true,
value: { writeText },
});
await renderPage();
await click("display-setup-copy");
expect(writeText).toHaveBeenCalledWith(`${apiBaseUrl}/display/setup`);
expect(required("display-setup").textContent).toContain("Link copied.");
Object.defineProperty(window.navigator, "clipboard", { configurable: true, value: undefined });
await click("display-setup-copy");
expect(required("display-setup").textContent).toContain("couldn't copy it");
});
it("offers the same setup and Add display with zero display modules installed", async () => {
const platform = await renderPage({ modules: [] });
// The generic platform address, and nothing that names a module.
expect(required("display-setup-url").textContent).toBe(`${apiBaseUrl}/display/setup`);
expect(required("display-setup").textContent).not.toContain("Signage");
expect(query("add-display")).not.toBeNull();
// A screen from /display/setup pairs as a platform display with no module.
await click("add-display");
await type("device-pairing-code-input", PLATFORM_CODE);
await submit("device-pairing-lookup");
expect(required("device-pairing-found").textContent).toContain(
"A new screen is waiting to be paired",
);
expect(query("device-pairing-shows")).toBeNull();
expect(required("device-pairing-no-modules").textContent).toContain(
"No installed module shows content on screens yet",
);
await type("device-pairing-name", "Foyer TV 2");
await submit("device-pairing-approve");
expect(
platform.requests.find((r) => r.path === "/api/v1/device-pairing/approvals")?.body,
).toEqual({ code: PLATFORM_CODE, deviceName: "Foyer TV 2" });
expect(required("device-pairing-success").textContent).toContain(
"Foyer TV 2 is paired. It shows its name until a module is set to show on it.",
);
expect(required("device-device-2").textContent).toContain("Not showing a module yet");
});
it("lets the administrator choose which installed module a new platform display shows", async () => {
const platform = await renderPage();
await click("add-display");
await type("device-pairing-code-input", PLATFORM_CODE);
await submit("device-pairing-lookup");
const shows = required("device-pairing-shows") as HTMLSelectElement;
expect([...shows.options].map((option) => option.textContent)).toEqual([
"Nothing yet",
"Signage",
]);
expect(shows.value).toBe("");
await choose("device-pairing-shows", "signage");
await type("device-pairing-name", "Lobby screen");
await submit("device-pairing-approve");
expect(
platform.requests.find((r) => r.path === "/api/v1/device-pairing/approvals")?.body,
).toEqual({ code: PLATFORM_CODE, deviceName: "Lobby screen", moduleId: "signage" });
expect(required("device-pairing-success").textContent).toContain(
"Lobby screen is paired and shows Signage.",
);
expect(required("device-device-2").textContent).toContain("Shows Signage");
});
it("still pairs, showing nothing yet, when the display modules cannot be read", async () => {
const platform = await renderPage({ modules: "fails" });
expect(required("display-setup-url").textContent).toBe(`${apiBaseUrl}/display/setup`);
await click("add-display");
await type("device-pairing-code-input", PLATFORM_CODE);
await submit("device-pairing-lookup");
expect(query("device-pairing-shows")).toBeNull();
await type("device-pairing-name", "Hall");
await submit("device-pairing-approve");
expect(
platform.requests.find((r) => r.path === "/api/v1/device-pairing/approvals")?.body,
).toEqual({ code: PLATFORM_CODE, deviceName: "Hall" });
// Without the module list the card does not guess what the display shows.
expect(required("device-device-1").textContent).not.toContain("showing");
});
});
/**
* Revoking a display strands that screen until someone re-pairs it in person, so the page explains
* the consequence in its own dialog first — never with a browser-native confirm (DESIGN §21).
*/
describe("display revocation", () => {
it("asks in a product dialog before revoking, and does nothing on cancel", async () => {
const confirm = vi.fn(() => true);
Object.assign(window, { confirm });
const platform = await renderPage();
await click("device-revoke-device-1");
const dialog = container.querySelector('[role="dialog"]');
expect(dialog?.textContent).toContain("Revoke Foyer TV?");
expect(dialog?.textContent).toContain("pairing code");
await click("device-revoke-cancel");
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(platform.requests.some((r) => r.path.endsWith("/revoke"))).toBe(false);
expect(confirm).not.toHaveBeenCalled();
});
it("revokes only after the destructive action is confirmed", async () => {
const platform = await renderPage();
await click("device-revoke-device-1");
await click("device-revoke-confirm");
expect(platform.requests.filter((r) => r.path.endsWith("/revoke"))).toHaveLength(1);
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(required("device-device-1").textContent).toContain("Revoked");
expect(query("device-revoke-device-1")).toBeNull();
});
});