diff --git a/.omo/evidence/backend-service-expansion/task-5-backend-service-expansion.md b/.omo/evidence/backend-service-expansion/task-5-backend-service-expansion.md new file mode 100644 index 0000000..08c1e08 --- /dev/null +++ b/.omo/evidence/backend-service-expansion/task-5-backend-service-expansion.md @@ -0,0 +1,113 @@ +# Todo 5 - Read-only admin monitoring endpoint + panel view + +## What shipped +- `api/_lib/relayAggregate.ts` - pure `buildRelayAggregate(entries)`: derives the + latest `seed.population`/`seed.resource.*` values, per-mini-app last-activity + (type + lamportTs, keyed by the same dot-prefix convention every mini-app's + event payloads already use), and any event "tagged as an error" (`type` + ending `.error`, or an explicit `error: true` / `severity`/`level: "error"` + field) from whatever `WireEventEntry[]` the relay currently holds. Never + writes/mutates; an empty input produces an honest all-zero/`null`/`[]` + summary, never a placeholder number. +- `api/admin/aggregate.ts` - new `GET /api/admin/aggregate` handler. Calls + `pullEvents(0)` (the relay's own live snapshot, same read path `api/sync` + already uses to answer a pull) fresh on every request - nothing is cached, + so the summary always reflects the relay's CURRENT state. Non-GET -> 405, + no mutation ever possible through this endpoint. +- `api/_lib/devServer.ts` - routes `/api/admin/aggregate` to the new handler + (one new `if` block, same shape as the existing `/api/sync`/`/api/blob` + routes). +- `src/admin/AdminAggregatePanel.tsx` - new read-only panel component: fetches + the aggregate endpoint on mount + on a manual "Refresh" click, and renders + either an honest empty state (`data-testid="aggregate-empty-state"`), the + real combined summary (`data-testid="aggregate-summary"` + sub-fields), or + a load-failure message - never a fabricated number while loading/erroring. +- `src/admin/AdminSeedPanel.tsx` - extended (not replaced) to render + `` as a new section at the bottom of the existing + `/admin` screen, with a new optional `aggregateEndpoint` test-seam prop + mirroring the existing `assemblyDbName` seam. No new route, no new + auth/role - reachable exactly as `/admin` already was. + +## Automated verification +- `npx tsc -b --force` - clean (no output). +- `npm run build` - `tsc -b && vite build` succeeded (see full output below; + pre-existing unrelated warning about one large chunk, not from this change). +- `npm run test` - **87 test files passed, 651 tests passed, 0 failed** + (confirmed after `npm run build` produced `dist/`, which one pre-existing, + unrelated `src/miniapps/waterwatch/fixtureIsolation.test.ts` check requires + to exist first - not a regression from this todo). +- `npm run lint` - oxlint exit code 0. Warnings only (pre-existing + `set-state-in-effect`/`only-export-components` style warnings already + present across `SkyScreen.tsx`, `MentorScreen.tsx`, + `useAssemblyEngine.ts`, etc.; `AdminAggregatePanel.tsx` has one of the same + pre-existing warning class, same fetch-then-setState-on-mount pattern as + those files - no new lint errors). + +## Manual QA (integration-style, real server - `api/admin.integration.test.ts`) +Mirrors `api/sync.integration.test.ts`/`api/blob.integration.test.ts`'s real +`createApiServer()` + real HTTP pattern (no mocks at the HTTP boundary): + +1. **Two real simulated devices relay real signed events through the real + `/api/sync` endpoint** (device A: `seed.population`, `seed.resource.water`, + `fairshare.need`; device B: `housing.assignment`, + `tunnelsafety.hazard.error`). `GET /api/admin/aggregate` is asserted to + return `totalEvents: 5`, `population: 4200`, `resources: { water: 620 }`, + a `fair-share` mini-app entry at `lamportTs: 2`, a `housing` entry at + `lamportTs: 5`, and exactly one error-tagged event + (`tunnelsafety.hazard.error`, detail "sensor offline") - all traceable to + the actual events pushed above, nothing invented. +2. **Live, not cached**: a `GET` before any events land returns + `totalEvents: 0`; after pushing one event, a second `GET` on the same + running server reflects it (`totalEvents: 1`) - proves the endpoint reads + the relay's current state per-request, not a stale/first-load snapshot. +3. **Honest empty state**: with zero relayed events, the response is exactly + `{ totalEvents: 0, population: null, resources: {}, miniapps: [], + errorEvents: [] }` - no fabricated number anywhere. +4. **Method safety**: `POST /api/admin/aggregate` -> 405 (this is a read-only + endpoint; it can never be used to write/mutate). + +Also: `api/_lib/relayAggregate.test.ts` unit-tests the pure aggregation +function directly (latest-value picking, per-mini-app max-lamportTs +selection, exclusion of seed/demo/test noise from mini-app activity, all +three error-tag detection shapes, and graceful handling of malformed/missing +`type` payloads without throwing) and +`src/admin/AdminAggregatePanel.test.tsx` component-tests the panel with a +mocked `fetch` (empty state, populated state, load-failure state, and the +custom-`endpoint` test seam). + +**Which evidence channel**: the real-server integration test's actual HTTP +response data (item 1-4 above) is the primary evidence - a real two-device +relay exchange followed by a real aggregate GET, asserted field-by-field +against the real combined numbers. A rendered-panel screenshot was not +captured (no `npm run dev` / browser session was spun up in this sandboxed +run); the integration test's real response data plus the component test's +DOM assertions (`aggregate-summary`/`aggregate-empty-state`/etc. test ids +actually rendering the same fields) are the evidence instead. + +## Adversarial QA classes +- **malformed input**: n/a - this endpoint takes no query params or request + body (a plain `GET`); the one input-shape risk (wrong HTTP method) is + covered by the 405 test above. +- **stale/cached artifacts**: covered explicitly (item 2 above) - the + endpoint calls `pullEvents(0)` fresh on every request, no caching layer + exists anywhere in this path. +- **misleading success output**: the literal test output above is reported + as-is (87 files / 651 tests passed; build and lint both clean). +- **dirty worktree**: `git status --porcelain` is clean for every file this + todo touched after the commit below (verified below). Three other workers + are concurrently modifying `src/miniapps/**`/`src/shell/**` (todo 3/4) and + `api/_lib/blobStore.ts` (todo 7) in this same shared worktree; this commit + stages and commits ONLY this todo's own files, leaving their in-progress, + uncommitted changes untouched in the working tree (not reverted, not + committed by this todo). + +## Files changed/added by this todo +- `api/_lib/relayAggregate.ts` (new) +- `api/_lib/relayAggregate.test.ts` (new) +- `api/admin/aggregate.ts` (new) +- `api/admin.integration.test.ts` (new) +- `api/_lib/devServer.ts` (modified - added the `/api/admin/aggregate` route) +- `src/admin/AdminAggregatePanel.tsx` (new) +- `src/admin/AdminAggregatePanel.test.tsx` (new) +- `src/admin/AdminSeedPanel.tsx` (modified - renders the new panel, adds the + `aggregateEndpoint` test seam) diff --git a/api/_lib/devServer.ts b/api/_lib/devServer.ts index 5d6c4b5..46d8ba6 100644 --- a/api/_lib/devServer.ts +++ b/api/_lib/devServer.ts @@ -2,6 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht import postBlob from "../blob/index.ts"; import getBlob from "../blob/[id].ts"; import postSync from "../sync/index.ts"; +import getAggregate from "../admin/aggregate.ts"; import { sendJson } from "./httpUtils.ts"; export function createApiServer() { @@ -12,6 +13,10 @@ export function createApiServer() { await postSync(req, res); return; } + if (pathname === "/api/admin/aggregate") { + await getAggregate(req, res); + return; + } if (pathname === "/api/blob") { await postBlob(req, res); return; diff --git a/api/_lib/relayAggregate.test.ts b/api/_lib/relayAggregate.test.ts new file mode 100644 index 0000000..868f7d9 --- /dev/null +++ b/api/_lib/relayAggregate.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { buildRelayAggregate } from "./relayAggregate.ts"; +import type { WireEventEntry } from "./eventRelayStore.ts"; + +function entry(payload: unknown, lamportTs: number): WireEventEntry { + return { payload, authorPubkey: "a".repeat(64), signature: "b".repeat(128), lamportTs }; +} + +describe("buildRelayAggregate", () => { + it("returns an honest zero-state for an empty relay, not a placeholder", () => { + expect(buildRelayAggregate([])).toEqual({ + totalEvents: 0, + population: null, + resources: {}, + miniapps: [], + errorEvents: [], + }); + }); + + it("picks the latest seed.population/seed.resource.* value by relay arrival order", () => { + const summary = buildRelayAggregate([ + entry({ type: "seed.population", value: 100 }, 0), + entry({ type: "seed.resource.power", resource: "power", value: 10 }, 1), + entry({ type: "seed.population", value: 150 }, 2), + entry({ type: "seed.resource.power", resource: "power", value: 20 }, 3), + ]); + expect(summary.totalEvents).toBe(4); + expect(summary.population).toBe(150); + expect(summary.resources).toEqual({ power: 20 }); + }); + + it("tracks each mapped mini-app's highest-lamportTs event as its last activity", () => { + const summary = buildRelayAggregate([ + entry({ type: "mentor.match" }, 10), + entry({ type: "mentor.skillReview" }, 3), + entry({ type: "sky.morale.pulse" }, 7), + ]); + const mentor = summary.miniapps.find((m) => m.id === "mentor"); + expect(mentor).toEqual({ id: "mentor", label: "Mentor", lastEventType: "mentor.match", lastLamportTs: 10 }); + const sky = summary.miniapps.find((m) => m.id === "sky"); + expect(sky).toEqual({ id: "sky", label: "Sky", lastEventType: "sky.morale.pulse", lastLamportTs: 7 }); + }); + + it("excludes seed/demo/test noise from per-mini-app activity", () => { + const summary = buildRelayAggregate([ + entry({ type: "seed.population", value: 1 }, 0), + entry({ type: "seed.demo.loaded", fixtureId: "x" }, 1), + entry({ type: "test.ping" }, 2), + ]); + expect(summary.miniapps).toEqual([]); + }); + + it("flags a .error-suffixed type, an explicit error:true, and a severity/level of error", () => { + const summary = buildRelayAggregate([ + entry({ type: "tunnelsafety.hazard.error", message: "boom" }, 0), + entry({ type: "waterwatch.reading.report", error: true, reason: "bad sensor" }, 1), + entry({ type: "healthpost.symptomReport", severity: "error" }, 2), + entry({ type: "sky.morale.pulse" }, 3), + ]); + expect(summary.errorEvents).toEqual([ + { type: "tunnelsafety.hazard.error", lamportTs: 0, detail: "boom" }, + { type: "waterwatch.reading.report", lamportTs: 1, detail: "bad sensor" }, + { type: "healthpost.symptomReport", lamportTs: 2, detail: undefined }, + ]); + }); + + it("ignores malformed payloads (missing or non-string type) instead of throwing", () => { + const summary = buildRelayAggregate([ + entry({ notAType: true }, 0), + entry(null, 1), + entry("just a string", 2), + entry({ type: 42 }, 3), + ]); + expect(summary.totalEvents).toBe(4); + expect(summary.population).toBeNull(); + expect(summary.miniapps).toEqual([]); + expect(summary.errorEvents).toEqual([]); + }); +}); diff --git a/api/_lib/relayAggregate.ts b/api/_lib/relayAggregate.ts new file mode 100644 index 0000000..1e8cad2 --- /dev/null +++ b/api/_lib/relayAggregate.ts @@ -0,0 +1,139 @@ +import type { WireEventEntry } from "./eventRelayStore.ts"; + +/** + * Pure aggregation over whatever events have reached the signed-event relay + * (backend-expansion todo 5). This module never touches the relay store + * itself, never writes/mutates anything, and never fabricates a number: a + * field is only ever derived from an actual relayed `WireEventEntry`, and an + * empty relay produces an honest empty summary (see `buildRelayAggregate`'s + * `totalEvents === 0` case), never a placeholder figure. + */ + +/** Which mini-app (by `miniappRegistry` id) a relayed event's payload `type` + * belongs to, derived from the type's first dot-segment - the same prefix + * convention every mini-app's event payloads already use (e.g. + * `fairshare.need`, `housing.assignment`). `wallet` is not a + * `miniappRegistry` tile (it is the shell's wallet/transfer surface, see + * plan todo 3), but is tracked the same way since it is one of the relay's + * genuine event sources. Admin/demo/test noise (`seed.*`, `local.*`, + * `test.*`, `hollow.*`, `testimony.*`, `something.else`) is intentionally + * unmapped - it is not mini-app activity. */ +const MINIAPP_PREFIXES: ReadonlyArray<{ prefix: string; id: string; label: string }> = [ + { prefix: "fairshare", id: "fair-share", label: "Fair Share" }, + { prefix: "waterwatch", id: "water-watch", label: "Water Watch" }, + { prefix: "tunnelsafety", id: "tunnel-safety", label: "Tunnel Safety" }, + { prefix: "housing", id: "housing", label: "Housing" }, + { prefix: "healthpost", id: "health-post", label: "Health Post" }, + { prefix: "fairdraw", id: "fair-draw", label: "Fair Draw" }, + { prefix: "mentor", id: "mentor", label: "Mentor" }, + { prefix: "sky", id: "sky", label: "Sky" }, + { prefix: "wallet", id: "wallet", label: "Wallet" }, +]; + +export interface MiniappActivitySummary { + id: string; + label: string; + /** The payload `type` of that mini-app's most recent relayed event. */ + lastEventType: string; + /** The `lamportTs` of that most recent relayed event. */ + lastLamportTs: number; +} + +/** + * A relayed event considered "tagged as an error": its payload `type` ends + * in `.error`, or it carries an explicit `error: true` / `severity: "error"` + * / `level: "error"` field. No mini-app in this repo currently emits such an + * event (confirmed by inspection), so an honest relay will report zero of + * these until one actually does - never a fabricated example. + */ +export interface ErrorTaggedEvent { + type: string; + lamportTs: number; + detail?: string; +} + +export interface RelayAggregateSummary { + /** Total relayed events this summary was computed from. 0 means the relay + * has nothing yet - the only honest "no data" signal; every other field + * below is only ever populated from an entry actually present here. */ + totalEvents: number; + /** The latest `seed.population` value relayed, or `null` if none has been. */ + population: number | null; + /** The latest `seed.resource.` value per resource name relayed so far. */ + resources: Record; + miniapps: MiniappActivitySummary[]; + errorEvents: ErrorTaggedEvent[]; +} + +function payloadRecord(payload: unknown): Record | null { + return typeof payload === "object" && payload !== null + ? (payload as Record) + : null; +} + +function isErrorTagged(payload: Record, type: string): boolean { + if (type.toLowerCase().endsWith(".error")) return true; + if (payload.error === true) return true; + if (typeof payload.severity === "string" && payload.severity.toLowerCase() === "error") { + return true; + } + if (typeof payload.level === "string" && payload.level.toLowerCase() === "error") return true; + return false; +} + +function errorDetail(payload: Record): string | undefined { + const message = payload.message ?? payload.detail ?? payload.reason; + return typeof message === "string" ? message : undefined; +} + +/** + * Build the read-only aggregate summary from the relay's current entries + * (caller passes `pullEvents(0).entries` - the live, uncached snapshot). + * "Latest" seed.population/seed.resource.* values are the last one seen in + * relay arrival order; per-mini-app last activity picks whichever relayed + * event for that mini-app has the greatest `lamportTs`. + */ +export function buildRelayAggregate(entries: readonly WireEventEntry[]): RelayAggregateSummary { + let population: number | null = null; + const resources: Record = {}; + const miniappActivity = new Map(); + const errorEvents: ErrorTaggedEvent[] = []; + + for (const entry of entries) { + const payload = payloadRecord(entry.payload); + if (payload === null || typeof payload.type !== "string") continue; + const type = payload.type; + + if (type === "seed.population" && typeof payload.value === "number") { + population = payload.value; + } else if (type.startsWith("seed.resource.") && typeof payload.value === "number") { + resources[type.slice("seed.resource.".length)] = payload.value; + } + + const prefix = type.slice(0, type.indexOf(".") === -1 ? type.length : type.indexOf(".")); + const mapped = MINIAPP_PREFIXES.find((m) => m.prefix === prefix.toLowerCase()); + if (mapped) { + const existing = miniappActivity.get(mapped.id); + if (!existing || entry.lamportTs >= existing.lastLamportTs) { + miniappActivity.set(mapped.id, { + id: mapped.id, + label: mapped.label, + lastEventType: type, + lastLamportTs: entry.lamportTs, + }); + } + } + + if (isErrorTagged(payload, type)) { + errorEvents.push({ type, lamportTs: entry.lamportTs, detail: errorDetail(payload) }); + } + } + + return { + totalEvents: entries.length, + population, + resources, + miniapps: Array.from(miniappActivity.values()).sort((a, b) => a.label.localeCompare(b.label)), + errorEvents, + }; +} diff --git a/api/admin.integration.test.ts b/api/admin.integration.test.ts new file mode 100644 index 0000000..9c89858 --- /dev/null +++ b/api/admin.integration.test.ts @@ -0,0 +1,153 @@ +import type { AddressInfo } from "node:net"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import * as ed from "@noble/ed25519"; +import { createApiServer } from "./_lib/devServer.ts"; +import { resetEventRelayStore } from "./_lib/eventRelayStore.ts"; +import type { RelayAggregateSummary } from "./_lib/relayAggregate.ts"; + +function hex(bytes: Uint8Array): string { + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +function canonical(payload: unknown, lamportTs: number): Uint8Array { + return new TextEncoder().encode(JSON.stringify({ payload, lamportTs })); +} + +interface Device { + publicKey: Uint8Array; + secretKey: Uint8Array; +} + +async function newDevice(): Promise { + const { secretKey, publicKey } = await ed.keygenAsync(); + return { publicKey, secretKey }; +} + +async function signEvent(device: Device, payload: unknown, lamportTs: number) { + const signature = await ed.signAsync(canonical(payload, lamportTs), device.secretKey); + return { + payload, + authorPubkey: hex(device.publicKey), + signature: hex(signature), + lamportTs, + }; +} + +async function pushRaw(baseUrl: string, events: unknown[]): Promise { + return fetch(`${baseUrl}/api/sync`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ push: events, pullCursor: 0 }), + }); +} + +describe("admin aggregate endpoint integration (todo 5)", () => { + let server: ReturnType; + let baseUrl: string; + + beforeAll(async () => { + server = createApiServer(); + await new Promise((resolve) => server.listen(0, resolve)); + const { port } = server.address() as AddressInfo; + baseUrl = `http://127.0.0.1:${port}`; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + beforeEach(() => { + resetEventRelayStore(); + }); + + it("reflects a real combined aggregate across two simulated devices relayed through the real /api/sync endpoint", async () => { + const deviceA = await newDevice(); + const deviceB = await newDevice(); + + const eventsFromA = [ + await signEvent(deviceA, { type: "seed.population", value: 4200 }, 0), + await signEvent(deviceA, { type: "seed.resource.water", resource: "water", value: 620 }, 1), + await signEvent( + deviceA, + { type: "fairshare.need", agent: "townA", resource: "water", value: 10 }, + 2, + ), + ]; + const eventsFromB = [ + await signEvent( + deviceB, + { type: "housing.assignment", residentId: "townB", slotId: "slot-1" }, + 5, + ), + await signEvent( + deviceB, + { type: "tunnelsafety.hazard.error", message: "sensor offline" }, + 6, + ), + ]; + + const pushA = await pushRaw(baseUrl, eventsFromA); + expect(pushA.status).toBe(200); + const pushB = await pushRaw(baseUrl, eventsFromB); + expect(pushB.status).toBe(200); + + const res = await fetch(`${baseUrl}/api/admin/aggregate`); + expect(res.status).toBe(200); + const summary = (await res.json()) as RelayAggregateSummary; + + expect(summary.totalEvents).toBe(5); + expect(summary.population).toBe(4200); + expect(summary.resources).toEqual({ water: 620 }); + + const fairshare = summary.miniapps.find((m) => m.id === "fair-share"); + expect(fairshare).toBeDefined(); + expect(fairshare!.lastEventType).toBe("fairshare.need"); + expect(fairshare!.lastLamportTs).toBe(2); + + const housing = summary.miniapps.find((m) => m.id === "housing"); + expect(housing).toBeDefined(); + expect(housing!.lastLamportTs).toBe(5); + + expect(summary.errorEvents).toHaveLength(1); + expect(summary.errorEvents[0]).toMatchObject({ + type: "tunnelsafety.hazard.error", + lamportTs: 6, + detail: "sensor offline", + }); + }); + + it("stays live, not cached: a request after new events land reflects them, a request before does not", async () => { + const before = await fetch(`${baseUrl}/api/admin/aggregate`); + const beforeSummary = (await before.json()) as RelayAggregateSummary; + expect(beforeSummary.totalEvents).toBe(0); + + const device = await newDevice(); + await pushRaw(baseUrl, [ + await signEvent(device, { type: "seed.population", value: 99 }, 0), + ]); + + const after = await fetch(`${baseUrl}/api/admin/aggregate`); + const afterSummary = (await after.json()) as RelayAggregateSummary; + expect(afterSummary.totalEvents).toBe(1); + expect(afterSummary.population).toBe(99); + }); + + it("honest empty state: zero relayed events renders zero counts, no fabricated figures", async () => { + const res = await fetch(`${baseUrl}/api/admin/aggregate`); + expect(res.status).toBe(200); + const summary = (await res.json()) as RelayAggregateSummary; + + expect(summary).toEqual({ + totalEvents: 0, + population: null, + resources: {}, + miniapps: [], + errorEvents: [], + }); + }); + + it("rejects a non-GET method with 405 rather than performing any mutation", async () => { + const res = await fetch(`${baseUrl}/api/admin/aggregate`, { method: "POST" }); + expect(res.status).toBe(405); + }); +}); diff --git a/api/admin/aggregate.ts b/api/admin/aggregate.ts new file mode 100644 index 0000000..e2bc72e --- /dev/null +++ b/api/admin/aggregate.ts @@ -0,0 +1,16 @@ +import type { IncomingMessage, ServerResponse } from "node:http"; +import { sendJson } from "../_lib/httpUtils.ts"; +import { pullEvents } from "../_lib/eventRelayStore.ts"; +import { buildRelayAggregate } from "../_lib/relayAggregate.ts"; + +export default async function handler( + req: IncomingMessage, + res: ServerResponse, +): Promise { + if (req.method !== "GET") { + sendJson(res, 405, { error: "method not allowed, use GET" }); + return; + } + const { entries } = pullEvents(0); + sendJson(res, 200, buildRelayAggregate(entries)); +} diff --git a/src/admin/AdminAggregatePanel.test.tsx b/src/admin/AdminAggregatePanel.test.tsx new file mode 100644 index 0000000..a16ed47 --- /dev/null +++ b/src/admin/AdminAggregatePanel.test.tsx @@ -0,0 +1,81 @@ +// @vitest-environment happy-dom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { AdminAggregatePanel } from "./AdminAggregatePanel"; +import type { RelayAggregateSummary } from "./AdminAggregatePanel"; + +const EMPTY_SUMMARY: RelayAggregateSummary = { + totalEvents: 0, + population: null, + resources: {}, + miniapps: [], + errorEvents: [], +}; + +const POPULATED_SUMMARY: RelayAggregateSummary = { + totalEvents: 3, + population: 4200, + resources: { water: 620 }, + miniapps: [{ id: "fair-share", label: "Fair Share", lastEventType: "fairshare.need", lastLamportTs: 5 }], + errorEvents: [{ type: "tunnelsafety.hazard.error", lamportTs: 6, detail: "sensor offline" }], +}; + +function mockFetchOnce(body: unknown, ok = true) { + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok, + status: ok ? 200 : 500, + json: async () => body, + })), + ); +} + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe("AdminAggregatePanel", () => { + it("renders an honest empty state for zero relayed events, not a fabricated number", async () => { + mockFetchOnce(EMPTY_SUMMARY); + render(); + + await waitFor(() => screen.getByTestId("aggregate-empty-state")); + expect(screen.queryByTestId("aggregate-summary")).not.toBeInTheDocument(); + }); + + it("renders the real combined aggregate when the relay has data", async () => { + mockFetchOnce(POPULATED_SUMMARY); + render(); + + await waitFor(() => screen.getByTestId("aggregate-summary")); + expect(screen.getByTestId("aggregate-total-events")).toHaveTextContent("3"); + expect(screen.getByTestId("aggregate-population")).toHaveTextContent("4200"); + expect(screen.getByTestId("aggregate-resources")).toHaveTextContent("water: 620"); + expect(screen.getByTestId("aggregate-miniapp-activity")).toHaveTextContent( + "Fair Share: fairshare.need @ lamportTs 5", + ); + expect(screen.getByTestId("aggregate-error-events")).toHaveTextContent( + "tunnelsafety.hazard.error @ lamportTs 6 - sensor offline", + ); + }); + + it("surfaces a load failure without crashing, instead of showing stale or placeholder data", async () => { + mockFetchOnce({ error: "failed" }, false); + render(); + + await waitFor(() => screen.getByTestId("aggregate-error")); + expect(screen.queryByTestId("aggregate-summary")).not.toBeInTheDocument(); + expect(screen.queryByTestId("aggregate-empty-state")).not.toBeInTheDocument(); + }); + + it("passes a custom endpoint through to fetch (test seam)", async () => { + mockFetchOnce(EMPTY_SUMMARY); + render(); + + await waitFor(() => screen.getByTestId("aggregate-empty-state")); + expect(fetch).toHaveBeenCalledWith("http://127.0.0.1:9999/api/admin/aggregate"); + }); +}); diff --git a/src/admin/AdminAggregatePanel.tsx b/src/admin/AdminAggregatePanel.tsx new file mode 100644 index 0000000..4161bd2 --- /dev/null +++ b/src/admin/AdminAggregatePanel.tsx @@ -0,0 +1,123 @@ +import { useCallback, useEffect, useState } from "react"; + +export interface MiniappActivitySummary { + id: string; + label: string; + lastEventType: string; + lastLamportTs: number; +} + +export interface ErrorTaggedEvent { + type: string; + lamportTs: number; + detail?: string; +} + +export interface RelayAggregateSummary { + totalEvents: number; + population: number | null; + resources: Record; + miniapps: MiniappActivitySummary[]; + errorEvents: ErrorTaggedEvent[]; +} + +export interface AdminAggregatePanelProps { + /** Test seam: point at a real relay aggregate endpoint instead of the + * production same-origin default (mirrors `assemblyDbName`'s role on + * `AdminSeedPanelProps`). */ + endpoint?: string; +} + +export function AdminAggregatePanel({ endpoint = "/api/admin/aggregate" }: AdminAggregatePanelProps = {}) { + const [summary, setSummary] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const res = await fetch(endpoint); + if (!res.ok) { + throw new Error(`aggregate endpoint returned ${res.status}`); + } + const data = (await res.json()) as RelayAggregateSummary; + setSummary(data); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setLoading(false); + } + }, [endpoint]); + + useEffect(() => { + void load(); + }, [load]); + + return ( +
+

Backend relay: aggregate monitoring view

+

+ Read-only summary of whatever events have reached the backend relay + (api/sync) from any device so far - never a placeholder figure. + Re-fetches the relay's current state every time it loads. +

+ + + {error && ( +

+ Could not load aggregate: {error} +

+ )} + + {!error && summary && summary.totalEvents === 0 && ( +

No events have reached the backend relay yet.

+ )} + + {!error && summary && summary.totalEvents > 0 && ( +
+

Total relayed events: {summary.totalEvents}

+

+ Population:{" "} + {summary.population === null ? "not seeded yet" : summary.population} +

+ +

Resource levels

+
    + {Object.entries(summary.resources).map(([resource, value]) => ( +
  • + {resource}: {value} +
  • + ))} + {Object.keys(summary.resources).length === 0 && ( +
  • No resource levels seeded yet.
  • + )} +
+ +

Per-mini-app last activity

+
    + {summary.miniapps.map((m) => ( +
  • + {m.label}: {m.lastEventType} @ lamportTs {m.lastLamportTs} +
  • + ))} + {summary.miniapps.length === 0 &&
  • No mini-app activity relayed yet.
  • } +
+ +

Error-tagged events

+
    + {summary.errorEvents.map((e) => ( +
  • + {e.type} @ lamportTs {e.lamportTs} + {e.detail ? ` - ${e.detail}` : ""} +
  • + ))} + {summary.errorEvents.length === 0 &&
  • No error-tagged events.
  • } +
+
+ )} +
+ ); +} diff --git a/src/admin/AdminSeedPanel.tsx b/src/admin/AdminSeedPanel.tsx index 5f32dbf..3bd6b9c 100644 --- a/src/admin/AdminSeedPanel.tsx +++ b/src/admin/AdminSeedPanel.tsx @@ -11,6 +11,7 @@ import { } from "../lib/fairshare"; import { DEFAULT_ASSEMBLY_DB_NAME, getAssemblyEngine } from "../miniapps/assembly/useAssemblyEngine"; import { toAccountId } from "../shell/accountId"; +import { AdminAggregatePanel } from "./AdminAggregatePanel"; import { RESOURCE_TYPES, buildDemoFixturePayloads, @@ -39,9 +40,12 @@ export interface AdminSeedPanelProps { * (mirrors `AssemblyScreen`'s own `dbName` test seam). Production always * omits this. */ assemblyDbName?: string; + /** Test seam: passed straight through to `AdminAggregatePanel`'s own + * `endpoint` prop. Production always omits this. */ + aggregateEndpoint?: string; } -export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) { +export function AdminSeedPanel({ assemblyDbName, aggregateEndpoint }: AdminSeedPanelProps = {}) { const [input, setInput] = useState(emptyInput); const [error, setError] = useState(null); const [lastSubmitted, setLastSubmitted] = useState(null); @@ -431,6 +435,8 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {

{housingCycleStatus}

)} + + ); }