diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
| commit | 93970f361b831f17d48ff2a345fc78488ac71fba (patch) | |
| tree | f3844cc343c95dcc19a1444bdb6666e807bc59ef /web | |
| parent | b884441ba0d10bdd3559748507a0991888f66194 (diff) | |
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.
Diffstat (limited to 'web')
| -rw-r--r-- | web/src/App.svelte | 8 | ||||
| -rw-r--r-- | web/src/app.css | 5 | ||||
| -rw-r--r-- | web/src/lib/protocol/connection.ts | 6 | ||||
| -rw-r--r-- | web/src/lib/protocol/session.ts | 25 | ||||
| -rw-r--r-- | web/src/lib/ui/CharacterRow.svelte | 20 | ||||
| -rw-r--r-- | web/src/lib/ui/StatusMenu.svelte | 106 | ||||
| -rw-r--r-- | web/src/lib/ui/decks/AbilityCardsMenu.svelte | 29 | ||||
| -rw-r--r-- | web/src/lib/ui/menus/AddCharacterMenu.svelte | 51 | ||||
| -rw-r--r-- | web/test/connection.test.ts | 16 | ||||
| -rw-r--r-- | web/test/fake-socket.ts | 7 | ||||
| -rw-r--r-- | web/vite.config.ts | 3 |
11 files changed, 260 insertions, 16 deletions
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<void> { + 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<HTMLInputElement | null>(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 @@ }} ></div> </div> -</div> -{#if unclaimed} - <button class="chip chip--claim" onclick={() => session.claim(item.id)}>Claim</button> -{/if} + <!-- The claim chip anchors to the row (position:relative) so it sits in + the row's corner; kept inside `.row` so it moves with it. --> + {#if unclaimed} + <button class="chip chip--claim" onclick={() => session.claim(item.id)}>Claim</button> + {/if} +</div> <style> /* The summon standees sit above the row, like the reference. */ diff --git a/web/src/lib/ui/StatusMenu.svelte b/web/src/lib/ui/StatusMenu.svelte index eb1090a..b14e2b0 100644 --- a/web/src/lib/ui/StatusMenu.svelte +++ b/web/src/lib/ui/StatusMenu.svelte @@ -203,6 +203,49 @@ function presetLinkTarget(): string { return figure.ownerId ?? figure.figureId; } + + // --- Character level + name (the reference `SetCharacterLevelMenu`) ------ + + /** The character's class model (its per-level health bounds the level range). */ + const charClass = $derived.by(() => { + if (figure.kind !== 'character' || !liveCharacter || !campaignData) + return null; + return ( + campaignData.classes.find( + (c) => + c.id === liveCharacter.characterClass || + c.name === liveCharacter.characterClass + ) ?? null + ); + }); + + const maxLevel = $derived(charClass?.health.length ?? 9); + const currentLevel = $derived(liveCharacter?.characterState.level ?? 1); + + function setLevel(nr: number) { + if (nr === currentLevel) return; + cmd('setCharacterLevel', { level: nr, characterId: figure.figureId }); + } + + // The name field mirrors the server's display, resetting only when the + // display itself changes (so a live edit is never clobbered by an + // unrelated state update). + let nameDraft = $state(''); + let lastSeenDisplay = $state(''); + $effect(() => { + const display = liveCharacter?.characterState.display ?? ''; + if (display !== lastSeenDisplay) { + lastSeenDisplay = display; + nameDraft = display; + } + }); + + function submitName() { + const name = nameDraft.trim(); + if (name && name !== liveCharacter?.characterState.display) { + cmd('changeName', { name, characterId: figure.figureId }); + } + } </script> <Menu open={open} title={figure.title}> @@ -230,6 +273,35 @@ </div> {/if} + <!-- Level + name (the reference `SetCharacterLevelMenu`); characters only. --> + {#if figure.kind === 'character' && !figure.isObjective && liveCharacter} + <div class="statrow statrow--wrap"> + <span class="statrow__label">{t('web:level')}</span> + <div class="levelbtns"> + {#each Array(maxLevel) as _, i} + <button + class="pill" + class:pill--on={i + 1 === currentLevel} + disabled={!canAct || i + 1 === currentLevel} + onclick={() => setLevel(i + 1)} + >{i + 1}</button> + {/each} + </div> + </div> + <div class="statrow"> + <span class="statrow__label">{t('changeName')}</span> + <input + class="search" + style="margin: 0; width: auto; flex: 1" + value={nameDraft} + oninput={(e) => (nameDraft = e.currentTarget.value)} + onkeydown={(e) => { + if (e.key === 'Enter') submitName(); + }} + /> + </div> + {/if} + {#if counters} <div class="statrow"> <span class="statrow__label">{t('cmdAddBless')}</span> @@ -340,3 +412,37 @@ bind:open={noteOpen} /> {/if} + +<style> + .statrow--wrap { + flex-wrap: wrap; + } + .levelbtns { + display: flex; + flex-wrap: wrap; + gap: 4px; + flex: 1; + justify-content: flex-end; + } + .pill { + min-width: 26px; + padding: 3px 6px; + font-size: 13px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + } + .pill:hover { + background: rgba(255, 255, 255, 0.25); + } + .pill--on { + background: #2196f3; + color: #fff; + } + .pill:disabled { + opacity: 0.4; + cursor: default; + } +</style> 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)} + <!-- Only draw-pile (undrawn) cards can be sent to the bottom or have + their pile re-shuffled (the reference `RemoveCardMenu`); the wire + draw pile is bottom-first, so the bottom is index 0. --> + {@const inDrawPile = deck.drawPile.some((r) => r.nr === rt.nr)} + {@const drawPileIndex = deck.drawPile.findIndex((r) => r.nr === rt.nr)} <div class="confirm" role="dialog" aria-modal="true"> {#if card != null} <MonsterAbilityCard @@ -231,6 +236,30 @@ > {t('removeCardQuestion')} </button> + {#if inDrawPile} + <button + class="pill pill--text" + onclick={() => { + cmd('reorderAbilityList', { + deck: rt.deck, + oldIndex: drawPileIndex, + newIndex: 0 + }); + removeTarget = null; + }} + > + {t('sendToBottom')} + </button> + <button + class="pill pill--text" + onclick={() => { + cmd('shuffleDrawnAbilityCard', { deck: rt.deck }); + removeTarget = null; + }} + > + {t('shuffleUndrawnCards')} + </button> + {/if} </div> </div> {/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 @@ <script lang="ts"> import type { GameSession } from '$lib/state/session'; import { gameData, type ClassData } from '$lib/data/gameData'; + import { isObjectiveOrEscort } from '$lib/data/classInfo'; import { classColor, classIcon } from '$lib/game/art'; import { t } from '$lib/i18n'; import Menu from '../Menu.svelte'; @@ -21,7 +22,6 @@ } = $props(); const gameState = session.state; - const player = session.player; let campaignData = $state<ClassData[] | null>(null); let search = $state(''); @@ -57,11 +57,50 @@ (campaignData ?? []).filter((c) => !c.hidden || q.includes(c.name.toLowerCase())) ); + // The character items in the current list (their `characterClass` is the + // class id — the same key the reference's `_characterAlreadyAdded` + // compares on). + const existingClasses = $derived.by(() => { + const set = new Set<string>(); + for (const item of $gameState?.currentList ?? []) { + if ('characterClass' in item) set.add(item.characterClass); + } + return set; + }); + + /** + * The reference disables a class once it has been added — except + * Objective/Escort, which may be added repeatedly under a numbered + * display name. + */ + function alreadyAdded(cls: ClassData): boolean { + if (isObjectiveOrEscort(cls.name)) return false; + return existingClasses.has(cls.id); + } + + /** The reference's display numbering for a repeated objective/escort. */ + function objectiveDisplay(cls: ClassData): string | null { + if (!isObjectiveOrEscort(cls.name)) return null; + let count = 1; + for (const item of $gameState?.currentList ?? []) { + if ('characterClass' in item && item.characterClass === cls.name) count++; + } + return count > 1 ? `${cls.name} ${count}` : null; + } + let charsOpen = $state(false); + // No player gate: the server lets a spectator add a character, and the + // adding session owns it — this is how a fresh session becomes a player + // on an empty table (PLAN.md section 3.3). function pick(cls: ClassData) { - if (!$player) return; - session.command('addCharacter', { id: cls.id, edition: cls.edition, level }); + const display = objectiveDisplay(cls); + session.command('addCharacter', { + id: cls.id, + edition: cls.edition, + level, + ...(display != null ? { display } : {}) + }); open = false; } </script> @@ -74,9 +113,9 @@ <div class="statrow"> <span class="statrow__label">{t('web:level')}</span> - <button class="stepbtn" disabled={!$player || level <= 1} onclick={() => (level -= 1)}>−</button> + <button class="stepbtn" disabled={level <= 1} onclick={() => (level -= 1)}>−</button> <span class="statrow__value">{level}</span> - <button class="stepbtn" disabled={!$player || level >= 10} onclick={() => (level += 1)}>+</button> + <button class="stepbtn" disabled={level >= 10} onclick={() => (level += 1)}>+</button> </div> {#if campaignData === null} @@ -87,7 +126,7 @@ <ul class="menulist"> {#each classes as cls (cls.id)} <li> - <button class="menulist__item" disabled={!$player} onclick={() => pick(cls)}> + <button class="menulist__item" disabled={alreadyAdded(cls)} onclick={() => pick(cls)}> <img src={classIcon(cls.name)} alt="" loading="lazy" style="background: {classColor(cls.color)}" /> {cls.name} </button> diff --git a/web/test/connection.test.ts b/web/test/connection.test.ts index 27958ba..3426881 100644 --- a/web/test/connection.test.ts +++ b/web/test/connection.test.ts @@ -53,6 +53,22 @@ describe('GameConnection', () => { expect(statuses).toContain('open'); }); + // Regression: the open gate must compare against the real + // `WebSocket.OPEN` readyState (1). A wrong constant (e.g. 0 = CONNECTING) + // silently dropped every outbound frame — hello, ping, and every command + // — because the readyState check never matched, while the unit tests + // passed only because the fake mirrored the same wrong constant. + it('sends frames only when readyState is the real WebSocket.OPEN (1)', () => { + conn.connect(); + const socket = sockets.current; + // Before open the socket is CONNECTING (0): nothing may be sent. + expect(socket.sent).toHaveLength(0); + expect(socket.readyState).toBe(0); + socket.open(); // → OPEN (1) + expect(socket.readyState).toBe(1); + expect(socket.lastJson()).toEqual({ t: 'hello', v: 1 }); + }); + it('forwards update, seats, and error to their handlers', () => { const messages: string[] = []; let errorMessage: string | null = null; diff --git a/web/test/fake-socket.ts b/web/test/fake-socket.ts index 290f9a8..61208e4 100644 --- a/web/test/fake-socket.ts +++ b/web/test/fake-socket.ts @@ -9,13 +9,14 @@ export class FakeSocket implements Transport { onclose: ((ev?: unknown) => void) | null = null; onerror: ((ev?: unknown) => void) | null = null; onmessage: ((ev: { data: unknown }) => void) | null = null; - readyState = 1; // CONNECTING + // Real WebSocket readyState: 0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED. + readyState = 0; // CONNECTING readonly sent: string[] = []; closed = false; send(data: string): void { - if (this.readyState !== 0) throw new Error('not open'); + if (this.readyState !== 1) throw new Error('not open'); this.sent.push(data); } @@ -29,7 +30,7 @@ export class FakeSocket implements Transport { // test drivers -------------------------------------------------------- open(): void { - this.readyState = 0; + this.readyState = 1; // OPEN this.onopen?.(); } diff --git a/web/vite.config.ts b/web/vite.config.ts index 772ea4c..87e256f 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -25,6 +25,9 @@ export default defineConfig({ // production (where the Dart server serves the built app too). '/data': 'http://localhost:4567', '/images': 'http://localhost:4567', + // The session endpoint mints/returns the `x-haven-session` cookie + // that the `/ws` upgrade relies on (seat persistence). + '/session': 'http://localhost:4567', }, }, test: { |
