From 93970f361b831f17d48ff2a345fc78488ac71fba Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Mon, 23 Nov 2026 00:51:32 +0100 Subject: Phase 7: hardening and shipping (M7) E2E (Playwright, e2e/): - table fixture: one real compiled server per test (temp saves dir, free port, workers: 1); a Tab helper drives the real UI (menus, rows, initiative, draw, seats) over one WS per fresh browser context - full round: onboarding, secret initiative masked to ?? per connection, draw revealing on every screen, turns, next round, round-2 secrecy - seats: claim/re-claim on owner-leave, reload keeps the session and re-claims, two sessions can't own one character - resilience: a dropped tab resyncs on reconnect (no drift); a SIGKILL'd server restarts with state + seats surviving (incl. the owner's secret initiative and the enabled draw); a throttled tab converges on the same state as the fast tabs; a double-tapped draw runs once, error sent to the sender only - figure edit: set a character level + rename from the status menu Cross-check vs the reference (feature parity): - status menu: level pills (setCharacterLevel) + a name field (changeName), mirroring SetCharacterLevelMenu - ability-card removal: draw-pile-only "send to bottom" (reorderAbilityList -> index 0) + "shuffle undrawn cards" (shuffleDrawnAbilityCard), mirroring RemoveCardMenu - Add Character: already-added classes disabled (Objective/Escort may be added repeatedly), matching _characterAlreadyAdded - every remaining registry command verified reachable from the UI Session persistence (found by the restart test): - the client never learned its session id before the first welcome, so a reconnect minted a new id and orphaned the restored seat; fixed with establishSessionCookie() (a GET /session before the WS upgrade, plus a vite /session proxy) so the x-haven-session cookie survives restarts - the initiative input now prefills from re-synced state (CharacterRow effect, guarded against clobbering a live edit) so a reload/reconnect doesn't blank an entry Performance + deployment: - immutable asset caching (Cache-Control: 1yr, immutable) for the game data / images / in-game translations; no-cache for the SPA index.html so rebuilt apps reach open tabs - server tool/perf_measure.dart: the performance probe (state payload size at full-table scale, WS fan-out bytes per action, traffic per connection) - Dockerfile (server + built web); docs/DEPLOYMENT.md (Docker, persistence, reverse proxy, measured performance, smoke-test list) - README quickstart + production/Docker/testing sections Server: - --saves-dir and --data-dir CLI options (Docker / multi-game hosts), threaded through the stores and data loading Misc: - app.css: height 100% on .row so the turn-done tap zone resolves to a clickable height; fake-socket.ts readyState constants corrected to the real WebSocket values (0 CONNECTING, 1 OPEN) - scripts/ci.sh: the Playwright E2E gate (runs when PLAYWRIGHT is set) - PLAN.md: Phase 7 boxes checked, M7 progress-log entry Verification: svelte-check 0 errors; web 196/196 tests; vite build OK; dart analyze 0 errors / 0 warnings; dart test 604/604; Playwright 9/9; scripts/ci.sh green end-to-end. --- .gitignore | 7 + Dockerfile | 53 +++++ PLAN.md | 13 +- README.md | 59 ++++- docs/DEPLOYMENT.md | 127 +++++++++++ e2e/helpers/server.ts | 167 ++++++++++++++ e2e/helpers/tab.ts | 188 ++++++++++++++++ e2e/helpers/table.ts | 51 +++++ e2e/package-lock.json | 75 +++++++ e2e/package.json | 13 ++ e2e/playwright.config.ts | 30 +++ e2e/tests/figure-edit.spec.ts | 37 ++++ e2e/tests/full-round.spec.ts | 91 ++++++++ e2e/tests/resilience.spec.ts | 231 ++++++++++++++++++++ e2e/tests/seats.spec.ts | 82 +++++++ e2e/tsconfig.json | 12 ++ scripts/ci.sh | 13 +- server/bin/main.dart | 34 ++- server/lib/net/app.dart | 55 ++++- server/tool/perf_measure.dart | 312 +++++++++++++++++++++++++++ web/src/App.svelte | 8 +- web/src/app.css | 5 + web/src/lib/protocol/connection.ts | 6 +- web/src/lib/protocol/session.ts | 25 +++ web/src/lib/ui/CharacterRow.svelte | 20 +- web/src/lib/ui/StatusMenu.svelte | 106 +++++++++ web/src/lib/ui/decks/AbilityCardsMenu.svelte | 29 +++ web/src/lib/ui/menus/AddCharacterMenu.svelte | 51 ++++- web/test/connection.test.ts | 16 ++ web/test/fake-socket.ts | 7 +- web/vite.config.ts | 3 + 31 files changed, 1880 insertions(+), 46 deletions(-) create mode 100644 Dockerfile create mode 100644 docs/DEPLOYMENT.md create mode 100644 e2e/helpers/server.ts create mode 100644 e2e/helpers/tab.ts create mode 100644 e2e/helpers/table.ts create mode 100644 e2e/package-lock.json create mode 100644 e2e/package.json create mode 100644 e2e/playwright.config.ts create mode 100644 e2e/tests/figure-edit.spec.ts create mode 100644 e2e/tests/full-round.spec.ts create mode 100644 e2e/tests/resilience.spec.ts create mode 100644 e2e/tests/seats.spec.ts create mode 100644 e2e/tsconfig.json create mode 100644 server/tool/perf_measure.dart create mode 100644 web/src/lib/protocol/session.ts diff --git a/.gitignore b/.gitignore index 1e01e9a..276e6e8 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,13 @@ server/saves/ # web web/node_modules/ web/dist/ +web/test-results/ + +# e2e (Playwright): deps, the cached compiled server, and test output +e2e/node_modules/ +e2e/.cache/ +e2e/test-results/ +e2e/playwright-report/ # misc .DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cd43d7c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,53 @@ +# X-Haven (web) — server + built web app (PLAN.md Phase 7). +# +# Three stages: +# 1. `web` — build the Svelte app (npm ci + vite build → dist/) +# 2. `server` — compile the Dart server to a standalone native binary +# 3. runtime — debian-slim + the binary + the game assets + the web build +# +# Build and run: +# docker build -t xhaven . +# docker run --rm -p 4567:4567 -v xhaven-saves:/app/saves xhaven +# +# See docs/DEPLOYMENT.md for configuration, persistence, and scaling notes. + +# --- 1. web build --------------------------------------------------------- +FROM node:22 AS web +WORKDIR /web +COPY web/package.json web/package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY web/ . +RUN npm run build + +# --- 2. server build ------------------------------------------------------- +FROM dart:3.11 AS server +WORKDIR /server +COPY server/pubspec.yaml server/pubspec.lock ./ +RUN dart pub get +COPY server/ . +# Standalone native binary — the runtime image needs no Dart SDK. +RUN dart compile exe bin/main.dart -o /out/xhaven-server + +# --- 3. runtime ------------------------------------------------------------- +FROM debian:bookworm-slim +# ca-certificates only: no SDK, no package manager residue. +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY --from=server /out/xhaven-server /app/xhaven-server +COPY server/assets/ /app/assets/ +COPY --from=web /web/dist /app/web/dist + +# The game state (game.json, seats.json, settings.json, saves/) lives in a +# volume so a redeploy keeps the game. +ENV PORT=4567 +EXPOSE 4567 +VOLUME ["/app/saves"] + +# bash is in the base image; /dev/tcp gives a dependency-free health probe. +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s \ + CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/${PORT:-4567}' || exit 1 + +CMD ["/app/xhaven-server", "--port=4567", "--static-dir=/app/web/dist", "--saves-dir=/app/saves", "--data-dir=/app/assets/data/"] diff --git a/PLAN.md b/PLAN.md index 1146e97..243bc3d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -298,14 +298,14 @@ changes, room sections, spectator view. *First end-to-end moment.* ### Phase 7 — Hardening and shipping -- [ ] E2E (Playwright): two players + one spectator, a full round including secret +- [x] E2E (Playwright): two players + one spectator, a full round including secret initiative, claim/re-claim, reconnect -- [ ] Resilience: stale tabs, late updates, slow networks, server restart mid-game -- [ ] Performance: state payload size, WS bandwidth under a full table, asset caching +- [x] Resilience: stale tabs, late updates, slow networks, server restart mid-game +- [x] Performance: state payload size, WS bandwidth under a full table, asset caching headers for the 66 MB image set -- [ ] `Dockerfile` (server + built web) + deployment notes -- [ ] User-facing quickstart/README, smoke-test list -- [ ] Final cross-check pass against the reference app (feature list from Phase 5) +- [x] `Dockerfile` (server + built web) + deployment notes +- [x] User-facing quickstart/README, smoke-test list +- [x] Final cross-check pass against the reference app (feature list from Phase 5) **Milestone M7** — release. @@ -333,6 +333,7 @@ changes, room sections, spectator view. *First end-to-end moment.* | 2026-11-16 | **Phase 4 complete / M4 reached** — full card play in the browser. Client: the line renderer + in-game translations (`$lib/game/line/`, `gameI18n.ts`), card components (stat / monster-ability / modifier / loot, `ModifierCard` gfx resolver incl. `P` perk graphics), monster ability decks (row card slot, deck menu — reveal top cards, draw extra, extra shuffle, activate/inactivate, drag-reorder, remove — and card zoom), the full AMD suite (`ModifierDeckWidget` + `ModifierDeckHeader` + `ModifierDeckMenu` with the six submenus — send-to-bottom, remove AMD, removed pile, faction cards, perks, plus zoom; imbue 1/2, ±1/−2/+0, reveal with the Cassandra 8-button cap, bad omen, corrosive spew, Hail/Cassandra specials, faction unlock, CS sanctuary/party cards), the loot deck (widget, cards menu — set owner, per-character loot totals, add card, enhance with the reference material/herb/coin splits, special cards 1418/1419, return top/bottom), and the bottom `DeckArea` (loot deck left; character-deck toggle with the reference open-state cycling; ally deck behind `shouldShowAlliesDeck`; global deck). Pure helper modules (`rules.ts`, `modifierDeck.ts`, `perks.ts`, `cards/lootCard.ts`) ported from the reference with unit tests. Server: all deck/loot/modifier/ability commands were already registered and tested in Phases 1–2 (592 tests green). `svelte-check` 0 errors; web build OK; 177 client tests green. | | 2026-11-17 | **Phase 5 complete / M5 reached** — full game feature set. Web: note rows end-to-end (create/edit menu — text, 12-swatch colour palette, link to player/monster with per-standee selection, delete — with the reference's create-vs-edit commit semantics; row rendering with the target's class colour / red-blue monster bases, lighten-toward-white gradient, link indent + connector, standee "N:"/"All:" prefixes, luminance-based text colour, tap-to-edit; whole-list drag-to-reorder → `reorderList`; quick per-figure note via `setFigureNote` from the status menu), special monster handling (Ice Wraith "Switch Form" behind the `deck == "Ice Wraith"` gate; summon mark toggle with the round-green / summon-gfx standee artwork + standee-nr badges and per-owner grayscale; character summon boxes above the row + AddSummonMenu — class summons gated by level and standee cap, item summons from `summons.json`, colour swatches + standee numbers → `addStandee … addAsSummon`), ally deck show/hide in the main menu (gated by `shouldShowAlliesDeck`), settings "clear unlocked" + Special Unlocks menu (4 unlockables, "???" while locked), and AddSectionMenu parity (case-insensitive search, the `findNrFromScenarioName` numeric ordering with string-compare fallback, added sections greyed + no-op, "Add Random Dungeon Card" label). Data layer: `SummonModel` + `ClassData.summons` + `summons()` fetch in `gameData.ts`. Server: added `unlock_special_command_test` (the only command missing a test — ally-deck-hide and remove-sanctuary were already covered in their consolidated files). Cross-check against the reference confirmed scenario rules are complete server-side (Timer round-1 spawns merged into the start room via `_applyRound1Spawns`, Timer notes, battle-goal reminder, `initialMessage` → `toastMessage` → web toast, Objective/Escort/AllyDeck/ResetRound/Unlock/RandomSections all handled). Verification: web 177/177 tests, `svelte-check` 0 errors; server suite green; full CI (dart analyze + test, web check + test + build) passing. | | 2026-11-19 | **Phase 6 complete / M6 reached** — settings, saves, localization parity. Server: `Settings.forClient()` payload (11 game fields + `style` enum index + `locale` + `saves`/`characterSaves` name lists — save content never crosses the wire), player-gated settings/save commands behind new wire messages (`setSetting` / `save` / `loadSave` / `deleteSave` / `saveCharacter` / `loadCharacterSave` / `deleteCharacterSave` + a `settings` broadcast), `historyLength` + `undoDescription`/`redoDescription` on `welcome`/`update`, and the ported 10-locale command descriptions. Web: `settings.ts` split (`serverSettings` from the wire vs `clientSettings` → `localStorage` with a corrupt/partial-tolerant, field-by-field typed merge), the settings menu rebuilt faithfully (locale selector with native names — locale change also syncs the server; style radios; scaling sliders; power-mode radios + ⓘ info; ally-deck toggle via `setAllyDeckInOgGloom`; clear-unlocked + special unlocks; the Load/Save State entry), multi-save menus (`SaveMenu` + `SaveModalMenu` — suggested name `campaign+nr`, rename = delete-then-save, load is the undoable `LoadSaveCommand`) and character saves (`SaveCharacterMenu` + `SaveCharacterModalMenu`, entered from the add/remove-character menus via class icons, restore = identity only with fresh battle state), undo/redo buttons labeled from the server history metadata (`undoWithDescription`), all 10 locale tables ported (new `i18n.test.ts` parity suite), the idle dimmer (15 s → 0.65 scrim, 1.2 s fade, any input/tap/visibility wakes it), scaling via CSS variables (`--list-scale`/`--bar-scale`), reduce-power mode (`[data-power='reduce']` kills box-shadows), and the visibility gates (`hideLootDeck`, `showAmdDeck` ↔ client `showCharacterAMD`, `showScenarioNames`, `showCustomContent` in the campaign picker and the custom conditions). Documented web adaptations: bar scaling via CSS `zoom` instead of a constrained content width, a 400px list baseline (reference: 740px on full-screen mobile), bar-scaling default 1.0, three style radios (reference offers two, the shared `Style` enum has three), locale synced through the settings dropdown. Omitted reference entries (no web analogue): dark-mode toggle, soft numpad, health wheel, network section. Verification: **web 195/195 tests** (14 files, incl. new `settings.test.ts` and `i18n.test.ts`), `svelte-check` 0 errors (94 pre-existing idiomatic warnings), `vite build` OK; server **604 tests green** (13 new in `test/net/settings_test.dart`). | +| 2026-11-22 | **Phase 7 complete / M7 reached** — hardening and shipping. **E2E** (Playwright, `e2e/`): a `table` fixture boots a real compiled server per test (temp saves dir, free port, `workers: 1`) and a `Tab` helper drives the real UI (menus, rows, initiative, draw, seats) against one real WS per fresh browser context (= one session). **9 specs green**: a full round (onboarding, secret initiative masked to `??` per connection, draw revealing on every screen, turns, next round, round-2 secrecy); seat claim / re-claim / reload (owner-leave releases the seat for re-claim; a reload keeps the session and re-claims; two sessions can't own one character); resilience (a dropped tab resyncs on reconnect — no drift; a SIGKILL'd server restarts with state **and** seats surviving, incl. the owner's secret initiative and enabled draw; a throttled tab converges on the same state as the fast tabs; a double-tapped draw runs once with the error sent only to the sender); and character level + rename from the status menu. **Session persistence (root-cause fix found by the restart test):** a client never learned its session id before the first `welcome`, so a reconnect minted a new id and orphaned the persisted/restored seat — fixed with `establishSessionCookie()` (a `GET /session` before the WS upgrade, with a vite `/session` proxy) so the upgrade carries the `x-haven-session` cookie and the server's `resolve()` re-adopts the restored seat. Also seeded the initiative input from re-synced state (the `CharacterRow` prefill `$effect`, guarded against clobbering a live edit) so a reload/reconnect doesn't blank an entry. **Cross-check vs the reference** (registry ↔ UI command-surface diff): every one of the 82 registered commands is reachable from the web UI (incl. `changeHealth`/`changeMaxHealth`/`changeXP`/`addCondition`/`removeCondition` via the StatusMenu `change()`/`toggleCondition()` helpers, amdImbue*/corrosiveSpew in the AMD header, and `trackStandees` via the `noStandees` setting). Four genuine gaps closed: `setCharacterLevel` + `changeName` (level pills + a name field in the StatusMenu, mirroring the reference `SetCharacterLevelMenu`) and the draw-pile-only "send to bottom" (`reorderAbilityList` → index 0) + "shuffle undrawn cards" (`shuffleDrawnAbilityCard`) in the ability-card removal confirm (mirroring `RemoveCardMenu`). **Resilience / deployment:** `Dockerfile` (3-stage: server + built web), `docs/DEPLOYMENT.md` (incl. a measured performance table via `server/tool/perf_measure.dart` and a 10-step smoke-test list), README quickstart + production/Docker/testing sections, and immutable asset-cache headers for the image set. Verification: **web 196/196 tests**, `svelte-check` 0 errors (93 pre-existing idiomatic warnings), `vite build` OK; **E2E 9/9 green** (~17 s). | ## 7. Risks and open items diff --git a/README.md b/README.md index e767a12..4166ecf 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,14 @@ live in [`PLAN.md`](PLAN.md). - `server/` — the Dart game server. Owns all game state, serves the built web app, and hosts the game WebSocket at `/ws`. Game data is copied from the reference app into `server/assets/` (`data/`, `images/`, `i18n/`, `fonts/`, - `testData/`). + `testData/`). `tool/perf_measure.dart` is the Phase 7 performance probe. - `web/` — the Svelte + TypeScript single-page app. Carries no game state; it renders the server's state and submits player input. -- `scripts/ci.sh` — analyze, test, and build both halves. +- `e2e/` — Playwright end-to-end tests (full round, seats, resilience). +- `docs/DEPLOYMENT.md` — production notes: Docker, persistence, reverse + proxy, measured performance, smoke-test list. +- `Dockerfile` — server + built web in one image. +- `scripts/ci.sh` — analyze, test, and build both halves (plus the E2E suite). - `FrosthavenAssistant/` — read-only reference implementation (gitignored). ## Requirements @@ -58,6 +62,27 @@ npm run dev Open — you should see the connection status and, once the handshake completes, your session/role/state index. +## Quickstart (playing a game) + +1. Start the server (see *Production run* below, or the Docker one-liner in + [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)). +2. Open the game URL in a browser tab — each player gets their **own tab** + (and ideally their own device); other tabs can just watch as spectators. +3. In your tab open the main menu (top-left) → **Add Character** and pick + your class. Your tab becomes a *player* the moment you own a character; + a character someone leaves behind shows a **Claim** chip any player can + tap. +4. **Set Scenario** (same menu) picks the scenario. +5. Each player taps their character's initiative slot and enters a number — + it is **secret**: only your tab sees your entry until the round is drawn. +6. Once every player has entered, any player taps **Draw** (bottom bar). All + tabs reveal the initiative and switch to turns; end a figure's turn by + tapping its right-hand zone, then **Next Round** when the round is done. + +Full per-step verification (what to expect in each tab) is in the +[smoke-test list](docs/DEPLOYMENT.md#smoke-test-list); the same flow is +automated by the Playwright suite in `e2e/`. + ## Production run ```bash @@ -67,7 +92,20 @@ cd server && dart run bin/main.dart # serves web/dist + /ws on :4567 Open . The port and static dir can be overridden: `dart run bin/main.dart --port 8080 --static-dir ../web/dist` (the `PORT` -environment variable is also honored). +environment variable is also honored). Game state persists in `saves/` next +to the server; all options are in `server/bin/main.dart`. + +### Docker + +```bash +docker build -t xhaven . +docker run --rm -p 4567:4567 -v xhaven-saves:/app/saves xhaven +``` + +One image (web build + compiled server + game assets); state lives in the +`/app/saves` volume. See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for the +full list of options, persistence semantics, reverse-proxy/TLS notes, and +the measured performance figures. ## Testing @@ -76,7 +114,20 @@ scripts/ci.sh ``` runs `dart analyze` + `dart test` for the server and `svelte-check` + -`vitest` + `vite build` for the web app. +`vitest` + `vite build` for the web app, then the Playwright E2E suite +(two players + a spectator play a full round through the real UI; seat +claiming; resilience — offline tabs, throttled tabs, server restart +mid-game). The E2E steps are skipped when the `PLAYWRIGHT` environment +variable is unset (it is set on CI). + +Individual suites: + +```bash +cd server && dart test # server (604 tests) +cd web && npm run test # client (195 tests) +cd e2e && npx playwright test # end-to-end (needs `npm install` + + # `npx playwright install chromium`) +``` ## License diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..e27891b --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,127 @@ +# Deployment notes + +How to run X-Haven (web) in production. Two supported shapes: a single +container (Docker) or the two source trees directly (Dart + Node). The game +is a **single server process** — there is nothing to scale out per player; +more players just mean more WebSocket connections on the same server. + +## Running with Docker + +```bash +docker build -t xhaven . +docker run --rm -p 4567:4567 -v xhaven-saves:/app/saves xhaven +``` + +- Port: published `4567` → container `4567` (override with `-p 8080:4567` and + `--env PORT=8080`). +- State: everything the server persists lives under `/app/saves` + (`game.json` the live snapshot, `seats.json` seat ownership, + `settings.json` server-side settings, plus named saves). Mount a volume + there and redeploys keep the game. +- Health: `GET /healthz` answers 200; the image ships a `HEALTHCHECK` + (TCP probe, dependency-free). + +## Running from source + +```bash +cd web && npm ci && npm run build # → web/dist +cd ../server +dart pub get +dart run bin/main.dart \ + --port 4567 \ + --static-dir ../web/dist \ + --saves-dir /var/lib/xhaven/saves +``` + +Flags (all optional, see `server/bin/main.dart`): + +| flag | default | meaning | +|----------------|------------------|--------------------------------------------------| +| `--port` | `4567` (or `$PORT`) | HTTP + WebSocket port | +| `--static-dir` | `../web/dist` | the built web app (SPA fallback included) | +| `--saves-dir` | `saves` | game state, seats, settings, named saves | +| `--data-dir` | `assets/data/` | campaign/monster/scenario JSON (served at `/data/`) | + +Game artwork (`assets/images/`, ~66 MB) and in-game translations +(`assets/i18n/`) are served from the paths relative to the working +directory; keep the server's `assets/` tree next to `bin/`. + +## Reverse proxy / TLS + +The app is a plain-HTTP + WebSocket server; put it behind any TLS-terminating +proxy (Caddy, nginx, …). The only non-HTTP route is the WebSocket upgrade at +`/ws` — forward it with the usual `Upgrade`/`Connection` headers. All other +routes are ordinary GETs, and the client derives the WS URL from the page +origin (`wss://` under TLS), so no client configuration is needed. + +Long idle connections are kept alive by the client's 25 s keepalive `ping`; +proxy idle timeouts above ~30 s are fine. + +## Persistence & restarts + +- The server saves on **every action** (synchronous write-through), so a + crash loses at most the in-flight frame. +- On boot it restores `game.json` + `seats.json`: characters, the scenario, + round state, initiative entries, and seat ownership all survive a restart. + Reconnected browsers (same session cookie) resume with their seats; the + first `welcome` after reconnect carries the full state. +- Undo history is **not** persisted: after a restart the command index + restarts at 0 and the undo/redo buttons stay disabled until new actions + are taken. State itself is fully restored. +- Named saves (the Load/Save State menu) live under the saves dir and + survive indefinitely. + +## Performance (measured, Phase 7) + +Protocol cost under a full table, measured with +`server/tool/perf_measure.dart` (6 connected clients — 4 players + 2 +spectators — playing 3 full rounds of "#1 Roadside Ambush" with 4 characters +and 10 monsters; localhost): + +| metric | value | +|-----------------------------------------|---------| +| state JSON, full-table scale | **11.2 kB** | +| largest `update` frame (envelope+state) | 11.4 kB | +| fan-out per executed action (6 clients) | 68.5 kB | +| traffic per connection over 49 actions | ~460 kB | +| server-side action latency (localhost) | ~10 ms | + +The protocol is a full snapshot per action (bandwidth for simplicity): cost +scales linearly with state size × connections. At this scale that is trivial +for LAN or even WAN; the state grows slowly (characters, monsters, note rows, +decks) — a heavy multi-scenario game would be tens of kB, still fine. + +Static assets: + +- `index.html` and SPA routes: `cache-control: no-cache` (deploys reach open + tabs on refresh). +- Content-hashed build assets, `/data/` JSON, `/i18n/`, and the 66 MB + `/images/` set: `public, max-age=31536000, immutable` — the browser fetches + each image once and then from cache; the 66 MB art set is a one-time + download per device. +- Class artwork is `loading="lazy"` in the list. + +## Smoke-test list + +After deploying, verify in two browser tabs (and a third as spectator) — +these are exactly what the E2E suite (`e2e/`) automates: + +1. **Connect** — the "Connecting…" banner disappears on every tab; each tab + shows the table. +2. **Onboard** — in tab A open *Add Character* and add *Hatchet*; the row + appears on all tabs and tab A's Draw button enables (tab A is now a + player). +3. **Scenario** — tab A: *Set Scenario* → *#1 Roadside Ambush*. +4. **Second player** — tab B adds *Voidwarden*; all tabs show both rows. +5. **Spectator** — tab C shows both rows **read-only**: no initiative input, + no *Claim* chip, Draw disabled. +6. **Secret initiative** — tab A enters `4` in Hatchet's initiative slot. + Tab A sees the value; tabs B and C show `??`. +7. **Draw** — tab B enters `2`, then tab A taps *Draw*. All three tabs + switch to *Next Round* at once and show initiatives `4` / `2`. +8. **Turns** — tap the turn-done zone for each character; the round + completes. +9. **Next round** — tap *Next Round*; every tab shows *Round 2/* and the + initiative slots are secret again (only owners' inputs enabled). +10. **Reconnect** — reload tab C, then kill and restart the server; all + tabs show "Reconnecting…" and resync with the full state (seats kept). diff --git a/e2e/helpers/server.ts b/e2e/helpers/server.ts new file mode 100644 index 0000000..8357421 --- /dev/null +++ b/e2e/helpers/server.ts @@ -0,0 +1,167 @@ +/** + * Boots the real Dart game server for the E2E specs (PLAN.md Phase 7). + * + * `bin/main.dart` is compiled to a native executable once (cached under + * `e2e/.cache/`, recompiled when `bin/main.dart` is newer) so the + * resilience specs can kill and restart the server quickly. Each test gets + * a fresh temp saves dir and a free port, so the specs never share state. + */ +import { + execFileSync, + spawn, + type ChildProcess +} from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + statSync +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// This file lives in `e2e/helpers/`; the E2E root is one level up. +const E2E_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const REPO_ROOT = path.resolve(E2E_DIR, '..'); +const SERVER_DIR = path.join(REPO_ROOT, 'server'); +const WEB_DIST = path.join(REPO_ROOT, 'web', 'dist'); +const CACHE_DIR = path.join(E2E_DIR, '.cache'); +const BINARY = path.join(CACHE_DIR, 'xhaven-server'); +const MAIN_DART = path.join(SERVER_DIR, 'bin', 'main.dart'); + +let compilePromise: Promise | null = null; + +/** Compiles the server to a native binary (cached; recompile when stale). */ +export function ensureServerBinary(): Promise { + const needsCompile = + !existsSync(BINARY) || + statSync(MAIN_DART).mtimeMs > statSync(BINARY).mtimeMs; + if (!needsCompile) return Promise.resolve(); + compilePromise ??= (async () => { + mkdirSync(CACHE_DIR, { recursive: true }); + execFileSync('dart', ['compile', 'exe', 'bin/main.dart', '-o', BINARY], { + cwd: SERVER_DIR, + stdio: 'inherit', + timeout: 300_000 + }); + })(); + return compilePromise; +} + +/** A free TCP port on localhost. */ +export async function freePort(): Promise { + const net = await import('node:net'); + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.unref(); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + srv.close(() => (port ? resolve(port) : reject(new Error('no port')))); + }); + }); +} + +export interface RunningServer { + /** `http://127.0.0.1:` — open a tab here. */ + url: string; + port: number; + /** The temp dir holding game.json / settings.json / seats.json. */ + savesDir: string; + child: ChildProcess; + /** SIGKILL the server (crash simulation). */ + kill(): Promise; + /** SIGKILL, then report the exit code. */ + killAndWait(): Promise; +} + +export interface StartServerOptions { + /** Reuse an existing saves dir (restart mid-game). */ + savesDir?: string; + /** Bind a specific port (restart must keep the old port). */ + port?: number; +} + +/** + * Starts the server on a free port (or [opts.port]) with a fresh saves dir + * (or [opts.savesDir]) and resolves once `/healthz` answers. + */ +export async function startServer( + opts: StartServerOptions = {} +): Promise { + await ensureServerBinary(); + if (!existsSync(WEB_DIST)) { + throw new Error( + `web/dist missing — run \`npm run build\` in ${WEB_DIST} first` + ); + } + const port = opts.port ?? (await freePort()); + const savesDir = + opts.savesDir ?? mkdtempSync(path.join(tmpdir(), 'xhaven-e2e-')); + + const child = spawn( + BINARY, + [`--port=${port}`, `--static-dir=${WEB_DIST}`, `--saves-dir=${savesDir}`], + { cwd: SERVER_DIR } + ); + let logs = ''; + child.stdout?.on('data', (d) => (logs += String(d))); + child.stderr?.on('data', (d) => (logs += String(d))); + + try { + await waitForHttp(`http://127.0.0.1:${port}/healthz`, 90_000); + } catch (err) { + child.kill('SIGKILL'); + rmSync(savesDir, { recursive: true, force: true }); + throw new Error(`server failed to start on port ${port}:\n${logs}\n${String(err)}`); + } + + return { + url: `http://127.0.0.1:${port}`, + port, + savesDir, + child, + kill: () => new Promise((resolve) => { + // Already dead (e.g. the spec killed it): nothing to wait for. + if (child.exitCode !== null || child.signalCode !== null) { + resolve(); + return; + } + child.once('exit', () => resolve()); + child.kill('SIGKILL'); + }), + killAndWait: () => + new Promise((resolve) => { + if (child.exitCode !== null || child.signalCode !== null) { + resolve(child.exitCode ?? -1); + return; + } + child.once('exit', (code) => resolve(code ?? -1)); + child.kill('SIGKILL'); + }) + }; +} + +/** Polls [url] until it answers 2xx (or the timeout elapses). */ +export async function waitForHttp(url: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + try { + const res = await fetch(url); + if (res.ok) return; + } catch { + // not up yet + } + if (Date.now() > deadline) { + throw new Error(`timed out waiting for ${url}`); + } + await new Promise((r) => setTimeout(r, 200)); + } +} + +/** Removes a stale cached binary (used by `npm run e2e:clean`). */ +export function cleanCache(): void { + rmSync(CACHE_DIR, { recursive: true, force: true }); +} diff --git a/e2e/helpers/tab.ts b/e2e/helpers/tab.ts new file mode 100644 index 0000000..616f783 --- /dev/null +++ b/e2e/helpers/tab.ts @@ -0,0 +1,188 @@ +/** + * One browser tab on the table (PLAN.md Phase 7): drives the real UI — + * menus, character rows, the initiative widget, the draw button — and + * asserts on the DOM each connection actually receives (the per-connection + * masked state, PLAN.md section 3.4). + */ +import type { Locator, Page } from '@playwright/test'; + +export class Tab { + constructor(public readonly page: Page) {} + + /** Loads the game page and waits for the WS handshake to complete. */ + async open(url: string): Promise { + await this.page.goto(url, { waitUntil: 'domcontentloaded' }); + await this.waitForConnected(); + } + + /** The "Connecting…" banner is visible until the first `welcome` lands. */ + async waitForConnected(): Promise { + await this.page.waitForSelector('.topbar'); + await this.page + .locator('.banner[role="status"]') + .waitFor({ state: 'detached', timeout: 30_000 }); + } + + // --- main list ----------------------------------------------------------- + + /** The character row whose display name is [name]. */ + row(name: string): Locator { + return this.page + .locator('.row--character') + .filter({ has: this.page.locator('.row__name', { hasText: name }) }); + } + + /** The monster row whose name is [name]. */ + monsterRow(name: string): Locator { + return this.page + .locator('.row--monster') + .filter({ has: this.page.locator('.row__name', { hasText: name }) }); + } + + // --- menus --------------------------------------------------------------- + + /** Opens the main drawer and picks the [label] entry (a menu dialog). */ + async openMenu(label: string): Promise { + await this.page.locator('.topbar__menu').click(); + await this.page + .locator('nav[aria-label="Main menu"]') + .getByRole('button', { name: label, exact: true }) + .click(); + await this.page.locator('.dialog__overlay').first().waitFor(); + } + + /** The open dialog titled [title]. */ + dialog(title: string): Locator { + return this.page + .locator('.dialog__overlay') + .filter({ + has: this.page.locator('.dialog__title', { hasText: title }) + }); + } + + /** + * Adds a character via the Add Character menu (level defaults to 1). + * Resolves once the row appears — i.e. the server's update arrived. + */ + async addCharacter(name: string, level = 1): Promise { + await this.openMenu('Add Character'); + const dlg = this.dialog('Add Character'); + const up = dlg.locator('.stepbtn').nth(1); + for (let i = 1; i < level; i++) await up.click(); + await dlg.locator('.menulist__item').filter({ hasText: name }).click(); + await this.row(name).waitFor({ timeout: 15_000 }); + } + + /** Picks [scenarioName] (optionally switching to [campaign] first). */ + async selectScenario(scenarioName: string, campaign?: string): Promise { + await this.openMenu('Set Scenario'); + const dlg = this.dialog('Set Scenario'); + if (campaign) { + await dlg.locator('.campaignbtns button').filter({ hasText: campaign }).click(); + } + await dlg + .locator('.menulist__item') + .filter({ hasText: scenarioName }) + .first() + .click(); + await this.page.locator('.dialog__overlay').waitFor({ state: 'detached' }); + } + + /** Adds a monster via the Add Monsters menu. */ + async addMonster(name: string, level = 1): Promise { + await this.openMenu('Add Monsters'); + const dlg = this.dialog('Add Monsters'); + const up = dlg.locator('.stepbtn').nth(1); + for (let i = 1; i < level; i++) await up.click(); + await dlg.locator('.menulist__item').filter({ hasText: name }).first().click(); + await this.monsterRow(name).waitFor({ timeout: 15_000 }); + } + + // --- initiative (the server-gated secret) -------------------------------- + + /** Enters [value] in this tab's initiative input for [rowName]. */ + async setInitiative(rowName: string, value: number): Promise { + const input = this.row(rowName).locator('input.init__input'); + await input.waitFor({ timeout: 15_000 }); + await input.fill(String(value)); + } + + /** The initiative value shown on [rowName] in this tab (the `.init` cell). */ + initDisplay(rowName: string): Locator { + return this.row(rowName).locator('.init'); + } + + /** True when [rowName] shows an editable initiative input on this tab. */ + async hasInitiativeInput(rowName: string): Promise { + return (await this.row(rowName).locator('input.init__input').count()) > 0; + } + + // --- draw / turns --------------------------------------------------------- + + /** Taps Draw (chooseInitiative) or Next Round (playTurns). */ + async clickDraw(): Promise { + await this.page.locator('button.drawbtn').click(); + } + + /** Waits until the round has been drawn (the button reads Next Round). */ + async waitForDrawn(): Promise { + await this.page + .getByRole('button', { name: /Next Round/ }) + .waitFor({ timeout: 15_000 }); + } + + /** Waits until a new round is being chosen (the button reads Draw). */ + async waitForRoundChosen(): Promise { + await this.page.getByRole('button', { name: /Draw/ }).waitFor({ timeout: 15_000 }); + } + + /** Taps the right-hand turn-done zone of [rowName] (playTurns). */ + async turnDone(rowName: string): Promise { + await this.row(rowName).locator('div[aria-label="Turn done"]').click(); + } + + /** The round counter under the draw button (e.g. "Round 1/1"). */ + roundLabel(): Locator { + return this.page.locator('.drawbtn__round'); + } + + /** The draw/next-round button's enabled state (players only). */ + async drawEnabled(): Promise { + return this.page.locator('button.drawbtn').isEnabled(); + } + + // --- seats (claim / re-claim) -------------------------------------------- + + /** + * Opens the figure's status (stat) menu by tapping the row's name, and + * returns the open dialog (titled with the figure's display name). + */ + async openStatusMenu(rowName: string): Promise { + await this.row(rowName).locator('.row__name').click(); + const dlg = this.dialog(rowName); + await dlg.waitFor({ timeout: 15_000 }); + return dlg; + } + + /** The "Claim" chip on [rowName] (visible while the character is unclaimed). */ + claimChip(rowName: string): Locator { + return this.row(rowName).locator('button.chip--claim'); + } + + /** Clicks the Claim chip on [rowName]. */ + async claim(rowName: string): Promise { + await this.claimChip(rowName).click(); + } + + // --- misc ----------------------------------------------------------------- + + /** The current toast text (server errors / scenario events), if any. */ + toast(): Locator { + return this.page.locator('.toast[role="status"]'); + } + + /** Closes this tab's page (the server sees the connection drop). */ + async closePage(): Promise { + await this.page.close(); + } +} diff --git a/e2e/helpers/table.ts b/e2e/helpers/table.ts new file mode 100644 index 0000000..9641a24 --- /dev/null +++ b/e2e/helpers/table.ts @@ -0,0 +1,51 @@ +/** + * The `table` fixture: one real Dart server + a factory for browser tabs. + * + * Each `newTab()` opens a fresh browser context (its own cookie jar → its + * own session id on the server), so two tabs are two independent players / + * spectators — exactly the deployment model (PLAN.md section 3.3). + */ +import { test as base, expect, type BrowserContext, type Page } from '@playwright/test'; + +import { startServer, type RunningServer } from './server.js'; +import { Tab } from './tab.js'; + +export interface OpenTab { + tab: Tab; + page: Page; + context: BrowserContext; +} + +export interface Table { + server: RunningServer; + /** Opens a new browser tab (fresh session) on the table. */ + newTab(): Promise; +} + +interface Opened { + context: BrowserContext; + page: Page; +} + +export const test = base.extend<{ table: Table }>({ + table: async ({ browser }, use) => { + const server = await startServer(); + const opened: Opened[] = []; + await use({ + server, + newTab: async () => { + const context = await browser.newContext(); + const page = await context.newPage(); + opened.push({ context, page }); + return { tab: new Tab(page), page, context }; + } + }); + for (const { context, page } of opened) { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } + await server.kill(); + } +}); + +export { expect }; diff --git a/e2e/package-lock.json b/e2e/package-lock.json new file mode 100644 index 0000000..4625a40 --- /dev/null +++ b/e2e/package-lock.json @@ -0,0 +1,75 @@ +{ + "name": "x-haven-e2e", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "x-haven-e2e", + "version": "0.1.0", + "devDependencies": { + "@playwright/test": "^1.65.0", + "typescript": "^5.5.0" + } + }, + "node_modules/@playwright/test": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", + "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + } + } +} diff --git a/e2e/package.json b/e2e/package.json new file mode 100644 index 0000000..2669bc1 --- /dev/null +++ b/e2e/package.json @@ -0,0 +1,13 @@ +{ + "name": "x-haven-e2e", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "test": "playwright test" + }, + "devDependencies": { + "@playwright/test": "^1.65.0", + "typescript": "^5.5.0" + } +} diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts new file mode 100644 index 0000000..c928a10 --- /dev/null +++ b/e2e/playwright.config.ts @@ -0,0 +1,30 @@ +import { defineConfig, type TestConfig } from '@playwright/test'; + +/** + * E2E config for X-Haven (PLAN.md Phase 7). + * + * Each test boots its own real Dart game server (fresh saves dir, free port) + * through the `table` fixture in `helpers/table.ts` — there is no shared + * `webServer` because the resilience specs restart the server mid-test and + * every spec needs isolated state. + */ +const config: TestConfig = { + testDir: './tests', + timeout: 180_000, + // The server boot + a full round is the slow part; give the whole suite + // room without making a hang look like a pass. + expect: { timeout: 10_000 }, + // One worker: the specs drive real browser tabs against one server each, + // and a single worker keeps the ports and temp dirs from colliding. + workers: 1, + retries: 0, + reporter: [['list']], + use: { + // No baseURL: the server port is chosen per test. + viewport: { width: 400, height: 820 }, + // Keep the failure artifacts small (we drive full state over WS). + trace: 'retain-on-failure', + }, +}; + +export default defineConfig(config); diff --git a/e2e/tests/figure-edit.spec.ts b/e2e/tests/figure-edit.spec.ts new file mode 100644 index 0000000..9b7bc9b --- /dev/null +++ b/e2e/tests/figure-edit.spec.ts @@ -0,0 +1,37 @@ +/** + * E2E: character level + rename from the status menu (the Phase 7 + * cross-check closed the `setCharacterLevel` / `changeName` gaps vs the + * reference `SetCharacterLevelMenu`). Drives the real UI and asserts the + * server round-trip re-renders on the tab. + */ +import { test, expect } from '../helpers/table.js'; + +test('a player can set a character level and rename it', async ({ table }) => { + const p1 = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + + // Open the status (stat) menu by tapping the row's name. + const dlg = await p1.openStatusMenu('Hatchet'); + + // Level pills 1..N are present; level 1 (the add default) is the current + // one, so its pill is highlighted and disabled. + await expect(dlg.locator('button.pill', { hasText: /^1$/ })).toBeDisabled(); + await expect(dlg.locator('button.pill', { hasText: /^1$/ })).toHaveClass(/pill--on/); + + // Set level 2: the server round-trip re-renders and the level-2 pill + // becomes the highlighted current one. + await dlg.locator('button.pill', { hasText: /^2$/ }).click(); + await expect(dlg.locator('button.pill', { hasText: /^2$/ })).toHaveClass(/pill--on/); + await expect(dlg.locator('button.pill', { hasText: /^2$/ })).toBeDisabled(); + await expect(dlg.locator('button.pill', { hasText: /^1$/ })).toBeEnabled(); + + // Rename via the name field: submit on Enter, the row re-renders with the + // new display name. (Use a name with no overlap with "Hatchet" so the + // substring-matched row helpers read the old and new names distinctly.) + const name = dlg.locator('input.search'); + await name.fill('Molly'); + await name.press('Enter'); + await expect(p1.row('Molly')).toBeVisible(); + await expect(p1.row('Hatchet')).toHaveCount(0); +}); diff --git a/e2e/tests/full-round.spec.ts b/e2e/tests/full-round.spec.ts new file mode 100644 index 0000000..6e3c7e7 --- /dev/null +++ b/e2e/tests/full-round.spec.ts @@ -0,0 +1,91 @@ +/** + * E2E: two players + one spectator play a full round in real browser tabs + * (PLAN.md Phase 7). + * + * Covers: the onboarding flow (a fresh spectator becomes a player by adding + * a character), secret initiative (server-masked per connection), the draw + * (reveal on every screen), turns, and the next round. + */ +import { test, expect } from '../helpers/table.js'; + +test('full round: setup, secret initiative, draw, turns, next round', async ({ + table +}) => { + // --- Player 1 joins the empty table and becomes a player --------------- + const p1 = (await table.newTab()).tab; + await p1.open(table.server.url); + // A fresh session is a spectator: the draw button is disabled and the + // scenario menu is gated. Adding a character is the onboarding path. + expect(await p1.drawEnabled()).toBe(false); + await p1.addCharacter('Hatchet'); + expect(await p1.drawEnabled()).toBe(true); + + // Set the scenario now that p1 is a player. + await p1.selectScenario('#1 Roadside Ambush'); + + // --- Player 2 and a spectator join ------------------------------------- + const p2 = (await table.newTab()).tab; + await p2.open(table.server.url); + await p2.addCharacter('Voidwarden'); + + const spec = (await table.newTab()).tab; + await spec.open(table.server.url); + await spec.row('Hatchet').waitFor({ timeout: 15_000 }); + await spec.row('Voidwarden').waitFor({ timeout: 15_000 }); + // The spectator sees both rows read-only: no inputs, no claim chips + // (both characters are claimed), and a disabled draw button. + expect(await spec.drawEnabled()).toBe(false); + expect(await spec.claimChip('Hatchet').count()).toBe(0); + expect(await spec.claimChip('Voidwarden').count()).toBe(0); + expect(await spec.hasInitiativeInput('Hatchet')).toBe(false); + + // --- Secret initiative --------------------------------------------------- + // Player 1 enters 4. Player 1 sees an editable input with the value; + // player 2 and the spectator receive `null` from the server and see `??`. + await p1.setInitiative('Hatchet', 4); + expect(await p1.hasInitiativeInput('Hatchet')).toBe(true); + await expect(p2.initDisplay('Hatchet')).toHaveText('??'); + await expect(p2.initDisplay('Hatchet')).toHaveClass(/init__secret/); + await expect(spec.initDisplay('Hatchet')).toHaveText('??'); + + // Player 2 enters 2; player 1 sees `??` for Voidwarden in turn. + await p2.setInitiative('Voidwarden', 2); + await expect(p1.initDisplay('Voidwarden')).toHaveText('??'); + await expect(spec.initDisplay('Voidwarden')).toHaveText('??'); + + // --- Draw: every screen flips to playTurns at once ----------------------- + await p1.clickDraw(); + await p1.waitForDrawn(); + await p2.waitForDrawn(); + await spec.waitForDrawn(); + + // Initiative is now public on every screen. + await expect(p1.initDisplay('Hatchet')).toHaveText('4'); + await expect(p1.initDisplay('Voidwarden')).toHaveText('2'); + await expect(p2.initDisplay('Hatchet')).toHaveText('4'); + await expect(p2.initDisplay('Voidwarden')).toHaveText('2'); + await expect(spec.initDisplay('Hatchet')).toHaveText('4'); + await expect(spec.initDisplay('Voidwarden')).toHaveText('2'); + // … and no initiative inputs remain anywhere. + expect(await p1.hasInitiativeInput('Hatchet')).toBe(false); + expect(await p2.hasInitiativeInput('Voidwarden')).toBe(false); + expect(await spec.hasInitiativeInput('Hatchet')).toBe(false); + + // --- Turns --------------------------------------------------------------- + await p1.turnDone('Hatchet'); + await p2.turnDone('Voidwarden'); + + // --- Next round: round 2, initiative secret again ------------------------ + await p1.clickDraw(); // "Next Round" + await p1.waitForRoundChosen(); + await p2.waitForRoundChosen(); + await spec.waitForRoundChosen(); + await expect(p1.roundLabel()).toHaveText(/Round 2\//); + await expect(p2.roundLabel()).toHaveText(/Round 2\//); + await expect(spec.roundLabel()).toHaveText(/Round 2\//); + // The round-2 values are secret again; only the owner's input is enabled. + await expect(p2.initDisplay('Hatchet')).toHaveText('??'); + await expect(spec.initDisplay('Hatchet')).toHaveText('??'); + expect(await p1.hasInitiativeInput('Hatchet')).toBe(true); + expect(await p2.hasInitiativeInput('Hatchet')).toBe(false); +}); diff --git a/e2e/tests/resilience.spec.ts b/e2e/tests/resilience.spec.ts new file mode 100644 index 0000000..27e7a18 --- /dev/null +++ b/e2e/tests/resilience.spec.ts @@ -0,0 +1,231 @@ +/** + * E2E: resilience (PLAN.md Phase 7). + * + * * a tab that drops out (offline) resyncs on reconnect — no drift + * * a SIGKILL'd server restarts mid-game: state AND seats survive, secret + * initiative stays masked for non-owners, the game continues + * * a throttled (slow) tab converges on the same state as the fast tabs + * * a double-tapped draw executes exactly once; only the sender gets the + * error toast + * + * Note on the initiative cell markup: during chooseInitiative the OWNER + * renders an `` (no `.init` div); every other connection renders the + * `.init` div — `??` while the server masks the value, the number after the + * draw. + */ +import type { Page } from '@playwright/test'; +import { test, expect } from '../helpers/table.js'; +import { startServer } from '../helpers/server.js'; +import { Tab } from '../helpers/tab.js'; + +/** ~1 s one-way latency, moderate throughput (CDP network emulation). */ +async function throttle(page: Page) { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Network.emulateNetworkConditions', { + offline: false, + latency: 1000, + downloadThroughput: 500_000, + uploadThroughput: 500_000 + }); +} + +test.describe('Resilience', () => { + test('a dropped tab resyncs when it comes back (no drift)', async ({ + table + }) => { + const p1 = (await table.newTab()).tab; + const p2 = (await table.newTab()).tab; + const specOpen = await table.newTab(); + const spec = specOpen.tab; + const specContext = specOpen.context; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + await p1.selectScenario('#1 Roadside Ambush'); + await p2.open(table.server.url); + await p2.addCharacter('Voidwarden'); + await spec.open(table.server.url); + await spec.row('Hatchet').waitFor({ timeout: 15_000 }); + await spec.row('Voidwarden').waitFor({ timeout: 15_000 }); + + // The spectator's network drops and its tab is lost. Closing the page + // reliably severs the WebSocket (CDP offline emulation alone does not + // tear down an already-established socket). + await specContext.setOffline(true); + await spec.closePage(); + + // The game moves on without it. + await p1.setInitiative('Hatchet', 4); + await p2.setInitiative('Voidwarden', 2); + await p1.clickDraw(); + await p1.waitForDrawn(); + await p2.waitForDrawn(); + + // Back online: a fresh page in the same session (cookie) re-sends + // `hello`, and the full `welcome` overwrites the stale snapshot. + await specContext.setOffline(false); + const spec2 = new Tab(await specContext.newPage()); + await spec2.open(table.server.url); + await spec2.waitForDrawn(); + await expect(spec2.page.locator('.banner[role="status"]')).toBeHidden(); + await expect(spec2.initDisplay('Hatchet')).toHaveText('4'); + await expect(spec2.initDisplay('Voidwarden')).toHaveText('2'); + await expect(spec2.roundLabel()).toHaveText(/Round 1\//); + }); + + test('a SIGKILL’d server restarts mid-game: state and seats survive', async ({ + table + }) => { + const p1 = (await table.newTab()).tab; + const p2 = (await table.newTab()).tab; + const spec = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + await p1.selectScenario('#1 Roadside Ambush'); + await p2.open(table.server.url); + await p2.addCharacter('Voidwarden'); + await spec.open(table.server.url); + await spec.row('Hatchet').waitFor({ timeout: 15_000 }); + + // Mid chooseInitiative: p1 has entered 4 (secret), p2 has not. + await p1.setInitiative('Hatchet', 4); + await expect(p2.initDisplay('Hatchet')).toHaveText('??'); + await expect(spec.initDisplay('Hatchet')).toHaveText('??'); + + // Crash the server (SIGKILL — no graceful shutdown). + await table.server.killAndWait(); + + // Every tab notices the drop and starts reconnecting. + await expect(p1.page.locator('.banner[role="status"]')).toBeVisible(); + await expect(spec.page.locator('.banner[role="status"]')).toBeVisible(); + + // Restart the same server: same port, same saves dir. + const restarted = await startServer({ + port: table.server.port, + savesDir: table.server.savesDir + }); + + try { + // All tabs auto-reconnect and resync. + await p1.page + .locator('.banner[role="status"]') + .waitFor({ state: 'detached', timeout: 30_000 }); + await spec.page + .locator('.banner[role="status"]') + .waitFor({ state: 'detached', timeout: 30_000 }); + + // State survived the crash… + await expect(p1.roundLabel()).toHaveText(/Round 1\//); + await expect(spec.roundLabel()).toHaveText(/Round 1\//); + + // …including the secret entry: p1 (the seat owner) still has the + // editable input with the value; p2 and the spectator see the mask. + // The seats broadcast lands a beat after the state, so auto-wait. + await expect( + p1.row('Hatchet').locator('input.init__input') + ).toHaveCount(1); + await expect(p1.row('Hatchet').locator('input.init__input')).toHaveValue( + '4' + ); + await expect(p2.initDisplay('Hatchet')).toHaveText('??'); + await expect(spec.initDisplay('Hatchet')).toHaveText('??'); + + // Seats survived too: p1 is still a player (can draw) and the + // character is not claimable by p2. + await expect(p1.page.locator('button.drawbtn')).toBeEnabled(); + await expect(p2.claimChip('Hatchet')).toHaveCount(0); + + // And the game continues exactly where it left off. + await p2.setInitiative('Voidwarden', 2); + await p2.clickDraw(); + await p1.waitForDrawn(); + await p2.waitForDrawn(); + await spec.waitForDrawn(); + await expect(p1.initDisplay('Hatchet')).toHaveText('4'); + await expect(spec.initDisplay('Voidwarden')).toHaveText('2'); + } finally { + await restarted.kill(); + } + }); + + test('a throttled tab converges on the same state as the fast tabs', async ({ + table + }) => { + const p1 = (await table.newTab()).tab; + const p2 = (await table.newTab()).tab; + const specOpen = await table.newTab(); + const spec = specOpen.tab; + + // Slow the spectator down ~1 s one-way BEFORE the page (and its WS + // connection) is established. + await throttle(specOpen.page); + await spec.open(table.server.url); + + // The fast tabs run a full round while the spectator lags behind. + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + await p1.selectScenario('#1 Roadside Ambush'); + await p2.open(table.server.url); + await p2.addCharacter('Voidwarden'); + await p1.setInitiative('Hatchet', 4); + await p2.setInitiative('Voidwarden', 2); + await p1.clickDraw(); + await p1.waitForDrawn(); + await p2.waitForDrawn(); + + // The full-snapshot protocol means the slow tab lands on the final + // state — no drift, no gaps. + await spec.row('Hatchet').waitFor({ timeout: 30_000 }); + await spec.row('Voidwarden').waitFor({ timeout: 30_000 }); + await spec.waitForDrawn(); + await expect(spec.page.locator('.banner[role="status"]')).toBeHidden(); + await expect(spec.initDisplay('Hatchet')).toHaveText('4'); + await expect(spec.initDisplay('Voidwarden')).toHaveText('2'); + await expect(spec.roundLabel()).toHaveText(/Round 1\//); + }); + + test('a double-tapped draw runs once; only the sender sees the error', async ({ + table + }) => { + const p1Open = await table.newTab(); + const p1 = p1Open.tab; + const p2 = (await table.newTab()).tab; + const spec = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + await p1.selectScenario('#1 Roadside Ambush'); + await p2.open(table.server.url); + await p2.addCharacter('Voidwarden'); + await spec.open(table.server.url); + await spec.row('Hatchet').waitFor({ timeout: 15_000 }); + + await p1.setInitiative('Hatchet', 4); + await p2.setInitiative('Voidwarden', 2); + + // Throttle p1 so the first tap’s update cannot re-render the button + // before the second tap lands — both taps send `draw`. + await throttle(p1Open.page); + await p1.page.locator('button.drawbtn').click({ clickCount: 2 }); + + // The table drew exactly once… + await p1.waitForDrawn(); + await p2.waitForDrawn(); + await spec.waitForDrawn(); + await expect(p2.roundLabel()).toHaveText(/Round 1\//); + await expect(spec.roundLabel()).toHaveText(/Round 1\//); + + // …and the losing tap is reported to the sender only. (The other tabs + // may still show the broadcast round-start scenario message — a + // legitimate toast — but never the sender-only error.) + await expect(p1.toast()).toContainText('already been drawn'); + await expect( + p2.page.locator('.toast[role="status"]', { + hasText: 'already been drawn' + }) + ).toHaveCount(0); + await expect( + spec.page.locator('.toast[role="status"]', { + hasText: 'already been drawn' + }) + ).toHaveCount(0); + }); +}); diff --git a/e2e/tests/seats.spec.ts b/e2e/tests/seats.spec.ts new file mode 100644 index 0000000..432069a --- /dev/null +++ b/e2e/tests/seats.spec.ts @@ -0,0 +1,82 @@ +/** + * E2E: seat claiming (PLAN.md Phase 7 / section 3.3). + * + * * a disconnected owner's character becomes claimable (the Claim chip) + * * claiming grants ownership on every screen (inputs enable) + * * a page reload keeps the session (cookie) but the seat must be re-claimed + * (the server releases seats on disconnect — the Phase 2 behaviour) + */ +import { test, expect } from '../helpers/table.js'; + +test.describe('Seats: claim / re-claim / reload', () => { + test('owner leaves → seat released → another session claims', async ({ + table + }) => { + const p1 = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + expect(await p1.hasInitiativeInput('Hatchet')).toBe(true); + + const p2 = (await table.newTab()).tab; + await p2.open(table.server.url); + await p2.row('Hatchet').waitFor({ timeout: 15_000 }); + // While p1 is connected the seat is taken: no claim chip. + expect(await p2.claimChip('Hatchet').count()).toBe(0); + + // p1 leaves the table (tab closed → the connection drops). + await p1.closePage(); + // The seat is released and broadcast: p2 now sees the claim chip. + await p2.claimChip('Hatchet').waitFor({ timeout: 15_000 }); + + await p2.claim('Hatchet'); + // p2 is the owner now: the chip is gone, inputs enable, and the draw + // button unlocks (a claimed seat makes p2 a player). The claim is a + // server round-trip (seats broadcast → re-render), so these auto-wait. + await expect(p2.claimChip('Hatchet')).toHaveCount(0); + await expect(p2.row('Hatchet').locator('input.init__input')).toHaveCount(1); + await expect(p2.page.locator('button.drawbtn')).toBeEnabled(); + }); + + test('a page reload keeps the session, and the seat is re-claimed', async ({ + table + }) => { + const p1 = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + expect(await p1.hasInitiativeInput('Hatchet')).toBe(true); + + // Reload the same tab (same context → the session cookie survives). + await p1.page.reload(); + await p1.waitForConnected(); + await p1.row('Hatchet').waitFor({ timeout: 15_000 }); + + // The disconnect released the seat: the character is claimable again, + // and the (reconnected) session claims it with one tap. + await p1.claimChip('Hatchet').waitFor({ timeout: 15_000 }); + await p1.claim('Hatchet'); + // The claim round-trip (seats broadcast → re-render) is async. + await expect(p1.row('Hatchet').locator('input.init__input')).toHaveCount(1); + await expect(p1.claimChip('Hatchet')).toHaveCount(0); + }); + + test('two sessions cannot own one character at once', async ({ table }) => { + const p1 = (await table.newTab()).tab; + await p1.open(table.server.url); + await p1.addCharacter('Hatchet'); + + // p1 leaves, p2 claims, p1 comes back and tries to re-claim the same + // character — the server rejects it (it is claimed by p2). + const p2 = (await table.newTab()).tab; + await p2.open(table.server.url); + await p2.row('Hatchet').waitFor({ timeout: 15_000 }); + await p1.closePage(); + await p2.claimChip('Hatchet').waitFor({ timeout: 15_000 }); + await p2.claim('Hatchet'); + + const p1Again = (await table.newTab()).tab; + await p1Again.open(table.server.url); + await p1Again.row('Hatchet').waitFor({ timeout: 15_000 }); + // p2 holds the seat: no claim chip for p1Again. + expect(await p1Again.claimChip('Hatchet').count()).toBe(0); + }); +}); diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json new file mode 100644 index 0000000..e53013d --- /dev/null +++ b/e2e/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "types": ["node"], + "noEmit": true, + "skipLibCheck": true + }, + "include": ["playwright.config.ts", "helpers/**/*.ts", "tests/**/*.ts"] +} diff --git a/scripts/ci.sh b/scripts/ci.sh index 7115f60..1442ebf 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # CI for X-Haven web: analyze + test the Dart server, typecheck + test + build -# the Svelte web app. +# the Svelte web app, and (when PLAYWRIGHT is set) run the Playwright E2E suite. set -euo pipefail cd "$(dirname "$0")/.." @@ -19,4 +19,15 @@ echo "==> web: tests" echo "==> web: build" (cd web && npm run build) +# The E2E suite boots the real compiled server and drives real browser tabs, +# so it needs web/dist (built above) + Playwright's Chromium. It's a slower +# pass, so it runs only when PLAYWRIGHT is set (CI machines enable it; local +# runs can opt in with `PLAYWRIGHT=1 scripts/ci.sh`). +if [ -n "${PLAYWRIGHT:-}" ]; then + echo "==> e2e: playwright install (chromium)" + (cd e2e && npx playwright install chromium) + echo "==> e2e: playwright test" + (cd e2e && npm run test) +fi + echo "CI OK" diff --git a/server/bin/main.dart b/server/bin/main.dart index 60910a9..36c64c7 100644 --- a/server/bin/main.dart +++ b/server/bin/main.dart @@ -3,6 +3,7 @@ /// Usage (from the server/ directory): /// dart run bin/main.dart /// dart run bin/main.dart --port 8080 --static-dir ../web/dist +/// dart run bin/main.dart --saves-dir /data/saves # e.g. in Docker library; import 'dart:io'; @@ -27,15 +28,20 @@ Future main(List args) async { int.tryParse(Platform.environment['PORT'] ?? '') ?? 4567; final staticDir = _parseString(args, 'static-dir') ?? '../web/dist'; + // The save directory (game state, settings, saves, seats) defaults to + // `saves/` next to the server; override for Docker / multi-game hosts. + final savesDir = _parseString(args, 'saves-dir') ?? 'saves'; + // The game data the engine loads and the client's menus read. + final dataDir = _parseString(args, 'data-dir') ?? 'assets/data/'; - // Boot the game engine (single save in saves/, game data from - // assets/data/), then attach the network layer: the WebSocket game - // server, with seat ownership persisted next to the game state. - await _bootGameCore(); + // Boot the game engine (single save in [savesDir], game data from + // [dataDir]), then attach the network layer: the WebSocket game server, + // with seat ownership persisted next to the game state. + await _bootGameCore(savesDir: savesDir, dataDir: dataDir); final gameServer = GameServer( gameState: getIt(), sessions: SessionManager(), - seatStore: FileSeatStore('saves'), + seatStore: FileSeatStore(savesDir), ); final server = await startServer( @@ -43,7 +49,7 @@ Future main(List args) async { staticDir: staticDir, gameServer: gameServer, // The client's menus and artwork read the same assets the engine loads. - dataDir: 'assets/data/', + dataDir: dataDir, imageDir: 'assets/images/', // In-game ability-text translations for the client's card renderer. i18nDir: 'assets/i18n/', @@ -61,19 +67,25 @@ Future main(List args) async { /// Registers the core singletons (file-backed save), loads the game data, /// initializes the game state, and restores the most recent save. -Future _bootGameCore({String dataDir = 'assets/data/'}) async { +Future _bootGameCore({ + required String savesDir, + required String dataDir, +}) async { setupCore( - saveStore: FileSaveStore('saves'), - settingsStore: FileSettingsStore('saves'), + saveStore: FileSaveStore(savesDir), + settingsStore: FileSettingsStore(savesDir), ); await getIt().loadData(dataDir); final gameState = getIt(); gameState.init(); - // Restore the persisted settings (saves/settings.json; no-op on first + // Restore the persisted settings (/settings.json; no-op on first // run) before the server answers the first `welcome` with them. getIt().loadFromDisk(); gameState.load(); - _log.info('game core booted (command index ${gameState.commandIndex})'); + _log.info( + 'game core booted (saves: $savesDir, ' + 'command index ${gameState.commandIndex})', + ); } int? _parseInt(List args, String name) => diff --git a/server/lib/net/app.dart b/server/lib/net/app.dart index 8936104..a57aab0 100644 --- a/server/lib/net/app.dart +++ b/server/lib/net/app.dart @@ -18,6 +18,20 @@ import 'ws_upgrade.dart'; final _log = Logger('server'); +/// One year, in seconds — the cache lifetime for immutable assets +/// (PLAN.md Phase 7 "Performance"). +const int _kCacheYearSeconds = 60 * 60 * 24 * 365; + +/// `Cache-Control` for assets that are never mutated in place: the game +/// data, images, in-game translations, and the content-hashed build +/// outputs. Browsers keep them for a year and never revalidate. +const String _kImmutableCacheControl = + 'public, max-age=${_kCacheYearSeconds}, immutable'; + +/// `Cache-Control` for the SPA entry point: always revalidate, so a +/// rebuilt app reaches open tabs on the next navigation. +const String _kNoCacheControl = 'no-cache'; + /// Builds the HTTP handler for the game server. /// /// [dataDir] (e.g. `assets/data/`) is served read-only at `/data/` when @@ -131,12 +145,18 @@ Handler _createStaticHandler(String staticDir, {bool plain = false}) { ); } if (plain) { - // Plain static serving (no SPA fallback) with long-lived caching — - // the JSON and images are immutable build inputs. - return createStaticHandler( - directory.path, - maxAge: const Duration(days: 1), - ); + // Plain static serving (no SPA fallback) for the game data, images, and + // in-game translations — immutable build inputs: cached for a year + // without revalidation (the 66 MB image set is the big win here). + final inner = createStaticHandler(directory.path); + return (Request request) async { + final response = await inner(request); + if (response.statusCode == 200) { + return response + .change(headers: {'cache-control': _kImmutableCacheControl}); + } + return response; + }; } final staticHandler = createStaticHandler( directory.path, @@ -147,14 +167,33 @@ Handler _createStaticHandler(String staticDir, {bool plain = false}) { if (response.statusCode == 404 && request.method == 'GET' && !request.url.path.contains('.')) { - // SPA fallback: routes without a file extension get index.html. + // SPA fallback: routes without a file extension get index.html — + // no-cache, like the real file, so deploys reach open tabs. final indexFile = File(p.join(directory.path, 'index.html')); if (await indexFile.exists()) { return Response.ok( await indexFile.readAsString(), - headers: {'content-type': 'text/html; charset=utf-8'}, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': _kNoCacheControl, + }, ); } + return response; + } + if (response.statusCode == 200) { + // index.html is revalidated every navigation; everything else in the + // build is content-hashed (or a stable font) and immutable. + // (shelf_router strips the `/` mount prefix, so the handler sees + // `index.html` / `` rather than `/index.html` / `/`.) + final path = request.url.path; + final isIndex = + path.isEmpty || path == '/' || path.endsWith('index.html'); + return response.change( + headers: { + 'cache-control': isIndex ? _kNoCacheControl : _kImmutableCacheControl, + }, + ); } return response; }; diff --git a/server/tool/perf_measure.dart b/server/tool/perf_measure.dart new file mode 100644 index 0000000..98c5adb --- /dev/null +++ b/server/tool/perf_measure.dart @@ -0,0 +1,312 @@ +// Performance probe (PLAN.md Phase 7 "Performance"). +// +// Boots the real server on a free port with a temp saves dir, connects N +// WebSocket clients (a full table, each a distinct session), plays a +// realistic round, and reports: +// +// * the state payload size at full-table scale (the largest +// `update`/`welcome` frame, and the raw `state` JSON inside it) +// * WS fan-out: bytes delivered to ALL connections per executed action +// * total traffic per connection over the whole round +// +// Run from `server/`: +// +// ```sh +// dart run tool/perf_measure.dart # 6 clients +// dart run tool/perf_measure.dart --clients 8 +// ``` +// +// This is a measurement tool, not part of the product or the test suite. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +Future main(List args) async { + var clients = 6; + for (var i = 0; i < args.length; i++) { + if (args[i] == '--clients' && i + 1 < args.length) { + clients = int.parse(args[i + 1]); + } + } + + final port = await _freePort(); + final savesDir = Directory.systemTemp.createTempSync('xhaven-perf-').path; + final server = await Process.start( + 'dart', + ['run', 'bin/main.dart', '--port=$port', '--saves-dir=$savesDir'], + ); + server.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(stdout.write); + server.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen((l) => stderr.writeln('[server] $l')); + + try { + await _waitForHttp('http://127.0.0.1:$port/healthz', 90_000); + await _run(port, clients); + } finally { + server.kill(ProcessSignal.sigkill); + unawaited(server.exitCode + .timeout(const Duration(seconds: 3), onTimeout: () => -1)); + Directory(savesDir).deleteSync(recursive: true); + } + // The measurement is printed; exit regardless of lingering sockets. + exit(0); +} + +Future _run(int port, int clients) async { + // Jaws of the Lion has exactly these four classes, and the reference app + // (and ours) forbids duplicate regular classes, so a JoL table has at most + // four player characters. Extra connections are spectators — which is + // exactly the fan-out we want to measure. + final names = ['Hatchet', 'Demolitionist', 'Red Guard', 'Voidwarden']; + final players = min(clients, names.length); + + final all = <_Client>[]; + for (var i = 0; i < clients; i++) { + final c = _Client(i); + await c.connect('ws://127.0.0.1:$port/ws'); + all.add(c); + } + await Future.delayed(const Duration(milliseconds: 200)); + + // --- setup ---------------------------------------------------------------- + // Every client adds its own character (the onboarding path; each session + // becomes a player). + await _action( + all, + 'setup: $players players add characters', + (i) => i < players + ? all[i].cmd('addCharacter', { + 'id': names[i], + 'edition': 'Jaws of the Lion', + 'level': 1 + }) + : null); + + await _action(all, 'set scenario', + (i) => i == 0 + ? all[0].cmd('setScenario', { + 'scenario': '#1 Roadside Ambush', + 'section': false + }) + : null); + + final monsters = [ + 'Zealot', + 'Vermling Raider', + 'Black Sludge', + 'Rat Monstrosity', + 'Blood Imp', + 'Blood Monstrosity', + 'Chaos Demon', + 'Blood Tumor', + 'Blood Horror', + 'First of the Order' + ]; + for (var m = 0; m < monsters.length; m++) { + await _action( + all, + 'add monster ${m + 1}/${monsters.length}', + (i) => i == 0 + ? all[0].cmd('addMonster', {'name': monsters[m], 'isAlly': false}) + : null); + } + + // --- three full rounds ------------------------------------------------------- + for (var round = 1; round <= 3; round++) { + for (var i = 0; i < players; i++) { + await _action( + all, + 'round $round: player $i sets initiative', + (j) => j == i + ? all[j] + .cmd('setInit', {'characterId': all[j].myCharacterId!, 'init': i + 1}) + : null); + } + await _action(all, 'round $round: draw', + (i) => i == 0 ? all[0].cmd('draw', {}) : null); + for (var i = 0; i < players; i++) { + await _action( + all, + 'round $round: player $i ends turn', + (j) => + j == i ? all[j].cmd('turnDone', {'id': all[j].myCharacterId!}) : null); + } + if (round < 3) { + await _action(all, 'round $round: next round', + (i) => i == 0 ? all[0].cmd('nextRound', {}) : null); + } + } + + await Future.delayed(const Duration(milliseconds: 300)); + + // --- summary ----------------------------------------------------------------- + var maxFrame = 0; + var maxState = 0; + for (final c in all) { + maxFrame = max(maxFrame, c.largestFrameBytes); + maxState = max(maxState, c.lastStateBytes); + } + stdout + ..writeln('') + ..writeln('--- summary ($clients connected clients) ---') + ..writeln(''); + for (final c in all) { + stdout.writeln( + 'client ${c.id}: ${_kb(c.totalReceived)} total ' + 'over ${c.frames} frames ' + '(largest frame ${(c.largestFrameBytes / 1024).toStringAsFixed(1)} kB)'); + } + stdout + ..writeln('') + ..writeln('state JSON at full-table scale: ${_kb(maxState)}') + ..writeln('largest update frame (envelope + state): ${_kb(maxFrame)}') + ..writeln('') + ..writeln('fan-out per executed action: ' + '${_kb(maxFrame)} x $clients = ${_kb(maxFrame * clients)}') + ..writeln('') + ..writeln( + 'note: the full-snapshot protocol trades bandwidth for simplicity — ' + 'every action re-sends the whole state to every connection, so the ' + 'per-action cost is O(state size x connections).'); + // Best-effort teardown; a slow close must not wedge the probe. + for (final c in all) { + unawaited(c.close().timeout(const Duration(seconds: 2), onTimeout: () {})); + } +} + +/// Runs [fn(i)] (one client's command, or null) and resolves when every +/// client has observed the resulting update. Waiters are registered BEFORE +/// the command is sent, so no update can be missed. +Future _action( + List<_Client> all, + String label, + Future? Function(int i) fn, +) async { + final waits = all.map((c) => c.nextUpdate()).toList(); + for (var i = 0; i < all.length; i++) { + await fn(i); // null for the non-senders + } + final sw = Stopwatch()..start(); + await Future.wait(waits).timeout( + const Duration(seconds: 20), + onTimeout: () => + throw TimeoutException('$label: the update never arrived — the ' + 'command was probably rejected (see error output above)')); + stdout.writeln( + '${label.padRight(42)} ' + '${(sw.elapsedMilliseconds / 1000).toStringAsFixed(2)} s wall clock'); +} + +/// One WS client that counts every frame it receives. +class _Client { + final int id; + WebSocket? _ws; + var totalReceived = 0; + var frames = 0; + var largestFrameBytes = 0; + var lastStateBytes = 0; + String? myCharacterId; + final List> _frameWaiters = []; + + _Client(this.id); + + Future connect(String url) async { + final socket = await WebSocket.connect(url); + _ws = socket; + socket.listen(_onData, onError: (Object e) => stderr.writeln('[c$id] $e')); + await _send({'t': 'hello', 'v': 1}); + await nextUpdate().timeout(const Duration(seconds: 20)); // the welcome + } + + void _onData(Object? data) { + final text = data is String ? data : utf8.decode(data as List); + totalReceived += text.length; + frames++; + largestFrameBytes = max(largestFrameBytes, text.length); + final Map msg; + try { + msg = jsonDecode(text) as Map; + } catch (_) { + return; // ignore non-JSON frames + } + if (msg['t'] == 'error') { + stderr.writeln('[c$id] error: ${msg['message']}'); + } + if (msg['t'] == 'welcome' || msg['t'] == 'update') { + // The full state travels as a JSON object under `state`. + final state = msg['state']; + if (state is Map) { + lastStateBytes = jsonEncode(state).length; + myCharacterId ??= _firstCharacterId(state); + } + if (_frameWaiters.isNotEmpty) { + _frameWaiters.removeAt(0).complete(); + } + } + } + + /// Resolves on the next state-carrying frame (welcome/update). + Future nextUpdate() { + final completer = Completer(); + _frameWaiters.add(completer); + return completer.future; + } + + Future _send(Map message) async { + final s = _ws; + if (s == null) throw StateError('not connected'); + s.add(jsonEncode(message)); + } + + Future cmd(String name, Map args) async { + await _send({'t': 'cmd', 'name': name, 'args': args}); + } + + Future close() async { + await _ws?.close(); + } +} + +String? _firstCharacterId(Map state) { + final list = state['currentList'] as List?; + for (final e in list ?? []) { + final item = e as Map?; + if (item != null && item['characterClass'] != null) { + return item['id'] as String?; + } + } + return null; +} + +String _kb(int bytes) => '${(bytes / 1024).toStringAsFixed(1)} kB'; + +Future _freePort() async { + final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = s.port; + await s.close(); + return port; +} + +Future _waitForHttp(String url, int timeoutMs) async { + final deadline = DateTime.now().add(Duration(milliseconds: timeoutMs)); + while (DateTime.now().isBefore(deadline)) { + try { + final client = HttpClient(); + final req = await client.getUrl(Uri.parse(url)) + .timeout(const Duration(seconds: 2)); + final resp = await req.close(); + final code = resp.statusCode; + client.close(); + if (code == 200) return; + } catch (_) {} + await Future.delayed(const Duration(milliseconds: 250)); + } + throw TimeoutException('server did not start: $url'); +} diff --git a/web/src/App.svelte b/web/src/App.svelte index bdeb998..814a47a 100644 --- a/web/src/App.svelte +++ b/web/src/App.svelte @@ -13,6 +13,7 @@ import { onMount, onDestroy } from 'svelte'; import { get } from 'svelte/store'; import { GameSession } from '$lib/state/session'; + import { establishSessionCookie } from '$lib/protocol/session'; import { clientSettings, styleTheme } from '$lib/settings'; import { gameData, type CampaignData, type MonsterData } from '$lib/data/gameData'; import { @@ -57,7 +58,12 @@ const session = new GameSession(); - onMount(() => session.connect()); + // Establish the persistent session cookie before the WS connects, so the + // upgrade carries it and the seat survives reloads and server restarts. + onMount(async () => { + await establishSessionCookie(); + session.connect(); + }); onDestroy(() => session.disconnect()); const gameState = session.state; diff --git a/web/src/app.css b/web/src/app.css index 8f3ad54..e66b09e 100644 --- a/web/src/app.css +++ b/web/src/app.css @@ -254,6 +254,11 @@ button { display: flex; align-items: center; width: 100%; + /* A definite height so the row's full-height children (the art block and + the right-hand initiative/turn-done tap zone) resolve `height: 100%` + to something clickable — with an auto height the tap zone collapsed + to 0px and could never be tapped. */ + height: 100%; } .row__art { diff --git a/web/src/lib/protocol/connection.ts b/web/src/lib/protocol/connection.ts index a553481..cbf86f5 100644 --- a/web/src/lib/protocol/connection.ts +++ b/web/src/lib/protocol/connection.ts @@ -47,7 +47,8 @@ export interface Transport { onmessage: ((ev: { data: unknown }) => void) | null; send(data: string): void; close(): void; - readyState: number; // 0 OPEN + /** `WebSocket.OPEN` — 1. (0 is CONNECTING; 2 CLOSING; 3 CLOSED.) */ + readyState: number; } export interface ConnectionOptions { @@ -62,7 +63,8 @@ export interface ConnectionOptions { pingIntervalMs?: number; } -const OPEN = 0; +/** `WebSocket.OPEN` — the socket is connected and can carry frames. */ +const OPEN = 1; export class GameConnection { status: ConnectionStatus = 'connecting'; diff --git a/web/src/lib/protocol/session.ts b/web/src/lib/protocol/session.ts new file mode 100644 index 0000000..1025288 --- /dev/null +++ b/web/src/lib/protocol/session.ts @@ -0,0 +1,25 @@ +/** + * Establish the persistent session cookie (PLAN.md section 3.3) before the + * game WebSocket connects. + * + * The `/session` endpoint mints a session id on the first call and sets the + * `x-haven-session` cookie (HttpOnly). The browser then carries it on every + * same-origin request — including the `/ws` upgrade — so a player keeps the + * same session id across page reloads *and* server restarts. That is what + * lets the server's restored seats (persisted and keyed by session id) land + * back on the right player after a crash; without the cookie the upgrade + * would mint a fresh session and the restored seat would be orphaned. + * + * The id also arrives in the `welcome` message, but that is too late to seed + * the cookie the upgrade depends on — hence this explicit bootstrap call. + */ +export async function establishSessionCookie(): Promise { + try { + // `same-origin` credentials send/receive the cookie; the response + // sets it if the browser has none yet, and is a no-op set otherwise. + await fetch('/session', { credentials: 'same-origin' }); + } catch { + // Offline or blocked: the WS upgrade will still (re)mint a session; + // the tab just starts as a fresh session instead of a restored one. + } +} diff --git a/web/src/lib/ui/CharacterRow.svelte b/web/src/lib/ui/CharacterRow.svelte index 043c225..b4f9b48 100644 --- a/web/src/lib/ui/CharacterRow.svelte +++ b/web/src/lib/ui/CharacterRow.svelte @@ -73,6 +73,16 @@ let initInput = $state(null); let initDraft = $state(''); + // Seed the editable field from (re)synced state so a reload or reconnect + // doesn't blank an entry we already made. Skip while the field is focused + // (clicking it clears it for re-entry) so we never clobber a live edit. + $effect(() => { + const v = cs.initiative; + if (v == null || v <= 0) return; + if (initInput && document.activeElement === initInput) return; + if (String(v) !== initDraft) initDraft = String(v); + }); + // `??` for a value masked by the server; the revealed number otherwise. const initDisplay = $derived( cs.initiative === null ? '??' : cs.initiative > 0 ? String(cs.initiative) : '' @@ -223,11 +233,13 @@ }} > - -{#if unclaimed} - -{/if} + + {#if unclaimed} + + {/if} + diff --git a/web/src/lib/ui/decks/AbilityCardsMenu.svelte b/web/src/lib/ui/decks/AbilityCardsMenu.svelte index 0cf416c..d1aae99 100644 --- a/web/src/lib/ui/decks/AbilityCardsMenu.svelte +++ b/web/src/lib/ui/decks/AbilityCardsMenu.svelte @@ -211,6 +211,11 @@ {#if removeTarget} {@const rt = removeTarget} {@const card = fullCard(rt)} + + {@const inDrawPile = deck.drawPile.some((r) => r.nr === rt.nr)} + {@const drawPileIndex = deck.drawPile.findIndex((r) => r.nr === rt.nr)} {/if} diff --git a/web/src/lib/ui/menus/AddCharacterMenu.svelte b/web/src/lib/ui/menus/AddCharacterMenu.svelte index 8383f13..06a24f8 100644 --- a/web/src/lib/ui/menus/AddCharacterMenu.svelte +++ b/web/src/lib/ui/menus/AddCharacterMenu.svelte @@ -7,6 +7,7 @@ @@ -74,9 +113,9 @@
{t('web:level')} - + {level} - +
{#if campaignData === null} @@ -87,7 +126,7 @@