Files
Ekklesia/surfaces/shell/tests/display-offline-status.test.ts
ekklesiaandClaude Opus 5 ca3f37d5f9 feat: let a display survive its network — as code, not as authorization
A display is the one surface expected to outlive its network: a television on
a wall in a building whose uplink is a consumer router, with nobody standing
in front of it. When that uplink drops and the screen reboots, the browser
shows its own error page — not the display shell, not an Ekklesia message,
nothing that recovers on its own, because there is no Ekklesia code left
running to recover.

Cache the shell and the declared code, in a service worker scoped to
`/display/`: the page, the host script, the module's display artifact, and
every contributed renderer that display actually mounted. All of them are code
whose bytes already confer no authority, and all of them are addressed by a
URL carrying an exact version.

Cache nothing else, ever. Not the descriptor, not `/api/v1/principal`, not a
module or platform API response, not the realtime stream, not a pairing
exchange, and not any cross-origin request — which is what a signed
object-delivery URL is. It is an allowlist rather than a deny list, so the
cost of forgetting a new endpoint is that code goes uncached rather than that
a permission decision gets stored.

The consequence is stated rather than papered over: a display cannot render
module content while offline. Mounting needs a descriptor, a descriptor is
authorization-bearing, and it is never cached — so a revoked device stays
revoked and cached code can never manufacture current authorization. What the
cache buys is that a kiosk rebooting mid-outage boots into Ekklesia's own
offline state and keeps retrying, that reconnecting mounts with nothing left
to download, and that a hiccup fetching 600 KB of artifact after the tiny
descriptor already resolved falls back to identical bytes instead of failing
the display.

Network-first everywhere, so a screen picks up new code the moment the server
returns and can never be trapped on an obsolete build — the failure mode a
cache-first worker produces on a screen nobody visits. Only a complete
same-origin 200 is stored. Cache names carry a policy version and superseded
generations are deleted; artifacts are pruned to the current version per
module, keeping every artifact belonging to that version because a display
artifact and its contributed renderers share one. The worker never caches
itself.

The page gets a small signal built from two sources, because either alone
lies: `navigator.onLine` is optimistic behind a captive portal, and only the
worker knows it actually served from cache. A display shows a quiet corner
indicator rather than blanking a lobby wall, and resolves its descriptor again
by itself when the network returns — nobody presses Retry on a lobby TV.

Every caching decision lives in a module that touches no global, so the
behaviour is exercised directly rather than through a worker a test runner
cannot host. Registration is an enhancement: no service workers, plain HTTP,
or a refusing policy all leave a display that works exactly as before.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-27 16:08:34 -05:00

189 lines
6.3 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
type DisplayConnectivity,
type DisplayConnectivitySource,
DISPLAY_SERVICE_WORKER_URL,
registerDisplayServiceWorker,
watchDisplayConnectivity,
} from "../src/display/offline-status.js";
/**
* The display's connectivity signal (ADR 0043): what it reports, and what it deliberately refuses to
* decide.
*/
interface FakeSource extends DisplayConnectivitySource {
emitOnline(): void;
emitOffline(): void;
emitWorkerMessage(data: unknown): void;
readonly attached: () => number;
}
function fakeSource(initialOnline = true): FakeSource {
const windowListeners = new Map<string, Set<() => void>>();
const workerListeners = new Set<(event: MessageEvent) => void>();
return {
addEventListener(type, listener) {
const existing = windowListeners.get(type) ?? new Set();
existing.add(listener);
windowListeners.set(type, existing);
},
attached: () =>
[...windowListeners.values()].reduce((total, set) => total + set.size, 0) +
workerListeners.size,
emitOffline() {
for (const listener of windowListeners.get("offline") ?? []) {
listener();
}
},
emitOnline() {
for (const listener of windowListeners.get("online") ?? []) {
listener();
}
},
emitWorkerMessage(data: unknown) {
for (const listener of workerListeners) {
listener({ data } as MessageEvent);
}
},
initialOnline,
removeEventListener(type, listener) {
windowListeners.get(type)?.delete(listener);
},
serviceWorkerMessages: {
addEventListener(_type, listener) {
workerListeners.add(listener);
},
removeEventListener(_type, listener) {
workerListeners.delete(listener);
},
},
};
}
describe("display connectivity monitor", () => {
it("starts from what the browser believes and reports nothing else", () => {
const monitor = watchDisplayConnectivity(fakeSource(false));
expect(monitor.current()).toEqual({ online: false, usingFallback: false });
monitor.close();
});
it("reports the browser's online and offline transitions", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
const seen: DisplayConnectivity[] = [];
monitor.subscribe((next) => seen.push(next));
source.emitOffline();
source.emitOnline();
expect(seen).toEqual([
{ online: false, usingFallback: false },
{ online: true, usingFallback: false },
]);
monitor.close();
});
it("reports a cache fallback the worker actually performed, with its kind", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
const seen: DisplayConnectivity[] = [];
monitor.subscribe((next) => seen.push(next));
// The browser still claims to be online — a captive portal, or a dead uplink behind a live
// Wi-Fi association. Only the worker knows this application actually fell back.
source.emitWorkerMessage({ ekklesiaDisplayOffline: { kind: "artifact", usingFallback: true } });
expect(seen).toEqual([{ fallbackKind: "artifact", online: true, usingFallback: true }]);
monitor.close();
});
it("clears the fallback flag once the worker serves from the network again", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
source.emitWorkerMessage({ ekklesiaDisplayOffline: { kind: "shell", usingFallback: true } });
source.emitWorkerMessage({ ekklesiaDisplayOffline: { usingFallback: false } });
expect(monitor.current()).toEqual({ online: true, usingFallback: false });
monitor.close();
});
it("ignores a message that is not the worker's own status", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
const listener = vi.fn();
monitor.subscribe(listener);
for (const data of [null, "offline", { other: true }, { ekklesiaDisplayOffline: "yes" }, 7]) {
source.emitWorkerMessage(data);
}
expect(listener).not.toHaveBeenCalled();
monitor.close();
});
it("publishes only genuine changes, so an unattended screen is not re-rendered on every event", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
const listener = vi.fn();
monitor.subscribe(listener);
source.emitOnline();
source.emitOnline();
source.emitOffline();
source.emitOffline();
expect(listener).toHaveBeenCalledTimes(1);
monitor.close();
});
it("detaches everything on close, idempotently", () => {
const source = fakeSource(true);
const monitor = watchDisplayConnectivity(source);
monitor.subscribe(() => undefined);
expect(source.attached()).toBeGreaterThan(0);
monitor.close();
monitor.close();
expect(source.attached()).toBe(0);
});
it("works with no sources at all, reporting a display that simply never knows", () => {
const monitor = watchDisplayConnectivity();
expect(monitor.current()).toEqual({ online: true, usingFallback: false });
monitor.close();
});
});
describe("registering the display service worker", () => {
it("registers the one fixed platform path as a module worker", async () => {
const register = vi.fn().mockResolvedValue({});
const registered = await registerDisplayServiceWorker({
register,
} as unknown as ServiceWorkerContainer);
expect(registered).toBe(true);
expect(register).toHaveBeenCalledWith(DISPLAY_SERVICE_WORKER_URL, { type: "module" });
// The path's *directory* is the scope: `/display/`, so the worker controls display pages and
// nothing else.
expect(DISPLAY_SERVICE_WORKER_URL).toBe("/display/sw.js");
});
it("never lets a missing or refused registration break the display", async () => {
// Offline resilience is an enhancement. A browser without service workers, a page served over
// plain HTTP in development, and a policy that refuses all leave a display that works exactly as
// it did before — online only.
expect(await registerDisplayServiceWorker(undefined)).toBe(false);
expect(
await registerDisplayServiceWorker({
register: vi.fn().mockRejectedValue(new Error("SecurityError")),
} as unknown as ServiceWorkerContainer),
).toBe(false);
});
});