From 1ec4ff56a9916419926e58eb24c53547d7f7bedd Mon Sep 17 00:00:00 2001 From: Riccardo Capraro Date: Tue, 20 Oct 2026 22:41:52 +0200 Subject: [PATCH 01/11] feat(validator): add GET /api/tiles for per-pair live and replica state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wall needs two things the browser cannot work out for itself: whether a pair's frontend is serving yet, and how many frontend replicas are ready versus desired. Desired replicas reach the browser through the pair's own backend ConfigMap, but ready replicas cannot — the backend is nginx serving a static file and has no idea how many of its own pods are up. Only something holding a cluster client can answer that, hence the endpoint. One Deployment read per pair, behind a 3s cache. Much shorter than dashboardCacheTTL because this is one API call per pair rather than a full check matrix, and the wall's whole value is that an arrival shows up while the room is still looking at it. The cache still collapses a burst of concurrent polls into a single fan-out, which is what keeps the endpoint safe to expose unauthenticated (#113). Progress beyond "is it live" is deliberately not computed here. The wall reads /api/dashboard for that, which already runs the full check matrix behind its own cache; duplicating the stage calculation here would double the per-pair check fan-out for no new information. The Deployment is looked up as default/frontend because that is the contract the 101 Composition pins, and the same names the per-pair HTTPRoute resolves. A pair who renames them has already broken their own tile, so reporting not-live is the correct answer rather than a search. firstSeen is an in-memory map feeding arrival order ("3rd live") on the wall. A validator restart resets it — presentation sugar, not workshop state, the same tradeoff already accepted for vcClientCache. Refs #220 Assisted-by: claude-code/claude-opus-5 Signed-off-by: Riccardo Capraro --- validator/checks.go | 29 +++++ validator/main.go | 2 + validator/tiles.go | 241 ++++++++++++++++++++++++++++++++++++++++ validator/tiles_test.go | 137 +++++++++++++++++++++++ 4 files changed, 409 insertions(+) create mode 100644 validator/tiles.go create mode 100644 validator/tiles_test.go diff --git a/validator/checks.go b/validator/checks.go index 2ef8e6e..eeb67c4 100644 --- a/validator/checks.go +++ b/validator/checks.go @@ -599,6 +599,35 @@ func unstructuredNestedString(obj map[string]interface{}, fields ...string) (str return "", false, nil } +// unstructuredNestedInt64 is a thin helper for reading an integer out of +// a nested unstructured object (e.g. status.readyReplicas on a +// Deployment). JSON-decoded unstructured content carries whole numbers +// as int64, but a value that round-tripped through a float path arrives +// as float64, so both are accepted. A missing field reports ok=false +// rather than 0, because "no replicas yet" and "zero replicas" mean +// different things to the wall. +func unstructuredNestedInt64(obj map[string]interface{}, fields ...string) (int64, bool) { + cur := obj + for i, f := range fields { + if i == len(fields)-1 { + switch v := cur[f].(type) { + case int64: + return v, true + case float64: + return int64(v), true + default: + return 0, false + } + } + next, ok := cur[f].(map[string]interface{}) + if !ok { + return 0, false + } + cur = next + } + return 0, false +} + // unstructuredNestedSlice is a thin helper to avoid importing k8s.io/apimachinery/pkg/apis/meta/v1/unstructured // just for slice access. func unstructuredNestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) { diff --git a/validator/main.go b/validator/main.go index d0c9a32..d4e646a 100644 --- a/validator/main.go +++ b/validator/main.go @@ -68,6 +68,8 @@ func main() { mux.HandleFunc("GET /api/pairs", handlePairs) // GET /api/dashboard — aggregated pair × check matrix for the facilitator mux.HandleFunc("GET /api/dashboard", handleDashboard) + // GET /api/tiles — per-pair live/replica state for the wall page + mux.HandleFunc("GET /api/tiles", handleTiles) if localMode() { log.Println("validator: VALIDATOR_LOCAL set; using KUBECONFIG and the synthetic 'local' pair") diff --git a/validator/tiles.go b/validator/tiles.go new file mode 100644 index 0000000..d3024a2 --- /dev/null +++ b/validator/tiles.go @@ -0,0 +1,241 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "sync" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/kubernetes" +) + +// The wall (docs/src/pages/wall.jsx) renders one tile per pair and wants +// two things the browser cannot work out on its own: +// +// 1. Whether the pair's frontend is actually serving yet, so a pair who +// has not shipped renders as a dimmed placeholder instead of a dead +// iframe. +// 2. How many frontend replicas are *ready* versus *desired*, which is +// what the tile's replica dots draw. +// +// Desired replicas also reach the browser through the pair's own backend +// ConfigMap, but ready replicas cannot: the backend is nginx serving a +// static file and has no idea how many of its own pods are up. Only +// something holding a cluster client can answer that, hence this +// endpoint. +// +// Progress beyond "is it live" is deliberately NOT computed here. The +// wall reads /api/dashboard for that, which already runs the full check +// matrix behind its own cache — duplicating the stage calculation here +// would double the per-pair check fan-out for no new information. + +// tilesCacheTTL bounds how often the per-pair Deployment reads are +// repeated. Much shorter than dashboardCacheTTL on purpose: this +// endpoint is one API call per pair rather than a full check matrix, and +// the wall's whole value is that an arrival shows up while the room is +// still looking at it. The cache still collapses a burst of concurrent +// polls (several viewers plus a projector) into a single fan-out, which +// is what keeps this endpoint safe to expose unauthenticated — see the +// dashboardCacheTTL comment for the #113 history. +const tilesCacheTTL = 3 * time.Second + +// tilesReadTimeout caps a single pair's Deployment read. An unreachable +// vcluster becomes a not-live tile with a reason attached rather than +// stalling the whole response. +const tilesReadTimeout = 5 * time.Second + +// tilesCache holds the most recent response so repeated requests inside +// tilesCacheTTL share one fan-out. +var tilesCache struct { + mu sync.Mutex + body []byte + createdAt time.Time +} + +// firstSeen records, per pair, the first moment that pair was observed +// live. The wall turns this into arrival order ("3rd live"), which is +// the cheapest way to make finishing feel like an event. +// +// In-memory on purpose: it is presentation sugar, not workshop state. A +// validator restart resets the ordering, and for a three-hour workshop +// that is the same tradeoff already accepted for vcClientCache. Nothing +// downstream treats a missing firstSeenAt as an error. +var firstSeen struct { + mu sync.Mutex + at map[string]time.Time +} + +// markFirstSeen returns the pair's first-live timestamp, recording now +// as that timestamp if this is the first time the pair has been live. +func markFirstSeen(pair string, now time.Time) time.Time { + firstSeen.mu.Lock() + defer firstSeen.mu.Unlock() + if firstSeen.at == nil { + firstSeen.at = make(map[string]time.Time) + } + if at, ok := firstSeen.at[pair]; ok { + return at + } + firstSeen.at[pair] = now + return now +} + +// lookupFirstSeen returns a previously recorded first-live timestamp +// without recording one. +func lookupFirstSeen(pair string) (time.Time, bool) { + firstSeen.mu.Lock() + defer firstSeen.mu.Unlock() + at, ok := firstSeen.at[pair] + return at, ok +} + +type tileRow struct { + ID string `json:"id"` + Live bool `json:"live"` + DesiredReplicas int64 `json:"desiredReplicas"` + ReadyReplicas int64 `json:"readyReplicas"` + // FirstSeenAt is RFC3339, omitted until the pair has been live once. + FirstSeenAt string `json:"firstSeenAt,omitempty"` + // Details explains a not-live tile in the facilitator's words + // ("no frontend Deployment yet"), so a dimmed tile is diagnosable + // without opening the dashboard. + Details string `json:"details,omitempty"` +} + +type tilesResponse struct { + GeneratedAt time.Time `json:"generatedAt"` + Tiles []tileRow `json:"tiles"` +} + +// handleTiles serves the per-pair tile state behind tilesCache. Like +// handleDashboard, the rebuild happens while still holding the lock so a +// concurrent burst collapses into one fan-out instead of N. +func handleTiles(w http.ResponseWriter, r *http.Request) { + tilesCache.mu.Lock() + defer tilesCache.mu.Unlock() + + if tilesCache.body != nil && time.Since(tilesCache.createdAt) < tilesCacheTTL { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Cache", "HIT") + _, _ = w.Write(tilesCache.body) + return + } + + body, status := buildTilesJSON(r.Context()) + w.Header().Set("Content-Type", "application/json") + if status == http.StatusOK { + w.Header().Set("X-Cache", "MISS") + tilesCache.body = body + tilesCache.createdAt = time.Now() + } + w.WriteHeader(status) + _, _ = w.Write(body) +} + +// buildTilesJSON fans out across pairs and returns a marshaled response +// plus an HTTP status. Failing to build the management client or list +// pairs is a 500; a per-pair failure is a not-live tile inside a 200, +// because one broken vcluster must not blank the whole wall. +func buildTilesJSON(ctx context.Context) ([]byte, int) { + mgmtClient, err := newMgmtClient() + if err != nil { + body, _ := json.Marshal(map[string]string{"error": err.Error()}) + return body, http.StatusInternalServerError + } + + pairs, err := listPairIDs(ctx, mgmtClient) + if err != nil { + body, _ := json.Marshal(map[string]string{"error": err.Error()}) + return body, http.StatusInternalServerError + } + + rows := make([]tileRow, len(pairs)) + // Same concurrency bound as the dashboard: the concern is identical + // (don't hand the room's browsers a way to open N simultaneous + // apiserver handshakes), and one knob is easier to reason about. + sem := make(chan struct{}, dashboardMaxPairConcurrency) + var wg sync.WaitGroup + + for i, pair := range pairs { + wg.Add(1) + sem <- struct{}{} + go func(i int, pair string) { + defer wg.Done() + defer func() { <-sem }() + rows[i] = readPairTile(ctx, mgmtClient, pair) + }(i, pair) + } + + wg.Wait() + + body, _ := json.Marshal(tilesResponse{ + GeneratedAt: time.Now().UTC(), + Tiles: rows, + }) + return body, http.StatusOK +} + +// readPairTile reads one pair's frontend Deployment and derives whether +// the tile is live. +// +// The Deployment is looked up as `default/frontend` because that is the +// contract the Composition in Crossplane 101 pins: the composed +// resources are named `frontend` / `backend` in namespace `default`, and +// the per-pair HTTPRoute resolves /team// to the synced +// `frontend-x-default-x-` Service by those exact names. A pair who +// renames them has already broken their own tile, so reporting +// not-live here is the correct answer rather than a search. +func readPairTile(ctx context.Context, mgmtClient *kubernetes.Clientset, pair string) tileRow { + row := tileRow{ID: pair} + if at, ok := lookupFirstSeen(pair); ok { + row.FirstSeenAt = at.UTC().Format(time.RFC3339) + } + + vcClient, err := vclientForPair(ctx, mgmtClient, pair) + if err != nil { + row.Details = "vcluster client: " + err.Error() + return row + } + + deploymentsGVR := schema.GroupVersionResource{ + Group: "apps", + Version: "v1", + Resource: "deployments", + } + + ctxTimeout, cancel := context.WithTimeout(ctx, tilesReadTimeout) + defer cancel() + + dep, err := vcClient.Resource(deploymentsGVR).Namespace("default").Get(ctxTimeout, "frontend", metav1.GetOptions{}) + if err != nil { + row.Details = fmt.Sprintf("no frontend Deployment in default yet: %v", err) + return row + } + + // spec.replicas is optional in the API and defaults to 1 when the + // participant omits it, so an absent field means one desired pod, + // not zero. + desired, ok := unstructuredNestedInt64(dep.Object, "spec", "replicas") + if !ok { + desired = 1 + } + row.DesiredReplicas = desired + + // status.readyReplicas is absent until at least one pod is ready, + // which is exactly the pre-arrival state the wall dims. + ready, _ := unstructuredNestedInt64(dep.Object, "status", "readyReplicas") + row.ReadyReplicas = ready + + row.Live = ready > 0 + if !row.Live { + row.Details = fmt.Sprintf("frontend Deployment exists, %d/%d replicas ready", ready, desired) + return row + } + + row.FirstSeenAt = markFirstSeen(pair, time.Now()).UTC().Format(time.RFC3339) + return row +} diff --git a/validator/tiles_test.go b/validator/tiles_test.go new file mode 100644 index 0000000..8f4ad3e --- /dev/null +++ b/validator/tiles_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" +) + +// TestTilesCacheServesHit confirms a fresh cache entry is served without +// rebuilding. Same contract as the dashboard cache: the wall polls this +// endpoint every few seconds from every open browser in the room, so a +// cache miss per request would reopen a vcluster connection per pair per +// viewer. +func TestTilesCacheServesHit(t *testing.T) { + tilesCache.mu.Lock() + tilesCache.body = []byte(`{"cached":true}`) + tilesCache.createdAt = time.Now() + tilesCache.mu.Unlock() + t.Cleanup(resetTilesCache) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/tiles", nil) + + handleTiles(rec, req) + + if got, want := rec.Code, http.StatusOK; got != want { + t.Fatalf("status: got %d want %d", got, want) + } + if got, want := rec.Header().Get("X-Cache"), "HIT"; got != want { + t.Fatalf("X-Cache: got %q want %q", got, want) + } + if got, want := rec.Body.String(), `{"cached":true}`; got != want { + t.Fatalf("body: got %q want %q", got, want) + } +} + +// TestTilesCacheRebuildsAfterTTL verifies an entry older than +// tilesCacheTTL is not served. The rebuild itself fails here (no +// in-cluster config); what matters is that the stale body is not +// returned, because a stale wall is worse than an empty one — it shows +// pairs as live after their vcluster has gone away. +func TestTilesCacheRebuildsAfterTTL(t *testing.T) { + tilesCache.mu.Lock() + tilesCache.body = []byte(`{"stale":true}`) + tilesCache.createdAt = time.Now().Add(-2 * tilesCacheTTL) + tilesCache.mu.Unlock() + t.Cleanup(resetTilesCache) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/tiles", nil) + + handleTiles(rec, req) + + if rec.Header().Get("X-Cache") == "HIT" { + t.Fatalf("expired cache was served as HIT") + } + if rec.Body.String() == `{"stale":true}` { + t.Fatalf("expired body was served verbatim") + } +} + +// TestUnstructuredNestedInt64 covers the two numeric shapes unstructured +// content arrives in plus the absent cases. The ok=false distinction +// matters: a missing spec.replicas means "defaulted to 1", while a +// missing status.readyReplicas means "none ready yet" — the tile draws +// those differently. +func TestUnstructuredNestedInt64(t *testing.T) { + obj := map[string]interface{}{ + "spec": map[string]interface{}{ + "replicas": int64(3), + }, + "status": map[string]interface{}{ + "readyReplicas": float64(2), + "notANumber": "nope", + }, + } + + tests := []struct { + name string + fields []string + want int64 + wantOK bool + }{ + {"int64 value", []string{"spec", "replicas"}, 3, true}, + {"float64 value", []string{"status", "readyReplicas"}, 2, true}, + {"missing leaf", []string{"status", "replicas"}, 0, false}, + {"missing parent", []string{"nope", "replicas"}, 0, false}, + {"wrong type", []string{"status", "notANumber"}, 0, false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, ok := unstructuredNestedInt64(obj, tc.fields...) + if got != tc.want || ok != tc.wantOK { + t.Fatalf("got (%d, %v) want (%d, %v)", got, ok, tc.want, tc.wantOK) + } + }) + } +} + +// TestMarkFirstSeenIsStable asserts a pair's arrival timestamp is +// recorded once and never moves. Arrival order on the wall would be +// meaningless if every poll refreshed it. +func TestMarkFirstSeenIsStable(t *testing.T) { + t.Cleanup(resetFirstSeen) + resetFirstSeen() + + first := time.Now() + got := markFirstSeen("apollo", first) + if !got.Equal(first) { + t.Fatalf("first call: got %v want %v", got, first) + } + + later := first.Add(time.Minute) + got = markFirstSeen("apollo", later) + if !got.Equal(first) { + t.Fatalf("second call moved the timestamp: got %v want %v", got, first) + } + + if _, ok := lookupFirstSeen("mercury"); ok { + t.Fatalf("lookupFirstSeen reported an arrival for a pair never marked") + } +} + +func resetTilesCache() { + tilesCache.mu.Lock() + tilesCache.body = nil + tilesCache.createdAt = time.Time{} + tilesCache.mu.Unlock() +} + +func resetFirstSeen() { + firstSeen.mu.Lock() + firstSeen.at = nil + firstSeen.mu.Unlock() +} From fa852f7cc2b87d3d45df3e16c26768faea4ca39c Mon Sep 17 00:00:00 2001 From: Riccardo Capraro Date: Tue, 20 Oct 2026 22:45:26 +0200 Subject: [PATCH 02/11] feat(wall): render tiles natively, poll for arrivals, add presentation mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wall was the payoff of Crossplane 101 and it only updated when someone pressed Refresh, so the moment a pair went live was almost always missed by the room. Module 6's platform-side change had the same problem: nothing on screen moved. /wall, /team// and /team//api/message all hang off the same Gateway listener, so they are same-origin and this page can fetch a pair's JSON itself. Tiles are now rendered in React instead of through an iframe. The browser still hits the pair's own backend Service, so their infrastructure is genuinely in the path, but the wall owns layout and animation — which an iframe cannot give us. /team// stays a real page served by the pair's own nginx, and every tile links to it. Dropping the iframe also retires the trailing-slash footgun the old header comment had to warn about. What the wall now does: - Polls /api/tiles every 4s for the roster, live state and replica counts, and each live pair's payload from their own backend. - Animates a pair's arrival and names it in a banner. The first successful poll is deliberately quiet, so pairs already live when the page opens are not announced. - Pulses a tile whose payload changed since the last poll. This is what finally gives module 6 a visible payoff. - Dims pairs who have not shipped and labels them with how far they got, derived from /api/dashboard's existing contiguous-pass stageReached. No second notion of progress. - Badges arrival order from the validator's first-live timestamps. - Draws one dot per desired frontend replica, filled for each ready one, so the tile shows infrastructure rather than only text. - Resolves named themes to palettes here rather than in the cluster, keeping the XRD to an enum plus a default. A raw `color` hex is still honoured so a tile built before the enum keeps rendering. - Adds /wall?present=1: no navbar or footer, grid fitted to the tile count so N tiles fill the projector exactly, larger type, and an optional spotlight cycle for the recap. - Adds a pause toggle so the wall can be frozen mid-explanation. Animations sit in a stylesheet rather than inline styles, because keyframes cannot be inline and because prefers-reduced-motion is the right place to switch them off wholesale. Presentation mode is not a separate commit: it is interleaved with the render path in the same file, so splitting it would have been artificial. The file carries ai_edit: locked. Edited under the one-shot bypass with the owner's go-ahead; the marker and its provenance lines predate these edits and are left untouched for the owner to refresh on review. Refs #220 Assisted-by: claude-code/claude-opus-5 Signed-off-by: Riccardo Capraro --- docs/src/pages/wall.jsx | 594 ++++++++++++++++++++++++++++++++-------- 1 file changed, 483 insertions(+), 111 deletions(-) diff --git a/docs/src/pages/wall.jsx b/docs/src/pages/wall.jsx index 04375a1..d1d64a6 100644 --- a/docs/src/pages/wall.jsx +++ b/docs/src/pages/wall.jsx @@ -2,29 +2,46 @@ // ai_edit_reviewed: 2026-04-27 // ai_edit_reviewer: ricCap -import React, { useState, useEffect, useCallback, useRef } from 'react'; +import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'; import Layout from '@theme/Layout'; +import { useLocation } from '@docusaurus/router'; /** - * The workshop "wall": one iframe per participant pair, each pointing at - * `/team//`. Inside the iframe, the pair's frontend (an nginx - * serving a ConfigMap-mounted index.html produced by their Crossplane - * Composition) does a relative `fetch('./api/message')` which resolves - * to `/team//api/message` — same origin, no CORS. + * The workshop "wall": one tile per participant pair. * - * The pair list comes from `GET /api/pairs`, which the validator - * exposes by listing `participant-*` namespaces on the management - * cluster. We don't poll — a manual refresh button is enough for - * workshop pacing (new tiles appear when people apply their claim). + * Each pair's Crossplane Composition produces a `frontend` (nginx + * serving a ConfigMap-mounted index.html) and a `backend` (nginx + * serving a ConfigMap-mounted JSON file). The per-pair HTTPRoute maps + * `/team//` to the frontend and `/team//api/` to the + * backend. * - * The iframe src MUST include the trailing slash. Without it, - * `./api/message` inside the iframe resolves to `/team/api/message` - * and 404s — see PLAN.md §Risks #2. + * The wall renders tiles **natively** rather than through an iframe: + * `/wall`, `/team//` and `/team//api/message` all hang off + * the same Gateway listener, so they are same-origin and this page can + * fetch the pair's JSON directly. The browser still hits the pair's own + * backend Service, so their infrastructure is genuinely in the path — + * but the wall owns layout and animation, which an iframe cannot give + * us. `/team//` stays a real page served by the pair's own nginx; + * each tile links to it. + * + * Three fetches per cycle: + * - `/api/tiles` — the roster, plus live / desired / ready + * replicas and first-live timestamps. Ready + * replica counts cannot come from the pair's + * backend (static nginx), only from something + * holding a cluster client. + * - `/api/dashboard` — the check matrix, polled more slowly, used to + * label pairs who have not shipped yet. + * - `/team/

/api/message` per pair — the pair-authored payload. + * + * Arrivals and changes are animated, because the payoff of the whole + * hour used to require someone pressing Refresh. * * Tile sizing: tiles are user-resizable (CSS `resize: both`) and a * global S/M/L preset sets the default for tiles the user hasn't * touched. Both per-tile sizes and the preset are persisted in - * localStorage so a refresh keeps the layout. + * localStorage so a refresh keeps the layout. Presentation mode + * (`/wall?present=1`) ignores both and fits the grid to the viewport. */ const PRESETS = { @@ -36,9 +53,72 @@ const DEFAULT_PRESET = 'S'; const LS_DEFAULT = 'wall:tileSize:default'; const LS_TILE = (pair) => `wall:tileSize:${pair}`; -const page = { - padding: '1.5rem 2rem', +// Tile state and payloads are cheap to fetch, so they poll fast enough +// that an arrival lands while the room is still looking. The check +// matrix behind /api/dashboard is 16 checks per pair, so it polls at +// its own cache TTL instead. +const TILE_POLL_MS = 4000; +const STAGE_POLL_MS = 12000; +// How long an arrival stays in the banner. +const ARRIVAL_TOAST_MS = 6000; +// Spotlight dwell time in presentation mode. +const SPOTLIGHT_MS = 8000; + +/** + * Named themes, resolved here rather than in the cluster. + * + * The pair's `Application` carries a theme *name*; the palette lives in + * the renderer. That keeps the XRD to an enum plus a default — which is + * a Crossplane lesson worth teaching — and lets the wall use gradients + * a single hex field could not express. + * + * `color` in the payload is still honoured as a fallback so a tile + * built before the enum landed keeps rendering. + */ +const THEMES = { + ocean: { fg: '#0c4a6e', accent: '#0ea5e9', bg: 'linear-gradient(160deg, #e0f2fe, #bae6fd)' }, + sunset: { fg: '#7c2d12', accent: '#f97316', bg: 'linear-gradient(160deg, #ffedd5, #fed7aa)' }, + forest: { fg: '#14532d', accent: '#16a34a', bg: 'linear-gradient(160deg, #dcfce7, #bbf7d0)' }, + ember: { fg: '#7f1d1d', accent: '#dc2626', bg: 'linear-gradient(160deg, #fee2e2, #fecaca)' }, + violet: { fg: '#4c1d95', accent: '#7c3aed', bg: 'linear-gradient(160deg, #ede9fe, #ddd6fe)' }, }; +const FALLBACK_THEME = { fg: '#1e293b', accent: '#64748b', bg: 'linear-gradient(160deg, #f1f5f9, #e2e8f0)' }; + +function themeFor(payload) { + if (!payload) return FALLBACK_THEME; + if (payload.theme && THEMES[payload.theme]) return THEMES[payload.theme]; + // Pre-enum payloads carry a raw hex in `color`. + if (payload.color) return { fg: payload.color, accent: payload.color, bg: 'var(--ifm-background-surface-color)' }; + return FALLBACK_THEME; +} + +// Animations live in a stylesheet rather than inline styles because +// keyframes cannot be expressed inline, and because `prefers-reduced- +// motion` is the right place to switch them off wholesale. +const CSS = ` +@keyframes wallArrive { + from { opacity: 0; transform: scale(0.88); } + 60% { opacity: 1; transform: scale(1.04); } + to { opacity: 1; transform: scale(1); } +} +@keyframes wallPulse { + 0% { box-shadow: 0 0 0 0 var(--wall-pulse, rgba(37,99,235,0.55)); } + 100% { box-shadow: 0 0 0 18px rgba(0,0,0,0); } +} +@keyframes wallToast { + from { opacity: 0; transform: translateY(-8px); } + to { opacity: 1; transform: translateY(0); } +} +.wall-arrive { animation: wallArrive 520ms cubic-bezier(0.22, 1, 0.36, 1); } +.wall-pulse { animation: wallPulse 900ms ease-out; } +.wall-toast { animation: wallToast 240ms ease-out; } +@media (prefers-reduced-motion: reduce) { + .wall-arrive, .wall-pulse, .wall-toast { animation: none; } +} +`; + +const page = { padding: '1.5rem 2rem' }; +const presentPage = { padding: '1rem 1.25rem', height: '100vh', display: 'flex', flexDirection: 'column' }; const header = { display: 'flex', @@ -49,11 +129,7 @@ const header = { flexWrap: 'wrap', }; -const toolbar = { - display: 'flex', - alignItems: 'center', - gap: '0.5rem', -}; +const toolbar = { display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }; const button = { padding: '6px 14px', @@ -88,43 +164,7 @@ const resetLink = { textDecoration: 'underline', }; -const tileWrap = { - display: 'flex', - flexWrap: 'wrap', - gap: '1rem', -}; - -const tileStyle = ({ w, h }) => ({ - boxSizing: 'border-box', - border: '1px solid var(--ifm-color-emphasis-300)', - borderRadius: '8px', - overflow: 'hidden', - background: 'var(--ifm-background-surface-color)', - display: 'flex', - flexDirection: 'column', - width: `${w}px`, - height: `${h}px`, - minWidth: '200px', - minHeight: '140px', - resize: 'both', -}); - -const tileLabel = { - padding: '6px 10px', - fontSize: '0.85rem', - fontWeight: 600, - borderBottom: '1px solid var(--ifm-color-emphasis-300)', - background: 'var(--ifm-color-emphasis-100)', -}; - -const tileFrame = { - width: '100%', - flex: 1, - border: 'none', - // Iframe paints its own background; transparent lets the tile's - // surface colour show through during loading in either theme. - background: 'transparent', -}; +const tileWrap = { display: 'flex', flexWrap: 'wrap', gap: '1rem' }; const empty = { padding: '2rem', @@ -134,12 +174,13 @@ const empty = { borderRadius: '8px', }; -const error = { +const errorBox = { padding: '1rem', color: 'var(--ifm-color-danger-contrast-foreground)', background: 'var(--ifm-color-danger-contrast-background)', border: '1px solid var(--ifm-color-danger)', borderRadius: '8px', + marginBottom: '1rem', }; function readJSON(key, fallback) { @@ -161,7 +202,50 @@ function writeJSON(key, value) { } } -function Tile({ pair, size, onResize }) { +/** + * One dot per desired replica, filled for each ready one. + * + * This is the tile showing infrastructure rather than text: outlined + * dots are what the pair asked for, filled dots are what is actually + * running, and the gap between them is Kubernetes reconciling. + */ +function ReplicaDots({ desired, ready, accent }) { + if (!desired) return null; + const total = Math.min(desired, 12); + return ( +

+ {Array.from({ length: total }, (_, i) => ( + + ))} +
+ ); +} + +function Tile({ + pair, + size, + onResize, + payload, + state, + stageLabel, + arrivalPosition, + pulseKey, + justArrived, + present, +}) { const ref = useRef(null); const timer = useRef(null); const lastSize = useRef(size); @@ -172,7 +256,9 @@ function Tile({ pair, size, onResize }) { useEffect(() => { const el = ref.current; - if (!el || typeof ResizeObserver === 'undefined') return undefined; + // Presentation mode sizes tiles from the grid, so there is nothing + // to observe or persist. + if (present || !el || typeof ResizeObserver === 'undefined') return undefined; const ro = new ResizeObserver((entries) => { const entry = entries[0]; if (!entry) return; @@ -188,27 +274,145 @@ function Tile({ pair, size, onResize }) { ro.disconnect(); if (timer.current) clearTimeout(timer.current); }; - }, [pair, onResize]); + }, [pair, onResize, present]); + + const live = state?.live; + const theme = themeFor(payload); + + const frame = { + boxSizing: 'border-box', + border: '1px solid var(--ifm-color-emphasis-300)', + borderRadius: '8px', + overflow: 'hidden', + background: 'var(--ifm-background-surface-color)', + display: 'flex', + flexDirection: 'column', + opacity: live ? 1 : 0.55, + ...(present + ? { width: '100%', height: '100%', minWidth: 0, minHeight: 0 } + : { width: `${size.w}px`, height: `${size.h}px`, minWidth: '200px', minHeight: '140px', resize: 'both' }), + }; + + const label = { + padding: '6px 10px', + fontSize: present ? '1rem' : '0.85rem', + fontWeight: 600, + borderBottom: '1px solid var(--ifm-color-emphasis-300)', + background: 'var(--ifm-color-emphasis-100)', + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', + gap: '0.5rem', + }; + + const body = { + flex: 1, + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + padding: '1rem', + textAlign: 'center', + background: live ? theme.bg : 'var(--ifm-background-surface-color)', + color: theme.fg, + minHeight: 0, + }; return ( -
-
{pair}
-