Author SHA1 Message Date
SirStone 54f2a1e37a docs: freeze project (see docs/FROZEN.md) 2026-11-22 10:09:40 +01:00
SirStone fda83621f3 fix(server): broadcast roster on plain connect and close (#88)
A reconnect with an existing name fires no intent, so the only roster the
GM saw was the connecting connection's own resync; the row stayed offline
while the player badge said Connected.

Send the GM roster when a connection activates (skipping the connecting
connection, which already got it in the 6.3 resync) and after a close, with
the registry entry removed first so connected is recomputed. Also cover the
server-initiated malformed-flood close. The setname ack-before-resync
ordering is unchanged.

Tests: WS connect/close/reconnect roster states; e2e GM row follows a
player tab reload and close. protocol test updated for the extra roster on
a second connection.
2026-11-21 23:44:51 +01:00
SirStone b938e6f256 fix(client): read walls snapshot with the frame scene (#87)
The snapshot is {t:'walls', scene, walls:[{id, a, b, ...}]} per DESIGN 6.1:
scene lives on the frame, entries carry only the wall record. The client
required scene on each entry and dropped every snapshot wall, so a GM
reload/reconnect showed canvas.dataset.walls==='0' while the server still
blocked player sight.

Pass the enclosing frame's scene into wallViewFromFrame and keep an entry's
own scene as the tolerant fallback. The server already matched DESIGN, so
no wall wire shape changed.

Tests: client reducer from a real snapshot frame, WS pin that a snapshot
entry equals a wall delta record, and e2e reload plus server-restart.
The old e2e missed it because every wall test built walls in-session.
2026-11-21 23:44:37 +01:00
SirStone 7379d450d5 results: M4 UX gate on the fixed tree (#89) 2026-11-21 23:44:26 +01:00
SirStone e2295aa416 fix(client): usable GM column and phone HUD (#89) 2026-11-21 23:39:09 +01:00
SirStone f170b9c91a test(e2e): print combined total across serial and parallel groups 2026-11-21 22:57:21 +01:00
SirStone a79d809394 feat(m4): cap map images at Full HD and shrink on import (#85)
The owner fixed the map cap at 1920 px on the long side and 1080 px on the
short side (either orientation). fff-vtt import now shrinks a larger source
with ImageMagick Lanczos before tiling (alpha kept, proportions preserved,
no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a
source at or below the cap is untouched, so the pixel-identity tests still
hold. A scene row already above the cap is not rewritten: the server logs
`map_above_cap` at startup and serve prints the re-import advice.

Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README,
HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement
now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows
stay as labelled server stress references. import-scale now proves a 16384²
input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded.

Part of #63, #85. #77 is blocked by this issue.
2026-11-21 22:37:34 +01:00
SirStone 52ab50d765 fix(client): tile loading: centre-out, one request per tile, 404 recovery (#86)
The GM survey view asked row-major, at most 8 at a time, rebuilt the whole
wanted window on every settle, and paid two requests for every failed tile
(image error, then a fetch to learn the status). A 404/5xx was stored as
permanent `denied`, so a tile imported after page load stayed black until a
page reload, and `viewport.setScene` swallowed a same-id art_version change
so the old textures were never dropped.

- TILE_CONCURRENCY 8 -> 32, the measured knee on a Full HD scene (min-of-3
  headless: GM fit + player 0.5, tile 32/64; 64 is inside the noise).
- orderTilesCentreOut: nearest the viewport centre first.
- Settle path is incremental (one settle = one tile sprite/flag update);
  the window is rebuilt only on camera/scene changes.
- fetch + createImageBitmap: status from the same response, decode off the
  main thread, so a failure costs one request.
- 403 stays permanent (retried only on fog.fresh); 404/5xx/network retry
  with 250/500 ms backoff up to 3 loads, and `hello`/reconnect or a
  scene/art_version change resets the budget. A failure that lands after a
  reconnect is a fresh first attempt; a failure that leaves the window does
  not spend the budget.
- setScene emits for a same-id scene; a new art_version drops the texture
  cache and reschedules. Tiles are `Cache-Control: private, max-age=1y,
  immutable` (still gated), so a reload reuses them; DESIGN 3.3/11.1 and
  client/README updated.

Tests: vitest for ordering, incremental invariants, retry budget/backoff,
reconnect epoch and art_version invalidation; e2e for a GM survey fill (one
request per succeeded tile) and a 404 tile recovering after the file appears
and a real reconnect. Before -> after (min-of-3, saturated host, Full HD):
GM fit 32px 910->843 ms, player 0.5 32px 972->862 ms, GM fit 64px
320->249 ms, player 0.5 64px 332->368 ms (noise).

Part of #63. Blocks #77.
2026-11-21 22:28:18 +01:00
SirStone 54dbd68587 docs: final mutation time 2026-11-21 22:21:13 +01:00
SirStone 9f5e0fc58a docs: final wall-time numbers (172 node tests, e2e on a shared host) 2026-11-21 22:09:52 +01:00
SirStone 297718efdb test(e2e): count distinct tile URLs, tolerate transient image errors
The mobile map gate compared the cumulative request counter to the wanted
window, but the #70 rule re-asks a tile whose 403 became allowed when the
explored frame lands after the first window, so a correct load can be 481
attempts for a 480-tile window (seen once on a loaded host). Expose
data-tile-distinct and assert that no tile URL is fetched twice; the no-retry
proof stays the 403 test's per-URL count. The console collector now ignores the
browser's network-level resource line, like the fog suites: a transient tile
error is explicitly tolerated by the tile contract, and the page wait already
reflects it.
2026-11-21 22:09:42 +01:00
SirStone 100df38230 test: wait for the async log line instead of racing it
Under the fan-out a test that greps server.log right after an ack can lose:
the logger writes the line after the ack. waitForLog polls to a deadline and
the assertions are unchanged (the line must still appear; absence checks still
run on the same snapshot). Fixes the one observed assertion failure
(fault.test.mjs's intent_failed line) and the same latent race in the
opaque_refused and startup-line checks.
2026-11-21 21:42:34 +01:00
SirStone 514104f897 docs: record test wall times and the parallelism knob
Adds the warmed/cold table for test/client-test/e2e, the pre-push total,
mutation and bench, the machine/commit note and the FFF_TEST_JOBS /
FFF_E2E_JOBS overrides. TESTING explains what makes the fan-out safe (per-file
isolation, shared build cache, worktree-local nimcache, tmpfs state dirs) and
why the wall-clock gate files still run alone.
2026-11-21 21:42:34 +01:00
SirStone 1ac46b4969 test: fan out the gates and build shared binaries once
Every Nim test file and every Node test file is already isolated (own temp state
dir, free ports, own server/nginx), so run them FFF_TEST_JOBS at a time (default
half the cores, capped at 8) instead of one at a time. The real server (clean,
leakfault, dispfault) and the leak checker are built once per source+flags and
shared across the parallel files; nimcaches are worktree-local so two checkouts
cannot race on them. The 22 independent fault cases are sharded across
processes. The wall-clock gate files (persistence, tiles; e2e map/fog/fogbench/
perf) still run alone first so their budgets are not measured under the suite's
own load. No test or assertion changes.
2026-11-21 21:40:07 +01:00
SirStone 30b35592c7 fix: forward -- args through devbox scripts, fail serve loudly (#84)
devbox 0.17.2 runs .devbox/gen/scripts/<name>.sh with the args as positional
parameters but does not append "$@", so tools/serve.sh (and seed, bench,
mutation, import-scale, fogbench) saw an empty argv and a documented
`serve -- --image=...` silently served the default 4096 scene. End every
argument-taking script body with "$@".

serve: --dry-run parses and prints the options without building; unknown
options, non-numeric ports/tile sizes and --tile-size without --image fail
loudly; a no-image start prints the current map read from state.db; NixOS
gets security.pki.certificateFiles instead of the Debian trust steps.

Guard the faults import in worldmap/vision/markers with
`when defined(leakfault)` (it is only used inside those blocks), removing
the three UnusedImport warnings; leakfault builds still compile.

tools/devboxargs.test.mjs goes through `devbox run <script> -- <args>` for
serve (dry-run, unknown flag, tile-size without image) and seed (--help,
unknown flag), the seam the direct-tool tests missed.
2026-11-21 21:35:39 +01:00
SirStone c8b5289a3d fix: stream map import so 16384 px at 64 px is memory- and fd-bounded (#83)
The one-shot `magick -crop 64x64 +adjoin` built an image list of all 65,536 tiles; ImageMagick's
memory/map limits are per image, so the attempt held 4.3 GB of source cache plus every tile cache and
died after minutes with "Too many open files" at 1023 fds, having published nothing.

Slice by streaming instead: one disk-cache-backed decode of the source to raw samples, the CLI reads
it one tile row at a time, and a pool of 8 magick children cuts one row band each. Live caches and
fds are bounded by the worker count, never by the tile count. Progress goes to stderr ("rows 37/256,
tiles 9472/65536") and failures quote the image, row band and magick's own message. Atomicity is
unchanged: temp dir then rename, scene row only on success, same lock and exit codes.

Measured on the owner's 16384x16384 map at 64 px: 19 s, 391 MB peak RSS, 10 fds, 65,536 tiles (was
~5 min then failure). The tile pixels are identical to the old crop (proven tile by tile in
tools/import.test.mjs); PNG bytes can differ because the encoder now sees raw samples.

New gate: devbox run import-scale (16384/64 under ulimit -n 256) writes results/import-scale.log;
devbox run test keeps the fast fixtures and skips it.
2026-11-21 20:48:45 +01:00
SirStone b56d645b3a docs: M4 built, acceptance pending playtest #77 2026-11-21 18:22:36 +01:00
SirStone 9c05bb1f46 fix(client): make data-tiles ready when the pass completes
A transient tile load error is terminal for the current window (retried only on
a new window or a reconnect), but data-tiles treated it as never settled, so one
host hiccup left it at 'loading' forever and every e2e readiness wait hung
(audit.test.mjs timed out under a parallel lane). TileScheduler.isPending() now
reports loading only for queued/in-flight tiles; ready means the pass is done.
Proven by aborting one tile request: the wait timed out before, passes after.
Unit-tested at the scheduler seam.
2026-11-21 18:19:47 +01:00
SirStone ac5a6ac8dc test: deflake map fill gate and wall-locked under load
Map gate (a): measure the fastest of 4 fresh page loads after a warm-up (min-of-N,
TESTING 5.3) against 2x the 1 s DESIGN budget (the documented saturated-host
tolerance), and print every sample; a planted 50 ms/tile decode delay fails it.

Wall editor: an ack dispatch re-renders with the previous server record, and the
panel repopulated every control on every render, so a just-toggled checkbox was
reverted until the wall frame landed (Playwright saw 'did not change its state').
Repopulate only when the record changed (src/panels/wallSync.ts, unit-tested) and
restore the controls when the server refuses an edit.
2026-11-21 17:37:11 +01:00
SirStone 9c7f9de910 feat(m4): playtest friction: perf overlay, fresh import, token seed (#82)
Opt-in ?perf=1 overlay (fps, frame p50/p95, JS p50/p95, tokens, zoom; no node or ticker work when off). fff-vtt import creates and migrates a fresh/empty state dir through the shared server startup path; devbox run serve gains --image. devbox run seed creates deterministic labelled NPC tokens over the real WS (idempotent rerun, --replace), and the GM token form defaults X/Y to the viewport centre.
2026-11-21 17:20:05 +01:00
SirStone 356705823b feat(m4): LAN playtest run script (devbox run serve) (#80)
One command builds the client dist and server binary, then starts the
loopback server behind the DESIGN 11.1 TLS/HTTP2 nginx on the detected
LAN address. State, GM key and certificate persist under run/lan so a
table and a phone's trust survive Ctrl-C/restart; the certificate is
regenerated when the address changes. Prints the URL, GM key and
Android/laptop trust steps. tools/nginx.mjs and tools/tlsdev.mjs gained
the bind/SAN knobs the LAN needs (test defaults unchanged).
tools/serve.test.mjs proves h2 + verified TLS on /healthz and /, POST
/join, a /ws upgrade on the LAN address, loopback-only server binding,
and identical key/cert after a restart.
2026-11-21 16:33:57 +01:00
SirStone ad610abd65 feat(server): map import CLI, pulled forward to M4 (#79)
Slice a PNG/WebP map into the gate's <x>_<y>.png tree under
<state>/tiles/<scene>/v<art_version>/ and update the one scene row
(w, h, tile_size, art_version); a re-import grows art_version so
clients never serve stale tiles. The state-dir lock keeps a running
server out (it loads the scene at startup), so stop/import/restart.

Decoding is ImageMagick from the root devbox with a disk-backed
pixel cache (-limit memory/map), keeping a 16384 px source
memory-sane; no Nim/npm image dependency and the FIXED stack is
unchanged. The black-box harness covers the tile geometry, scene
row, restart pickup through the gate, re-import bump and every
refused-import case.

Records the M6 -> M4 move in DESIGN 3.3/11.1/13 and DESIGN-history,
and documents the CLI plus the 16384 px/50-token recipe in README.
2026-11-21 15:59:54 +01:00
SirStone bacf2e1412 feat(client): GM token panel sets vision and vision radius (#78)
Token create and edit now carry flags.vision and vision_radius; edits merge
only the vision key into the stored flags. A new token keeps DESIGN 8's
flags '{}' default (vision off, radius = scene default). The fog e2e authors
its sighted token through the GM panel, and the admin e2e proves the panel
round-trip plus an explored 200 / unexplored 403 tile probe.

Refs #78
2026-11-21 15:43:13 +01:00
SirStone fcd90529b6 test(m4): finish audit, measurement and archive (#76)
- client/e2e/audit.test.mjs: independent player-browser traffic audit (own
  frame catalogue and banned-key list, never leakcheck.nim), with a
  -d:leakfault/otherVision negative control.
- client/e2e/fogbench.test.mjs + tools/fogbench.nim: 50 tokens on a
  16384 px map (server move path and headless SwiftShader cadence);
  results/m4-fog-bench.md records both honestly (SW is not the phone gate).
- Archive prototype-* under docs/archive/prototypes (Q24); DESIGN 13 M4
  done, TESTING 13 M4 accept result, HANDOFF-M4 close-out.
- mutation.sh c1/c2 patch the post-#65 tile-gate line again (they had
  silently become sed no-ops).
2026-11-21 15:43:08 +01:00
SirStone fd711de152 docs: human README with usage and developer sections 2026-11-21 15:03:53 +01:00
SirStone 91a51c706d feat(client): GM wall editor, round-1 fields (#73)
Draw, select, edit and delete walls through the GM panel: the four 5.8
presets, raw switches (preset XOR raw, open excluded from wall.update), a
private label, the one-way arrow + flip (sight_dir names the blind side),
the player-marker switch, door open/close through door.set, secret/locked
with the locked hint and one-click unlock, delete and single-step undo.
No thickness, height or position-flip control (ADR-0012).

The pure rules and payload builders live in src/wallEditor.ts; the GM wall
slice (src/slices/walls.ts) owns the server records, selection and undo;
the render module draws on the gm layer and defines the input precedence:
token drag (#72) > armed wall draw > camera pan (#69), with a click (no
movement) selecting the nearest wall.

Shared core edits: client/src/reducer.ts gains the wall-select and
wall-record-undo events (the only new core events); style.css and the
client README document the panel and rules. Unit tests cover the slice,
presets, derived kind, arrow side, snapping, payload XOR, door intent and
undo builders; the e2e draws every preset, edits the fields, flips the
one-way wall, opens/closes a door, deletes and undoes, proves a token drag
still wins over draw mode, and probes the player's fog pixels, with the
player WS leaking no wall data.

Ref #73
2026-11-21 11:26:45 +01:00
SirStone 2d9548c941 feat(client): fog explored bitmap, vision cut-out and player markers (#70)
The fog layer (DESIGN 7.1 layer 4, spec #63 decision 9) keeps the explored
grid in one cell-resolution RGBA canvas: never-seen cells opaque black,
explored cells black at 0.6 alpha. A second canvas is the sprite texture:
the explored canvas is copied into it and the union of the server's vision
polygons is cut out with `destination-out`. A full explored snapshot
repaints; a cell diff mutates only the new bytes and uploads the dirty
rectangle. Player markers from the marker set/del frames are sprites above
the fog; the GM layer hides the fog.

The cut-out is baked instead of using a Graphics stencil mask: on the e2e's
software renderer the stencil state cost ~350 ms of the phone-class viewport
fill budget (412x869 dpr 2.625), while baking keeps the fill at the pre-fog
baseline. The cut-out is rasterized at cell resolution, the same grid the
server sends.

Integration fix in the tile layer: a tile denied with 403 because it was
unexplored is asked once more when the fog says its cells became explored;
unexplored denials still never retry (the map 403 test is unchanged).

Proven at the reducer seam (fog slice) and by screenshot pixel probes in the
browser e2e: black/dim/visible, window see-through, one-way blind side,
secret door, marker anchor and retraction, a drag that moves the fog with no
reload, and a reconnect resync. Fog update cost recorded under the 412x869
dpr 2.625 / 4x CPU emulation.
2026-11-21 10:44:32 +01:00
SirStone d225e956ca test(client): drag through the camera transform after #69
Rebase #72 onto the map/pan-zoom lane. Drag e2e now converts world points to
page points with the camera transform, drags at zoom 0.5 and 4, and proves a
token drag leaves the camera alone while an empty-canvas gesture still pans.
The camera publishes its x/y in `data-camera` for that (UI fact, like zoom).
Also folds #69's duplicate viewport import in tiles.ts into one.
2026-11-21 09:51:44 +01:00
SirStone c7d5e2cc69 feat(client): drag with prediction and rollback (#72)
Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release;
the sprite follows the pointer while authoritative frames are ignored for drawing.
Uniform move nacks roll back with a short tween (on release if still dragging),
rate-limited acks drop quietly, and pending reqIds die with the connection.

- slices/move.ts: pure drag/pending/ack state machine at the reducer seam
- render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins
  over pan/pinch (#69); sends via the new intents bridge
- tokens renderer draws the optimistic/confirmed position and tweens the rollback
- intents.ts + ws.send onReqId: one reqId-keyed sender for render modules
- e2e: drag persists after reload, wall refusal tween, GM move mid-drag,
  reconnect mid-drag dropping the pending map
2026-11-21 09:41:03 +01:00
SirStone 4534ed6426 feat(client): map tiles, grid and pan/zoom (#69)
T6 of spec #63. Tiles are requested only for the viewport plus one tile of
margin, in viewport order, at most 8 at a time (TileScheduler); decoded
textures are cached by URL so a reconnect refetches nothing; a 403/404 is
remembered as denied and never retried. The browser image loader is the hot
path, with one status fetch only to classify an error.

Camera: drag to pan, wheel/pinch to zoom around the pointer/midpoint; players
clamp at 0.5 (ADR-0013) and the GM has no player floor; both stop at 4.0.
Grid is one TilingSprite toggled by #grid-toggle. Camera is local UI state,
not a reducer slice, so hello/reconnect does not move the view.

Tests: viewport/tile unit tests (clamps, margin window, 8-wide queue, denial,
cache) and client/e2e/map.test.mjs (mobile viewport fill gate (a), grid,
pinch, cache across reconnect, GM zoom, 403 no-retry) against the real
server through TLS/h2. Tile-size gate (a) documented in client/README.md.
2026-11-21 01:11:12 +01:00
SirStone 0323fbd2ae feat: GM characters, reveals, who-sees-it and seen_by (#75)
Server: GM token frames gain the additive, GM-only seen_by:[player ids],
computed from each player's existing sight (PlayerVision.visibleTo) with
no extra polygon pass. Leakcheck BannedAlways bans seen_by; a seenBy
fault build is caught as exactly WALLDATA. proto stays 2 (6.2 additive).

Client: new cast slice parses character/character_gone/encountered frames
and seen_by; gmcast panel adds character create/rename/assign/remove,
reveal to one/all, encountered forget (grey entries only) and the
who-sees-it list (0/100 in M4). Mounted beside the #74 admin panel.

Docs: DESIGN 5.9/6.1/6.2/7.4 record the round-1 shape and the no-bump
call. Gates: devbox run test, client-test, e2e green; bench recorded.
2026-11-21 01:04:10 +01:00
SirStone 429f023c62 feat(client): tokens, BitmapText labels, statuses and lists (#71)
- slices/tokens.ts: token upsert, token_gone, hello reset; status names only.
- slices/characters.ts + slices/encountered.ts: own characters, encountered
  list with grey entries; the GM's per-player copies are ignored.
- render/tokenBoard.ts (pure): event -> entered/updated/left patches, so one
  changed token costs one container; seeds from the reducer on mount.
- render/modules/tokens.ts: pooled world-coordinate nodes on the tokens layer,
  one shared unit-circle context per kind, BitmapText from one pre-installed
  BitmapFont assigned only on a name change, stuck/squeezed badges, canvas
  dataset instrumentation for the "only changed entities" criterion.
- panels/lists.ts + render/modules/lists.ts: #lists under #panels, textContent
  only, greyed encountered rows; mounted by a render module so no shared
  bootstrap file changed.
2026-11-21 00:51:16 +01:00
SirStone 12c2e88f99 feat(client): GM roster, player keys and token panel (#74) 2026-11-21 00:38:52 +01:00
SirStone e254a0e0f3 docs: tile gate is dbLock-free, private mutex (#65) 2026-11-21 00:34:28 +01:00
SirStone 465259c853 feat(client): name prompt, connection badge, reconnect and resync (#68)
T5 of the M4 client (spec #63). All of it at the existing seams: the pure
reducer slice, the WS client and the browser e2e.

- First sign-in: a live player with `me.name === null` gets a name prompt
  instead of the HUD and no Pixi stage (the server sends no scene until named).
  `player.setname` is acked before the second `hello` (#33); `name-taken`,
  `invalid` and `not-allowed` become visible text and the prompt stays put.
  Acceptance is followed by `hello` + the 6.3 resync, so the prompt is keyed on
  state and is asked once.
- Badge (`#badge[data-state]`): connected / reconnecting / offline. Offline is
  driven by `navigator.onLine` (a phone with no network) and by terminal close
  outcomes; reconnecting keeps the stale map on screen.
- Reconnect: a transport close after a live connection retries with
  1/2/4/8/10 s base delays +/-20% jitter, then the cap. `revoked` and
  `proto-mismatch` stay terminal; pending `reqId`s die with the socket; the
  browser `online` event skips the rest of the wait. A drop does not clear the
  view: `hello` resets every slice and the resync rebuilds tokens, fog,
  explored, markers and lists.
- Two devices on one player key both stay live and receive the same frames.

Proof: new unit tests for the schedule/retry machine (`test/ws.test.ts`) and the
badge/reconnect/name transitions (`test/reducer.test.ts`); new
`client/e2e/session.test.mjs` runs the real server and TLS/HTTP2 vhost, kills
and restarts the server under a live page, drops the browser network with
`context.setOffline`, and asserts the full resync frames (roster, encountered,
vision, explored, marker, token) plus two pages on one key.

Refs #68
2026-11-21 00:18:17 +01:00
SirStone 2727617db9 feat: session cache, explored bitmap and lock-free tile gate (#65)
The tile gate no longer takes dbLock or runs a SQL session JOIN per tile: a published
in-memory view (server/sessions.nim) holds token hashes -> player/role and one explored
bitmap per player. Sessions load from the DB at startup and are updated by join, key
replacement and player removal in the same lock as the write; refreshed cells publish
before the ack. The gate is one snapshot read (parse + session + bit test + redirect)
over scalar data only, so a tile burst is answered while a mutation holds dbLock.

Evidence: tests/tsessions.nim pins the cache/bitmap lifecycle and gate rule; tiles.test
adds the lock-held burst and the revocation/restart seam; auth.test adds the
LEAK_FAULT=sessioncache negative control (a stale entry makes the auth group fail);
mutation c5 keeps the cache drop load-bearing. Explored wire and persistence untouched.

Bench (devbox run bench, in-process): tile gate old 0.006 ms -> new 0.001 ms per
request; incremental explored mark 0.001 ms; snapshot build 2.0 ms at 262144 cells
(startup only).
2026-11-21 00:10:39 +01:00
SirStone 3c0258ea31 feat: client shell, sign-in and protocol client (#67)
New `client/` package (Vite + TypeScript + PixiJS v8, plain DOM overlay):
the pure reducer seam (no Pixi import), an append-only slice registry
build-time glob, the `proto` 2 WS client with envelope/ack/closing mapping,
the sign-in door (`POST /join`, one "Key not recognised." for wrong and
unknown), the DOM shell/HUD and a minimal Pixi stage created only after a
live `hello`. `hello` resets every slice so a reconnect cannot show stale
state; `proto-mismatch` shows reload; `revoked` returns to the sign-in page
and stops.

The browser e2e moves into the client package (`client/e2e/`, owning
playwright-core) and runs the real Vite build through the TLS/HTTP2 test
nginx: join -> canvas -> hello/roster for GM and player, no data before
join, identical wrong/unknown key refusal, proto mismatch, revoked.
`devbox run client-test` adds the Vitest seam; `devbox run e2e` builds the
client first. The #66 stub dist stays local to `tools/vhost.test.mjs`, so
`devbox run test` still needs no npm install.

Refs #67
2026-11-20 23:57:16 +01:00
SirStone 97f618c5ad results: rerun the gates with the sector-limited fan (#64)
Rebased on origin/main (1dff520). devbox run test green (Nim suite + 149
node tests + group evidence); devbox run mutation green including a2 (a ray
tests the next sector's chord) failing 5 bit-identical tests. bench.log is
the rebased run: prototype polygon 0.009 ms, 5k sparse 0.035 ms, 5k dense
0.737 ms.

Refs #64.
2026-11-20 23:40:06 +01:00
SirStone d192381d13 perf: test only the in-sector 64-gon chord per vision ray (#64)
Each fan ray now tests the one circle-segment chord of its angular sector
instead of all 64. A sector-boundary ray tests both meeting chords, so the
rayHit set and the picked minimum are unchanged: the polygon is bit-identical
to the all-segments fan. tests/tgeometry.nim keeps the old fan as an oracle
and asserts exact float equality over the prototype corpus, the seed scene
(all switch shapes), the 5k sparse/dense scenegen layouts, the #26
collinear/radial cases and random walls. tools/mutation.sh gains a2 (a ray
tests the next sector's chord), which fails 5 of those tests.

Bench on this host, before -> after (3-run median):
  1 poly, prototype 0.028 -> 0.008 ms (3.5x)
  1 poly, 5k sparse 0.062 -> 0.033 ms (1.9x)
  1 poly, 5k dense  1.085 -> 0.708 ms (1.5x)

Refs #64.
2026-11-20 23:28:04 +01:00
SirStone 1dff520f31 test: TLS + HTTP/2 test vhost with the client dist served at /
The test nginx is now the production shape of DESIGN 11.1 and the browser
gate's real path (#66, spec #63 decision 6): TLS-only listener with
http2 on, a self-signed certificate generated per run (tools/tlsdev.mjs,
added to the process's default CA list so verification stays on), the
client dist at / with SPA fallback, index no-cache and a year-immutable
/assets/ cache, and the tile gate's internal /_tiles/ still unreachable.

Existing tile/doors/oneway/wallbehaviour harnesses point their server's
public origin at the https vhost, so they prove the same listener the
browser uses. tools/vhost.test.mjs is the independent node:http2 client
(cert SANs, ALPN h2, cache headers, SPA fallback, direct /_tiles/ 404);
e2e/h2.test.mjs drives devbox chromium via playwright-core and asserts
the page reports h2 (`devbox run e2e`, npm deps outside tools/).

Root devbox gains chromium + openssl. Harness builds use a worktree-local
nimcache so parallel worktrees stop corrupting each other's objects.

Refs #66
2026-11-20 23:11:05 +01:00
SirStone 0448002cc5 test: load-insensitive tviews perf gate; env note 2026-11-20 22:44:55 +01:00
SirStone 414bb0326c fix: hit a wall lying along a sight ray so it casts its line's shadow (#26)
visibilityPolygon casts one ray per 64-gon vertex and ang, ang+-RayEps per wall
endpoint. A wall radial to the viewer is collinear with the ray that crosses it,
and rayHit rejected the collinear case; its own +-RayEps rays meet the wall's
line at the viewer (t = 0, rejected by t > Eps). So the wall got no ray, no
vertex and no shadow, and a token on the line beyond it stayed inside the
polygon: a player-view fog leak (DESIGN 3.1).

Fix: rayHit returns the nearest point of the overlap when the wall lies on the
ray's line (and Inf only for a parallel wall on another line). {.inline.} keeps
the fan's inner loop at its previous cost (CPU-time cross-check on 20k dense
polygons: 25.8s before, 32.5s without the pragma, 24.9s with it).

Proof: tgeometry visibility tests (horizontal k=0, vertical k=16, both wall
directions, a 32 px grid translation, 10 degrees, plus the non-radial and
0.5 px-off negative controls); the leak world gains a wall on the subject's own
column with a hidden token beyond it, and leakcheck's HIDDEN_TOKEN class now
asserts the token-level over-approximation (token centre + viewer->token
segment, 5.4 tolerance), which the GEOMETRY class structurally cannot see.
2026-11-20 22:17:45 +01:00
SirStone a11782f00d results: rerun the gates on the rebased tree (#36)
devbox run test: Nim suites and 149 node tests pass (the 16 registered group
evidence tests included). devbox run mutation: control and all 78 mutations pass,
including s1-s7 and the new e4/e5/f1-f3 from #32/#33/#35.

Refs #36.
2026-11-20 22:13:04 +01:00
SirStone 1f11779658 test: tie group evidence to passing tests and baseline restart on the as-built server (#36)
- tools/groups.mjs evidence entries now name the exact test, a minimum assertion
  count and the calls its body must keep; groups.test.mjs checks all three.
- tools/evidence.mjs parses the spec reporter log and fails the gate unless every
  registered evidence test ran and passed; test.sh runs it after the Node suite.
- restart.test.mjs snapshots the live as-built world on the first server, then
  compares it to the post-SIGTERM/SIGKILL state (players connect before the GM, so
  the GM's derived encountered grey is computed on both sides).
- Negative controls: a hollowed auth test fails the new evidence check; a planted
  first-load drop of a token's gm prop bucket fails the new restart baseline while
  the old restart-to-restart test passed.
- Refresh the gate evidence (control + 73 mutations incl. s1-s7, 142 node tests).
2026-11-20 21:55:50 +01:00
SirStone b0e1633aa9 fix: cap wall flags and scene extra as opaque objects (#35)
One shared validator next to the property caps: 8 KB serialized, 64 keys
per object, depth 8 (top-level object = 1). At a cap is accepted; over
is invalid and applies nothing. Both call sites use it, and a refusal is
logged once with the field and limit, never the value. Token flags and
props keep their existing rules; stored over-cap rows still load as
stored.
2026-11-20 21:46:53 +01:00
SirStone 41c2fe695b fix: player.setname acks before its effects (#33)
The durable write and registry update stay put; the ack is enqueued
between the commit and the first effect, then hello, the full resync and
roster follow in their existing order. The failure paths are unchanged.
Frame-order test pins ack first on the renaming connection.
2026-11-20 21:36:47 +01:00
SirStone a5c0ee5d4c fix: dispatch guard and Defect-safe rollback (#32)
A readable intent that fails in handling now always gets exactly one ack:
the new static internal code, unless the handler's own ack was already
enqueued. Both transaction helpers roll back on every unwind path,
Defect included, so the shared SQLite connection never keeps an open
transaction. Test-only dispfault build covers catchable/defect/after-ack;
DESIGN 6.5 records internal as an owner decision and 6.2 names refusal
codes as additive.
2026-11-20 21:36:44 +01:00
SirStone 38941da003 test: walls r1 review — tests and tools
Ref #52
2026-11-20 08:59:24 +01:00
SirStone e1a5b297e4 fix: walls r1 review — server (ref #52) 2026-11-20 08:42:50 +01:00
SirStone f9f26a4a01 test(walls): rewrite the leak scenario as one world, gate every fault class (#61)
The Walls r1 scenario had grown appendages: a marked window bolted on in the
room, a one-way wall tacked onto the southern walk, and no secret or locked
door at all. #61 makes it one coherent world and proves the world itself.

The world now holds a room entered through an opening door, a far wall with a
solid stretch, a secret door and a locked door (a token behind each, so their
absence from the transcript is the leak proof), a one-way screen the subject
sees across, a marked window in the room, the same window's switch cleared and
restored (retraction and re-earn end to end), a marked solid wall, and a marked
window the subject never sees.

- tools/leak.mjs: declarative WORLD with role handles (no wallIds[1] indexing),
  narrative groups, and a scenarioCoverage() reading the GM's wall frames and
  the subject's marker frames.
- tools/leak.test.mjs: asserts the coverage on subject A: one-way wall, secret
  door, locked door, a marked window on each side of the sight gate and a
  marked non-window.
- tools/groups.mjs: the leak+fault group lists doors.test.mjs (#56) and
  markers.test.mjs (#59/#60) with their proving tests.
- docs/TESTING.md: the scenario, the coverage gate and the marker retraction
  exercise are recorded as built.

Fault matrix: all 21 fault classes still caught as exactly their own class
(oneWay, markerEarly/Extra/Off included); 22 tests with the clean-build gate.
That build passes and its bytes carry no LEAK_FAULT. nimble test and the
136-test node suite green.

Ref #61
2026-11-19 23:58:45 +01:00
SirStone a69563f701 fix: marker_seen deletes commit with the wall change
A wall cause change (endpoint move, thickness/position, player_marker off,
no longer window) committed the wall row in the FULL transaction while its
marker_seen deletes rode the later NORMAL derived-memory transaction. A crash
between them left the stale row, and restart restored the marker with the
anchor recomputed from the NEW geometry, revealing a position the player never
saw (DESIGN 5.8).

updateWall now deletes the affected rows in the same FULL transaction as the
replaced row, exactly as the composite FK cascade already does for wall.remove.
The live del frames are unchanged and marker inserts stay in the derived
transaction: wall+deletes commit, derived inserts, then ack.

The marker cause signature moves to world.markerSig so the write-time delete
and the online retraction cannot drift.

Proof: a leakfault-only markerCrash hook quits between the wall commit and
the derived write; tools/markers.test.mjs covers all four causes and restarts
on a clean build, asserting no marker for the changed wall (no new anchor) and
restoring the untouched window's marker as the positive control.

Ref #60
2026-11-19 23:52:13 +01:00
SirStone c3c0a39188 feat(walls): marker retraction, re-earn and marker fault classes (#60)
Retract a player marker when the GM removes the wall, clears
player_marker, makes the wall stop deriving window, or moves its
geometry (a/b, thickness, position). Retraction emits del only and
never the new anchor; a re-earned marker gets a fresh id. The
marker_seen deletes ride the same derived-memory NORMAL transaction as
the explored chunks, after the wall row commits and before the ack.

Replace the leak checker's aggregate MARKER class with MARKER_EARLY,
MARKER_EXTRA and MARKER_OFF, add their leakfault hooks and exact-class
fault tests, and extend the leak scenario with an unseen marked window
and a marked solid wall as the negative controls. WS black-box tests
cover all four causes, fresh re-earns, no untouched re-send, no
set/del for one id in a frame, no explored write from a retraction,
and delete/cascade durability across a restart.
2026-11-19 23:43:44 +01:00
SirStone edd4437f7e feat(walls): player markers — emission, opaque ids, storage, resync (#59)
A wall that is player_marker:true and derives window sends a player one
anchor (the drawn midpoint, integer px) and an opaque per-player 12-char id
once any point of its segment enters that player's vision polygon. Markers
live in PlayerVision like explored, persist to marker_seen in the same
derived-memory transaction, load before the first connection and resync as a
full set after explored; the GM and other players never receive one.

- markers.nim: emission gate, visible-extent test, id mint, anchor, marker_seen I/O.
- views/main: PlayerView markers + full/diff frames, refresh sync, startup load.
- markers.test.mjs: window preset, switch off, solid wall, any-part anchor,
  walk-away/door/lost sight, full-after-explored, per-player privacy, GM none.
- leakcheck: marker allowed type + independent visible-extent oracle with a
  positive control (a marked window the subject sees).
- restart: marked window in the fixture; marker set and marker_seen rows
  identical before/after SIGTERM and SIGKILL.
- protocol/tviews: catalogue and frame order pin the 16th message.

Retraction, re-earning and MARKER_* faults are #60.

Ref #59
2026-11-19 23:27:26 +01:00
SirStone e989100f50 feat(walls): windows — see-through barrier, movement follows blocks_movement (#57)
- geometry.Wall carries the stored blocks_sight/blocks_movement switches; sight asks
  blocksSight, movement and the status rules ask blocks (open door passes both).
- worldmap translates both switches; moverules only pushes on a movement barrier.
- leakcheck and the tile oracle read blocks_sight independently.
- Walls/token-details/tiles groups prove both forms, sight-through, stuck, push and
  the locked-window open refusal; existing scenes stay byte-identical.

Ref #57

# Conflicts:
#	server/geometry.nim
#	server/world.nim
#	server/worldmap.nim
#	tools/leakcheck.nim
2026-11-19 23:09:05 +01:00
SirStone cc566ee16e docs: one-way wall blocks the blind side (fix §5.1 inversion) 2026-11-19 23:03:37 +01:00
SirStone 9fcbe885c1 feat(walls): one-way sight per-viewer filter and ONEWAY fault (#58)
The vision fan blocks a sight-blocking one-way wall only for a viewer on
its blind side (sight_dir names it; left is the (-dy,dx) normal of a->b),
one sign test inline after the radius cull, so the hoisted wall list stays
viewer-independent. Movement never reads the direction: one-way walls block
both ways. Explored and tiles therefore differ by side and only ever grow.

- geometry: WallDir + Wall.sightDir + blindTo, filter in visibilityPolygon.
- worldmap: sight_dir mapping (movement mapping unchanged).
- vision: the ONEWAY leak-fault build drops sight_dir player-side.
- leakcheck: own side test for the fan and the clear-segment oracle; ONEWAY
  class detected against the sight_dir-dropped fan.
- leak scenario gains a one-way wall the subject sees across; fault test
  asserts exactly ONEWAY.
- oneway.test.mjs: both sides, tile sweep with its own oracle, flip with
  fixed endpoints, monotone explored/tiles, restart, two-way movement.
- docs: DESIGN 5.8 mechanism sentence corrected; TESTING #58 markers built.
- nginx harness: temp dirs created recursively (restart on one state dir).
2026-11-19 22:57:39 +01:00
SirStone 0f3aa2300f feat(walls): door refusals and secret/locked equivalence gate (#56)
- door.set: opening a secret or locked door is invalid; closing either is
  allowed; a fixed window/non-door still has no open state.
- new tools/doors.test.mjs: two fresh servers, one identical script, three
  equivalence pairs (secret/wall, secret+locked/wall, locked/closed door),
  canonicalised frame + full per-player tile sweeps, an open-door positive
  control and a pinned zero-thickness close-push.
- secretgap fault hook (sight-only) makes the pair fail as exactly SECRETGAP;
  the clean pair passes and the shipped binary carries no fault hook.
- docs/TESTING.md T2/T17 and the door-equivalence/10.3 sections: built.

Ref #56
2026-11-19 22:49:39 +01:00
SirStone 484275e8bb feat(walls): presets, label rule and one switch-set validation path (#55)
wall.add/wall.update now take a preset or raw switches, never both:
resolveWall expands the four 5.8 presets to switches before validating, so
a preset never touches geometry and preset+switch or preset+open is invalid.
A raw create starts from the wall defaults; a raw update patches only the
switches it names and {door:false} closes and de-secrets.

The switch-set invariants are enforced by that one path for add and update:
open/secret/locked without a door, a secret door that is open/one-way/not
opaque, open with secret or locked, and a direction with no sight to block
are all invalid. The DB gains the missing open+locked CHECK as the backstop,
and the now-redundant open/door parity test is gone from the server path.

A wall label is now the 6.5 text rule: trimmed, 1..64 code points, no control
characters, null clears, stored verbatim and GM-only. window/one_way presets
are accepted and expanded to their switch sets per DESIGN 5.8/6.1; their
player-facing behaviour stays with #57/#58.

Tests: WS black-box presets/patch semantics/every refusal/label round-trip;
Nim shape pins for expansion, invariants and the label rule.
Nim 385 / Node 117 green.
2026-11-19 22:35:57 +01:00
SirStone 77fa2dfe4c feat(walls): proto 2 typed wall record, inert geometry, derived kind (#54)
wall.add/wall.update take thickness, position, height and the eight raw
switches; kind is output-only and the GM wall frames echo the full typed
record. Geometry is stored but inert (0/full/centre behaviour), and the
legacy kind/open wire adapter is gone. proto is bumped to 2 with the
harness default, and BannedAlways gains every wall field name with a
WALLDATA positive control.

Tests: schema-7 migrated scene vs the same walls authored via raw switches
gives byte-identical player frames, refusals and per-tile statuses.
Nim 382 / Node 113 green.
2026-11-19 22:21:47 +01:00
SirStone c1b1e9cf91 feat(db): typed wall storage, marker_seen and height backfill (#53) 2026-11-19 22:03:11 +01:00
SirStone 6a443b4ec0 docs: mark Walls r1 test artefacts as planned 2026-11-19 21:49:29 +01:00
SirStone a4253957e0 docs: wall.update open is not a patch field 2026-11-19 21:40:00 +01:00
SirStone 0d5173d56b docs: trim duplicate statements from TESTING; refresh ledger size 2026-11-17 23:25:18 +01:00
SirStone 1c655314ed docs: record the DESIGN/TESTING split ledger
Sizes before/after, the moved-block ledger, per-section FIXED counts and the
judgement calls left in DESIGN; cross-reference check for § and TESTING links.
2026-11-17 23:24:52 +01:00
SirStone 6bfb032548 docs: finish the DESIGN/TESTING split (§6-§13)
Protocol, client, ops and milestone sections keep their rules and gate criteria;
message-size measurements, close-assertion detail, the test nginx, the restore
drill, the slow-log provenance and the M3/M4 gate mechanics move to TESTING.
DESIGN §10 becomes a pointer section that keeps 10.1-10.4 so existing refs
resolve.
2026-11-17 23:22:48 +01:00
SirStone e9c29675de docs: retarget ADR and research refs to TESTING
ADR-0015 no longer cites DESIGN §10.3 (now a pointer); ADR-0012 and the
thick/low-wall research note name TESTING.md for the proof side.
2026-11-17 23:22:48 +01:00
SirStone bc10780625 docs: point DESIGN §5 at TESTING; move vision/bench proof out
Edge-case counts and bug regressions, the perf table and bench scenes, oracle
citations, the move-rule regression baseline, the see-over oracle spec and the
thickness/joint measurements move to TESTING §5.1-§5.10. Targets, the 5k-wall
gate and the accepted thickness cost stay in DESIGN.
2026-11-17 23:22:06 +01:00
SirStone 6837bbcf11 docs: point DESIGN §3-§4 at TESTING for their proofs
Security and server sections keep the rules; measured runs, oracle citations,
test pins and the threat table's Test column move to TESTING §3.1, §3.3, §3.4,
§4.1-§4.4.
2026-11-17 23:21:16 +01:00
SirStone 39615afdf6 docs: add TESTING.md with the proof detail split out of DESIGN
New file holds test, acceptance, oracle, fault-class, gate and bench detail,
organised by DESIGN section number with a back-link per block. Tags, tickets
and evidence paths are preserved.
2026-11-17 23:21:16 +01:00
SirStone 9143cee536 docs: race fix merged 2026-11-17 23:17:06 +01:00
SirStone c5ec25eb11 merge: fix JsonNode race across worker threads 2026-11-17 23:13:25 +01:00
SirStone bd320014ca docs: final split-check sizes 2026-11-17 23:13:00 +01:00
SirStone 3ed8107908 docs: fix the D2 pointer in the history log 2026-11-17 23:12:43 +01:00
SirStone 7468196111 docs: record the 22nd reworded block in the split check 2026-11-17 23:12:33 +01:00
SirStone d8c807bbf2 docs: point wall geometry wire validation at 5.7/5.10
One statement of the thickness/position/height ranges; the wall payload rule keeps only the
defaults and the patch behaviour.
2026-11-17 23:12:25 +01:00
SirStone de633642c5 docs: mark DESIGN split done and record the verification (#51)
D2 marked done; the M3 handoff is marked historical with the §14-log pointer; the split
check records sizes, the section mapping, FIXED-marker coverage, the blocks that changed
wording and every statement dropped as superseded.
2026-11-17 23:12:08 +01:00
SirStone dc16db1b72 docs: rewrite DESIGN.md as the current-only spec (#51)
Same section numbers as v0.30, so all DESIGN §x.y references still resolve. Removes the
change log, the decision log, the HANDOFF table and the superseded/duplicated statements
(history + ADRs hold those); dedupes rules to one authoritative block with wire/storage/
recipient layers pointing at it; §14 now holds only open items and the ADR index; all prose
wrapped. No decision changed.
2026-11-17 23:12:08 +01:00
SirStone 8aaf03be04 docs: add ADRs for the durable design decisions
22 ADRs: server-authoritative sight and single egress, per-recipient views/diffs, uniform
nack, opaque ids, 32 px tile unit, wall switches/presets, see-over, thick walls, open-door
gap, typed wall columns, proto 2, build order, zoom clamp, accepted status leak, player
marker, chunked explored, slow-client policy, session/key split, closing message, character
records, global lock, synchronous choice. Each links its tickets and its spec section.
2026-11-17 23:12:04 +01:00
SirStone 7a69779c5a docs: extract DESIGN history (change log, decision log, superseded text)
The v0.4-v0.30 change log, the old §12 HANDOFF table and the whole §14 owner-decision log
(Q1-Q24) move here verbatim, with the superseded statements removed from the spec quoted
with their surviving rule. Non-normative.
2026-11-17 23:12:04 +01:00
SirStone 08363ef086 fix: stop sharing intent JSON refs with the world across worker threads
Mummy runs websocket handlers on worker threads. Intents are parsed outside
the one global lock, while the world is walked under it; ORC refcounts are
not atomic, so any JsonNode or string payload reachable from both an intent
tree and the world can be freed or leaked by two threads at once.

- Add server/jsonbound.nim: detachedJson/detachedString/detachedProps copies
  that share neither nodes nor string payloads (serialise+parse; std/json's
  copy() would still alias JString payloads).
- Detach every intent value that enters world state: wall.add/wall.update
  flags; token.create flags/props/names/kind/character_id; token.update
  patch fields; prop.set key and value (token and character); character.create
  props/names; scene.set name/extra. Use the world's own id in name.reveal.
- Build wall effects and create acks inside the mutation's critical section
  (settleLocked/settleWorldLocked). Wall/token/character record copies and
  frames no longer outlive the lock; only fresh scalars cross it.
- Move player.remove's in-memory follow-up under the lock (it mutated tokens,
  characters, visions, reveals and encountered outside it).
- Cap mummy at 4 worker threads (default was 10x cores) for a seven-person table.
- Add tests/tdetach.nim: identity and string-payload checks for the boundary
  helpers, plus the parseFlags-returns-the-caller's-node premise. A unit test
  can prove the copy semantics, not the absence of a race.
2026-11-17 23:02:32 +01:00
SirStone 7b804f4e5e docs: analysis review and decisions 2026-11-17 22:45:58 +01:00
SirStone 287859d890 design: wall wire format, schema and migration (#49) 2026-11-17 22:31:16 +01:00
SirStone 2a160fb274 design: door geometry, thick doors and door push (#50) 2026-11-17 22:17:16 +01:00
SirStone 409d2c8621 docs: tag #42 preset list superseded by #48 2026-11-16 22:42:56 +01:00
SirStone 7ac915ae6c design: terrain dropped, presets, window markers (#48) 2026-11-16 22:39:20 +01:00
SirStone b8f04c2faf design: windows and one-way walls (#47) 2026-11-16 22:08:14 +01:00
SirStone 5c3a123d41 design: thick walls sight and movement (#45) 2026-11-15 21:53:55 +01:00
SirStone afe19ac258 design: secret and locked doors (#46) 2026-11-15 19:27:15 +01:00
SirStone 4c968b78d8 design: low walls sight and see-over (#44) 2026-11-15 19:21:10 +01:00
344 changed files with 36783 additions and 16372 deletions
+7
View File
@@ -8,8 +8,15 @@ nimcache/
tests/t[a-z]*
!tests/*.nim
!tests/fixtures/
# tests/refold.nim is a helper module nimble test also compiles; its output binary is scratch
/tests/refold
tools/bench
tools/mkcorpus
run/
# node-test.log carries per-run durations; regenerate it, do not commit it
results/node-test.log
results/e2e.log
results/client-test.log
client/node_modules/
client/dist/
.cache-nim*/
+4
View File
@@ -1,5 +1,9 @@
# FFF_vtt
**FROZEN 2026-11-22, see [docs/FROZEN.md](docs/FROZEN.md).** This repository is an archive: no
further work is planned here. Do not open issues, change issue state, or build on this tree; the
successor project starts elsewhere and borrows the modules listed in FROZEN.md.
## Agent skills
### Issue tracker
+47 -11
View File
@@ -9,7 +9,7 @@ How big a token is on the map, as a radius in map pixels. A token uses its own s
_Avoid_: token scale, token diameter, size preset
**Height**:
How tall a figure is, in metres. A character has a base height; a token may carry its own instead, a temporary on-map override (a spell that enlarges the figure) that never changes the character and disappears with the token. A plain token has only its own height and must have one. Players never see the number, only what it lets them see.
How tall a figure is, in metres. A character has a base height; a token may carry its own instead, a temporary on-map override (a spell that enlarges the figure) that never changes the character and disappears with the token. A plain token has only its own height and must have one. Players never see the number, only what it lets them see. A wall's height is a different thing with the same unit: an optional field on the wall itself, in metres (see Wall).
_Avoid_: elevation, z, altitude (those are position above the ground)
**Eye height**:
@@ -21,7 +21,7 @@ A lock condition meaning the token is held in place: a wall runs through it, or
_Avoid_: blocked
**Squeezed**:
A lock condition meaning the token is pressed with no room: walls surround it, or a closing hand presses it. A player cannot move a squeezed token; the GM always can.
A lock condition meaning the token is pressed with no room: walls around it, a closing door with no room on either side, or a closing hand presses it. A player cannot move a squeezed token; the GM always can.
_Avoid_: blocked, crushed
Neither term names its cause. Stuck and squeezed both lock a token for its player in the same way; they differ only in why.
@@ -51,32 +51,68 @@ A figure on the map. It may belong to a character; a plain token (monster, item)
_Avoid_: entity, piece, counter
**Wall**:
A barrier on the map with a length, a thickness and a height. It hides what its dimensions hide. What it *does* is a set of **switches** it carries: blocks sight, blocks movement, and (for sight) a direction; a door is a wall with the door setting plus open/secret/locked. A named wall kind is only a preset over those switches, never the wall's own identity. A wall is full height unless the GM gives it a height in metres, so by default nobody sees over it; an older wall without a height keeps hiding everything behind it. In v1 a wall has zero thickness; per-wall thickness and what a low wall hides are pending (map #38).
A barrier on the map with a length, a thickness and a height. It hides what its dimensions hide. What it *does* is a set of **switches** it carries: blocks sight, blocks movement, (for sight) a direction, and whether players see a marker; a door is a wall with the door setting plus open/secret/locked. A named wall kind is only a preset over those switches, never the wall's own identity. A wall is full height unless the GM gives it a height in metres, so by default nobody sees over it; an older wall without a height keeps hiding everything behind it. The wall's height is its own field, never a token property, and only the GM sees the number. A low wall hides only what fails the see-over line (see Low wall, See-over). A wall has no thickness unless the GM gives it one; then it occupies a strip of floor on one side or both sides of the drawn line (see Wall body), and an older wall has none and hides exactly what is behind the line. Only the GM opens or closes a door in v1.
_Avoid_: blocker, collider, obstacle, sight blocker, wall type (use preset)
**Player marker**:
The one wall fact a player ever receives: an anchor point on a wall whose `player_marker` switch is on, sent once that player has seen part of the wall and then kept like explored memory. It is a point and nothing else — no kind, no open/closed, no direction, no label, no thickness, no wall id — and the client draws the window icon there. A wall with the marker off is invisible to players; a GM can turn the marker on for any wall, but a marker is only sent for a wall that is still a window. Only the GM's changes take it back (wall removed, marker off, no longer a window, geometry moved), and a moved wall has to be seen again before its marker returns. Each player gets their own markers as a full set when they connect and only changes after that; the GM never receives them.
_Avoid_: window marker, wall hint, marker flag (the switch is `player_marker`)
**Marker id**:
The opaque name a player's marker has on the wire: a short random string the server assigns per player, never the wall's id and never shared between players. It exists so the client can add a marker once and remove that exact one later without the frame revealing which wall it is or how many walls exist.
_Avoid_: wall id, marker index, window id
**Wall label**:
An optional free-text name the GM gives a wall, e.g. "railing", "pit edge", "the king's window". It has no behaviour, never changes the derived kind, and never reaches a player. It is how one object can be many things in the GM's head: a railing, a bush and a fixed window are the same wall with the same switches and different labels.
_Avoid_: wall name, wall description, wall type
**Wall body**:
The strip of floor a thick wall occupies: the drawn line widened by the wall's thickness, with square ends, sitting either half on each side of the line or all on one side (the GM's placement). The line itself is the room's interior edge, so a GM can draw an exact room and put its thickness outward. A body is solid floor: nobody sees into it or through it, nobody stands in it, and a figure the GM covers with one is stuck. A wall with no thickness has no body, only the line. A door's body is its leaf; an open door has no body at all, only the gap it leaves between the walls beside it.
_Avoid_: footprint, collider, hitbox, thickness (that is the number, not the strip)
**Low wall**:
A wall with its sight switch on and a height below full, so it hides some things and not others. It is not a kind or a preset. What it hides is not a property of the wall alone: it depends on whose eyes look, how tall the thing looked at is, and how far away it is.
_Avoid_: half wall, short wall, cover (that is a rules word)
**See-over**:
The rule for being seen across a low wall: the figure's top must rise strictly above the line from the viewer's eye to it, at every crossed wall and, for a thick wall, at every face the line crosses. So the same wall hides a crouched figure beside it and shows a distant standing one, and a giant's head shows over a fence. It changes no fog: the floor behind a low wall stays unexplored even while the figure standing on it is seen.
_Avoid_: see-through (that is a wall that does not block sight at all), over-the-wall vision
**Visible fraction**:
The share of a figure's height above the highest blocking sight line between a viewer's eye and the figure: 0 when hidden, 100 % when nothing is in the way. A GM-only number, shown in the GM's who-sees-it view; players always get a plain visible/hidden answer and never the number.
_Avoid_: cover percentage, exposure, concealment
**Wall switch**:
One independent setting a wall's behaviour is made of: `blocks sight` or `blocks movement`. Neither implies the other: a wall can hide what is behind it and let people walk through, or the reverse. A door's settings (open, secret, locked) and the sight direction are settings of the same wall but not switches. Switches are stored on the wall and read by the server.
One independent setting a wall's behaviour is made of: `blocks sight`, `blocks movement` or `player marker`. None implies another: a wall can hide what is behind it and let people walk through, block movement without hiding anything, or stay invisible to players even while it blocks them. A door's settings (open, secret, locked) and the sight direction are settings of the same wall but not switches. Switches are stored on the wall and read by the server.
_Avoid_: flag, bit, property (that word already means token data), restriction type
**Wall preset**:
A named combination of switches and door settings the GM picks in one action: wall, door, secret door, locked door, terrain, one-way wall. It is a shortcut and a label, not a stored kind: the wall keeps the switches, and the name is derived when they match a preset exactly (`custom` otherwise). So two presets can never drift from what the wall actually does.
A named combination of switches and door settings the GM picks in one action: wall, door, window, one-way. It is a shortcut and a label, not a stored kind: the wall keeps the switches, and the name is derived from them by shape (`window`, then one-way, then door, then wall; `custom` otherwise). So two presets can never drift from what the wall actually does. Secret and locked are not presets: they are settings on any door.
_Avoid_: wall kind, wall type, category
**One-way wall**:
A wall whose sight switch carries a direction: it blocks sight from one side and lets the other side see across it. Movement is unaffected by the direction, so a one-way wall still blocks (or lets through) movement on both sides alike. Which side is blocked is decided by the wall's `a -> b` order.
A wall whose sight switch carries a direction: it blocks sight from one side and lets the other side see across it. Movement is unaffected by the direction, so a one-way wall still blocks (or lets through) movement on both sides alike. The side is read from the wall's `a -> b` order: `left` is the left of that order, and the named side is the side that **cannot** see across — a viewer on the left of a `left` wall is blind across it, while a viewer on the right sees across. Explored area and tiles differ between the two sides as a consequence of that, and flipping the direction never takes back what either side has already explored. The GM's editor draws an arrow at the wall's middle from the seeing side toward the watched side.
_Avoid_: one-sided wall, directed wall, mirror wall
**Blind side**:
The side a one-way wall's sight direction names (its `sight_dir`, `left` or `right` of the wall's `a -> b` order). A viewer standing on the blind side cannot see across the wall; the opposite side, the seeing side, sees across it. The direction is sight only, so movement is the same from both sides.
_Avoid_: dark side, blocked side, back side
**Door**:
A piece of wall that can be opened. Closed, it blocks and pushes exactly as its switches say; its leaf is its own body, with the wall's thickness and placement, and nothing else. Open, that whole piece disappears from sight and movement — no leaf, no hinge, no swing, no arc — so the doorway is only the gap between the wall pieces on either side, and closing puts the same body back. A door has no shape of its own: jambs, leaf and thickness are just walls. In v1 only the GM opens or closes a door.
_Avoid_: gateway, portal, door object, swinging door, leaf as a separate thing
**Secret door**:
A door the players never learn exists. It is always closed and, to a player, behaves exactly like a solid wall: same sight, same explored cells, same refusals, nothing that marks it as a door. The GM reveals it by making it an ordinary door and opening it.
A door the players never learn exists. It is always closed and, to a player, behaves exactly like a solid wall: same sight, same explored cells, same refusals, nothing that marks it as a door. The GM reveals it by making it an ordinary door and opening it. In v1 no player action finds or opens a door, so the reveal is always the GM's.
_Avoid_: hidden door, concealed door, illusionary wall
**Locked door**:
A closed door the server refuses to open until it is unlocked. The lock is the GM's business only: players get no signal of it, and a locked door behaves exactly as a closed door to sight and movement. In v1 only the GM opens doors, so the setting is authoring state waiting for player door interaction.
A closed door the GM must unlock before it will open: opening a locked door is refused until the lock is cleared, while closing one is always allowed. The lock is the GM's business only: players get no signal of it, and a locked door behaves exactly as a closed door to sight and movement. In v1 only the GM opens or closes doors, so the setting is authoring state.
_Avoid_: barred door
**Terrain**:
A wall preset that blocks movement and not sight: a railing, bushes, a low barrier, a pit edge. People see over or through it and cannot pass. It is absent from the sight rules entirely, so its thickness and height never affect sight.
_Avoid_: transparent wall, invisible wall, obstacle (that names the thing, not the preset)
**Window**:
A see-through piece of a wall, drawn by the GM as its own short wall between wall pieces, like a door. There is no sill and no top: it can be seen through along its whole length, and no light comes through it. One wall with the same switches covers every "railing, bush, pit edge, fixed window" case: no sight block, movement blocked. A fixed window cannot be passed; an opening window is a door that can be seen through while closed and walked through once opened (and can be locked like any door; it can never be secret, because a see-through door would show itself). Both forms derive the label `window`; the difference is visible only in the GM's editor. `player_marker` is on by default for a window, so players learn "a window is here" once they see part of it; turn it off for an invisible barrier.
_Avoid_: window wall, hole, opening, glass wall, terrain (dropped; a fixed window is a window)
**Property**:
One named value a token carries, e.g. "aura" or "hp". The server stores it and does not interpret it in v1, apart from the few sight keys it reads itself (see Height and Eye height); FFF does the rest later.
+436
View File
@@ -0,0 +1,436 @@
> **FROZEN 2026-11-22, see [docs/FROZEN.md](docs/FROZEN.md).** This repository is an archive; no
> further work is planned here.
# FFF_vtt
A self-hosted browser virtual tabletop for one table: one GM and up to six players on phones,
tablets or laptops. Everyone opens the same site link; each person signs in with a personal key.
The server decides what each player sees — line of sight, explored area, tokens, map tiles — so a
modified client cannot reveal anything its player is not entitled to. No accounts, no external
database, one scene, no RPG rules or dice.
Status: the client (M4) is built; `devbox run serve` puts a table on the LAN for the manual phone
playtest. The NixOS deployment module is M6 and not written yet — for a permanent install you still
run the binary behind your own TLS nginx (the manual path below is the fallback).
---
## Using it
### What you need
- A Linux host with [devbox](https://www.jetify.com/devbox), or a machine that already has the
`fff-vtt` binary and the built client.
- An HTTPS site in front of it. The session cookie is `Secure`, so plain HTTP will not keep you
signed in. The server itself always binds `127.0.0.1`; nginx is the only public face.
### Start a LAN playtest (one command)
From the repo root, inside devbox:
```sh
devbox run serve
```
It builds the server binary and the client, starts a TLS + HTTP/2 nginx on the laptop's LAN address
in front of the server (the server itself stays on `127.0.0.1`), and prints:
- the `https://<lan-ip>:8443` URL to open on the phone and the laptop,
- the GM key (created on first run; an existing key is printed, never replaced),
- the certificate-trust steps for Android Chrome and for a laptop (Linux/macOS/Firefox; on NixOS it
prints the `security.pki.certificateFiles` option instead of the Debian `update-ca-certificates`
steps).
To import a map on the same first start, pass `--image` (an offline import runs before the server;
a fresh state dir is created and migrated first):
```sh
devbox run serve -- --image=run/map16384.png
```
Any single-frame PNG or WebP works: images larger than Full HD (1920 px long side, 1080 px short
side) are shrunk automatically on import (see below), so no tile-size juggling is needed.
Everything after `--` reaches the script (#84: devbox 0.17.2 needs the `"$@"` suffix in
`devbox.json`); an unknown or unusable flag fails loudly instead of being ignored. To check the
parsed options without building anything: `devbox run serve -- --dry-run`.
Ctrl-C stops nginx and the server and releases the port; the next start works. State (`state.db`,
`tiles/`), the GM key and the certificate live under `run/lan` and are **not** wiped, so a session
survives a restart and a phone that trusted the certificate does not have to trust it again.
| setting | env | default |
|---|---|---|
| LAN address nginx binds | `FFF_VTT_LAN_HOST` | detected LAN IPv4 (`ip -4 route get 1.1.1.1`) |
| nginx TLS port | `FFF_VTT_LAN_PORT` | `8443` |
| state directory | `FFF_VTT_STATE_DIR` | `run/lan` |
The certificate's SAN is the LAN address. If the laptop's address changes, `serve` regenerates the
certificate (and prints the trust steps again). This is the playtest path, not the M6 deployment:
no systemd unit, hardening or backups.
### Manual fallback: build it once
Everything below is what `devbox run serve` automates; use it when you need to arrange the
processes yourself (or to see the paths involved).
From the repo root, inside devbox:
```sh
devbox run -- nimble install -d -y
devbox run -- nim c --mm:orc --nimblePath:.devbox/nimble/pkgs2 \
--nimcache:run/nimcache/fff-vtt -o:run/fff-vtt server/main.nim
devbox run -- bash -c 'cd client && npm ci && npm run build' # writes client/dist
```
`--nimcache` inside `run/` matters in a worktree: Nim's default cache is shared by every checkout
of the repo and two parallel builds corrupt each other.
### Create the GM key
Only the command line can create or rotate the GM:
```sh
devbox run -- ./run/fff-vtt gm-key --state-dir=run
# prints: GM key: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
```
Re-running prints the same key. `gm-key --new` rotates it and revokes every GM session; it refuses
(exit 3) while the server is running on that state dir, so stop the server first. There is no
in-browser way to become GM and no first-visitor claim: without the key you only ever see the
sign-in page.
### Import the map
The map is a source image plus a tiled copy the server gates per player. One offline command slices
the image and updates the scene; the server must be **stopped** for it (it reads the scene once at
startup) and restarted afterwards. The command also works on a fresh/empty state dir: it creates
the directory, migrates the DB and seeds the scene through the same startup path as the server.
ImageMagick comes from the root devbox.
```sh
# stop the server first, then:
devbox run -- ./run/fff-vtt import --state-dir=run --image=/path/to/map.png
# restart the server with the usual command
```
**Any map image works, up to Full HD.** The cap is 1920 px on the long side and 1080 px on the
short side (either orientation). A larger source is shrunk with ImageMagick's Lanczos filter before
tiling, keeping proportions and alpha, and the import says what it did:
`scaled 4000×3000 → 1440×1080`. Smaller images are imported as-is; nothing is upscaled. The scene's
`w,h` become the (possibly shrunk) image size. A 16384×16384 source therefore becomes 1080×1080 —
1156 tiles at 32 px or 289 at 64 px, not the ~30k a 16384 map used to need.
| argument | meaning |
|---|---|
| `--image=<path>` | source PNG or WebP (required); tiles are always PNG |
| `--tile-size=<px>` | tile edge, default the scene's current tile size; must be a positive multiple of the 32 px explored cell (32 is the default, 64 a common larger choice) |
| `--scene=<id>` | target scene; v1 has exactly one, id 1 |
| `--state-dir=<path>` | the same state dir as the server (default `run`); created and migrated if absent |
Tiles land in `<state-dir>/tiles/1/v<art_version>/<x>_<y>.png`, origin at the world origin, which is
exactly what the gate parses and nginx's internal `/_tiles/` alias serves. The command sets the
scene's width, height and tile size from the image. Importing again grows `art_version` and writes a
new `v` directory, so browsers never keep a stale tile; old versions stay on disk until the M6
cleanup. Any problem exits non-zero and writes no tiles: a missing/unreadable source, an
unsupported or multi-frame image, a scene other than 1, a tile size that is not a multiple of the
cell, a malformed state DB, or a server still holding the state-dir lock (exit 3).
Slicing streams: one ImageMagick decode of the source supplies raw row bands, and a small pool of
`magick` children cuts one tile row each (live caches and file descriptors are bounded by the worker
count, never by the tile count). An import reports where it is on stderr, e.g.
`rows 12/34, tiles 720/2040` for a Full HD map at 32 px; a failure prints the image, the row band and
ImageMagick's own message.
**A Full HD scene with 50 tokens (the phone-playtest target).**
1. Use any single-frame PNG or WebP. Anything larger than 1920×1080 (long side × short side) is
shrunk to the cap automatically. The Full HD maximum is 60×34 = 2040 tiles at 32 px (30×17 = 510
at 64 px); a 16384×16384 square becomes 1080×1080, i.e. 34×34 = 1156 tiles at 32 px (17×17 = 289
at 64 px). The shrink uses ImageMagick's disk-backed pixel cache, so a huge source needs a few GB
of temp space but bounded RSS.
2. Start with the import in one step: `devbox run serve -- --image=run/map16384.png`
(or stop the server, run `fff-vtt import` as above, then restart it). The import prints
`scaled 16384×16384 → 1080×1080` before the tile report.
3. Create the 50 tokens with the seeding tool, not 50 panel submits (a rerun does not double up):
```sh
NODE_EXTRA_CA_CERTS=run/lan/tls/cert.pem \
devbox run seed -- --url=https://<lan-ip>:8443 --tokens=49 --vision=1
```
`--replace` clears the labelled `Seed NN` tokens first; `--seed` changes the deterministic
layout; the GM token panel's X/Y now default to the current viewport centre. Tokens, walls and
explored state are untouched by the import.
4. Point nginx's `/_tiles/` alias at `<state-dir>/tiles` as shown below.
### Start the server
```sh
devbox run -- ./run/fff-vtt --port=9000 --state-dir=run \
--public-origin=https://vtt.example.com
```
| flag | env | default | meaning |
|---|---|---|---|
| `--public-origin` | `FFF_VTT_PUBLIC_ORIGIN` | `http://localhost:8080` | origin the site is served from; compared byte for byte with the browser's `Origin` header, so it must match exactly |
| `--port` | `FFF_VTT_PORT` | `9000` | listen port on `127.0.0.1` |
| `--state-dir` | `FFF_VTT_STATE_DIR` | `run` | holds `state.db`, `instance.lock` and `tiles/` |
Flags win over env, env wins over defaults. A second server on the same state dir refuses to start
(the `instance.lock`).
### Put nginx in front
The server answers `/healthz`, `/join`, `/tiles/` and the `/ws` upgrade. Everything else — the
client build, TLS, the internal tile route — is nginx. This is the shape; `tools/nginx.mjs`
generates exactly this config for the tests and is the reference to copy:
```nginx
# inside http { ... }
map $http_upgrade $conn_up { default upgrade; '' close; }
server {
listen 443 ssl;
http2 on;
ssl_certificate /path/cert.pem;
ssl_certificate_key /path/key.pem;
location = /healthz { proxy_pass http://127.0.0.1:9000; }
location = /join { proxy_pass http://127.0.0.1:9000; access_log off;
add_header Referrer-Policy no-referrer; }
location /tiles/ { proxy_pass http://127.0.0.1:9000; } # server decides, answers X-Accel-Redirect
location = /ws { proxy_pass http://127.0.0.1:9000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $conn_up;
proxy_read_timeout 1h;
proxy_buffering off; }
location /_tiles/ { internal; alias /srv/fff-vtt/tiles/; } # never reachable from outside
location /assets/ { root /srv/fff-vtt/dist; try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable"; }
location = /index.html { root /srv/fff-vtt/dist; try_files /index.html =404;
add_header Cache-Control "no-cache"; }
location / { root /srv/fff-vtt/dist; try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache"; }
}
```
`/_tiles/` must point at `<state-dir>/tiles`; the server only tells nginx which tile to serve and
never sends the bytes itself. Nothing about production deployment (systemd unit, NixOS module,
backup timer) exists in the repo yet; that is M6.
### At the table, as GM
1. Open the site, paste the GM key. The GM is created with the display name `GM` and is not asked to
pick one.
2. **Player keys.** In the GM panel, *Create player key* makes an unused key (24 characters in five
groups of four; case and dashes do not matter). Hand it to one player and that player is bound to
it. *Show* reveals it again, *Replace* rotates it and closes all that player's sessions, *Remove*
frees the slot and hands their characters and tokens to the GM. Maximum six players; unused keys
count toward the cap.
3. **Map.** Only one scene exists. It is seeded at 4096×4096 px with 32 px tiles and cells, a 400 px
default vision radius, a 20 px default token radius and no grid (the grid toggle exists, but the
seeded grid size is 0 and only `scene.set` can change it). Replace the map with the offline
import CLI described under *Import the map* (`fff-vtt import`, server stopped first, restarted
after): it writes the tile tree under `<state-dir>/tiles/1/v<art_version>/` and sets the width,
height and tile size. There is still **no browser upload** (post-v1). A player is served a tile
only after they have explored a cell that overlaps it; the GM
always gets every tile. Because one 32 px cell is the unit of disclosure, do not paint secret
doors, traps or notes into map art near places players can reach — keep secrets as GM-only tokens.
4. **Tokens.** *Create token* takes a kind, a descriptive name, an actual name, a position (X/Y
default to the current viewport centre), a radius
(blank = scene default), a `gm_only` flag and a controller (a player, or blank for the GM).
*Select* a token to edit or remove it, resize it, or add and clear `stuck`/`squeezed` statuses.
The GM may drag any token; a player only their own.
5. **Characters and reveals.** Create a character with a descriptive name, an actual name and an
owner; rename it, move it to another owner, reveal its actual name to one player or to everyone,
remove it (refused while a token still links it). Each player's encountered list is visible to you
and you can delete entries.
6. **Who sees it.** The GM token panel shows which players currently see a token. In this build the
answer is binary — seen or not seen; the graded visible fraction arrives with wall heights.
7. **Walls.** Arm a preset (`wall`, `door`, `window`, `one_way`) and click twice to draw a segment.
Select a wall for its derived kind, a free-text label (never sent to players), the *Players see a
marker* switch, open/close, `secret`/`locked`, the one-way flip, the raw switches behind *Advanced
switches*, delete, and a single-step *Undo*. A secret or locked door looks exactly like a solid
wall to players. Thickness, height and placement controls are not in this build (ADR-0012).
### Not in this build yet
The server already speaks these; the browser has no control for them, so a table needs them only if
you write to the wire yourself:
- the token `vision` switch. It lives in the token's `flags` on the wire, and a token created from the
panel has no vision, so a player token made only through the UI sees no fog of its own;
- the token's character link (`character_id`);
- a property editor (`prop.set` / `prop.unset`, the `public`/`owner`/`gm` buckets);
- a scene settings panel (`scene.set`: name, grid size, default vision and token radii);
- renaming a player (`player.rename`).
Still missing entirely:
- browser map upload (post-v1; the offline `fff-vtt import` CLI exists);
- wall thickness, height, see-over and wall placement (built after the phone playtest, ADR-0012);
- the graded who-sees-it fraction (needs wall heights);
- the NixOS module, systemd unit and backup timer (M6);
- chat, dice, rulers, pings, audio, multiple scenes, accounts.
### As a player
1. Open the same link and enter your key. The first sign-in asks for a display name once; it must be
unique at the table.
2. One-finger drag pans, wheel or pinch zooms (0.5× to 4×).
3. Drag your own token. The move is drawn immediately, then confirmed by the server or rolled back
when a wall or the step limit refuses it.
4. Fog colours: opaque black is floor you have never seen, dimmed map is floor you explored earlier,
clear map is what you can see right now. The little lit-window icon is a window you have already
seen part of.
5. The badge shows `connected`, `reconnecting` or `offline`. A dropped connection keeps the map on
screen and retries; the server then resyncs everything.
### Measure fps on the phone
Open the site with `?perf=1` appended to the URL (for example
`https://192.168.1.50:8443/?perf=1`). After sign-in a small overlay appears in the top-right:
```
fps 59.8 · frame p50 16.6 p95 17.1 ms · JS p50 1.20 p95 2.40 ms · tokens 50 · zoom 1.00
```
It is off by default and adds no per-frame work when off. The line is computed over the last 10 s:
`fps` and the frame interval from the render loop, and `JS` is the main-thread time from the first
ticker listener to after the render submission, so it is an upper bound on the app's JS cost.
`chrome://inspect/#devices` remains the optional cross-check (Frame Rendering Stats + Performance
panel); it needs USB debugging, the overlay does not.
### When something goes wrong
- **"Key not recognised."** — wrong or unknown key; the server deliberately says the same thing for
both. Ask the GM to *Show* the key again. Case, dashes and spaces are ignored.
- **The page says to reload** — the client and server disagree about the protocol version (a
deployment replaced one side only). Reload; if it keeps happening, rebuild the client so both sides
come from the same commit.
- **You are back at the sign-in page** — the key was replaced, you were removed from the table, or
the GM key was rotated. Ask the GM for the current key.
- **The badge says reconnecting** — the network dropped. Retries back off 1, 2, 4, 8, 10 seconds with
jitter; a terminal reason (`revoked`, version mismatch) never retries.
- **A move snaps back** — a wall or the per-step distance limit refused it. Refusals never reveal
where the wall is.
- **The server will not start** — `state dir locked` means another instance already runs on that
directory; `gm-key --new` hits the same lock. Exit 1 is a database or state-dir error, 2 a bad
flag or env value.
---
## For developers
### Rules of the environment
- Everything runs through devbox: `devbox run <script>` or `devbox run -- <command>`. Nothing is
installed globally.
- **Never export devbox's `LD_LIBRARY_PATH` into host tools or stale binaries.** The devbox store is
built against a newer glibc than this NixOS host; a binary or `libsqlite3` built inside devbox and
run outside it fails to load. Run from inside devbox or not at all.
- A fresh worktree needs its dependencies first: `devbox run -- nimble install -d -y`.
- Rebuild after a `devbox.lock` change; never reuse an older binary.
### Commands
| command | what it does |
|---|---|
| `devbox run test` | the server gate: every Nim test file under `tests/`, then the Node black-box harnesses in `tools/*.test.mjs`, then a check that every registered evidence test actually ran and passed |
| `devbox run serve` | the LAN playtest stack: server + client build behind TLS/HTTP2 nginx, persistent state under `run/lan`; `-- --image=<file> [--tile-size=<px>]` imports first, `-- --dry-run` prints the parsed options and exits |
| `devbox run seed` | 49 deterministic NPC tokens over the real WebSocket; `-- --url=<origin> --tokens=49 --vision=1` |
| `devbox run client-test` | client unit tests (Vitest): the pure reducer, protocol client and envelope; no DOM, no GPU |
| `devbox run e2e` | builds `client/dist`, then drives headless Chromium against the real server through the TLS/HTTP2 test nginx |
| `devbox run mutation` | mutation suite on a temp copy of `server/`, `tests/`, `tools/`: every seeded mutation must fail at least one test |
| `devbox run bench` | release-build bench of the vision and egress paths, writing `results/bench.log` |
| `devbox run fogbench` | the 50-token / Full HD (1920×1080, the max scene) server measurement, writing `results/m4-fog-bench.log`; the numbers live in `results/m4-fog-bench.md` |
| `devbox run import-scale` | the map import at the old huge-input scale: a 16384×16384 source shrunk to 1080×1080 (289 tiles at 64 px) under a 256-fd limit, asserting bounded RSS/fds, the printed shrink and progress, writing `results/import-scale.log`; too slow for the pre-push gate (`test` skips it) |
| `devbox run -- nimble install -d -y` | install/refresh the pinned Nim dependencies |
| `devbox run -- bash -c 'cd client && npm ci && npm run dev'` | Vite dev server on :5173 — the UI only, no server API behind it |
The finish gate before a release is `test` + `client-test` + `e2e`; add `mutation` and `bench` when
you touch geometry, vision, move rules or egress.
### How long the tests take
Measured 2026-11-21 on the 16-core Linux host (NixOS, kernel 6.18.64), branch `chore/test-speed`
on 30b3559, with the owner's LAN `serve` running and a second worktree's suite sharing the host for
part of the run (so the numbers are conservative). "Warm" = the worktree's Nim cache
(`run/nimcache/`) is populated; "cold" = it was removed first. The client `node_modules`/`dist`
were present in both.
| suite | warm | cold | notes |
|---|---|---|---|
| `devbox run test` | 44 s | 91 s | 419 Nim checks + 172 Node tests; the 22 fault cases are sharded, the rest fan out at `FFF_TEST_JOBS` |
| `devbox run client-test` | 0.8 s | 0.8 s | Vitest reducer/protocol seam, no build |
| `devbox run e2e` | 157 s | 166 s | 31 browser tests; the client build runs every time; timing-gate files stay serial; ends with one `e2e total:` line (in `results/e2e.log` too) |
| **pre-push total** | **≈202 s** | **≈258 s** | `test` + `client-test` + `e2e` |
| `devbox run mutation` | 500 s | — | 81 mutations (control + 80) on temp copies; `MUTATION_JOBS` defaults to nproc/4 |
| `devbox run bench` | 8 s | — | release build plus the vision/egress run |
| `devbox run import-scale` | ~25 s | — | 16384 px / 65,536-tile import soak; its own script, not in the pre-push gate (#83) |
Before this change the same host measured 263 s warm / 422 s cold for `test` and 176 s for `e2e`
(pre-push 440 s warm / 598 s cold).
Parallelism defaults to half the cores, capped at 8 (the host froze under uncapped load before);
the e2e caps its browser workers at 4. Override with `FFF_TEST_JOBS` (e.g. `FFF_TEST_JOBS=1
devbox run test` serialises the whole gate) or `FFF_E2E_JOBS` for the browser suite alone. Tests
are not weakened by this: the isolation was already per test file (own state dir, free ports, own
nginx/server), and the files whose assertions are wall-clock gates (`persistence`, `tiles`; e2e
`map`, `fog`, `fogbench`, `perf`) run alone first. Harness state dirs live on tmpfs (`/dev/shm`)
when it exists, so the fan-out's SQLite fsyncs do not stall on the disk (`FFF_TEST_NO_TMPFS=1` opts
out). Per-job logs land in `run/logs/`; the gate summaries stay in `results/`.
### Layout
| path | contents |
|---|---|
| `server/` | the Nim server: config, auth, protocol, world/scene, walls, tokens, characters, vision, explored grid, per-recipient views (egress), SQLite migrations, tile gate |
| `client/` | Vite + TypeScript + PixiJS v8 client; `src/` (reducer, slices, render modules, panels), `test/` (Vitest), `e2e/` (Chromium) |
| `tests/` | Nim in-process suites, one file per area (`tvision.nim`, `tmoverules.nim`, `tdb.nim`, …) plus fixtures |
| `tools/` | Node black-box harnesses (WS/HTTP against the real binary), the test nginx, the tile and scene fixture writers, the bench and the mutation script |
| `docs/` | `DESIGN.md` (the spec), `TESTING.md` (how each rule is proven), `adr/` (decisions and why), `agents/` (agent workflow), `research/`, `DESIGN-history.md` |
| `results/` | committed gate evidence (`bench.log`, `leak-*.log`, `mutation.log`, `nimble-test.log`, `probing.log`, `faults.log`, `m4-fog-bench.*`); the per-run `node-test.log`, `e2e.log` and `client-test.log` are regenerated, not committed |
| `run/` | gitignored scratch: built binaries, worktree-local nimcache (including the test files'), per-job test logs (`run/logs/`), local state dirs |
| `docs/archive/prototypes/` | the three prototypes whose measurements the design cites, frozen at the M4 build (#76); the maintained code is `server/` and `client/` |
`GLOSSARY.md` at the root defines the domain words (wall switch, preset, token, character, player
marker, stuck, squeezed, …). Use those words in code, tests and issues.
### Architecture in short
- One Nim process (`mummy`, 4 worker threads) holds the whole world in memory and persists it to a
single SQLite file in WAL mode. Mutations are serialized by one global lock.
- Pipeline per intent: parse → authorize → validate → apply → recompute vision for affected players →
one transaction → ack → egress.
- Egress is the trust boundary: for each connection the server builds that recipient's view from
typed `GmView`/`PlayerView` values, diffs it against what that connection already has, and sends
only the difference. Raw world state has no other path to a socket (ADR-0001, ADR-0002).
- Players get no wall data at all, with one exception: an anchor point plus an opaque id for a marked
window they have already seen (ADR-0015).
- Map tiles are gated per player on the explored cell grid; a tile is allowed once any explored cell
overlaps it, and never taken back (ADR-0005, ADR-0016).
- Sessions are separate from keys: the key is posted to `/join` and only a hash of the session token
is stored (ADR-0018). Server-initiated closes are a `closing` message followed by the close frame,
because the mummy pin cannot put a code in the close frame (ADR-0019).
- Deep detail: `docs/DESIGN.md` §1–§11 (goals, security model, server, vision, protocol, client,
ops) and §13 (milestones); proofs by section number in `docs/TESTING.md`; client extension rules
(append-only slices and render modules) in `client/README.md`.
### Working on it
- Issues and specs live as Gitea issues at `git.fossellini.top`, repo `SirStone/FFF_vtt`. Triage
labels and tracker conventions: `docs/agents/issue-tracker.md`, `docs/agents/triage-labels.md`.
- Commits use conventional subjects with an optional area: `feat(client): drag with prediction and
rollback (#72)`, `fix(server): …`, `docs: …`, `test(walls): …`, `perf: …`, `results: …`. Reference
the issue number in the subject.
- A change lands with its proof: a rule stated once in `docs/DESIGN.md`, its test or oracle once in
`docs/TESTING.md`, and a new decision in `docs/adr/` when it is not obvious. Every check needs a
negative control that proves it can fail.
- Before you push: `devbox run test` and `devbox run client-test` at minimum; add `devbox run e2e`
for anything touching the client, the vhost or the wire, and `devbox run mutation` /
`devbox run bench` for geometry, vision, move rules and egress.
+240
View File
@@ -0,0 +1,240 @@
# FFF VTT client
Vite + TypeScript + PixiJS v8, plain DOM overlay, `proto` 2 (DESIGN §7, ADR-0011). No framework.
## Run and gates
All through devbox, from the repo root:
```sh
devbox run client-test # Vitest: pure reducer + protocol client + envelope (no DOM, no GPU)
devbox run e2e # builds client/dist, then Chromium against the real server through the
# TLS/HTTP2 test nginx (client/e2e/*.test.mjs, playwright-core)
devbox run test # the server gate; unaffected by the client
devbox run -- bash -c 'cd client && npm run dev' # local dev (Vite, no server API on :5173)
```
`npm run build` = `tsc --noEmit && vite build` into `client/dist`, which the test/production nginx
serves at `/` (DESIGN §11.1). `client/dist` and `client/node_modules` are not committed.
## The one seam that matters
`src/reducer.ts` is pure: server frames and connection events in, state out. **It must never import
Pixi, the DOM, or the socket.** Its unit tests (`test/*.test.ts`) are the contract. Everything else
is wiring:
| File | Owns |
|---|---|
| `src/protocol.ts` | Wire types, envelope/ack/closing guards, intent encoding, `/ws?proto=2` URL. Pure. |
| `src/reducer.ts` | `RootState`, phase machine (`boot/connecting/signin/live/reload/offline`), `hello` reset, slice registry. Pure. |
| `src/slices/*.ts` | Append-only domain state (roster today; fog, tokens, walls, panels later). |
| `src/ws.ts` | Socket, `reqId` counter, pending map, close-code mapping, backoff and retry. No DOM. |
| `src/shell.ts` | Sign-in, HUD/roster, fatal screens. Plain DOM, `textContent` only. |
| `src/render/stage.ts` | One Pixi `Application`, one world container, fixed layers. Pixi lives here and in modules only. |
| `src/render/modules/*.ts` | Append-only render modules. |
| `src/main.ts` | Wiring: store -> shell/stage, `/join`, connect. |
## Convention for the M4 fan-out (T7, T8/T9, T10, T11/T12)
The registry is a **build-time glob**, so parallel tickets are file-disjoint: no shared import list
to merge and no registry file to edit.
- **State slice**: add `src/slices/<feature>.ts` exporting `export const slice: Slice<YourState>`
(`name`, `init()`, `reduce(state, event, root)`). It is registered automatically. Read it with
`sliceOf<YourState>(state, '<name>')`. `hello` resets every slice for you (DESIGN §6.3): never
keep server-derived state outside a slice or the core session.
- **Render module**: add `src/render/modules/<feature>.ts` exporting
`export const renderModule: RenderModule` (`name`, `mount(context)`, optional teardown). Draw into
your layer: `tiles`, `grid`, `tokens`, `fog` (players), `gm` (GM only), `dom`.
- **Panel/DOM**: add `src/panels/<feature>.ts` and mount under the existing `#panels` host; do not
rewrite the sign-in flow. Server strings go through `textContent` (never `innerHTML`); token
labels use `BitmapText` with the pre-installed `BitmapFont` (DESIGN §7.2).
- **No per-frame full redraw**: subscribe to the store and touch only entities that changed
(DESIGN §7.2). Keep the DOM overlay work per frame minimal.
- **Protocol**: only the catalogue in DESIGN §6.1. The client ignores unknown frame types/fields
(§6.2). `closing` reasons map through `closeOutcome`: `proto-mismatch` -> reload, `revoked` ->
sign-in, `evicted`/`malformed-flood` -> offline. Do not invent wire fields; server-side additions
are separate tickets (e.g. `seen_by`, T12).
Suggested ownership (no file overlap): T7 fog = `slices/fog.ts` + `render/modules/fog.ts`; T8/T9
tokens/drag = `slices/tokens.ts`, `slices/move.ts`, `render/modules/tokens.ts`; T10 walls =
`slices/walls.ts` + `render/modules/walls.ts`; T11/T12 GM panels = `slices/admin.ts` +
`src/panels/*.ts`. `src/reducer.ts`, `src/main.ts` and `src/render/stage.ts` are already generic;
change them only if a slice needs a new *core* event, and say so in the PR.
## Protocol notes already encoded
- `/ws?proto=2`; a mismatch is `closing{reason:"proto-mismatch",code:4003}` then close. The reason
is read from the last `closing` frame because browsers report 1005 at the mummy pin (ADR-0019).
- `hello` resets all state; the resync after it rebuilds the view. Pending `reqId`s survive a
`hello` on a live connection and die with the socket (DESIGN §6.3).
- Sign-in is `POST /join` (form body, key never in the URL). A `401` for a wrong key and for an
unknown key is shown as the same "Key not recognised." (DESIGN §3.2, story 3).
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
only sees the sign-in page.
## Traffic audit and the M4 measurement (T13, #76)
- **Traffic audit** (`e2e/audit.test.mjs`) is the independent proof that the player browser cannot
become a leak. It records the page's own WebSocket frames and HTTP responses and applies its own
rules: only the 13 player frame types; no wall field and no GM-only token column at any depth; no
other player's id and no token outside the player's sight; vision polygons only for controlled
tokens; explored cells only inside a historical own-vision bbox; tiles only under `/tiles/`, only
200/403, every served tile covering an explored cell, and `/_tiles/` unreachable. The banned-key
list is written in the test, never imported from `tools/leakcheck.nim`, so the proof is independent
of the server's own list. A second test is the negative control: the same rules run against a
`-d:leakfault` build with `LEAK_FAULT=otherVision` and must catch the injected foreign polygon.
- **50-token measurement**: the server half is `tools/fogbench.nim` (`devbox run fogbench`, Full HD
1920×1080, the max scene, 50 tokens, thousands of walls); the headless half is
`e2e/fogbench.test.mjs`. Numbers and the honest caveat
(SwiftShader is a floor, not a phone) are in `results/m4-fog-bench.md`. The real 60 fps run is #77.
## Name, badge and reconnect (T5, #68)
- **First sign-in name prompt.** A live player with `me.name === null` gets the `#name` section
instead of the HUD, and no Pixi stage (the server sends no scene, no state, until named). Submitting
sends `player.setname`; the server acks *before* the second `hello` (FIXED #33), so a refusal's
code becomes visible text on the prompt (`name-taken` → "That name is taken. Choose another.",
`invalid` and `not-allowed` have their own copy) and an acceptance is followed by the `hello` that
resets every slice plus the 6.3 resync. The prompt is keyed on state, so it cannot come back and
survives a reload with the same session.
- **Badge** (`#badge[data-state]`): `connected` while live; `reconnecting` while the socket backs
off, with the stale map staying on screen; `offline` when the browser reports no network
(`navigator.onLine`/`online`/`offline` events) or after a terminal outcome (`evicted`,
`malformed-flood`, `server-shutdown`). Hidden on boot, sign-in and reload.
- **Reconnect** (DESIGN 6.3): a transport close (no `closing` frame) after a connection has been
live retries with `backoffDelay`: base 1/2/4/8/10 s then the cap, ±20 % jitter
(`RECONNECT_BASE_DELAYS_MS`, `RECONNECT_JITTER`). Terminal reasons never retry: `revoked` →
sign-in, `proto-mismatch` → reload. Pending `reqId`s die with the socket; a browser `online` event
calls `retryNow()` to skip the rest of the wait. The view is **not** cleared on a drop: `hello` is
the reset point, and the resync that follows rebuilds tokens, fog, explored, markers and lists.
- **Two devices** of one player both stay live and receive the same frame stream (each connection
has its own `known` table, DESIGN 6.3).
- **Proof**: `test/ws.test.ts` (schedule, retry state machine, pending drop) and
`test/reducer.test.ts` (badge transitions, reconnect reset, name errors) are the unit seam;
`e2e/session.test.mjs` kills and restarts the real server under a live page, drops the browser
network with `context.setOffline`, asserts the badge transitions and the full resync frames, and
runs two pages on one key.
## Map tiles, grid and pan/zoom (T6, #69)
- **Camera** (`src/viewport.ts`, pure): the world container is `screen = world * zoom + (x, y)`.
Players clamp at `0.5` and the GM has no player floor (a `1/64` sanity floor only keeps the
transform non-singular); both clamp at `4.0` (ADR-0013, spec #63 decision 7). Wheel and pinch zoom
around the pointer/midpoint, one-finger drag pans. Input is hand-rolled DOM pointer/wheel events
on the canvas (`src/render/modules/camera.ts`, DESIGN 7.2: no Pixi federated events), and the
canvas gets `touch-action: none`.
- **Camera is not a reducer slice.** It is local UI state; a `hello` resets every slice by design,
and a reconnect must not move the player's view. `ViewportModel` is owned by the render layer and
reset only when a new stage is created. The canvas carries the e2e facts `data-zoom`, `data-grid`
and `data-view` (viewport px).
- **Tiles** (`src/tiles.ts` scheduler + `src/render/modules/tiles.ts` layer): the wanted set is
`visibleTiles()` — every tile intersecting the viewport plus exactly one tile of margin, clamped
to the scene — ordered centre-out (`orderTilesCentreOut`), so a survey fill grows from what the
eye is on instead of the top-left corner. The scheduler keeps at most `TILE_CONCURRENCY` (32,
the measured knee on a Full HD scene) loads in flight, drops queued tiles that leave the window,
never asks twice for a tile, and remembers a `403` as `denied`: the gate has said "not yours", so
it is not retried in a loop (it is asked once more when `fog.fresh` says its cells were explored).
A `404`/`5xx`/network failure is transient: up to 3 loads with 250/500 ms backoff, and a
reconnect (`hello`) or a scene/`art_version` change resets the budget and re-asks. The settle path
is incremental (one settle = one tile), so filling tens of thousands of tiles is not quadratic.
The decoded-texture cache is module-level and keyed by URL, so a reconnect keeps every tile; a new
`art_version` changes every URL, so it drops the cache and refetches. `data-tiles` is `ready` once
the current pass is complete: every wanted tile has a terminal answer (`ok`, `denied`, or a
stored transient `error` that waits for a retry, a new window or a reconnect). A transient
`error` is deliberately not pending, otherwise one host hiccup would hold the flag at `loading`
and hang every e2e readiness wait. `data-tile-requests` counts fetches; `data-tile-distinct`
counts the distinct tile URLs fetched, so the #70 re-ask of a tile whose 403 became allowed shows
in the former, not the latter.
- **One request per tile:** `fetch` then `createImageBitmap` (decode off the main thread). An
`<img>` error carries no status, so classifying it cost a second `fetch` for *every* failure; the
fetch-first path gets 403 vs 404/5xx from the same response and lets the scheduler retry a
missing tile instead of leaving a permanent hole.
- **Grid** (`src/render/modules/grid.ts`): one `TilingSprite` over a `grid_size` cell texture, drawn
once, toggled by `#grid-toggle` (story 18). No per-frame redraw.
- **Tile-size gate (a)** (`client/e2e/map.test.mjs`): mobile emulation 412×869 CSS px, DPR 2.625,
touch; real server through the TLS/HTTP2 nginx; viewport **412×869 at zoom 1**. Each sample is a
fresh page load measured from the canvas becoming visible to `data-tiles=ready`, i.e. one first
viewport filling. A single wall-clock sample is host-load-sensitive, so the gate is the fastest of
**4 samples after 1 warm-up** (min-of-N, TESTING §5.3), asserted against **2× the 1 s budget**
(the documented saturated-host tolerance) and printed with every sample on every run. Measured
2026-11-21: **439 ms** fastest on the dev host (samples 628, 778, 444, 439 ms); **1.3–1.9 s**
fastest under a saturated 16-core host with the same binary. The same test then applies CDP's 4× CPU throttle for the grid,
pinch and reconnect checks. Note: under the 4× throttle the *fill itself* takes ~3.2 s, because CDP
multiplies each of the ~480 image-load callbacks; that measures the throttler rather than the app,
so the gate is measured at real CPU and gate (b), the real-phone run (#77), remains authoritative
for phone speed.
## GM wall editor, round-1 fields (T10, #73)
- **State**: `src/slices/walls.ts` is the GM wall slice: `walls` (full snapshot on connect/resync),
`wall` (upsert, doors included) and `wall_gone`, plus the editor's selected id and its single-step
undo descriptor. Wall frames are GM-only, and the slice also ignores them on a player-shaped
session, so a server bug could not quietly turn the client into a wall-data renderer. `hello`
resets it like every slice.
- **Pure rules**: `src/wallEditor.ts` expands the four 5.8 presets (`wall`, `door`, `window`,
`one_way`), derives `kind` in the fixed order (window, one_way, door, wall, else custom), computes
the one-way arrow toward the blind side named by `sight_dir`, snaps to endpoints then the grid,
and builds the exact DESIGN 6.1 payloads. A preset payload carries only `preset` (never a raw
switch, `open:false` included); `wall.update` never carries `open` because opening and closing are
`door.set`. The same module holds the local pre-flight validation so an impossible combination is
shown before an intent leaves the browser.
- **Renderer + input**: `src/render/modules/walls.ts` draws each wall on the `gm` layer (derived-kind
colour, open doors dashed, secret doors dotted, selected endpoints, the one-way arrow and the
marker switch). Input precedence is explicit: token drag (#72) wins first and consumes its
gesture; wall drawing wins next while a preset is armed (the two clicks never pan); otherwise the
camera (#69) pans and a click with no movement selects the nearest wall. A drag that moved is a
pan, not a selection. The canvas publishes `data-walls`, `data-wall-kinds`, `data-wall-selected`,
`data-wall-arrows`, `data-wall-markers`, `data-wall-draw`, `data-wall-preview` and `data-wall-undo`
for the e2e.
- **Panel**: `src/panels/walls.ts` adds `#gm-walls` under `#panels` via the render module (no shared
bootstrap edit): preset buttons arm the draw, then the selected wall exposes its server-derived
kind, label, `player_marker`, door/open/close, `secret`/`locked`, the advanced raw switches (with
`Apply switches`), the one-way flip, delete and Undo. A locked or secret door's open action shows
`locked: unlock first` / `secret: clear secret first` and the one click that clears the block
instead of sending a refused intent. No thickness, height or position control (ADR-0012).
Controls are repopulated only when the server record changed (`src/panels/wallSync.ts`): the ack
dispatch carries the previous record, so repopulating on every render would revert a just-toggled
switch for the round trip until the `wall` frame lands (and a host pause could make that visible).
- **Proof**: `test/walls.test.ts` (slice load/upsert/remove/reset, player frames ignored, preset
expansion, derived kind, arrow side, snap, payload XOR rules, `open` excluded from updates, undo
intents, local validation) and `e2e/walls.test.mjs` (real server: draw all four presets, label,
marker, locked hint + one-click unlock, open/close, advanced invalid combination shown, delete +
undo, a token drag still beats draw mode, and the player's fog pixels change for a wall, a one-way
flip, a door open/close and the marker, with no wall data in the player's frames).
## Tokens, labels, statuses and the two lists (T8, #71)
- **State**: `src/slices/tokens.ts` (`token` upsert, `token_gone`, `hello` reset; `tokensOf`),
`src/slices/characters.ts` (`character`/`character_gone`, `ownCharactersOf`) and
`src/slices/encountered.ts` (`full` replace, `set`/`del` diff, grey flag; the GM's per-player
copies are ignored). All three are append-only slice files: the registry and `main.ts` are
untouched.
- **Renderer**: `src/render/tokenBoard.ts` is the pure half. It turns the store's *events* into the
exact nodes to touch — `entered`, `updated`, `left`, or a `hello` reset — and keeps the view it
last drew, so a frame that moves one token updates one container and nothing else (DESIGN 7.2).
It also seeds itself from the reducer on mount, because `app.init()` is async and the resync can
beat the stage. `src/render/modules/tokens.ts` is the Pixi half: pooled containers on the
`tokens` layer **in world coordinates** (the camera from #69 transforms the layer's parent, never
a token), one shared unit-circle `GraphicsContext` per kind scaled to the effective radius, and
`BitmapText` labels from one pre-installed `BitmapFont` (`fff-token-label`: Latin, accented Latin
and ASCII) assigned only when the name actually changed. `stuck` and `squeezed` are drawn badges
(barred ring, inward brackets); the cause is never drawn because a player never receives it.
- **Instrumentation** for the "only changed entities touched" acceptance criterion lives on the
canvas dataset: `data-tokens`, `data-token-entered`, `data-token-updated`, `data-token-left`,
`data-token-labels`, `data-token-ids`, `data-token-statuses`. It is updated only when a patch did
something, and `e2e/tokens.test.mjs` reads it against the real server.
- **Lists panel**: `src/panels/lists.ts` (`#lists` under the shell's `#panels`: `#characters`,
`#encountered`, rows with `data-character`/`data-token` and `data-grey`, `textContent` only) is
mounted by `src/render/modules/lists.ts`, a render module, so the panel's lifetime is the live
stage's and no shared bootstrap file had to change. Greyed rows carry both `data-grey="true"` and
the `grey` class, plus an "out of sight" label so the state is not colour-only.
- **Drag seam (#72)**: `applyView(node, view, stats, at?)` already takes the position to draw, so a
drag module can pass its optimistic position for the node under the pointer and let the
authoritative view resume on ack/rollback. The reducer's token view stays the server's word.
- **Proof**: `test/tokens.test.ts` (enter/update/leave, status names without `source`, GM fields,
malformed frames), `test/lists.test.ts` (own characters, encountered full/diff/grey, GM copies),
`test/token-board.test.ts` (one changed entity per frame, no phantom enter+leave, reset on
`hello`, seeding) and `e2e/tokens.test.mjs` (real server: player and GM token sets, a `gm_only`
token the player never receives, the stuck badge, both lists, `token_gone` plus the grey flip,
and one-entity updates with unchanged label builds).
+28
View File
@@ -0,0 +1,28 @@
// #82: the GM token form starts at the viewport centre, not the old 400,400. The scene is the
// seeded 4096x4096 one, so the initial 1000x700 GM view centres on 2048,2048.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, signIn, waitForVisible, withStack } from './stack.mjs'
test('GM token create defaults X/Y to the viewport centre', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, '#stage canvas')
await page.click('#gm-token-create-section > summary')
await page.waitForFunction(() => {
const x = document.querySelector('#token-x')
const y = document.querySelector('#token-y')
return x?.value === '2048' && y?.value === '2048'
}, undefined, { timeout: 20000 })
assert.equal(await page.inputValue('#token-x'), '2048')
assert.equal(await page.inputValue('#token-y'), '2048')
} finally {
await browser.close()
}
})
})
+409
View File
@@ -0,0 +1,409 @@
// T11 (#74, TESTING 10.3): GM roster, player keys and the token panel against the real server
// through the TLS/HTTP2 test nginx. The GM drives the panel; a player page records its own WS
// frames so the test also proves that keys never reach player traffic and `gm_only` tokens never
// reach the player until the GM allows them.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, join, namePlayer } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
async function recordSockets(page) {
await page.addInitScript(() => {
window.__wsLog = { frames: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
this.addEventListener('message', event => {
try {
window.__wsLog.frames.push(JSON.parse(event.data))
} catch {
// non-JSON frames are not state
}
})
}
}
window.WebSocket = RecordingSocket
})
}
const frames = page => page.evaluate(() => window.__wsLog.frames ?? [])
async function lastTokenFrame(page, id) {
return page.evaluate(
tokenId => (window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1),
id,
)
}
async function keyFromStatus(page, pattern) {
const text = await waitForText(page, '#gm-key-status', pattern)
const match = /^(?:Key for player \d+|New key for player \d+): (.+)$/.exec(text.trim())
assert.ok(match, `no key in status ${JSON.stringify(text)}`)
return match[1]
}
async function waitTokenFrame(page, id, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await lastTokenFrame(page, id)
if (last && predicate(last)) return last
await new Promise(resolve => setTimeout(resolve, 50))
}
throw new Error(`token ${id} never matched; last was ${JSON.stringify(last)}`)
}
async function waitForHiddenRow(page, tokenId) {
await page.locator(`#gm-token-list li[data-token="${tokenId}"]`).waitFor({ state: 'detached', timeout: 20000 })
}
test('GM roster, keys and token panel drive the real server', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, server, stateDir }) => {
const keys = []
const browser = await launchBrowser()
const raw = await openAs(origin, gmKey)
const rawHello = await raw.ws.waitText('hello')
const scene = rawHello.scene?.id ?? (await raw.ws.waitText('walls')).scene
try {
// ---- sign in as GM and see the roster with connected state ------------------------------
const gmView = await newPage(browser)
const gm = gmView.page
await recordSockets(gm)
await gm.goto(`${origin}/`)
await waitForVisible(gm, '#signin')
await signIn(gm, gmKey)
await waitForVisible(gm, '#gm-panels')
await waitForText(gm, '#gm-roster-list', /GM/)
await waitForText(gm, '#gm-roster-list', /connected/)
assert.equal(await gm.locator('#gm-panels').isVisible(), true)
// The create form and the 50-row token list start folded (M4 UX); open both for this flow.
await gm.click('#gm-token-create-section > summary')
await gm.click('#gm-token-list-section > summary')
// ---- key.create through the panel, key visible only in the GM DOM ----------------------
await gm.click('#gm-key-create')
const firstStatus = await waitForText(gm, '#gm-key-status', /Key for player \d+: /)
const firstMatch = /^Key for player (\d+): (.+)$/.exec(firstStatus.trim())
assert.ok(firstMatch, `unexpected key status ${firstStatus}`)
const aliceId = Number(firstMatch[1])
const aliceKey = firstMatch[2]
keys.push(aliceKey)
assert.equal(await gm.textContent(`#gm-key-${aliceId}`), aliceKey)
// A player created outside the panel (an unused key) can be shown by the panel's Show.
const second = await createPlayer(raw.ws)
keys.push(second.key)
await waitForVisible(gm, `#gm-key-show-${second.id}`)
await gm.click(`#gm-key-show-${second.id}`)
await waitForText(gm, `#gm-key-${second.id}`, new RegExp(second.key.replace(/-/g, '\\-')))
// ---- key.replace through the panel ----------------------------------------------------
await gm.click(`#gm-key-replace-${second.id}`)
const replacement = await keyFromStatus(gm, /New key for player/)
keys.push(replacement)
assert.notEqual(replacement, second.key)
assert.equal((await join(origin, second.key)).status, 401, 'the replaced key is dead')
assert.equal((await join(origin, replacement)).status, 303, 'the new key works')
// ---- the cap, then remove frees the slot ----------------------------------------------
// alice + second are 2 of 6; fill the table to the cap with real key.create acks.
for (let i = 0; i < 4; i += 1) {
const extra = await createPlayer(raw.ws)
keys.push(extra.key)
}
await gm.click('#gm-key-create')
await waitForText(gm, '#gm-key-status', /full/i)
await waitForVisible(gm, `#gm-player-remove-${second.id}`)
await gm.click(`#gm-player-remove-${second.id}`)
await waitForText(gm, '#gm-key-status', /removed/i)
assert.equal(await gm.locator(`#gm-player-remove-${second.id}`).count(), 0)
await gm.click('#gm-key-create')
const freed = await keyFromStatus(gm, /Key for player \d+: /)
keys.push(freed)
// ---- a named player page records its own wire for the token and key assertions ---------
await namePlayer(origin, aliceKey, 'Alice')
const playerView = await newPage(browser)
const player = playerView.page
await recordSockets(player)
await player.goto(`${origin}/`)
await waitForVisible(player, '#signin')
await signIn(player, aliceKey)
await waitForVisible(player, '#hud')
await waitForText(player, '#me', /^Alice$/)
await waitForText(gm, '#gm-roster-list', /Alice/)
await waitForText(gm, '#gm-roster-list', /connected/)
// A scout gives the player a real line of sight, so a GM-controlled token can be shown and
// hidden by `gm_only` (a token the player controls is always visible, by 3.1). It is created
// through the token panel with vision on (#78): no raw `flags`/`vision_radius` shortcut.
await waitForVisible(gm, '#token-controller')
await gm
.locator(`#token-controller option[value="${aliceId}"]`)
.waitFor({ state: 'attached', timeout: 20000 })
await gm.fill('#token-kind', 'pc')
await gm.fill('#token-name', 'Scout')
await gm.fill('#token-actual', 'Scout')
await gm.fill('#token-x', '400')
await gm.fill('#token-y', '400')
await gm.fill('#token-radius', '20')
await gm.check('#token-vision')
await gm.fill('#token-vision-radius', '400')
await gm.selectOption('#token-controller', String(aliceId))
await gm.click('#token-create-submit')
const scoutRow = gm.locator('#gm-token-list li', { hasText: 'Scout' }).first()
await scoutRow.waitFor({ state: 'visible', timeout: 20000 })
const scoutId = await scoutRow.getAttribute('data-token')
assert.ok(scoutId, 'the panel-created scout has no id')
await waitTokenFrame(player, scoutId, frame => frame.mine === true)
// AC #78: the GM's `token` frame carries the same flags.vision and vision_radius after the ack.
const scoutFrame = await waitTokenFrame(
gm,
scoutId,
frame => frame.flags?.vision === true && frame.vision_radius === 400,
)
assert.equal(scoutFrame.flags.vision, true)
assert.equal(scoutFrame.vision_radius, 400)
// AC #78: the panel-created sight explores the player's set, without wire poking: an
// explored tile answers 200 and an unexplored one 403 for that player.
writeTileGrid(stateDir, {
scene,
artVersion: rawHello.scene.art_version,
size: rawHello.scene.tile_size,
x0: 0,
x1: 60,
y0: 0,
y1: 60,
})
const wallSession = await join(origin, aliceKey)
const tileStatus = async (x, y) =>
(await fetch(`${origin}/tiles/${scene}/v${rawHello.scene.art_version}/${x}_${y}.png`, {
headers: { cookie: wallSession.cookie },
})).status
await player.waitForFunction(
() => (window.__wsLog?.frames ?? []).some(frame => frame.t === 'vision'),
null,
{ timeout: 20000 },
)
assert.equal(await tileStatus(12, 12), 200, 'the explored tile is allowed')
assert.equal(await tileStatus(30, 30), 403, 'the unexplored tile is refused')
// ---- token.create through the panel ---------------------------------------------------
// Vision off by default (DESIGN 8 `flags: '{}'`): clear the scout's controls explicitly.
await gm.uncheck('#token-vision')
await gm.fill('#token-vision-radius', '')
await gm.fill('#token-name', 'Rat')
await gm.fill('#token-actual', 'Giant Rat')
await gm.fill('#token-x', '460')
await gm.fill('#token-y', '450')
await gm.fill('#token-radius', '5')
await gm.selectOption('#token-controller', '')
await gm.click('#token-create-submit')
const tokenRow = gm.locator('#gm-token-list li', { hasText: 'Rat' }).first()
await tokenRow.waitFor({ state: 'visible', timeout: 20000 })
const tokenId = await tokenRow.getAttribute('data-token')
assert.ok(tokenId, 'new token has no id in the panel')
await waitTokenFrame(player, tokenId, frame => frame.mine === false)
// ---- controller: the player becomes the token's controller ----------------------------
await gm.click(`#gm-token-select-${tokenId}`)
await waitForVisible(gm, '#gm-token-editor')
await gm.selectOption('#token-edit-controller', String(aliceId))
await gm.click('#token-save')
await waitTokenFrame(player, tokenId, frame => frame.mine === true)
assert.equal((await lastTokenFrame(player, tokenId)).name, 'Rat')
// ---- edit: a rename reaches the player ------------------------------------------------
await gm.fill('#token-edit-name', 'Big Rat')
await gm.click('#token-save')
await waitTokenFrame(player, tokenId, frame => frame.name === 'Big Rat')
await waitForText(gm, '#gm-token-list', /Big Rat/)
// ---- edit: vision and its radius round-trip through the panel (#78) -------------------
await gm.check('#token-edit-vision')
await gm.fill('#token-edit-vision-radius', '250')
await gm.click('#token-save')
const visionOn = await waitTokenFrame(
gm,
tokenId,
frame => frame.flags?.vision === true && frame.vision_radius === 250,
)
assert.equal(visionOn.flags.vision, true)
await gm.uncheck('#token-edit-vision')
await gm.fill('#token-edit-vision-radius', '')
await gm.click('#token-save')
const visionOff = await waitTokenFrame(
gm,
tokenId,
frame => frame.flags?.vision === false && frame.vision_radius === null,
)
assert.equal(visionOff.flags.vision, false)
// ---- gm_only hides the token from the player, clearing it reveals it again -------------
// A controlled token is always visible (3.1), so hand it back to the GM while it is hidden.
await gm.check('#token-edit-gm-only')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /gm_only/)
await gm.selectOption('#token-edit-controller', '')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /controller GM/)
await player.waitForFunction(
tokenId => {
const gone = (window.__wsLog?.frames ?? []).findLast(frame => frame.t === 'token_gone' && frame.id === tokenId)
if (!gone) return false
const last = (window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1)
return !last || (window.__wsLog.frames.indexOf(last) < window.__wsLog.frames.indexOf(gone))
},
tokenId,
{ timeout: 20000 },
)
await gm.uncheck('#token-edit-gm-only')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /visible/)
await player.waitForFunction(
tokenId => {
const log = window.__wsLog?.frames ?? []
const last = log.filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1)
const gone = log.findLast(frame => frame.t === 'token_gone' && frame.id === tokenId)
return Boolean(last) && (!gone || log.indexOf(last) > log.indexOf(gone))
},
tokenId,
{ timeout: 20000 },
)
// ---- status: GM-sourced stuck reaches the viewer, then clears --------------------------
await gm.click('#token-status-stuck')
await waitTokenFrame(player, tokenId, frame => (frame.statuses ?? []).some(entry => entry.status === 'stuck'))
await waitForText(gm, '#token-status', /stuck \(GM\)/i)
await gm.click('#token-status-clear-stuck')
await waitTokenFrame(
player,
tokenId,
frame => !(frame.statuses ?? []).some(entry => entry.status === 'stuck'),
)
// ---- resize: the server pushes the grown token away from a blocking wall ---------------
const wall = await raw.ws.request({
t: 'wall.add',
scene,
a: [500, 400],
b: [500, 500],
preset: 'wall',
})
assert.equal(wall.ok, true)
await gm.fill('#token-resize-radius', '60')
await gm.click('#token-resize')
await waitTokenFrame(player, tokenId, frame => Math.round(frame.radius) === 60)
const pushed = await lastTokenFrame(player, tokenId)
assert.ok(pushed.pos[0] < 460, `expected the grow push left of 460, got ${JSON.stringify(pushed.pos)}`)
await waitForText(gm, '#gm-token-list', /r60/)
// ---- remove: the panel drives token.remove and the player is told ----------------------
await gm.click('#token-remove')
await waitForHiddenRow(gm, tokenId)
await player.waitForFunction(
tokenId => (window.__wsLog?.frames ?? []).some(frame => frame.t === 'token_gone' && frame.id === tokenId),
tokenId,
{ timeout: 20000 },
)
// ---- keys never reach the player: no frame field, no DOM text, no server log ----------
const playerFrames = await frames(player)
assert.equal(
playerFrames.some(frame => frame && Object.prototype.hasOwnProperty.call(frame, 'key')),
false,
'a `key` field reached the player wire',
)
const wire = JSON.stringify(playerFrames)
const playerHtml = await player.content()
const log = server.log()
for (const key of keys) {
assert.equal(wire.includes(key), false, 'a player key reached the player wire')
assert.equal(playerHtml.includes(key), false, 'a player key reached the player DOM')
assert.equal(log.includes(key), false, 'a player key reached the server log')
}
assert.equal(await player.locator('#gm-panels').isVisible(), false)
} finally {
raw.ws.close()
await browser.close()
}
})
})
// #88: a plain reconnect is not a rename, so `roster` has to follow connections coming and going.
async function waitRosterState(page, id, want, timeout = 30000) {
try {
await page.waitForFunction(
([playerId, state]) => {
const node = document.querySelector(
`#gm-roster-list li[data-player="${playerId}"] .gm-roster-state, ` +
`#gm-roster-list li[data-player="${playerId}"] #gm-roster-state`,
)
return node?.textContent === state
},
[id, want],
{ timeout },
)
} catch (error) {
const rows = await page.evaluate(() =>
[...document.querySelectorAll('#gm-roster-list li')].map(li => li.textContent),
)
throw new Error(`${error.message}; roster was ${JSON.stringify(rows)}`)
}
}
test('GM roster connected follows a player tab reload and close', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const raw = await openAs(origin, gmKey)
await raw.ws.waitText('hello')
await raw.ws.waitText('walls')
const bob = await createPlayer(raw.ws)
await namePlayer(origin, bob.key, 'Bob')
const browser = await launchBrowser()
try {
const gmView = await newPage(browser)
const gm = gmView.page
await gm.goto(`${origin}/`)
await waitForVisible(gm, '#signin')
await signIn(gm, gmKey)
await waitForVisible(gm, '#gm-panels')
await gm.locator(`#gm-roster-list li[data-player="${bob.id}"]`).waitFor({ state: 'visible' })
await waitRosterState(gm, bob.id, 'offline')
const bobView = await newPage(browser)
const bobPage = bobView.page
await bobPage.goto(`${origin}/`)
await waitForVisible(bobPage, '#signin')
await signIn(bobPage, bob.key)
await waitForVisible(bobPage, '#hud')
await waitForText(bobPage, '#me', /^Bob$/)
await waitRosterState(gm, bob.id, 'connected')
// A reload is a plain reconnect: no setname, but the GM row must end up online again.
await bobPage.reload()
await waitForVisible(bobPage, '#hud')
await waitForText(bobPage, '#me', /^Bob$/)
await waitRosterState(gm, bob.id, 'connected')
// Closing the tab must flip the row offline without any intent from the player.
await bobView.context.close()
await waitRosterState(gm, bob.id, 'offline')
await gmView.context.close()
} finally {
raw.ws.close()
await browser.close()
}
})
})
+406
View File
@@ -0,0 +1,406 @@
// T13 (#76, TESTING 10.3 "Independent traffic audit"): record every WebSocket frame and every HTTP
// response the *player browser* receives, then judge that recording with this file's own rules.
//
// Independence is the point: the banned-key list, the frame catalogue and the geometry checks below
// are written here and never imported from the server's `tools/leakcheck.nim` or `BannedAlways`. A
// server list that quietly loses an entry must not be able to weaken this proof.
//
// The scenario is a player who must see a lot of interesting state (own token, an NPC in sight, a
// window marker, fog, explored cells, tile requests including refused ones) while the GM authors
// every round-1 wall field. A second player and a `gm_only` token sit outside the audited player's
// sight; none of their ids may appear in its traffic.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import { launchBrowser, newPage, signIn, waitForVisible, withStack } from './stack.mjs'
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
const OWN = [2048, 2048]
const OTHER = [3500, 3500]
/** DESIGN 6.1 server -> client rows a *player* may receive. GM-only rows are absent by design. */
const PLAYER_FRAMES = new Set([
'hello', 'ack', 'error', 'roster', 'vision', 'explored', 'token', 'token_gone',
'character', 'character_gone', 'encountered', 'closing', 'marker',
])
/**
* Fields a player must never receive. Own copy, deliberately broader than any server list: every
* wall geometry field, the GM-only wall and token columns, and the GM-only status cause.
*/
const BANNED_KEYS = new Set([
// wall rows and the GM-only wall frames
'wall', 'walls', 'wall_gone',
'a', 'b', 'thickness', 'position', 'height', 'kind',
'blocks_sight', 'blocks_movement', 'sight_dir', 'player_marker',
'door', 'open', 'secret', 'locked', 'label', 'flags',
// GM-only token columns
'controller', 'gm_only', 'descriptive_name', 'actual_name', 'reveal_all', 'revealed',
'seen_by', 'source',
])
/** Record the page's own WebSocket frames without changing what the app sees. */
async function recordSockets(page) {
await page.addInitScript(() => {
window.__audit = { sockets: 0, frames: [], closes: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
this.opened = false
window.__audit.sockets += 1
this.addEventListener('open', () => { this.opened = true })
this.addEventListener('message', event => {
try {
window.__audit.frames.push(JSON.parse(event.data))
} catch {
window.__audit.frames.push({ t: '<unparsed>', raw: String(event.data).slice(0, 80) })
}
})
this.addEventListener('close', event => {
window.__audit.closes.push({ code: event.code, reason: event.reason, opened: this.opened })
})
}
}
window.WebSocket = RecordingSocket
})
}
const framesOf = page => page.evaluate(() => window.__audit.frames)
async function waitForFrames(page, predicate, timeout = 20000) {
await page.waitForFunction(predicate, null, { timeout })
}
function walkKeys(value, visit) {
if (Array.isArray(value)) {
for (const item of value) walkKeys(item, visit)
return
}
if (value === null || typeof value !== 'object') return
for (const [key, child] of Object.entries(value)) {
visit(key)
walkKeys(child, visit)
}
}
/** Every explored cell the player was ever told about, from full RLE snapshots and cell diffs. */
function exploredCells(frames) {
const cells = new Set()
for (const frame of frames) {
if (frame.t !== 'explored') continue
if (frame.full) {
for (const row of frame.rle ?? []) {
const cy = row[0]
for (let i = 1; i + 1 < row.length; i += 2) {
const x0 = row[i]
const len = row[i + 1]
for (let x = x0; x < x0 + len; x += 1) cells.add(`${x},${cy}`)
}
}
} else {
for (const [cx, cy] of frame.cells ?? []) cells.add(`${cx},${cy}`)
}
}
return cells
}
/** Bounding boxes (cell coordinates) of every vision polygon the player was ever sent. */
function visionBoxes(frames, cell) {
const boxes = []
for (const frame of frames) {
if (frame.t !== 'vision') continue
for (const poly of frame.polys ?? []) {
const pts = poly.pts ?? []
if (pts.length === 0) continue
const xs = pts.map(([x]) => x)
const ys = pts.map(([, y]) => y)
boxes.push({
id: poly.id,
x0: Math.floor(Math.min(...xs) / cell) - 1,
y0: Math.floor(Math.min(...ys) / cell) - 1,
x1: Math.ceil(Math.max(...xs) / cell) + 1,
y1: Math.ceil(Math.max(...ys) / cell) + 1,
})
}
}
return boxes
}
function insideAnyBox(cx, cy, boxes) {
return boxes.some(b => cx >= b.x0 && cx <= b.x1 && cy >= b.y0 && cy <= b.y1)
}
/** Judge the player's frame stream. Every rule below returns what it found, so the negative
* control can prove each rule can fail, not only that a clean run is empty. */
function frameViolations(frames, { foreignPlayerId = null, foreignTokenIds = [], cell = 32, near = null } = {}) {
const offCatalogue = frames.filter(frame => !PLAYER_FRAMES.has(frame.t))
const banned = []
for (const frame of frames) {
walkKeys(frame, key => {
if (BANNED_KEYS.has(key)) banned.push({ t: frame.t, key })
})
}
const ownIds = new Set(frames.filter(f => f.t === 'token' && f.mine === true).map(f => f.id))
const polyIds = new Set(frames.filter(f => f.t === 'vision').flatMap(f => (f.polys ?? []).map(p => p.id)))
const offSightPolys = [...polyIds].filter(id => !ownIds.has(id))
const withoutRoster = frames.filter(f => f.t !== 'roster')
const idFields = new Set(['id', 'player', 'owner', 'controller', 'seen_by'])
const foreignPlayers = []
if (foreignPlayerId !== null) {
const visitIdFields = value => {
if (Array.isArray(value)) return value.forEach(visitIdFields)
if (value === null || typeof value !== 'object') return
for (const [key, child] of Object.entries(value)) {
if (idFields.has(key)) {
const values = Array.isArray(child) ? child : [child]
if (values.includes(foreignPlayerId)) foreignPlayers.push({ key, value: child })
}
visitIdFields(child)
}
}
withoutRoster.forEach(visitIdFields)
}
const foreignTokens = foreignTokenIds.filter(id => withoutRoster.some(f => JSON.stringify(f).includes(id)))
const boxes = visionBoxes(frames, cell)
const explored = exploredCells(frames)
const exploredOutside = []
for (const key of explored) {
const [cx, cy] = key.split(',').map(Number)
if (!insideAnyBox(cx, cy, boxes)) exploredOutside.push([cx, cy])
}
const exploredNear = []
if (near) {
for (const key of explored) {
const [cx, cy] = key.split(',').map(Number)
if (Math.abs(cx * cell - near[0]) < 300 && Math.abs(cy * cell - near[1]) < 300) exploredNear.push([cx, cy])
}
}
return { offCatalogue, banned, ownIds, polyIds, offSightPolys, foreignPlayers, foreignTokens, boxes, explored, exploredOutside, exploredNear }
}
test('player browser traffic: catalogue-only frames, no wall data, no other player, allowed tiles', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
const scene = hello.scene ?? walls.scene
assert.deepEqual(walls.walls, [], 'the seeded scene starts without walls')
// The audited player and a second player whose room stays out of Ann's sight.
const ann = await createPlayer(gm.ws)
await namePlayer(origin, ann.key, 'Ann')
const bea = await createPlayer(gm.ws)
await namePlayer(origin, bea.key, 'Bea')
// Every round-1 wall field is authored around Ann *before* her token exists, so every explored
// cell derives from a polygon this page is actually sent (no pre-wall memory).
const authored = [
{ a: [1848, 2248], b: [2248, 2248], thickness: 20, position: 'left', height: 2.5, label: 'south wall' },
{ a: [1848, 1848], b: [1848, 2248], preset: 'door', thickness: 10 },
{ a: [2248, 1848], b: [2248, 2248], door: true, secret: true, blocks_sight: true, blocks_movement: true, label: 'hidden door' },
{ a: [1748, 1898], b: [1748, 2198], door: true, locked: true },
{ a: [1898, 1748], b: [2198, 1748], blocks_sight: true, blocks_movement: true, sight_dir: 'left', player_marker: true },
{ a: [1848, 1848], b: [2248, 1848], preset: 'window' },
{ a: [2648, 1848], b: [2648, 2248], flags: { note: 'opaque' } },
]
const ids = []
for (const payload of authored) {
const ack = await gm.ws.request({ t: 'wall.add', scene: scene.id, ...payload })
assert.equal(ack.ok, true, `wall.add ${JSON.stringify(payload)}: ${JSON.stringify(ack)}`)
ids.push(ack.id)
}
// One sighted token plus an NPC inside its sight, a second player and a GM-only token outside.
const own = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: OWN,
descriptive_name: 'Ann', actual_name: 'Ann', controller: ann.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(own.ok, true, JSON.stringify(own))
const npc = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc', pos: [2128, 2048],
descriptive_name: 'Rat', actual_name: 'Giant Rat',
})
assert.equal(npc.ok, true, JSON.stringify(npc))
const other = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: OTHER,
descriptive_name: 'Bea', actual_name: 'Bea', controller: bea.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(other.ok, true, JSON.stringify(other))
const hidden = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc', pos: [1968, 1978],
descriptive_name: 'Secret', actual_name: 'Secret', gm_only: true,
})
assert.equal(hidden.ok, true, JSON.stringify(hidden))
writeTileGrid(stateDir, {
scene: scene.id, artVersion: scene.art_version, size: scene.tile_size,
x0: 40, x1: 85, y0: 40, y1: 85,
})
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const tileTraffic = []
const requests = []
page.on('request', request => requests.push(request.url()))
page.on('response', response => {
tileTraffic.push({ url: response.url(), status: response.status() })
})
await recordSockets(page)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, ann.key)
await waitForVisible(page, '#stage canvas')
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout: 30000 },
)
// The whole initial view has arrived (including the marker for the window Ann can see).
await waitForFrames(page, () => {
const seen = new Set(window.__audit.frames.map(frame => frame.t))
return ['hello', 'roster', 'token', 'vision', 'explored', 'marker', 'encountered']
.every(type => seen.has(type))
})
// GM activity while the page records: edits, a door, a removal, a move of Ann's own token
// (new vision + explored cells) and of the NPC (a token update), then an untouched settle.
assert.equal((await gm.ws.request({ t: 'wall.update', scene: scene.id, id: ids[0], height: 3 })).ok, true)
assert.equal((await gm.ws.request({ t: 'door.set', scene: scene.id, id: ids[1], open: true })).ok, true)
assert.equal((await gm.ws.request({ t: 'wall.remove', scene: scene.id, id: ids[6] })).ok, true)
assert.equal((await gm.ws.request({ t: 'token.move', id: own.id, pos: [2048, 2160] })).ok, true)
assert.equal((await gm.ws.request({ t: 'token.move', id: npc.id, pos: [2100, 2080] })).ok, true)
await sleep(500)
const frames = await framesOf(page)
assert.ok(frames.length > 10, `the audit recorded a real stream: ${frames.length} frames`)
const v = frameViolations(frames, {
foreignPlayerId: bea.id,
foreignTokenIds: [other.id, hidden.id],
cell: scene.cell,
near: OTHER,
})
// 1. Catalogue only: every frame type is a row a player may receive.
assert.deepEqual(v.offCatalogue, [], `off-catalogue frames: ${JSON.stringify(v.offCatalogue.slice(0, 3))}`)
// 2. No wall field and no GM-only column anywhere in the player's frames, at any depth.
assert.deepEqual(v.banned, [], `player frames carried forbidden keys: ${JSON.stringify(v.banned.slice(0, 5))}`)
// 3. Vision polygons belong to Ann's own controlled token and nothing else.
assert.ok(v.polyIds.size > 0, 'the player received its vision polygons')
assert.deepEqual(v.offSightPolys, [], 'a vision polygon for a token Ann does not control')
// 4. No other player's or hidden token's id anywhere except the roster's own player list.
// Player ids are small integers, so they are checked in id-shaped fields only (a `reqId`
// or a coordinate may legitimately equal one); token ids are opaque strings.
assert.deepEqual(v.foreignPlayers, [], `another player's id reached the player: ${JSON.stringify(v.foreignPlayers)}`)
assert.deepEqual(v.foreignTokens, [], `a token outside Ann's sight reached her: ${JSON.stringify(v.foreignTokens)}`)
// 5. Explored is this player's own memory: every cell lies in the bbox of a polygon Ann was
// sent, and no cell is anywhere near the other player's room.
assert.ok(v.boxes.length > 0, 'historical vision polygons were recorded')
assert.ok(v.explored.size > 100, `explored has real content: ${v.explored.size} cells`)
assert.deepEqual(v.exploredOutside.slice(0, 5), [], `explored cells outside Ann's own sight: ${v.exploredOutside.length}`)
assert.deepEqual(v.exploredNear, [], 'no explored cell near the other player')
const explored = v.explored
// 6. Tiles: only the product path, only 200/403, and every served tile overlaps a cell Ann
// has explored. `/_tiles/` is never reachable from the page.
const tileResponses = tileTraffic.filter(r => new URL(r.url).pathname.startsWith('/tiles/'))
assert.ok(tileResponses.length > 0, 'the page fetched map tiles')
for (const r of tileResponses) {
assert.ok([200, 403].includes(r.status), `unexpected tile status ${r.status} for ${r.url}`)
}
const served = tileResponses.filter(r => r.status === 200)
const refused = tileResponses.filter(r => r.status === 403)
assert.ok(served.length > 0 && refused.length > 0, 'the scenario has both allowed and refused tiles')
for (const r of served) {
const path = new URL(r.url).pathname
const match = /^\/tiles\/(\d+)\/v(\d+)\/(\d+)_(\d+)\.png$/.exec(path)
assert.ok(match, `tile URL not on the catalogue path: ${r.url}`)
const tx = Number(match[3])
const ty = Number(match[4])
assert.ok(
explored.has(`${tx},${ty}`),
`a served tile the player never explored: ${path} (${served.length} served)`,
)
}
for (const url of requests) {
assert.ok(!url.includes('/_tiles/'), `the page requested the internal tile alias: ${url}`)
if (url.includes('/tiles/')) {
assert.match(new URL(url).pathname, /^\/tiles\/\d+\/v\d+\/\d+_\d+\.png$/, `unexpected tile path ${url}`)
}
}
const direct = await page.evaluate(async () => {
const response = await fetch('/_tiles/1/v1/60_60.png')
return response.status
})
assert.equal(direct, 404, 'a direct /_tiles/ request from the page is refused')
// 7. The live socket never closed during the audit. The boot probe's 1006 (the client asks
// `/ws` with no session and lands on sign-in) is expected and never opened.
const closes = await page.evaluate(() => window.__audit.closes)
assert.deepEqual(
closes.filter(c => c.opened && c.code !== 1005),
[],
`the live player socket closed: ${JSON.stringify(closes)}`,
)
} finally {
await browser.close()
gm.ws.close()
}
})
})
// Negative control: the audit must fail on a build that really leaks. `-d:leakfault` with
// `LEAK_FAULT=otherVision` injects another player's vision polygon into this player's `vision`
// frame (the server's own fault hook, not a fixture). The rule that catches it is rule 3: a polygon
// for a token the player does not control.
test('audit rules catch a leaking build (negative control)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
await gm.ws.waitText('walls')
const scene = hello.scene
const ann = await createPlayer(gm.ws)
await namePlayer(origin, ann.key, 'Ann')
const bea = await createPlayer(gm.ws)
await namePlayer(origin, bea.key, 'Bea')
for (const [player, pos, name] of [[ann, [1200, 1200], 'Ann'], [bea, [3000, 3000], 'Bea']]) {
const ack = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos,
descriptive_name: name, actual_name: name, controller: player.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await recordSockets(page)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, ann.key)
await waitForVisible(page, '#stage canvas')
await waitForFrames(page, () =>
(window.__audit.frames ?? []).some(f => f.t === 'vision' && (f.polys ?? []).length >= 2))
const frames = await framesOf(page)
const v = frameViolations(frames)
assert.ok(v.offSightPolys.length > 0, 'the off-sight polygon rule fired on the leaking build')
} finally {
await browser.close()
gm.ws.close()
}
}, { server: { defines: ['leakfault'], env: { LEAK_FAULT: 'otherVision' } } })
})
+212
View File
@@ -0,0 +1,212 @@
// T12 (#75, TESTING 10.3): GM characters, reveals, encountered remove and who-sees-it against the
// real server through the TLS/HTTP2 test nginx. The GM drives the panels; a player page records its
// own WS frames, so the reveal and the encountered removal are proven on the player wire and the
// GM-only `seen_by` field is proven absent from it.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
async function recordSockets(page) {
await page.addInitScript(() => {
window.__wsLog = { frames: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
this.addEventListener('message', event => {
try {
window.__wsLog.frames.push(JSON.parse(event.data))
} catch {
// non-JSON frames are not state
}
})
}
}
window.WebSocket = RecordingSocket
})
}
const frames = page => page.evaluate(() => window.__wsLog.frames ?? [])
async function waitTokenFrame(page, id, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await page.evaluate(
tokenId =>
(window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1),
id,
)
if (last && predicate(last)) return last
await sleep(50)
}
throw new Error(`token ${id} never matched; last was ${JSON.stringify(last)}`)
}
test('GM characters, reveals, encountered remove and who-sees-it', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const browser = await launchBrowser()
const raw = await openAs(origin, gmKey)
const rawHello = await raw.ws.waitText('hello')
const scene = rawHello.scene?.id ?? (await raw.ws.waitText('walls')).scene
try {
// Two named players and one scout each; Alice's scout stands beside the linked token.
const alice = await createPlayer(raw.ws)
await namePlayer(origin, alice.key, 'Alice')
const bob = await createPlayer(raw.ws)
await namePlayer(origin, bob.key, 'Bob')
const playerView = await newPage(browser)
const player = playerView.page
await recordSockets(player)
await player.goto(`${origin}/`)
await waitForVisible(player, '#signin')
await signIn(player, alice.key)
await waitForVisible(player, '#hud')
await waitForText(player, '#me', /^Alice$/)
const gmView = await newPage(browser)
const gm = gmView.page
await gm.goto(`${origin}/`)
await waitForVisible(gm, '#signin')
await signIn(gm, gmKey)
await waitForVisible(gm, '#gm-panels')
await waitForVisible(gm, '#gm-cast')
// Characters and the per-player encountered lists start folded (M4 UX).
await gm.click('#gm-characters > summary')
await gm.click('#gm-encountered-section > summary')
// ---- character.create through the panel (owner defaults to the GM) --------------------
await gm.fill('#character-name', 'a cloaked figure')
await gm.fill('#character-actual', 'Lord Vex')
await gm.click('#character-create-submit')
await waitForText(gm, '#gm-character-status', /created/i)
const row = gm.locator('#gm-character-list li[data-character]').first()
await row.waitFor({ state: 'visible', timeout: 20000 })
const characterId = await row.getAttribute('data-character')
assert.ok(characterId, 'created character has no id in the panel')
await waitForText(gm, `#gm-character-title-${characterId}`, /a cloaked figure/)
// ---- fixture tokens: Alice's scout, Bob's far scout and one token linked to the character
const aScout = await raw.ws.request({
t: 'token.create', scene, kind: 'pc', pos: [400, 400], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id, flags: { vision: true },
})
assert.equal(aScout.ok, true, JSON.stringify(aScout))
const bScout = await raw.ws.request({
t: 'token.create', scene, kind: 'pc', pos: [3900, 3900], descriptive_name: 'Bob',
actual_name: 'Bob', controller: bob.id, flags: { vision: true },
})
assert.equal(bScout.ok, true, JSON.stringify(bScout))
const linked = await raw.ws.request({
t: 'token.create', scene, kind: 'npc', pos: [500, 500], character_id: characterId,
controller: alice.id,
})
assert.equal(linked.ok, true, 'a linked token needs no names of its own (6.1)')
// Alice sees it by sight, Bob by control; a far, uncontrolled token has nobody.
const shared = await raw.ws.request({
t: 'token.create', scene, kind: 'npc', pos: [300, 300], descriptive_name: 'a shared thing',
actual_name: 'Shared Thing', controller: bob.id,
})
assert.equal(shared.ok, true, JSON.stringify(shared))
const unseen = await raw.ws.request({
t: 'token.create', scene, kind: 'npc', pos: [2000, 2000], descriptive_name: 'a far thing',
actual_name: 'Far Thing',
})
assert.equal(unseen.ok, true, JSON.stringify(unseen))
// The owner sees the descriptive name until the GM reveals the actual one.
await waitTokenFrame(player, linked.id, frame => frame.name === 'a cloaked figure')
await waitTokenFrame(player, linked.id, frame => frame.seen_by === undefined)
// ---- who-sees-it: Alice's sight reaches the token, Bob's does not ---------------------
const seenText = await waitForText(gm, `#gm-seen-${linked.id}`, /Alice.*100 %/)
assert.equal(seenText.includes('Bob'), false, `Bob must not be a viewer: ${seenText}`)
await waitForText(gm, `#gm-seen-${shared.id}`, /Alice, Bob.*100 %/)
await waitForText(gm, `#gm-seen-${unseen.id}`, /nobody \(0 %\)/)
assert.equal(await gm.locator('#gm-cast').isVisible(), true)
// ---- reveal to one player through the panel ------------------------------------------
await gm.selectOption(`#gm-character-reveal-player-${characterId}`, String(alice.id))
await gm.click(`#gm-character-reveal-${characterId}`)
await waitForText(gm, '#gm-character-status', /revealed/i)
await waitTokenFrame(player, linked.id, frame => frame.name === 'Lord Vex')
await waitForText(gm, `#gm-character-meta-${characterId}`, /told: Alice/)
// ---- a character owner change never moves a token controller -------------------------
const before = await new Promise(resolve => {
const deadline = Date.now() + 20000
const poll = () => {
const frame = raw.ws.messages.filter(m => m.t === 'token' && m.id === linked.id).at(-1)
if (frame) resolve(frame)
else if (Date.now() > deadline) resolve(null)
else setTimeout(poll, 25)
}
poll()
})
assert.equal(before?.controller, alice.id)
await gm.selectOption(`#gm-character-owner-${characterId}`, String(bob.id))
await gm.click(`#gm-character-reassign-${characterId}`)
await waitForText(gm, '#gm-character-status', /reassigned/i)
await waitForText(gm, `#gm-character-meta-${characterId}`, /owner Bob/)
await sleep(250)
const after = raw.ws.messages.filter(m => m.t === 'token' && m.id === linked.id).at(-1)
assert.equal(after.controller, alice.id, 'character.reassign must not touch token controllers')
await waitForText(
gm,
`#gm-token-list li[data-token="${linked.id}"]`,
/controller Alice/,
)
// ---- encountered remove through the panel --------------------------------------------
// The entry exists while the token is in sight; forgetting becomes meaningful once the
// player can no longer see it (DESIGN 8: a sighting is re-recorded while it stays in view).
await waitForText(gm, `#gm-encountered-${alice.id}`, /Lord Vex/)
assert.equal(await gm.locator(`#gm-encountered-remove-${alice.id}-${linked.id}`).count(), 0,
'an in-sight entry has no Forget button')
assert.equal((await raw.ws.request({ t: 'token.remove', id: linked.id })).ok, true)
await player.waitForFunction(
tokenId =>
(window.__wsLog?.frames ?? []).some(
frame => frame.t === 'token_gone' && frame.id === tokenId,
),
linked.id,
{ timeout: 20000 },
)
await waitForText(gm, `#gm-encountered-${alice.id}`, /met, not in sight/)
await waitForVisible(gm, `#gm-encountered-remove-${alice.id}-${linked.id}`)
await gm.click(`#gm-encountered-remove-${alice.id}-${linked.id}`)
await waitForText(gm, '#gm-encountered-status', /forgotten/i)
await player.waitForFunction(
tokenId =>
(window.__wsLog?.frames ?? []).some(
frame =>
frame.t === 'encountered' &&
(frame.del ?? []).includes(tokenId),
),
linked.id,
{ timeout: 20000 },
)
// ---- the GM-only field never reaches a player ----------------------------------------
const playerFrames = await frames(player)
assert.equal(JSON.stringify(playerFrames).includes('seen_by'), false,
'seen_by reached the player wire')
assert.equal(await player.locator('#gm-cast').isVisible(), false,
'a player page must not show the GM cast panel')
} finally {
raw.ws.close()
await browser.close()
}
})
})
+428
View File
@@ -0,0 +1,428 @@
// T9 (#72, TESTING 10.3): drag with prediction and rollback against the real server through the
// TLS/HTTP2 nginx. The browser's real mouse drives the canvas; the assertions read the sprite
// positions the renderer publishes on the canvas dataset, and the real per-recipient `token`
// frames a GM connection receives. No fixture, no mocked protocol.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForVisible,
withStack,
} from './stack.mjs'
async function waitForBadge(page, state, timeout = 30000) {
await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout })
}
/** The renderer's instrumentation: what the browser actually draws, plus the move counters. */
async function renderState(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) return null
const data = canvas.dataset
const positions = {}
for (const entry of (data.tokenPositions ?? '').split(' ').filter(Boolean)) {
const [id, point] = entry.split(':')
const [x, y] = point.split(',').map(Number)
positions[id] = [x, y]
}
return {
ids: (data.tokenIds ?? '').split(' ').filter(Boolean),
positions,
dragId: data.dragId ?? '',
dragPos: data.dragPos ?? '',
dragPhase: data.dragPhase ?? '',
pending: Number(data.dragPending ?? '0'),
refused: Number(data.dragRefused ?? '0'),
rateLimited: Number(data.dragRateLimited ?? '0'),
rollbacks: Number(data.dragRollbacks ?? '0'),
}
})
}
async function waitForRender(page, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await renderState(page)
if (last !== null && predicate(last)) return last
await sleep(25)
}
throw new Error(`drag renderer never reached the expected state: ${JSON.stringify(last)}`)
}
/** The world is 4096 px; the camera starts centred, so this is the middle of the screen at zoom 1. */
const CENTRE = [2048, 2048]
/** Canvas rect plus the world container's transform (#69): `screen = world * zoom + camera.xy`. */
async function viewOf(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) throw new Error('no canvas')
const rect = canvas.getBoundingClientRect()
const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number)
return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') }
})
}
/** Page coordinates of a world point, through the camera at any zoom (no 1:1 assumption). */
async function screenOf(page, world) {
const view = await viewOf(page)
return {
x: view.left + world[0] * view.zoom + view.x,
y: view.top + world[1] * view.zoom + view.y,
}
}
/** Wheel-zoom around `anchorWorld`, keeping that point under the pointer; read the clamped zoom. */
async function zoomTo(page, zoom, anchorWorld) {
for (let attempt = 0; attempt < 30; attempt += 1) {
const view = await viewOf(page)
if (Math.abs(view.zoom - zoom) < 1e-9) return view.zoom
const point = await screenOf(page, anchorWorld)
await page.mouse.move(point.x, point.y)
await page.mouse.wheel(0, view.zoom < zoom ? -250 : 250)
await sleep(40)
}
const view = await viewOf(page)
throw new Error(`zoom never reached ${zoom}, stuck at ${view.zoom}`)
}
/** Press on a world point, move in real steps (so the 20 Hz sender emits several), release. */
async function drag(page, from, to, steps = 8) {
const start = await screenOf(page, from)
await page.mouse.move(start.x, start.y)
await page.mouse.down()
for (let step = 1; step <= steps; step += 1) {
const x = from[0] + ((to[0] - from[0]) * step) / steps
const y = from[1] + ((to[1] - from[1]) * step) / steps
const point = await screenOf(page, [x, y])
await page.mouse.move(point.x, point.y)
await sleep(60)
}
await page.mouse.up()
}
/** One GM-owned scene with a player and one controlled token. */
async function sceneWithPlayer(origin, gmKey, pos = CENTRE) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const scene = (await gm.ws.waitText('walls')).scene
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
const token = await gm.ws.request({
t: 'token.create',
scene,
kind: 'pc',
pos,
descriptive_name: 'Ann',
actual_name: 'Ann',
controller: player.id,
flags: { vision: true },
radius: 20,
})
assert.equal(token.ok, true)
return { gm, scene, player, token: token.id }
}
test('drag persists after reload (stories 38, 39)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
await drag(page, CENTRE, [2148, 2108])
// The server remains the only judge: its frame carries the final position (story 39).
const frame = await gm.ws.waitFor(
message =>
message.t === 'token' &&
message.id === token &&
Math.abs(message.pos[0] - 2148) <= 2 &&
Math.abs(message.pos[1] - 2108) <= 2,
10000,
)
assert.deepEqual(frame.pos, [2148, 2108])
const settled = await waitForRender(
page,
view =>
Math.abs(view.positions[token]?.[0] - 2148) <= 2 &&
Math.abs(view.positions[token]?.[1] - 2108) <= 2 &&
view.dragId === '' &&
view.pending === 0,
)
assert.equal(settled.pending, 0, 'the final ack settled the pending intent')
// The move is durable: a reload rebuilds the view from the server, not from the drag.
await page.reload()
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const reloaded = await waitForRender(
page,
view =>
Math.abs(view.positions[token]?.[0] - 2148) <= 2 &&
Math.abs(view.positions[token]?.[1] - 2108) <= 2,
)
assert.equal(reloaded.dragPhase, '')
// The player's own frame after the resync is the server's position, not a replay.
assert.deepEqual(gm.ws.messages.filter(m => m.t === 'token' && m.id === token).at(-1).pos, [2148, 2108])
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('a wall refuses the move and the sprite slides back (story 40)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, scene, player, token } = await sceneWithPlayer(origin, gmKey)
// A blocking wall between the token and the drop point. A player cannot see it: prediction is
// optimistic and the server judges (DESIGN 7.5).
const wall = await gm.ws.request({
t: 'wall.add', scene, a: [2248, 1948], b: [2248, 2148],
})
assert.equal(wall.ok, true)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
await drag(page, CENTRE, [2328, 2048], 10)
// The refusal increments the counter and starts the cosmetic tween (436/440: a slide back).
await page.waitForFunction(
() => {
const canvas = document.querySelector('#stage canvas')
return canvas && Number(canvas.dataset.dragRollbacks ?? '0') >= 1
},
null,
{ timeout: 10000, polling: 16 },
)
// Catch the tween mid-flight: the sprite is strictly between the drop point and the rollback
// target while the reducer's rollback is live.
const mid = await page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
return { phase: canvas.dataset.dragPhase ?? '', positions: canvas.dataset.tokenPositions ?? '' }
})
assert.equal(mid.phase, 'rollback')
const entry = mid.positions.split(' ').find(item => item.startsWith(`${token}:`))
const midX = Number(entry?.split(':')[1]?.split(',')[0])
assert.ok(Number.isFinite(midX), `the sprite is being drawn mid-tween: ${mid.positions}`)
const settled = await waitForRender(
page,
view => view.dragPhase === '' && view.refused >= 1 && view.rollbacks >= 1 && view.pending === 0,
)
assert.equal(settled.refused >= 1, true)
const finalX = settled.positions[token]?.[0] ?? 0
assert.ok(finalX <= 2230, `rolled back to the clear side of the wall, got ${finalX}`)
assert.ok(finalX >= 2048, 'the rollback is left of the wall but not past the start')
assert.ok(midX > finalX, `the tween is between the drop and the target: mid=${midX} final=${finalX}`)
// The authoritative frame says the same thing the sprite shows.
await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && message.pos[0] === finalX,
5000,
)
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('authoritative frames are ignored under the finger; the GM can move the token meanwhile', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const start = await screenOf(page, CENTRE)
const held = await screenOf(page, [2128, 2048])
await page.mouse.move(start.x, start.y)
await page.mouse.down()
await page.mouse.move(held.x, held.y)
await sleep(80)
let view = await waitForRender(page, state => state.dragId === token)
assert.deepEqual(view.dragPos, '2128,2048')
// Story 41/43: the GM moves the same token while the player still holds it. The player's
// sprite must not jump (the authoritative frame is ignored for drawing while dragging).
const gmMove = await gm.ws.request({ t: 'token.move', id: token, pos: [2098, 2048] })
assert.equal(gmMove.ok, true)
await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && message.pos[0] === 2098,
5000,
)
await sleep(150)
view = await renderState(page)
assert.equal(view.dragId, token)
assert.deepEqual(view.positions[token], [2128, 2048], 'the sprite stayed under the pointer')
await page.mouse.up()
// The release send starts from the GM's position (2098) to 2128: inside the step cap, accepted.
await gm.ws.waitFor(
message =>
message.t === 'token' && message.id === token &&
Math.abs(message.pos[0] - 2128) <= 2 && Math.abs(message.pos[1] - 2048) <= 2,
10000,
)
const settled = await waitForRender(page, state => state.dragId === '' && state.pending === 0)
assert.deepEqual(settled.positions[token], [2128, 2048])
assert.equal(settled.rollbacks, 0, 'an accepted release needs no rollback')
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('a reconnect mid-drag drops the pending intent and resumes from the server', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, server }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
let restarted = null
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const start = await screenOf(page, CENTRE)
const held = await screenOf(page, [2118, 2048])
await page.mouse.move(start.x, start.y)
await page.mouse.down()
await page.mouse.move(held.x, held.y)
await sleep(80)
await waitForRender(page, state => state.dragId === token)
const before = await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && Math.abs(message.pos[0] - 2118) <= 2,
5000,
)
assert.ok(before)
// Kill the server with the finger still down: the close ends the drag and every pending
// `reqId` dies with the socket (DESIGN 6.3), so no orphan awaits an ack that cannot come.
await stopServer(server)
await waitForBadge(page, 'reconnecting')
const dropped = await waitForRender(page, state => state.dragId === '' && state.pending === 0)
assert.equal(dropped.dragPhase, '')
restarted = await startServer({
stateDir: server.stateDir,
port: server.port,
publicOrigin: server.publicOrigin,
})
await waitForBadge(page, 'connected', 60000)
await waitForRender(page, state => state.ids.includes(token))
const resumed = await waitForRender(
page,
state => Math.abs(state.positions[token]?.[0] - 2118) <= 2 && state.dragPhase === '',
)
assert.deepEqual(resumed.positions[token], [2118, 2048], 'the resync is the server position')
assert.equal(resumed.pending, 0)
await page.mouse.up() // the stale release must not send a move onto the new connection
await sleep(150)
const after = await renderState(page)
assert.deepEqual(after.positions[token], [2118, 2048])
} finally {
if (restarted) await stopServer(restarted)
gm.ws.close()
await browser.close()
}
})
})
test('drag follows the camera transform at zoom 0.5 and 4, and a token drag never pans', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
// Player maximum (4.0): 80 screen px is 20 world px.
assert.equal(await zoomTo(page, 4, CENTRE), 4)
const cameraAt4 = await viewOf(page)
await drag(page, CENTRE, [2068, 2048], 6)
await gm.ws.waitFor(
message =>
message.t === 'token' && message.id === token &&
Math.abs(message.pos[0] - 2068) <= 2 && Math.abs(message.pos[1] - 2048) <= 2,
10000,
)
await waitForRender(
page,
view =>
Math.abs(view.positions[token]?.[0] - 2068) <= 2 &&
Math.abs(view.positions[token]?.[1] - 2048) <= 2 &&
view.dragId === '',
)
// The press landed on a controlled token, so the camera's pan never saw the gesture.
const afterTokenDrag = await viewOf(page)
assert.equal(afterTokenDrag.zoom, 4)
assert.equal(afterTokenDrag.x, cameraAt4.x, 'a token drag must not pan the map')
assert.equal(afterTokenDrag.y, cameraAt4.y, 'a token drag must not pan the map')
// Player minimum (0.5): 80 world px is only 40 screen px, still a real pointer path.
const moved = [2068, 2048]
assert.equal(await zoomTo(page, 0.5, moved), 0.5)
await drag(page, moved, [2148, 2048], 6)
await gm.ws.waitFor(
message =>
message.t === 'token' && message.id === token &&
Math.abs(message.pos[0] - 2148) <= 2 && Math.abs(message.pos[1] - 2048) <= 2,
10000,
)
await waitForRender(
page,
view =>
Math.abs(view.positions[token]?.[0] - 2148) <= 2 &&
Math.abs(view.positions[token]?.[1] - 2048) <= 2 &&
view.dragId === '',
)
// Elsewhere the same gesture is a pan (#69): the empty canvas still moves the camera.
const empty = await screenOf(page, [2280, 2048])
const cameraBeforePan = await viewOf(page)
await page.mouse.move(empty.x, empty.y)
await page.mouse.down()
await page.mouse.move(empty.x + 40, empty.y + 20)
await page.mouse.up()
await sleep(80)
const afterPan = await viewOf(page)
assert.equal(afterPan.zoom, 0.5)
assert.ok(afterPan.x > cameraBeforePan.x + 20, `the empty canvas panned: ${cameraBeforePan.x} -> ${afterPan.x}`)
const panned = await renderState(page)
assert.deepEqual(panned.positions[token], [2148, 2048], 'panning never moves the token')
} finally {
gm.ws.close()
await browser.close()
}
})
})
+503
View File
@@ -0,0 +1,503 @@
// T7 (#70): the three-state fog, the vision cut-out and the player markers, against the real server
// behind the TLS/HTTP2 test nginx (TESTING 10.3). The gate is a pixel probe: what the browser shows
// at a world point, read from a screenshot (client/e2e/pixels.mjs), never from renderer internals.
//
// The scene is the seeded 4096 px map, cell 32 (128x128 cells), tile 32. Fixture tiles are one solid
// colour per tile, so a probe has an independent expected colour (the same formula the fixture
// writer uses, re-written here on purpose). The player's token sits near the middle; three walls
// shape the sight: a window (sight passes), a one-way wall (the blind side is below it) and a closed
// secret door (an opaque wall to a player).
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import {
launchBrowser,
signIn,
waitForText,
waitForVisible,
withStack,
sleep,
} from './stack.mjs'
import { differs, luminance, probe } from './pixels.mjs'
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
/** The fixture writer's colour formula (tools/tilefixture.mjs), re-written for the oracle. */
function tileColour(worldX, worldY) {
const x = Math.floor(worldX / SCENE.tile)
const y = Math.floor(worldY / SCENE.tile)
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
}
/** Cell centres (cell = 32): the middle of a cell keeps clear of grid lines and cell edges. */
const cellCentre = (cx, cy) => [cx * SCENE.cell + 16, cy * SCENE.cell + 16]
/** World points probed in the fog test (each one is a cell centre; see the test's geometry notes). */
const POINTS = {
visible: cellCentre(68, 64), // inside the token's sight, no wall on the ray
throughWindow: cellCentre(72, 64), // beyond the window: a window lets sight pass
blindBehindOneWay: cellCentre(64, 58), // above the one-way wall, on its blind side
behindSecretDoor: cellCentre(55, 64), // left of the closed secret door
unexplored: cellCentre(51, 54), // beyond the sight radius, explored by nobody
gmMap: cellCentre(60, 64), // left of centre: the GM's panels cover the right of the viewport
afterMove: cellCentre(68, 73), // inside the new sight after the token moves
}
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: hello.scene ?? walls.scene }
}
/**
* Create the player's sighted token through the GM token panel (#78): the fog test's world is
* authored the way a GM authors it, with no raw `flags`/`vision_radius` on a wire `token.create`.
* Returns the new token id.
*/
async function createSightedToken(origin, gmKey, player, { pos, name, radius, visionRadius }) {
const browser = await launchBrowser()
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 900, height: 900 },
})
const page = await context.newPage()
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, '#gm-panels')
await waitForText(page, '#gm-roster-list', new RegExp(name))
// The create form and the token list start folded (M4 UX).
await page.click('#gm-token-create-section > summary')
await page.click('#gm-token-list-section > summary')
await page
.locator(`#token-controller option[value="${player.id}"]`)
.waitFor({ state: 'attached', timeout: 20000 })
await page.fill('#token-kind', 'pc')
await page.fill('#token-name', name)
await page.fill('#token-actual', name)
await page.fill('#token-x', String(pos[0]))
await page.fill('#token-y', String(pos[1]))
await page.fill('#token-radius', String(radius))
await page.check('#token-vision')
await page.fill('#token-vision-radius', String(visionRadius))
await page.selectOption('#token-controller', String(player.id))
await page.click('#token-create-submit')
const row = page.locator('#gm-token-list li', { hasText: name }).first()
await row.waitFor({ state: 'visible', timeout: 20000 })
const id = await row.getAttribute('data-token')
assert.ok(id, 'the panel-created token has no id')
await context.close()
return id
} finally {
await browser.close()
}
}
/** One player, one sighted token and the three walls; returns the wall ids. */
async function fogWorld(origin, gmKey, stateDir) {
const gm = await gmWorld(origin, gmKey)
const scene = gm.scene
writeTileGrid(stateDir, {
scene: scene.id,
artVersion: scene.art_version,
size: scene.tile_size,
x0: 40,
x1: 87,
y0: 40,
y1: 87,
})
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
// The walls exist before the token, so the first vision fan already has the blind zones and
// explored memory never covers them (explored only grows, 6.1 / 5.8).
// Window: sight passes; the preset turns the player marker on.
const window = await gm.ws.request({
t: 'wall.add', scene: scene.id, preset: 'window', a: [2250, 1950], b: [2250, 2150],
})
assert.equal(window.ok, true, JSON.stringify(window))
// One-way: `sight_dir:"left"` names the blind side; a->b runs +x, so +y (below) is blind.
const oneWay = await gm.ws.request({
t: 'wall.add', scene: scene.id, a: [1800, 1950], b: [2300, 1950],
blocks_sight: true, blocks_movement: true, sight_dir: 'left',
})
assert.equal(oneWay.ok, true, JSON.stringify(oneWay))
// A closed secret door: a solid, sight-blocking wall to a player (5.8).
const secret = await gm.ws.request({
t: 'wall.add', scene: scene.id, a: [1850, 1980], b: [1850, 2140],
blocks_sight: true, blocks_movement: true, door: true, secret: true,
})
assert.equal(secret.ok, true, JSON.stringify(secret))
const tokenId = await createSightedToken(origin, gmKey, player, {
pos: [2048, 2048],
name: 'Ann',
radius: 20,
visionRadius: 300,
})
// The GM's own frame confirms the panel round-trip before the pixel probes rely on the sight.
await gm.ws.waitFor(
frame => frame.t === 'token' && frame.id === tokenId &&
frame.flags?.vision === true && frame.vision_radius === 300,
20000,
)
return { gm, player, scene, tokenId, windowId: window.id, playerId: player.id }
}
/** Canvas rect plus the world container's transform (#69): `screen = world * zoom + camera.xy`. */
async function viewOf(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) throw new Error('no canvas')
const rect = canvas.getBoundingClientRect()
const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number)
return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') }
})
}
async function screenOf(page, [wx, wy]) {
const view = await viewOf(page)
return {
x: view.left + wx * view.zoom + view.x,
y: view.top + wy * view.zoom + view.y,
}
}
async function probeWorld(page, world) {
const point = await screenOf(page, world)
return probe(page, point.x, point.y)
}
async function fogState(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) return null
const data = canvas.dataset
return {
mode: data.fog ?? '',
cells: Number(data.fogCells ?? '-1'),
polys: Number(data.fogPolys ?? '-1'),
markers: (data.fogMarkers ?? '').split(' ').filter(Boolean),
cellsPainted: Number(data.fogCellsPainted ?? '-1'),
fullRedraws: Number(data.fogFullRedraws ?? '-1'),
visionBuilds: Number(data.fogVisionBuilds ?? '-1'),
lastFresh: Number(data.fogLastFresh ?? '-1'),
exploredMs: Number(data.fogExploredMs ?? '-1'),
fullMs: Number(data.fogFullMs ?? '-1'),
visionMs: Number(data.fogVisionMs ?? '-1'),
}
})
}
async function waitFog(page, predicate, timeout = 30000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await fogState(page)
if (last !== null && predicate(last)) return last
await sleep(50)
}
throw new Error(`fog never reached the expected state: ${JSON.stringify(last)}`)
}
async function waitTilesReady(page, timeout = 30000) {
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout },
)
}
/** Drag the token with real mouse steps (the #72 path), so the server recomputes vision. */
async function drag(page, from, to, steps = 10) {
const start = await screenOf(page, from)
await page.mouse.move(start.x, start.y)
await page.mouse.down()
for (let step = 1; step <= steps; step += 1) {
const point = await screenOf(page, [
from[0] + ((to[0] - from[0]) * step) / steps,
from[1] + ((to[1] - from[1]) * step) / steps,
])
await page.mouse.move(point.x, point.y)
await sleep(60)
}
await page.mouse.up()
}
function near(actual, expected, tolerance = 10) {
return (
Math.abs(actual.r - expected.r) <= tolerance &&
Math.abs(actual.g - expected.g) <= tolerance &&
Math.abs(actual.b - expected.b) <= tolerance
)
}
test('fog: unexplored black, explored dim, visible map colour; markers; a move; a resync', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const { gm, player, scene, windowId } = await fogWorld(origin, gmKey, stateDir)
const browser = await launchBrowser()
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 900, height: 900 },
})
const page = await context.newPage()
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
// Unfogged tiles are refused with 403 by design (story 20/27); the browser logs each one.
if (
message.type() === 'error' &&
!message.text().includes('WebSocket connection') &&
!message.text().includes('403') &&
// The deliberate offline window aborts in-flight tile requests (status fetch or retry).
!message.text().includes('net::ERR_')
) {
errors.push(message.text())
}
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#stage canvas')
await waitTilesReady(page)
const initial = await waitFog(page, state => state.mode === 'player' && state.polys > 0 && state.markers.length === 1)
assert.ok(initial.cells > 100, `the sight explored cells: ${initial.cells}`)
assert.equal(initial.fullRedraws, 1, 'the connect snapshot is the only full explored repaint')
// Story 20/21/22: three states at cell-resolution probes.
const unexplored = await probeWorld(page, POINTS.unexplored)
assert.ok(luminance(unexplored) < 8, `unexplored floor is near-black: ${JSON.stringify(unexplored)}`)
assert.ok(luminance(unexplored) < 8, 'never-seen floor leaks no map colour')
const visible = await probeWorld(page, POINTS.visible)
assert.ok(near(visible, tileColour(...POINTS.visible)), `visible floor shows the map: ${JSON.stringify(visible)}`)
// Story 22 + §5.8: a window does not block sight; the floor beyond it is visible.
const windowView = await probeWorld(page, POINTS.throughWindow)
assert.ok(
near(windowView, tileColour(...POINTS.throughWindow)),
`a window lets sight through: ${JSON.stringify(windowView)}`,
)
// Story 20/23 + §5.8: the one-way wall's blind side is dark, unlike the window's far side.
const blind = await probeWorld(page, POINTS.blindBehindOneWay)
assert.ok(luminance(blind) < 8, `the one-way blind side is unexplored: ${JSON.stringify(blind)}`)
// §5.8: a closed secret door blocks sight like a solid wall.
const secretView = await probeWorld(page, POINTS.behindSecretDoor)
assert.ok(luminance(secretView) < 8, `the secret door blocks sight: ${JSON.stringify(secretView)}`)
// Story 24: the window marker sits at the wall's drawn anchor, above the fog.
const anchor = [2250, 2048]
const markerPoint = await screenOf(page, anchor)
const markerPixel = await probe(page, markerPoint.x, markerPoint.y)
assert.ok(
near(markerPixel, { r: 255, g: 204, b: 51 }, 24),
`the seen window shows a marker at its anchor: ${JSON.stringify(markerPixel)}`,
)
// Story 25: the GM turns the marker off; the marker is retracted (its own `del` frame).
const update = await gm.ws.request({ t: 'wall.update', scene: scene.id, id: windowId, player_marker: false })
assert.equal(update.ok, true, JSON.stringify(update))
await waitFog(page, state => state.markers.length === 0)
const afterMarker = await probe(page, markerPoint.x, markerPoint.y)
assert.ok(differs(afterMarker, markerPixel, 30), 'the marker pixel is gone after `del`')
assert.ok(
luminance(afterMarker) > 60,
`the seen floor shows through where the marker was, not fog: ${JSON.stringify(afterMarker)}`,
)
// Story 23: a real drag moves the token; the server's new `vision` cuts the fog with no reload.
await page.evaluate(() => {
window.__fogKept = 'alive'
})
const beforeMove = await fogState(page)
await drag(page, [2048, 2048], [2048, 2400])
const moved = await waitFog(
page,
state => state.cells > beforeMove.cells && state.visionBuilds > beforeMove.visionBuilds,
)
assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the fog followed the move without a reload')
assert.equal(moved.fullRedraws, beforeMove.fullRedraws, 'the move painted cells, not the whole map')
assert.ok(moved.cellsPainted > beforeMove.cellsPainted, 'the new cells were painted')
assert.ok(
moved.cellsPainted - beforeMove.cellsPainted <= moved.cells - beforeMove.cells + 1,
`only the new cells were painted (${moved.cellsPainted - beforeMove.cellsPainted} painted for ${moved.cells - beforeMove.cells} cells)`,
)
const nowDim = await probeWorld(page, POINTS.visible)
const expectedDim = tileColour(...POINTS.visible)
assert.ok(
near(nowDim, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 12),
`explored floor is dim (~0.6 alpha): ${JSON.stringify(nowDim)} for tile ${JSON.stringify(expectedDim)}`,
)
assert.ok(
luminance(nowDim) < luminance(tileColour(...POINTS.visible)) * 0.6,
'explored floor is visibly darker than visible floor',
)
const newView = await probeWorld(page, POINTS.afterMove)
assert.ok(
near(newView, tileColour(...POINTS.afterMove)),
`the new sight is clear: ${JSON.stringify(newView)}`,
)
const stillBlind = await probeWorld(page, POINTS.blindBehindOneWay)
assert.ok(luminance(stillBlind) < 8, 'the blind side never becomes visible')
assert.deepEqual((await fogState(page)).markers, [], 'the retracted marker stays retracted')
// Story 11: a reconnect resyncs explored, vision and markers; the view is the same, no reload.
const beforeReconnect = await fogState(page)
await context.setOffline(true)
await page.locator('#badge[data-state="offline"]').waitFor({ state: 'visible', timeout: 20000 })
await context.setOffline(false)
await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 })
await waitFog(page, state => state.cells === beforeReconnect.cells && state.polys > 0)
assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the resync did not reload the page')
assert.deepEqual((await fogState(page)).markers, [], 'a full marker snapshot does not resurrect a retracted marker')
const dimAgain = await probeWorld(page, POINTS.visible)
assert.ok(near(dimAgain, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 14),
`explored memory survives the resync: ${JSON.stringify(dimAgain)}`)
const visibleAgain = await probeWorld(page, POINTS.afterMove)
assert.ok(near(visibleAgain, tileColour(...POINTS.afterMove)), 'the current sight survives the resync')
assert.deepEqual(errors, [])
await context.close()
} finally {
await browser.close()
gm.ws.close()
}
})
})
test('GM map is unfogged (story 26)', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const { gm } = await fogWorld(origin, gmKey, stateDir)
const browser = await launchBrowser()
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 900, height: 900 },
})
const page = await context.newPage()
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, '#stage canvas')
await waitTilesReady(page)
const state = await waitFog(page, fog => fog.mode === 'gm')
assert.equal(state.cells, 0)
assert.deepEqual(state.markers, [], 'the GM never receives a player marker')
// The point the player is blind to (behind the one-way wall) is plain map for the GM.
const gmView = await probeWorld(page, POINTS.gmMap)
assert.ok(
near(gmView, tileColour(...POINTS.gmMap)),
`the GM map is unfogged: ${JSON.stringify(gmView)} for tile ${JSON.stringify(tileColour(...POINTS.gmMap))}`,
)
await context.close()
} finally {
await browser.close()
gm.ws.close()
}
})
})
test('fog cost on the phone-class emulation: full snapshot, a cell diff and a vision rebuild', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const { gm, player, scene } = await fogWorld(origin, gmKey, stateDir)
// The 50-token target (spec #63, M4): 49 more tokens packed inside the sight, no walls near
// them, so the player's renderer draws 50 tokens with the fog on.
for (let i = 0; i < 49; i += 1) {
const ack = await gm.ws.request({
t: 'token.create',
scene: scene.id,
kind: 'npc',
pos: [2048 + ((i % 7) - 3) * 28, 2048 + (Math.floor(i / 7) - 3) * 28],
descriptive_name: `T${i}`,
actual_name: `T${i}`,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
const browser = await launchBrowser()
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 412, height: 869 },
deviceScaleFactor: 2.625,
isMobile: true,
hasTouch: true,
})
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
const errors = []
page.on('pageerror', error => errors.push(error.message))
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#stage canvas')
await waitTilesReady(page)
await waitFog(page, state => state.mode === 'player' && state.polys > 0)
// Checked after the page-load fill, as in the tile-size gate: throttling multiplies every
// image callback, so the fill itself is measured at real CPU.
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
const snapshot = await fogState(page)
assert.ok(snapshot.fullMs > 0 && snapshot.fullMs < 250,
`the connect snapshot repaints 128x128 cells under throttling: ${snapshot.fullMs} ms`)
const before = snapshot
await drag(page, [2048, 2048], [2048, 2250], 8)
const after = await waitFog(page, state => state.cells > before.cells && state.visionBuilds > before.visionBuilds)
assert.ok(after.lastFresh > 0, 'the move added explored cells')
assert.ok(after.exploredMs < 50, `a cell diff is cheap under 4x CPU: ${after.exploredMs} ms for ${after.lastFresh} cells`)
assert.ok(after.visionMs < 50, `a vision cut-out rebuild is cheap under 4x CPU: ${after.visionMs} ms`)
// Frame cadence with 50 tokens and the fog active; recorded, not a hard gate (the phone run
// is the human ticket), so a pathological regression still fails.
const frames = await page.evaluate(async () => {
const samples = []
await new Promise(resolve => {
let last = performance.now()
let count = 0
const step = () => {
const now = performance.now()
samples.push(now - last)
last = now
count += 1
if (count < 90) requestAnimationFrame(step)
else resolve()
}
requestAnimationFrame(step)
})
samples.sort((a, b) => a - b)
return {
samples: samples.length,
median: samples[Math.floor(samples.length / 2)],
p95: samples[Math.floor(samples.length * 0.95)],
}
})
// Recorded, not a gate (spec #63: no timing gate in the client suite; the phone run is the
// human ticket). The fog's own update costs above are the assertion.
assert.deepEqual(errors, [])
console.log(
`fog cost (#70, 412x869 dpr2.625, 4x CPU, 4096px map = 16384 cells, 50 tokens): ` +
`snapshot=${snapshot.fullMs.toFixed(3)}ms cells=${snapshot.cells} ` +
`diff=${after.exploredMs.toFixed(3)}ms fresh=${after.lastFresh} ` +
`vision=${after.visionMs.toFixed(3)}ms polys=${after.polys} ` +
`frames median=${frames.median.toFixed(1)}ms p95=${frames.p95.toFixed(1)}ms ` +
`(16384px map = 262144 cells: full repaint scales ~16x, a diff does not)`,
)
await context.close()
} finally {
await browser.close()
gm.ws.close()
}
})
})
+162
View File
@@ -0,0 +1,162 @@
// T13 (#76): the 50-token, Full HD map measurement the finish ticket records in
// `results/m4-fog-bench.md`. This is NOT the phone gate: headless Chromium here renders with
// SwiftShader (software), so its frame cadence is a floor for correctness work, never a substitute
// for the Note 10 run (#77). The server half of the same measurement is `tools/fogbench.nim`.
//
// The scene is the real one, patched to the Full HD cap (1920x1080; only the importer owns w/h, so
// the harness writes the scene row before the server loads it). 50 tokens sit inside the player's
// sight; the fog texture is therefore 60x34 cells, the real M4 maximum (#85).
import test from 'node:test'
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import path from 'node:path'
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import { launchBrowser, signIn, waitForVisible, withStack, sleep } from './stack.mjs'
const MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true }
const SIZE = { w: 1920, h: 1080 }
const CENTRE = [SIZE.w / 2, SIZE.h / 2]
/** The scene row is the importer's (DESIGN 6.1: w/h are not wire fields); write it before boot. */
function setSceneSize(stateDir, size) {
const db = path.join(stateDir, 'state.db')
const r = spawnSync('sqlite3', [db, `UPDATE scene SET w=${size.w}, h=${size.h} WHERE id=1`], { encoding: 'utf8' })
assert.equal(r.status, 0, `set scene size: ${r.stderr}`)
}
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: hello.scene ?? walls.scene }
}
/** 50 tokens: one controlled sighted token and 49 NPCs packed inside its radius. */
async function fiftyTokens(gm, scene, player) {
const own = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: CENTRE,
descriptive_name: 'Ann', actual_name: 'Ann', controller: player.id,
flags: { vision: true }, vision_radius: 400, radius: 20,
})
assert.equal(own.ok, true, JSON.stringify(own))
for (let i = 0; i < 49; i += 1) {
const ack = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc',
pos: [CENTRE[0] + ((i % 7) - 3) * 28, CENTRE[1] + (Math.floor(i / 7) - 3) * 28],
descriptive_name: `T${i}`, actual_name: `T${i}`,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
}
/** rAF cadence over `count` frames, summarised the way the fog-cost test does. */
async function cadence(page, count) {
return page.evaluate(async frames => {
const samples = []
await new Promise(resolve => {
let last = performance.now()
let seen = 0
const step = () => {
const now = performance.now()
samples.push(now - last)
last = now
seen += 1
if (seen < frames) requestAnimationFrame(step)
else resolve()
}
requestAnimationFrame(step)
})
samples.sort((a, b) => a - b)
return {
samples: samples.length,
median: samples[Math.floor(samples.length / 2)],
p95: samples[Math.floor(samples.length * 0.95)],
}
}, count)
}
const fogState = page =>
page.evaluate(() => {
const data = document.querySelector('#stage canvas')?.dataset
if (!data) return null
return {
cells: Number(data.fogCells ?? -1),
polys: Number(data.fogPolys ?? -1),
fullMs: Number(data.fogFullMs ?? -1),
tokens: Number(data.tokens ?? -1),
}
})
test('50-token fog measurement on a Full HD map (headless SwiftShader, not the phone gate)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const gm = await gmWorld(origin, gmKey)
const scene = gm.scene
assert.equal(scene.w, SIZE.w, 'the prepared scene is 1920 px wide')
assert.equal(scene.h, SIZE.h, 'the prepared scene is 1080 px high')
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
await fiftyTokens(gm, scene, { id: player.id })
// The capped map is only 60x34 tiles at 32 px, so write the whole grid: no viewport edge can
// ask for a missing tile (the old 16384 px scene only had a viewport window, thousands of files).
writeTileGrid(stateDir, {
scene: scene.id, artVersion: scene.art_version, size: scene.tile_size,
x0: 0, x1: Math.ceil(scene.w / scene.tile_size) - 1,
y0: 0, y1: Math.ceil(scene.h / scene.tile_size) - 1,
})
const browser = await launchBrowser()
try {
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
if (message.type() === 'error' && !message.text().includes('WebSocket connection') &&
!message.text().includes('403') && !message.text().includes('net::ERR_')) {
errors.push(message.text())
}
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#stage canvas')
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout: 30000 },
)
await page.waitForFunction(
() => Number(document.querySelector('#stage canvas')?.dataset.fogPolys ?? 0) > 0,
null,
{ timeout: 30000 },
)
const initial = await fogState(page)
assert.equal(initial.tokens, 50, `the client draws 50 tokens: ${initial.tokens}`)
assert.ok(initial.cells > 300, `the Full HD map's explored cells: ${initial.cells}`)
assert.ok(initial.fullMs > 0, `the 60x34 fog snapshot was repainted: ${initial.fullMs}`)
const real = await cadence(page, 120)
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
await sleep(200)
const throttled = await cadence(page, 90)
assert.deepEqual(errors, [])
console.log(
`fogbench (#76): Full HD map 1920x1080 (60x34 cells), 50 tokens, 412x869 dpr2.625, ` +
`SwiftShader: fog snapshot=${initial.fullMs.toFixed(3)}ms exploredCells=${initial.cells} ` +
`frames real median=${real.median.toFixed(1)}ms p95=${real.p95.toFixed(1)}ms ` +
`4xCPU median=${throttled.median.toFixed(1)}ms p95=${throttled.p95.toFixed(1)}ms ` +
`(software rasteriser: floor only, not the phone number)`,
)
await context.close()
} finally {
await browser.close()
gm.ws.close()
}
}, { prepare: stateDir => setSceneSize(stateDir, SIZE) })
})
+53
View File
@@ -0,0 +1,53 @@
// The browser half of the vhost gate (#66, TESTING 10.3): real Chromium loads the real client build
// from `/` through the TLS/HTTP2 test nginx and reports h2 for the document and its hashed assets.
// The client bundle replaces the throwaway `tools/distfixture.mjs` of #66; `client/e2e/run.sh`
// builds it before this test runs.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, withStack } from './stack.mjs'
test('e2e: headless chromium loads the real client build and the page reports h2', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const loaded = []
page.on('response', response => loaded.push({ url: response.url(), status: response.status() }))
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
// A fresh visitor no longer probes `/ws` before signing in (M4 UX), so a healthy load has
// no refused-upgrade noise: every console error is a real error here.
if (message.type() === 'error') errors.push(message.text())
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
assert.equal(await page.title(), 'FFF VTT')
await page.locator('#app').waitFor({ state: 'attached' })
// A visitor with no session gets the sign-in door; the canvas is created only after `hello`.
await page.locator('#signin').waitFor({ state: 'visible', timeout: 20000 })
assert.deepEqual(errors, [])
const assets = loaded.filter(response => new URL(response.url).pathname.startsWith('/assets/'))
assert.ok(assets.length > 0, `the page loaded hashed assets: ${JSON.stringify(loaded)}`)
assert.ok(assets.every(response => response.status === 200))
const proto = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0]
const resources = performance
.getEntriesByType('resource')
.map(entry => ({ name: entry.name, protocol: entry.nextHopProtocol }))
return { scheme: location.protocol, navigation: navigation.nextHopProtocol, resources }
})
assert.equal(proto.scheme, 'https:')
assert.equal(proto.navigation, 'h2', 'the document came over HTTP/2')
assert.ok(
proto.resources.some(resource => resource.protocol === 'h2' && resource.name.endsWith('.js')),
`subresources are h2 too: ${JSON.stringify(proto.resources)}`,
)
} finally {
await browser.close()
}
})
})
+479
View File
@@ -0,0 +1,479 @@
// T6 / #69: map tiles, grid and pan/zoom, against the real server behind the TLS/HTTP2 test nginx
// (TESTING 10.3, spec #63 decisions 7/8/12). The mobile context is the phone-class emulation of the
// tile-size gate (a): 412x869 CSS px, DPR 2.625, touch, no network throttle. The gate measures the
// first viewport filling at zoom 1; the 4x CPU throttle is applied right after that measurement for
// the grid/pinch/reconnect checks (the fill is page-load work, and CDP throttling multiplies each of
// the ~480 image callbacks; see client/README.md, gate (a)).
import test from 'node:test'
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import path from 'node:path'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import { writeTileGrid, writeTiles } from '../../tools/tilefixture.mjs'
import { launchBrowser, signIn, waitForVisible, withStack } from './stack.mjs'
import { probe } from './pixels.mjs'
const MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true }
const SMALL = { viewport: { width: 160, height: 160 }, deviceScaleFactor: 1 }
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: hello.scene ?? walls.scene }
}
/** Player with one sighted token at `pos`; the server then explores around it. */
async function playerWithToken(origin, gmKey, { pos, radius }) {
const gm = await gmWorld(origin, gmKey)
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Alice')
const ack = await gm.ws.request({
t: 'token.create',
scene: gm.scene.id,
kind: 'pc',
pos,
flags: { vision: true },
vision_radius: radius,
controller: player.id,
descriptive_name: 'Alice',
actual_name: 'Alice',
})
assert.equal(ack.ok, true, JSON.stringify(ack))
gm.ws.close()
await gm.ws.closed
return { player, scene: gm.scene }
}
async function tileMap(stateDir, scene) {
const tile = scene.tile_size
const last = Math.ceil(scene.w / tile) - 1
writeTileGrid(stateDir, { scene: scene.id, artVersion: scene.art_version, size: tile, x0: 40, x1: last - 40, y0: 40, y1: last - 40 })
}
/** The importer owns w/h/tile_size (DESIGN 6.1); a harness writes the row before the server boots. */
function setScene(stateDir, { w, h, tile }) {
const db = path.join(stateDir, 'state.db')
const sql = `UPDATE scene SET w=${w}, h=${h}, tile_size=${tile}, cell=${tile} WHERE id=1`
const r = spawnSync('sqlite3', [db, sql], { encoding: 'utf8' })
assert.equal(r.status, 0, `set scene: ${r.stderr}`)
}
/** The fixture tile colour (tools/tilefixture.mjs `colourOf`), for a pixel probe. */
function tileColour(x, y) {
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
}
function nearColour(a, b, tolerance = 40) {
return Math.abs(a.r - b.r) <= tolerance && Math.abs(a.g - b.g) <= tolerance && Math.abs(a.b - b.b) <= tolerance
}
async function mobileContext(browser) {
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
return { context, page, cdp }
}
const canvas = '#stage canvas'
const zoomOf = page => page.evaluate(() => document.querySelector('#stage canvas')?.dataset.zoom ?? null)
const gridOf = page => page.evaluate(() => document.querySelector('#stage canvas')?.dataset.grid ?? null)
const requestsOf = page => page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.tileRequests ?? -1))
const distinctOf = page => page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.tileDistinct ?? -1))
const waitTilesReady = (page, timeout = 30000) =>
page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready', null, { timeout })
const fillDebugOf = page =>
page.evaluate(() => {
const c = document.querySelector('#stage canvas')
return c ? { ...c.dataset, cw: c.clientWidth, ch: c.clientHeight } : null
})
// Gate (a) budget, DESIGN 13: the viewport fills in < 1 s at zoom 1. A single wall-clock sample is
// host-load-sensitive (a renderer the OS descheduled is not the app's speed), so the gate is the
// fastest fresh first fill after a warm-up, the min-of-N shape of TESTING 5.3. A real regression
// raises every sample, so the minimum fails with it. TESTING 5.3's documented 2x tolerance for a
// saturated box applies to the budget: the gate is 2x the 1 s budget and the absolute minimum is
// always reported. A reload is a fresh page load (new JS context, empty module-level tile cache), so
// every sample is a real "first viewport" fill rather than a cache hit.
const FILL_BUDGET_MS = 1000
const FILL_GATE_MS = FILL_BUDGET_MS * 2
const FILL_WARMUP = 1
const FILL_SAMPLES = 4
/**
* One first-viewport fill: a reload is a fresh page load (new JS context, empty module-level tile
* cache), so every sample is a real "first viewport" rather than a cache hit. The session cookie
* carries the sign-in across the reload, so the page goes live without the key again.
*/
async function firstFill(page, origin) {
await page.goto(`${origin}/`)
await waitForVisible(page, canvas)
const shownAt = Date.now()
await waitTilesReady(page)
return { fillMs: Date.now() - shownAt, debug: await fillDebugOf(page) }
}
test('mobile player: first viewport fills in under a second at zoom 1, grid toggles, pinch works, cache survives reconnect', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const world = await gmWorld(origin, gmKey)
await tileMap(stateDir, world.scene)
const { player } = await playerWithToken(origin, gmKey, { pos: [2048, 2048], radius: 1200 })
world.ws.close()
const browser = await launchBrowser()
try {
const { context, page } = await mobileContext(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, canvas)
const cdp = await context.newCDPSession(page)
const errors = []
// No per-response listener while measuring: Playwright serialising ~480 tile responses
// through Node would double the measurement; the status split is the 403 test.
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
// A transient tile-image failure is tolerated by the tile contract (the hole fills on the
// next window or reconnect; the no-retry proof is the 403 test below, per URL), so the
// browser's network-level resource line is not a client error, same as in the fog suites.
const text = message.text()
if (message.type() === 'error' && !text.includes('WebSocket connection') &&
!text.includes('403') && !text.includes('net::ERR_')) {
errors.push(text)
}
})
// Tile-size gate (a): the viewport fills at zoom 1 on the phone-class viewport/DPR/touch.
// Warm-up first (module cache, JIT, TLS), then the fastest of FILL_SAMPLES fresh fills.
for (let i = 0; i < FILL_WARMUP; i++) await firstFill(page, origin)
const fills = []
for (let i = 0; i < FILL_SAMPLES; i++) fills.push(await firstFill(page, origin))
const best = fills.reduce((a, b) => (b.fillMs < a.fillMs ? b : a))
// Recorded on every run, pass or fail: the absolute gate measurement for this host.
console.log(
`tile-size gate (a): fastest first viewport fill ${best.fillMs} ms ` +
`(samples ${fills.map(f => f.fillMs).join(', ')} ms, budget ${FILL_BUDGET_MS} ms, gate ${FILL_GATE_MS} ms)`,
)
assert.ok(
best.fillMs < FILL_GATE_MS,
`fastest of ${FILL_SAMPLES} first viewport fills after ${FILL_WARMUP} warm-up: ${best.fillMs} ms, ` +
`budget ${FILL_BUDGET_MS} ms, gate ${FILL_GATE_MS} ms (2x saturated-host tolerance; ` +
`samples ${fills.map(f => f.fillMs).join(', ')} ms; ${JSON.stringify(best.debug)})`,
)
assert.equal(await zoomOf(page), '1')
// Phone-class CPU for everything after the fill measurement (the gate itself is page-load
// work and is measured at real CPU; the interactions below must still hold on a slow phone).
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
// Viewport + exactly one tile of margin, each distinct tile fetched once: the distinct-URL
// count is the wanted count, and it is the 480-tile window the maths predicts for 412x869 at
// zoom 1. `tileRequests` can be one larger when the #70 rule re-asks a tile whose 403 became
// allowed (the explored frame landing after the first window), so it is not the duplicate
// check; a tile fetched twice would show up in the distinct count.
const visible = await page.evaluate(() =>
Number(document.querySelector('#stage canvas')?.dataset.visibleTiles ?? 0))
assert.ok(visible > 300, `a phone viewport wants its tiles: ${visible}`)
assert.equal(await distinctOf(page), visible, 'one fetch per wanted tile, none twice')
assert.ok(await requestsOf(page) >= visible, 'the attempt counter covers every distinct tile')
// Story 18: the grid toggle changes both the button state and the rendered canvas.
await waitForVisible(page, '#grid-toggle')
assert.equal(await page.getAttribute('#grid-toggle', 'aria-pressed'), 'true')
const gridOn = await page.screenshot()
await page.click('#grid-toggle')
await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.grid === 'off')
assert.equal(await page.getAttribute('#grid-toggle', 'aria-pressed'), 'false')
await sleep(120)
const gridOff = await page.screenshot()
assert.ok(!gridOn.equals(gridOff), 'turning the grid off changes what is drawn')
await page.click('#grid-toggle')
assert.equal(await gridOf(page), 'on')
// Story 15: a synthetic two-finger pinch zooms (touch pointers, the same path a finger takes).
const beforePinch = Number(await zoomOf(page))
await page.evaluate(() => {
const target = document.querySelector('#stage canvas')
const fire = (type, id, x) =>
target.dispatchEvent(new PointerEvent(type, {
pointerId: id, pointerType: 'touch', isPrimary: id === 1,
clientX: x, clientY: 400, bubbles: true, cancelable: true,
}))
fire('pointerdown', 1, 150)
fire('pointerdown', 2, 250)
fire('pointermove', 1, 50)
fire('pointermove', 2, 350)
fire('pointerup', 1, 50)
fire('pointerup', 2, 350)
})
const afterPinch = Number(await zoomOf(page))
assert.ok(afterPinch > beforePinch, `pinch apart zoomed in: ${beforePinch} -> ${afterPinch}`)
assert.ok(afterPinch <= 4, 'at most 4')
// Story 14: a reconnect keeps the decoded tiles; the page makes no new tile fetch.
const fetchesBefore = await requestsOf(page)
await context.setOffline(true)
await page.locator('#badge[data-state="offline"]').waitFor({ state: 'visible', timeout: 20000 })
await context.setOffline(false)
await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 })
await waitTilesReady(page)
const fetchesAfter = await requestsOf(page)
assert.equal(fetchesAfter, fetchesBefore, 'the tile cache survives the reconnect: no refetch')
assert.deepEqual(errors, [])
await context.close()
} finally {
await browser.close()
}
})
})
test('clamps: player stops at 0.5 and 4, the GM goes below 0.5 and stops at 4', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const world = await gmWorld(origin, gmKey)
await tileMap(stateDir, world.scene)
const { player } = await playerWithToken(origin, gmKey, { pos: [2048, 2048], radius: 1200 })
world.ws.close()
const browser = await launchBrowser()
try {
const playerContext = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL })
const page = await playerContext.newPage()
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, canvas)
await waitTilesReady(page)
await page.mouse.move(80, 80)
await page.mouse.wheel(0, 2000)
await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '0.5')
assert.equal(await zoomOf(page), '0.5')
await page.mouse.wheel(0, -2000)
await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '4')
assert.equal(await zoomOf(page), '4')
await playerContext.close()
const gmContext = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL })
const gmPage = await gmContext.newPage()
await gmPage.goto(`${origin}/`)
await waitForVisible(gmPage, '#signin')
await signIn(gmPage, gmKey)
await waitForVisible(gmPage, canvas)
await waitTilesReady(gmPage)
// 0.25 is below the player's 0.5 floor: the GM's survey zoom is not clamped there. Wheel
// over the left edge: the GM column (Walls first) now owns the right side of this tiny view.
await gmPage.mouse.move(20, 80)
await gmPage.mouse.wheel(0, 924)
await gmPage.waitForFunction(() => {
const zoom = Number(document.querySelector('#stage canvas')?.dataset.zoom)
return zoom < 0.3 && zoom > 0.2
})
const gmZoom = Number(await zoomOf(gmPage))
assert.ok(gmZoom < 0.5, `the GM zoomed to ${gmZoom}, below the player floor`)
await gmPage.mouse.wheel(0, -2000)
await gmPage.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '4')
assert.equal(await zoomOf(gmPage), '4')
await gmContext.close()
} finally {
await browser.close()
}
})
})
test('a 403 is remembered: no retry loop, even when the viewport re-syncs', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const world = await gmWorld(origin, gmKey)
await tileMap(stateDir, world.scene)
// A sighted token far from the map centre: the camera looks at unexplored floor, so the gate
// answers 403 for every tile in view.
const { player } = await playerWithToken(origin, gmKey, { pos: [300, 300], radius: 200 })
world.ws.close()
const browser = await launchBrowser()
try {
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL })
const page = await context.newPage()
const perUrl = new Map()
const statuses = []
page.on('request', request => {
const path = new URL(request.url()).pathname
if (!path.startsWith('/tiles/')) return
perUrl.set(path, (perUrl.get(path) ?? 0) + 1)
})
page.on('response', response => {
if (new URL(response.url()).pathname.startsWith('/tiles/')) statuses.push(response.status())
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, canvas)
await waitTilesReady(page)
const first = await requestsOf(page)
assert.ok(first > 20, `the viewport asked for tiles: ${first}`)
assert.ok(statuses.length > 0 && statuses.every(status => status === 403),
`unexplored floor is refused: ${JSON.stringify([...new Set(statuses)])}`)
// Re-sync (toggle the grid twice) and wait: not one denied tile may be asked for twice.
await page.click('#grid-toggle')
await page.click('#grid-toggle')
await sleep(2000)
assert.equal(await requestsOf(page), first, 'no retry after a viewport re-sync')
// A denied tile costs exactly one request: the status comes from the fetch itself (#86).
assert.ok([...perUrl.values()].every(count => count === 1),
`a denied tile was requested more than once: ${JSON.stringify([...perUrl].filter(([, count]) => count !== 1))}`)
await context.close()
} finally {
await browser.close()
}
})
})
// #86: a GM survey zoom asks for the whole map. The fill must be one request per tile (no
// duplicate classification fetches), centre-out, and it must reach `ready`. Headless SwiftShader,
// so the time is a host floor, not the phone budget; recorded, never gated tightly.
test('GM survey zoom on a Full HD map fills one request per tile', { timeout: 120000 }, async () => {
const W = 1920
const H = 1080
const TILE = 32
await withStack(
async ({ origin, gmKey }) => {
const browser = await launchBrowser()
try {
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
const page = await context.newPage()
const perUrl = new Map()
const transient = new Set()
page.on('request', request => {
const p = new URL(request.url()).pathname
if (p.startsWith('/tiles/')) perUrl.set(p, (perUrl.get(p) ?? 0) + 1)
})
page.on('response', response => {
const p = new URL(response.url()).pathname
if (p.startsWith('/tiles/') && response.status() !== 200 && response.status() !== 403) transient.add(p)
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, canvas)
await waitTilesReady(page)
const before = await requestsOf(page)
// Fit: zoom = min(1000/1920, 700/1080); one wheel is enough (delta -> exp factor).
const fit = Math.min(1000 / W, 700 / H)
await page.mouse.move(500, 350)
const startedAt = Date.now()
await page.mouse.wheel(0, Math.log(1 / fit) / 0.0015)
await page.waitForFunction(
() => {
const data = document.querySelector('#stage canvas')?.dataset ?? {}
return Number(data.zoom ?? 1) < 0.53 && Number(data.visibleTiles ?? 0) > 1900 && data.tiles === 'ready'
},
null,
{ timeout: 60000, polling: 50 },
)
const fillMs = Date.now() - startedAt
const visible = await page.evaluate(() =>
Number(document.querySelector('#stage canvas')?.dataset.visibleTiles ?? 0))
const requests = await requestsOf(page)
console.log(`#86 GM survey fill: ${fillMs} ms, ${visible} tiles, ${requests} requests (before ${before})`)
assert.equal(visible, (W / TILE) * Math.ceil(H / TILE), 'the whole Full HD map at this zoom')
assert.ok(perUrl.size >= visible, `every wanted tile was asked for: ${perUrl.size} of ${visible}`)
// No tile that answered 200 cost a second request (the old path re-asked on every image
// error to learn its status). A genuinely failed tile may retry.
const duplicated = [...perUrl].filter(([url, count]) => count > 1 && !transient.has(url))
assert.deepEqual(duplicated, [], 'one request per tile that succeeded')
assert.ok(fillMs < 30000, `the survey fill reached ready in ${fillMs} ms`)
await context.close()
} finally {
await browser.close()
}
},
{
prepare: stateDir => {
setScene(stateDir, { w: W, h: H, tile: TILE })
writeTileGrid(stateDir, {
scene: 1, artVersion: 1, size: TILE, x0: 0, x1: W / TILE - 1, y0: 0, y1: Math.ceil(H / TILE) - 1,
})
},
},
)
})
// #86: a tile that 404s (art imported after the page loaded) is retried a bounded number of times,
// and a reconnect retries it after the file appears. Before, the void was permanent until reload.
test('a 404 tile is retried with a budget and recovers on reconnect', { timeout: 120000 }, async () => {
const W = 1920
const H = 1080
const TILE = 32
const MISSING = [Math.floor(W / 2 / TILE), Math.floor(H / 2 / TILE)]
const missingUrl = `/tiles/1/v1/${MISSING[0]}_${MISSING[1]}.png`
await withStack(
async ({ origin, gmKey, stateDir, server }) => {
const browser = await launchBrowser()
let restarted = null
try {
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
const page = await context.newPage()
let missingRequests = 0
page.on('request', request => {
if (new URL(request.url()).pathname === missingUrl) missingRequests += 1
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, canvas)
await waitTilesReady(page)
// The first pass spends its whole budget (3 loads), not 2 requests per load.
for (let i = 0; i < 100 && missingRequests < 3; i++) await sleep(100)
assert.equal(missingRequests, 3, 'three bounded loads, one request each')
const camera = await page.evaluate(() =>
(document.querySelector('#stage canvas')?.dataset.camera ?? '0,0').split(',').map(Number))
const zoom = Number(await zoomOf(page))
const at = [(MISSING[0] + 0.5) * TILE * zoom + camera[0], (MISSING[1] + 0.5) * TILE * zoom + camera[1]]
const blank = await probe(page, at[0], at[1])
assert.ok(!nearColour(blank, tileColour(MISSING[0], MISSING[1])),
`the missing tile is not painted yet: ${JSON.stringify(blank)}`)
// The art arrives, then a reconnect (a real socket close and a fresh `hello`) gives the
// stored failure another chance. A server restart on the same port is the honest trigger:
// CDP "offline" does not necessarily close an established WebSocket.
writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles: [MISSING] })
await stopServer(server)
restarted = await startServer({ stateDir, port: server.port, publicOrigin: origin })
// The badge may flip through `reconnecting` faster than a poll sees it; `connected` after a
// real socket close is the hello that matters.
await page.locator('#badge[data-state="reconnecting"]').waitFor({ state: 'visible', timeout: 20000 })
.catch(() => {})
await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 })
let painted = null
for (let i = 0; i < 100; i++) {
painted = await probe(page, at[0], at[1])
if (nearColour(painted, tileColour(MISSING[0], MISSING[1]))) break
await sleep(100)
}
assert.ok(missingRequests >= 4, `the reconnect re-asked for the failed tile: ${missingRequests}`)
assert.ok(nearColour(painted, tileColour(MISSING[0], MISSING[1])),
`the recovered tile is painted: ${JSON.stringify(painted)}`)
await context.close()
} finally {
if (restarted) await stopServer(restarted)
await browser.close()
}
},
{
prepare: stateDir => {
setScene(stateDir, { w: W, h: H, tile: TILE })
const tiles = []
for (let y = 0; y <= Math.ceil(H / TILE) - 1; y++) for (let x = 10; x <= 50; x++) {
if (x === MISSING[0] && y === MISSING[1]) continue
tiles.push([x, y])
}
writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles })
},
},
)
})
+41
View File
@@ -0,0 +1,41 @@
// Story 9 / DR 6.2 (#67): a proto mismatch completes the upgrade, sends closing{proto-mismatch}
// and closes; the client must show "reload" and stop, not sign in and not retry.
//
// The real server's mismatch path is already proven by tools/protocol.test.mjs (it takes a build
// whose proto differs). Here the browser's own WebSocket is intercepted and given exactly that
// documented frame sequence, so the assertion is about the client's UI and close-code mapping.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, waitForText, waitForVisible, withStack } from './stack.mjs'
test('protocol mismatch: the client shows reload and does not reconnect', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
// The client only dials on boot when its session marker exists (M4 UX). This test is about
// the upgrade outcome, so tell the page a session may exist before it loads.
await page.addInitScript(() => localStorage.setItem('fff-vtt.session', '1'))
let sockets = 0
await page.routeWebSocket(/\/ws\?proto=2$/, ws => {
sockets += 1
// DESIGN 6.5 row 5: closing then the close frame; no hello, no state.
ws.send(JSON.stringify({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 }))
ws.close()
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#fatal')
await waitForText(page, '#fatal-text', /out of date.*reload/i)
const reload = page.locator('#reload')
assert.equal(await reload.isVisible(), true)
assert.equal(await page.locator('#signin').isVisible(), false)
assert.equal(await page.locator('#stage canvas').count(), 0)
await new Promise(resolve => setTimeout(resolve, 400))
assert.equal(sockets, 1, 'a mismatch is terminal: exactly one connection attempt')
} finally {
await browser.close()
}
})
})
+46
View File
@@ -0,0 +1,46 @@
// #82: the opt-in perf overlay. Hidden by default (no node, no work), and with `?perf=1` it shows
// the numbers the phone checklist records, from the real client through the real server/nginx.
import test from 'node:test'
import assert from 'node:assert/strict'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
async function signInGm(browser, origin, gmKey, path = '/') {
const view = await newPage(browser)
await view.page.goto(`${origin}${path}`)
await waitForVisible(view.page, '#signin')
await signIn(view.page, gmKey)
await waitForVisible(view.page, '#stage canvas')
return view
}
test('perf overlay: absent by default, `?perf=1` shows fps/frame/JS/tokens/zoom', { timeout: 120000 },
async () => {
await withStack(async ({ origin, gmKey }) => {
const browser = await launchBrowser()
try {
const normal = await signInGm(browser, origin, gmKey)
assert.equal(await normal.page.locator('#perf').count(), 0,
'no overlay node without the opt-in')
await normal.context.close()
const perf = await signInGm(browser, origin, gmKey, '/?perf=1')
await waitForVisible(perf.page, '#perf')
const text = await waitForText(perf.page, '#perf', /fps \d/)
assert.match(text, /fps \d+\.\d/)
assert.match(text, /frame p50 \d+\.\d p95 \d+\.\d ms/)
assert.match(text, /JS p50 \d+\.\d\d p95 \d+\.\d\d ms/)
assert.match(text, /tokens visible \d+ \/ total \d+/)
assert.match(text, /zoom \d+\.\d\d/)
await perf.context.close()
} finally {
await browser.close()
}
})
})
+139
View File
@@ -0,0 +1,139 @@
// Pixel probes for the client e2e (TESTING 10.3). A probe is the colour the browser actually shows
// at one CSS point: Playwright screenshots a 3x3 CSS-pixel clip and this module decodes the PNG and
// averages it. No renderer internals, no WebGL readPixels, no preserveDrawingBuffer.
//
// The decoder is intentionally small: Chromium screenshots are non-interlaced 8-bit truecolour
// (RGB or RGBA), which is all a screenshot can be. Anything else is a programmer error here, not a
// browser case to support.
import zlib from 'node:zlib'
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
function paeth(a, b, c) {
const p = a + b - c
const pa = Math.abs(p - a)
const pb = Math.abs(p - b)
const pc = Math.abs(p - c)
if (pa <= pb && pa <= pc) return a
if (pb <= pc) return b
return c
}
/** Decode an 8-bit, non-interlaced RGB/RGBA PNG into `{ width, height, data }` (RGBA bytes). */
export function decodePng(buffer) {
if (!Buffer.isBuffer(buffer) || !buffer.subarray(0, 8).equals(SIGNATURE)) {
throw new Error('not a PNG')
}
let offset = 8
let width = 0
let height = 0
let channels = 0
const idat = []
while (offset + 8 <= buffer.length) {
const length = buffer.readUInt32BE(offset)
const type = buffer.toString('latin1', offset + 4, offset + 8)
const body = buffer.subarray(offset + 8, offset + 8 + length)
offset += 12 + length
if (type === 'IHDR') {
width = body.readUInt32BE(0)
height = body.readUInt32BE(4)
const depth = body[8]
const colorType = body[9]
const interlace = body[12]
if (depth !== 8 || interlace !== 0) throw new Error(`unsupported PNG depth/interlace ${depth}/${interlace}`)
if (colorType === 2) channels = 3
else if (colorType === 6) channels = 4
else throw new Error(`unsupported PNG colour type ${colorType}`)
} else if (type === 'IDAT') {
idat.push(body)
} else if (type === 'IEND') {
break
}
}
if (!width || !height || !channels) throw new Error('PNG without IHDR/IDAT')
const raw = zlib.inflateSync(Buffer.concat(idat))
const stride = width * channels
const pixels = Buffer.alloc(stride * height)
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)]
const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
const out = pixels.subarray(y * stride, (y + 1) * stride)
const prev = y > 0 ? pixels.subarray((y - 1) * stride, y * stride) : null
for (let x = 0; x < stride; x++) {
const a = x >= channels ? out[x - channels] : 0
const b = prev ? prev[x] : 0
const c = prev && x >= channels ? prev[x - channels] : 0
let value = line[x]
switch (filter) {
case 0:
break
case 1:
value = (value + a) & 0xff
break
case 2:
value = (value + b) & 0xff
break
case 3:
value = (value + ((a + b) >> 1)) & 0xff
break
case 4:
value = (value + paeth(a, b, c)) & 0xff
break
default:
throw new Error(`unsupported PNG filter ${filter}`)
}
out[x] = value
}
}
if (channels === 4) return { width, height, data: pixels }
const rgba = Buffer.alloc(width * height * 4)
for (let i = 0, j = 0; i < pixels.length; i += 3, j += 4) {
rgba[j] = pixels[i]
rgba[j + 1] = pixels[i + 1]
rgba[j + 2] = pixels[i + 2]
rgba[j + 3] = 255
}
return { width, height, data: rgba }
}
/** Average every pixel of a decoded image (the probe clip is small and uniform). */
export function averageColour(image) {
let r = 0
let g = 0
let b = 0
let a = 0
const count = image.width * image.height
for (let i = 0; i < image.data.length; i += 4) {
r += image.data[i]
g += image.data[i + 1]
b += image.data[i + 2]
a += image.data[i + 3]
}
return { r: r / count, g: g / count, b: b / count, a: a / count }
}
/**
* The colour shown at CSS point `(x, y)`: a 3x3 CSS-pixel screenshot clip, decoded and averaged.
* Screenshots are in device pixels, so DPR is handled by the browser, not by this helper.
*/
export async function probe(page, x, y) {
const px = Math.max(0, Math.round(x) - 1)
const py = Math.max(0, Math.round(y) - 1)
const buffer = await page.screenshot({ clip: { x: px, y: py, width: 3, height: 3 } })
return averageColour(decodePng(buffer))
}
/** Mean absolute channel difference, for "did this area change" assertions. */
export function differs(a, b, tolerance = 12) {
return (
Math.abs(a.r - b.r) > tolerance ||
Math.abs(a.g - b.g) > tolerance ||
Math.abs(a.b - b.b) > tolerance
)
}
export function luminance({ r, g, b }) {
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
# devbox run e2e: the headless-browser gate (TESTING 10.3). Builds the real client, then runs the
# browser suite against the real server through the TLS/HTTP2 test nginx. Separate from
# `devbox run test` so the fast server gate stays fast (TESTING 11.1); the client's own unit tests
# are `devbox run client-test`.
#
# Parallelism: every test gets its own stack (state dir, free ports, nginx, server) and its own
# browser, so test files run FFF_E2E_JOBS at a time (default: half the cores, capped at 4;
# FFF_TEST_JOBS/FFF_E2E_JOBS=1 serialises). The files whose assertions are timing gates (the
# tile-fill budget, the fog costs, the perf overlay) run alone first, unloaded, then the rest fan
# out. The client dist and the server binaries are built once, before any worker starts.
set -euo pipefail
cd "$(dirname "$0")/../.." || exit 1
. tools/jobs.sh
mkdir -p results run/logs
fff_setup_tmpdir
JOBS=$(fff_e2e_jobs)
export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}"
if [ -z "$CHROMIUM" ]; then
echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2
exit 1
fi
# npm deps stay out of tools/ (TESTING 10.4) and out of git; install once per checkout.
( cd client && { [ -d node_modules ] || npm ci --no-audit --no-fund; } )
( cd client && npm run build )
# Shared Nim build cache: the server binaries the stacks launch (and the leak checker) are built
# once here, not once per test file.
node tools/prebuild.mjs server-only > run/logs/prebuild-e2e.log 2>&1
E2E_SERIAL=(client/e2e/map.test.mjs client/e2e/fog.test.mjs client/e2e/fogbench.test.mjs
client/e2e/perf.test.mjs)
E2E_PARALLEL=()
for f in client/e2e/*.test.mjs; do
case " ${E2E_SERIAL[*]} " in
*" $f "*) ;;
*) E2E_PARALLEL+=("$f") ;;
esac
done
node --test --test-concurrency=1 --test-reporter=spec "${E2E_SERIAL[@]}" \
> run/logs/e2e-serial.log 2>&1 || rc=$?
node --test --test-concurrency="$JOBS" --test-reporter=spec "${E2E_PARALLEL[@]}" \
> run/logs/e2e-parallel.log 2>&1 || rc=$?
cat run/logs/e2e-serial.log run/logs/e2e-parallel.log > results/e2e.log
cat results/e2e.log
# Each group's spec reporter ends with its own summary. Print one combined line so a reader (or an
# agent) cannot mistake the parallel group's "N pass" for the suite total; it is the last line of
# results/e2e.log too. Field names are matched from the end so the leading "ℹ" is irrelevant.
summary_field() { # <tests|pass|fail|skipped> <log>
awk -v k="$1" 'NF >= 2 && $(NF-1) == k && $NF ~ /^[0-9]+$/ { v = $NF } END { print v + 0 }' "$2"
}
S_TESTS=$(summary_field tests run/logs/e2e-serial.log)
S_PASS=$(summary_field pass run/logs/e2e-serial.log)
S_FAIL=$(summary_field fail run/logs/e2e-serial.log)
S_SKIP=$(summary_field skipped run/logs/e2e-serial.log)
P_TESTS=$(summary_field tests run/logs/e2e-parallel.log)
P_PASS=$(summary_field pass run/logs/e2e-parallel.log)
P_FAIL=$(summary_field fail run/logs/e2e-parallel.log)
P_SKIP=$(summary_field skipped run/logs/e2e-parallel.log)
printf 'e2e total: tests %d / pass %d / fail %d / skip %d (serial %d, parallel %d)\n' \
"$((S_TESTS + P_TESTS))" "$((S_PASS + P_PASS))" "$((S_FAIL + P_FAIL))" \
"$((S_SKIP + P_SKIP))" "$S_TESTS" "$P_TESTS" | tee -a results/e2e.log
[ "${rc:-0}" -eq 0 ] || exit "$rc"
+285
View File
@@ -0,0 +1,285 @@
// T5 (#68, TESTING 10.3): the name prompt, the connection badge, reconnect + full resync and two
// devices on one player key. Everything runs against the real server through the TLS/HTTP2 test
// nginx; the browser's own WebSocket is wrapped only to *record* frames (the app is untouched), so
// the resync assertions read the real wire.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForHidden,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
/** Record every WS frame/close on `window.__wsLog` without changing what the app sees. */
async function recordSockets(page) {
await page.addInitScript(() => {
window.__wsLog = { sockets: 0, frames: [], closes: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
window.__wsLog.sockets += 1
this.addEventListener('message', event => {
try {
window.__wsLog.frames.push(JSON.parse(event.data))
} catch {
// a non-JSON frame is not state; the client ignores it too
}
})
this.addEventListener('close', event => {
window.__wsLog.closes.push({ code: event.code, reason: event.reason })
})
}
}
window.WebSocket = RecordingSocket
})
}
const frames = page => page.evaluate(() => window.__wsLog.frames)
const frameCount = async page => (await frames(page)).length
async function waitForFrame(page, predicate, timeout = 20000) {
await page.waitForFunction(predicate, null, { timeout })
}
async function waitForBadge(page, state, timeout = 30000) {
await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout })
}
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: walls.scene }
}
test('first sign-in asks once for a name and shows a taken name', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const alice = await createPlayer(gm.ws)
await namePlayer(origin, alice.key, 'Alice')
const unnamed = await createPlayer(gm.ws)
gm.ws.close()
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, unnamed.key)
// Stories 5: the prompt, and no game data (canvas/HUD) before the name is accepted.
await waitForVisible(page, '#name')
assert.equal(await page.locator('#stage canvas').count(), 0)
assert.equal(await page.locator('#hud').isVisible(), false)
assert.equal(await page.locator('#name-error').isVisible(), false)
// Story 6: a taken name is refused with a visible reason, and the prompt stays.
await page.fill('#name-input', 'alice')
await page.click('#name-submit')
await waitForText(page, '#name-error', /taken/i)
assert.equal(await page.locator('#name').isVisible(), true)
// A free name lands on the map; `hello` (name set) + the resync rebuild the view.
await page.fill('#name-input', 'Bob')
await page.click('#name-submit')
await waitForVisible(page, '#hud')
await waitForVisible(page, '#stage canvas')
await waitForText(page, '#me', /^Bob$/)
// The HUD roster lists the other players; this connection's own name is #me.
await waitForText(page, '#roster', /GM/)
await waitForBadge(page, 'connected')
await waitForHidden(page, '#name')
// Asked once: a reload with the same session comes straight back to the table.
await page.reload()
await waitForVisible(page, '#hud')
await waitForText(page, '#me', /^Bob$/)
await waitForHidden(page, '#name')
await waitForBadge(page, 'connected')
} finally {
await browser.close()
}
})
})
test('a killed server under a live player: badge reconnecting, then a full resync', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, server }) => {
const gm = await gmWorld(origin, gmKey)
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
// The view the resync must rebuild: a controlled token (vision + explored), another token in
// sight (encountered + token) and a player-marked window (marker).
const own = await gm.ws.request({
t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'Ann', actual_name: 'Ann', controller: player.id,
})
assert.equal(own.ok, true)
const npc = await gm.ws.request({
t: 'token.create', scene: gm.scene, kind: 'npc', pos: [460, 400],
descriptive_name: 'Rat', actual_name: 'Rat',
})
assert.equal(npc.ok, true)
const windowAck = await gm.ws.request({
t: 'wall.add', scene: gm.scene, a: [430, 360], b: [430, 440], preset: 'window',
})
assert.equal(windowAck.ok, true)
gm.ws.close()
const browser = await launchBrowser()
let restarted = null
try {
const { page } = await newPage(browser)
await recordSockets(page)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#hud')
await waitForBadge(page, 'connected')
// The first connect already carries the full view; wait for all of it before the drop.
await waitForFrame(page, () => {
const seen = new Set((window.__wsLog?.frames ?? []).map(frame => frame.t))
return ['hello', 'roster', 'encountered', 'vision', 'explored', 'marker', 'token']
.every(type => seen.has(type))
})
const before = await frameCount(page)
await stopServer(server)
// Story 7/8: the map stays up (stale) and the badge says reconnecting, with no reload.
await waitForBadge(page, 'reconnecting')
assert.equal(await page.locator('#stage canvas').count(), 1)
assert.equal(await page.locator('#signin').isVisible(), false)
// Restart the real server on the same port and state (sessions are durable, DESIGN 4.4).
restarted = await startServer({
stateDir: server.stateDir,
port: server.port,
publicOrigin: server.publicOrigin,
})
await waitForBadge(page, 'connected', 60000)
// Story 11: the reconnect's `hello` is followed by the whole 6.3 resync, not a stale diff.
await page.waitForFunction(
beforeIndex => {
const log = window.__wsLog.frames
const helloAt = log.findIndex((frame, index) => index >= beforeIndex && frame.t === 'hello')
if (helloAt < 0) return false
const after = log.slice(helloAt)
const seen = new Set(after.map(frame => frame.t))
return ['roster', 'encountered', 'vision', 'explored', 'marker', 'token']
.every(type => seen.has(type))
},
before,
{ timeout: 30000 },
)
const log = await frames(page)
const helloAt = log.findLastIndex(frame => frame.t === 'hello')
const after = log.slice(helloAt)
const full = type => after.find(frame => frame.t === type)
assert.equal(full('explored')?.full, true, 'explored comes back as a full snapshot')
assert.equal(full('marker')?.full, true, 'markers come back as a full snapshot')
assert.equal(full('encountered')?.full, true, 'the encountered list comes back full')
assert.ok(after.some(frame => frame.t === 'token'), 'tokens come back')
assert.ok(after.some(frame => frame.t === 'vision'), 'fog/vision comes back')
assert.match(await page.textContent('#roster'), /GM/)
assert.equal(await page.locator('#hud').isVisible(), true)
} finally {
if (restarted) await stopServer(restarted)
await browser.close()
}
})
})
test('a dropped network is offline, and coming back reconnects to the same view', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Cara')
gm.ws.close()
const browser = await launchBrowser()
try {
const { context, page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#hud')
await waitForBadge(page, 'connected')
await context.setOffline(true)
// Story 7: no network at all is the `offline` badge, distinct from a socket retrying.
await waitForBadge(page, 'offline', 15000)
await context.setOffline(false)
// The `online` event skips the rest of the backoff; the session is still valid.
await waitForBadge(page, 'connected', 30000)
await waitForText(page, '#me', /^Cara$/)
assert.equal(await page.locator('#stage canvas').count(), 1)
} finally {
await browser.close()
}
})
})
test('two connections of one player are both live and stay in sync', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await gmWorld(origin, gmKey)
const scene = gm.scene
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Dee')
gm.ws.close()
const browser = await launchBrowser()
try {
const first = await newPage(browser)
const second = await newPage(browser)
for (const view of [first, second]) {
await recordSockets(view.page)
await view.page.goto(`${origin}/`)
await waitForVisible(view.page, '#signin')
await signIn(view.page, player.key)
await waitForVisible(view.page, '#hud')
await waitForBadge(view.page, 'connected')
}
assert.equal(await first.page.textContent('#me'), 'Dee')
assert.equal(await second.page.textContent('#me'), 'Dee')
// A state change after both are connected reaches both connections: the GM places the
// player's own token, and each device's `token` frame carries it with `mine:true`.
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const created = await gm.ws.request({
t: 'token.create', scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'Dee', actual_name: 'Dee', controller: player.id,
})
assert.equal(created.ok, true)
for (const view of [first, second]) {
await view.page.waitForFunction(
id => (window.__wsLog?.frames ?? []).some(frame => frame.t === 'token' && frame.id === id && frame.mine === true),
created.id,
{ timeout: 20000 },
)
}
// A later roster change is broadcast to every connection of the named player too.
const renamed = await gm.ws.request({ t: 'player.rename', id: player.id, name: 'Dee Two' })
assert.equal(renamed.ok, true)
gm.ws.close()
for (const view of [first, second]) {
await waitForText(view.page, '#me', /Dee Two/)
await waitForBadge(view.page, 'connected')
}
} finally {
await browser.close()
}
})
})
+106
View File
@@ -0,0 +1,106 @@
// T4 client shell (#67, TESTING 10.3): join -> canvas -> hello/roster for the GM and a player, no
// data before join, one plain refusal for a wrong and an unknown key, and a revoked session
// returning to sign-in. The server, the nginx vhost and the client are the real ones.
import test from 'node:test'
import assert from 'node:assert/strict'
import { sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
makePlayer,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
const KEY_REFUSED = 'Key not recognised.'
async function canvasAndRoster(page, expectedNames) {
await waitForVisible(page, '#stage canvas')
await waitForVisible(page, '#hud')
const roster = await waitForText(page, '#roster', new RegExp(expectedNames[0]))
for (const name of expectedNames) assert.match(roster, new RegExp(name))
return roster
}
test('no session: only the sign-in page, and a wrong and an unknown key look identical', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const joins = []
page.on('response', response => {
if (new URL(response.url()).pathname === '/join') joins.push(response.status())
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
// Story 1: a stranger gets the door and no game data.
assert.equal(await page.locator('#stage').isVisible(), false)
assert.equal(await page.locator('#hud').isVisible(), false)
assert.equal(await page.locator('#roster li').count(), 0)
// Story 3: the same answer for a well-formed but wrong key and for an unknown one.
await signIn(page, 'ABCD-EFGH-JKMN-PQRS')
await waitForVisible(page, '#signin-error')
const wrong = await page.textContent('#signin-error')
await signIn(page, 'not-a-key')
await waitForVisible(page, '#signin-error')
const unknown = await page.textContent('#signin-error')
assert.equal(wrong, KEY_REFUSED)
assert.equal(unknown, KEY_REFUSED)
assert.deepEqual(joins, [401, 401])
// No map request was made before a session existed.
assert.equal(await page.locator('#stage canvas').count(), 0)
} finally {
await browser.close()
}
})
})
test('GM and player: join -> canvas -> hello and roster; revoked returns to sign-in', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const player = await makePlayer(origin, gmKey, 'Alice')
const browser = await launchBrowser()
try {
const gmView = await newPage(browser)
await gmView.page.goto(`${origin}/`)
await waitForVisible(gmView.page, '#signin')
await signIn(gmView.page, gmKey)
// The HUD names this connection separately and lists the other players (no self row).
const gmRoster = await canvasAndRoster(gmView.page, ['Alice'])
assert.equal(await gmView.page.textContent('#role'), 'GM')
// Alice has a key but no live connection yet: the other-player row says offline.
assert.match(gmRoster, /offline/)
const playerView = await newPage(browser)
await playerView.page.goto(`${origin}/`)
await waitForVisible(playerView.page, '#signin')
await signIn(playerView.page, player.key)
const playerRoster = await canvasAndRoster(playerView.page, ['GM'])
assert.equal(await playerView.page.textContent('#role'), 'Player')
assert.equal(await playerView.page.textContent('#me'), 'Alice')
assert.match(playerRoster, /connected/)
// Story 10: the GM replaces the key, the server revokes the session, and the browser stops
// at the sign-in door instead of hammering a dead socket.
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const ack = await gm.ws.request({ t: 'key.replace', id: player.id })
assert.equal(ack.ok, true)
gm.ws.close()
await waitForVisible(playerView.page, '#signin')
await waitForText(playerView.page, '#signin-notice', /session has ended/i)
assert.equal(await playerView.page.locator('#stage canvas').count(), 0)
assert.equal(await playerView.page.locator('#roster li').count(), 0)
// No automatic reconnection: still on the sign-in page a moment later.
await sleep(300)
assert.equal(await playerView.page.locator('#signin').isVisible(), true)
} finally {
await browser.close()
}
})
})
+97
View File
@@ -0,0 +1,97 @@
// Shared stack for the client e2e (TESTING 10.3): the real client build served by the TLS/HTTP2
// test nginx in front of the real server binary. Never a fixture, never a mocked protocol.
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright-core'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot, sleep } from '../../tools/lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import { startTestNginx, stopTestNginx } from '../../tools/nginx.mjs'
export const CHROMIUM = process.env.CHROMIUM ?? 'chromium'
export const LAUNCH_ARGS = [
'--no-sandbox',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'--ignore-gpu-blocklist',
]
export const CLIENT_DIST = path.join(projectRoot, 'client', 'dist')
export function assertClientBuild() {
assert.ok(
fs.existsSync(path.join(CLIENT_DIST, 'index.html')),
`client build missing at ${CLIENT_DIST}: run \`npm run build\` in client/ (client/e2e/run.sh does)`,
)
}
export async function withStack(fn, opts = {}) {
assertClientBuild()
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
if (opts.prepare) await opts.prepare(stateDir, gmKey)
const nginxPort = await freePort()
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort), ...(opts.server ?? {}) })
let nginx
try {
nginx = await startTestNginx({
backendPort: server.port,
stateDir,
port: nginxPort,
distDir: CLIENT_DIST,
})
return await fn({ stateDir, server, nginx, origin: nginx.origin, gmKey })
} finally {
if (nginx) await stopTestNginx(nginx)
await stopServer(server)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
export async function launchBrowser() {
return chromium.launch({ executablePath: CHROMIUM, args: LAUNCH_ARGS })
}
export async function newPage(browser) {
// The certificate is generated per run by tools/tlsdev.mjs; trusting it in the browser is the
// one concession, the rest of the page is the real https/h2 path.
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
return { context, page: await context.newPage() }
}
/** A named player created the way the product creates one: a GM key.create, then player.setname. */
export async function makePlayer(origin, gmKey, name) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const created = await createPlayer(gm.ws)
await namePlayer(origin, created.key, name)
gm.ws.close()
await gm.ws.closed
return { id: created.id, key: created.key, name }
}
export async function signIn(page, key) {
await page.fill('#key', key)
await page.click('#signin-submit')
}
export async function waitForVisible(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'visible', timeout })
}
export async function waitForHidden(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'hidden', timeout })
}
export async function waitForText(page, selector, pattern, timeout = 20000) {
const deadline = Date.now() + timeout
let last = ''
while (Date.now() < deadline) {
last = (await page.locator(selector).textContent()) ?? ''
if (pattern.test(last)) return last
await sleep(50)
}
throw new Error(`${selector} never matched ${pattern}: last was ${JSON.stringify(last)}`)
}
export { sleep }
+202
View File
@@ -0,0 +1,202 @@
// T8 (#71, TESTING 10.3): tokens, BitmapText labels, statuses and the two lists, against the real
// server through the TLS/HTTP2 nginx. The browser's own WebSocket is only *recorded* (as in
// session.test.mjs), so the assertions read the real per-recipient frames; the canvas dataset is
// the token renderer's own instrumentation (published by render/modules/tokens.ts).
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
async function recordSockets(page) {
await page.addInitScript(() => {
window.__wsLog = { frames: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
this.addEventListener('message', event => {
try {
window.__wsLog.frames.push(JSON.parse(event.data))
} catch {
// not a frame; the app ignores it too
}
})
}
}
window.WebSocket = RecordingSocket
})
}
const frames = page => page.evaluate(() => window.__wsLog.frames)
async function waitForBadge(page, state, timeout = 30000) {
await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout })
}
/** The token renderer's instrumentation, read from the canvas it draws on. */
async function tokenRender(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) return null
const data = canvas.dataset
return {
count: Number(data.tokens ?? '0'),
entered: Number(data.tokenEntered ?? '0'),
updated: Number(data.tokenUpdated ?? '0'),
left: Number(data.tokenLeft ?? '0'),
labels: Number(data.tokenLabels ?? '0'),
ids: (data.tokenIds ?? '').split(' ').filter(Boolean),
statuses: (data.tokenStatuses ?? '').split(' ').filter(Boolean),
}
})
}
async function waitForRender(page, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await tokenRender(page)
if (last !== null && predicate(last)) return last
await sleep(50)
}
throw new Error(`token renderer never reached the expected state: ${JSON.stringify(last)}`)
}
test('tokens: enter/leave/update, labels once, statuses, lists, GM sees gm_only', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const scene = (await gm.ws.waitText('walls')).scene
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
// Story 31: a character owned by the player, with a value only the owner's side carries.
const character = await gm.ws.request({
t: 'character.create',
descriptive_name: 'Ann',
actual_name: 'Ann of the Vale',
owner: player.id,
props: { public: { kind: 'pc' }, owner: { hp: 12 } },
})
assert.equal(character.ok, true)
// Story 28: the player's own token (linked to the character) and another figure in sight.
const own = await gm.ws.request({
t: 'token.create', scene, kind: 'pc', character_id: character.id, controller: player.id,
pos: [400, 400], flags: { vision: true },
})
assert.equal(own.ok, true)
const rat = await gm.ws.request({
t: 'token.create', scene, kind: 'npc', pos: [460, 400],
descriptive_name: 'Rat', actual_name: 'Giant Rat',
})
assert.equal(rat.ok, true)
// Story 34: a gm_only token next to the others; if the player ever received it, it would show.
const ghost = await gm.ws.request({
t: 'token.create', scene, kind: 'npc', pos: [520, 400],
descriptive_name: 'Ghost', actual_name: 'Ghost', gm_only: true,
})
assert.equal(ghost.ok, true)
// Story 30: a status the server records and every viewer sees (cause GM-only).
const stuck = await gm.ws.request({ t: 'status.set', id: own.id, status: 'stuck' })
assert.equal(stuck.ok, true)
const browser = await launchBrowser()
try {
const gmView = await newPage(browser)
const playerView = await newPage(browser)
await recordSockets(gmView.page)
await recordSockets(playerView.page)
for (const view of [gmView, playerView]) {
await view.page.goto(`${origin}/`)
await waitForVisible(view.page, '#signin')
}
await signIn(gmView.page, gmKey)
await waitForBadge(gmView.page, 'connected')
await signIn(playerView.page, player.key)
await waitForBadge(playerView.page, 'connected')
// Story 34: the GM renders every token, the gm_only one included.
await waitForRender(gmView.page, view => view.ids.includes(ghost.id))
const gmTokens = await tokenRender(gmView.page)
assert.deepEqual(gmTokens.ids.slice().sort(), [own.id, rat.id, ghost.id].sort())
assert.equal(gmTokens.count, 3)
// Story 28: the player renders their own token and the one in sight, labelled with the name
// the server gave them, and never the gm_only one.
await waitForRender(playerView.page, view => view.ids.includes(own.id) && view.ids.includes(rat.id))
const playerTokens = await tokenRender(playerView.page)
assert.deepEqual(playerTokens.ids.slice().sort(), [own.id, rat.id].sort())
assert.equal(playerTokens.ids.includes(ghost.id), false, 'a gm_only token never reaches a player')
// Story 30: the stuck badge is on the player's own token.
assert.ok(playerTokens.statuses.includes(`${own.id}:stuck`), playerTokens.statuses.join(' '))
// Q17/DESIGN 7.2: one label per name, built once (two names, two builds).
assert.equal(playerTokens.labels, 2)
// The player's own frames: the status carries no `source`, and the gm_only id never appears.
const playerFrames = await frames(playerView.page)
const ownFrame = playerFrames.filter(frame => frame.t === 'token' && frame.id === own.id).at(-1)
assert.ok(ownFrame, 'the player received their own token')
assert.deepEqual(ownFrame.statuses, [{ status: 'stuck' }])
assert.equal(playerFrames.some(frame => frame.t === 'token' && frame.id === ghost.id), false)
// Story 31: the owner's list, with the owner's own value.
await waitForVisible(playerView.page, '#lists')
const characterRow = playerView.page.locator(`#characters li[data-character="${character.id}"]`)
await characterRow.waitFor({ state: 'visible' })
assert.match(await characterRow.textContent(), /Ann/)
assert.match(await characterRow.textContent(), /hp 12/)
// Story 32: met figures, in sight first.
const ratRow = playerView.page.locator(`#encountered li[data-token="${rat.id}"]`)
await ratRow.waitFor({ state: 'visible' })
assert.equal(await ratRow.getAttribute('data-grey'), 'false')
// Story 29: the figure leaves sight -> token_gone, and the encountered entry greys out.
const movedRat = await gm.ws.request({ t: 'token.move', id: rat.id, pos: [2000, 2000] })
assert.equal(movedRat.ok, true)
await waitForRender(playerView.page, view => !view.ids.includes(rat.id))
const afterLeave = await tokenRender(playerView.page)
assert.deepEqual(afterLeave.ids, [own.id], 'the token that left sight is gone from the renderer')
assert.equal(afterLeave.left, 1, 'exactly one entity left')
assert.equal(afterLeave.updated, 0)
assert.equal(afterLeave.entered, 0)
await playerView.page.locator(`#encountered li[data-token="${rat.id}"][data-grey="true"]`).waitFor({
state: 'visible',
timeout: 20000,
})
assert.match(await playerView.page.textContent(`#encountered li[data-token="${rat.id}"]`), /Rat/)
// DESIGN 7.2 / the instrumented count: moving one token updates one entity, nothing else.
const movedOwn = await gm.ws.request({ t: 'token.move', id: own.id, pos: [400, 430] })
assert.equal(movedOwn.ok, true)
await waitForRender(playerView.page, view => view.updated === 1)
const afterMove = await tokenRender(playerView.page)
assert.equal(afterMove.updated, 1, 'one changed token, one updated entity')
assert.equal(afterMove.entered, 0)
assert.equal(afterMove.left, 0)
assert.equal(afterMove.count, 1)
// The label was built once per name: a move does not rebuild it.
assert.equal(afterMove.labels, 2)
// The GM saw the same move (one entity updated) and still holds all three tokens.
await waitForRender(gmView.page, view => view.updated === 1)
const gmAfter = await tokenRender(gmView.page)
assert.equal(gmAfter.updated, 1)
assert.equal(gmAfter.count, 3)
assert.ok(await waitForText(gmView.page, '#lists', /No characters yet/))
} finally {
gm.ws.close()
await browser.close()
}
})
})
+180
View File
@@ -0,0 +1,180 @@
// M4 UX dry-run (issue: GM panel and phone HUD usability). Real stack, real browser:
// - a 390x844 phone viewport keeps the HUD inside the screen (no clipped "…Pl…" row) and folds
// the player lists to two summary rows, with a capped scroll when opened;
// - the GM column puts Walls at the top, selection brings the token editor into view, and every
// long section collapses;
// - the rendered DOM has no duplicate ids (the old per-row `#gm-token-name` etc.).
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
test('M4 UX: phone HUD, collapsible GM column, unique ids', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const browser = await launchBrowser()
const raw = await openAs(origin, gmKey)
const hello = await raw.ws.waitText('hello')
const scene = hello.scene?.id ?? (await raw.ws.waitText('walls')).scene
try {
// One named player with a sighted token (so the phone's encountered list has 20+ rows) and
// 49 NPCs, the playtest shape that made the column 8k px tall.
const alice = await createPlayer(raw.ws)
await namePlayer(origin, alice.key, 'Alice')
const own = await raw.ws.request({
t: 'token.create',
scene,
kind: 'pc',
pos: [960, 540],
descriptive_name: 'Alice',
actual_name: 'Alice',
controller: alice.id,
flags: { vision: true },
vision_radius: 5000,
radius: 20,
})
assert.equal(own.ok, true, JSON.stringify(own))
for (let i = 0; i < 49; i += 1) {
const ack = await raw.ws.request({
t: 'token.create',
scene,
kind: 'npc',
pos: [120 + (i % 7) * 240, 120 + Math.floor(i / 7) * 120],
descriptive_name: `T${i}`,
actual_name: `T${i}`,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
// ---- phone -----------------------------------------------------------------------------
const phoneContext = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 390, height: 844 },
})
const phone = await phoneContext.newPage()
await phone.goto(`${origin}/`)
await waitForVisible(phone, '#signin')
await signIn(phone, alice.key)
await waitForVisible(phone, '#hud')
await waitForText(phone, '#me', /^Alice$/)
await phone.waitForFunction(() => document.querySelectorAll('#encountered li').length > 20, null, {
timeout: 20000,
})
const hud = await phone.evaluate(() => {
const node = document.querySelector('#hud')
const rect = node.getBoundingClientRect()
return {
left: rect.left,
right: rect.right,
width: rect.width,
scrollWidth: node.scrollWidth,
clientWidth: node.clientWidth,
innerWidth: window.innerWidth,
children: [...node.children].map(child => {
const r = child.getBoundingClientRect()
return { id: child.id, left: r.left, right: r.right, height: r.height }
}),
}
})
assert.equal(hud.left, 0, 'the HUD starts at the left edge')
assert.ok(hud.right <= hud.innerWidth + 0.5, `the HUD ends inside the screen: ${JSON.stringify(hud)}`)
assert.ok(
hud.scrollWidth <= hud.clientWidth + 1,
`the HUD scrolls horizontally (clipped text): ${JSON.stringify(hud)}`,
)
for (const child of hud.children) {
if (child.height === 0) continue // a hidden span (e.g. #me when the name equals the role)
assert.ok(child.left >= 0, `${child.id} starts inside the screen`)
assert.ok(child.right <= hud.innerWidth + 0.5, `${child.id} ends inside the screen: ${JSON.stringify(child)}`)
}
const folded = await phone.evaluate(() => ({
characters: document.querySelector('#characters-panel')?.open,
encountered: document.querySelector('#encountered-panel')?.open,
}))
assert.equal(folded.characters, false, 'My characters starts folded on a phone')
assert.equal(folded.encountered, false, 'Encountered starts folded on a phone')
await phone.click('#encountered-panel > summary')
const cap = await phone.evaluate(() => {
const list = document.querySelector('#encountered')
const style = getComputedStyle(list)
return {
maxHeight: style.maxHeight,
overflowY: style.overflowY,
height: list.getBoundingClientRect().height,
}
})
assert.equal(cap.overflowY, 'auto', 'an opened list scrolls on its own')
assert.ok(parseFloat(cap.maxHeight) > 0 && parseFloat(cap.maxHeight) <= 300, `capped: ${cap.maxHeight}`)
assert.ok(cap.height <= parseFloat(cap.maxHeight) + 1, `the list is capped: ${JSON.stringify(cap)}`)
// ---- GM --------------------------------------------------------------------------------
const gmView = await newPage(browser)
const gm = gmView.page
await gm.goto(`${origin}/`)
await waitForVisible(gm, '#signin')
await signIn(gm, gmKey)
await waitForVisible(gm, '#gm-panels')
await waitForVisible(gm, '#gm-walls')
await waitForText(gm, '#gm-token-list-section > summary', /Tokens/)
// Walls are the first block in the column (reachable without scrolling past the lists).
const wallsTop = await gm.evaluate(() => {
const wall = document.querySelector('#gm-walls').getBoundingClientRect()
const panel = document.querySelector('#panels').getBoundingClientRect()
return { wall: wall.top, panel: panel.top, viewport: window.innerHeight }
})
assert.ok(wallsTop.wall < wallsTop.panel + 40, `Walls is at the top: ${JSON.stringify(wallsTop)}`)
assert.ok(wallsTop.wall < wallsTop.viewport / 2, `Walls is on the first screen: ${JSON.stringify(wallsTop)}`)
// Selecting a token (from the folded list) brings its editor into view.
await gm.click('#gm-token-list-section > summary')
const first = gm.locator('#gm-token-list li[data-token]').first()
const tokenId = await first.getAttribute('data-token')
await gm.click(`#gm-token-select-${tokenId}`)
await waitForVisible(gm, '#gm-token-editor')
const editor = await gm.evaluate(() => {
const node = document.querySelector('#gm-token-editor')
const rect = node.getBoundingClientRect()
return { top: rect.top, bottom: rect.bottom, viewport: window.innerHeight }
})
assert.ok(editor.top >= 0, `the selected token editor starts on screen: ${JSON.stringify(editor)}`)
assert.ok(
editor.bottom <= editor.viewport + 0.5,
`the selected token editor fits on one screen: ${JSON.stringify(editor)}`,
)
// Sections collapse: closing the token list hides its rows.
await gm.click('#gm-token-list-section > summary')
assert.equal(await gm.locator('#gm-token-list').isVisible(), false, 'the token list collapsed')
// ---- ids -------------------------------------------------------------------------------
const duplicates = await gm.evaluate(() => {
const seen = new Set()
const repeated = new Set()
for (const node of document.querySelectorAll('[id]')) {
if (seen.has(node.id)) repeated.add(node.id)
seen.add(node.id)
}
return [...repeated]
})
assert.deepEqual(duplicates, [], `duplicate DOM ids: ${duplicates.join(', ')}`)
await sleep(50)
await phoneContext.close()
await gmView.context.close()
} finally {
raw.ws.close()
await browser.close()
}
})
})
+480
View File
@@ -0,0 +1,480 @@
// T10 (#73, TESTING 10.3): the GM wall editor against the real server through the TLS/HTTP2 nginx.
// The browser's real mouse draws walls; the assertions read the real GM `wall`/`wall_gone` frames,
// the player's real fog pixels and a second real player WebSocket for the leak scan. No fixture, no
// mocked protocol.
//
// Two tests:
// 1. every round-1 field round-trips (four presets, label, marker switch, open/close, secret,
// locked hint + one click, advanced raw switches with the invalid combination shown, delete +
// undo, and token drag still beats draw mode);
// 2. the player's fog changes: a drawn wall blocks, the one-way flip re-blocks the floor, opening
// a door reveals it again, and a marked window sends its marker pixel.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
import { luminance, probe } from './pixels.mjs'
const CENTRE = [2048, 2048]
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
function tileColour(worldX, worldY) {
const x = Math.floor(worldX / SCENE.tile)
const y = Math.floor(worldY / SCENE.tile)
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
}
const cellCentre = (cx, cy) => [cx * SCENE.cell + 16, cy * SCENE.cell + 16]
// Cell centres chosen off the drawn wall lines (DESIGN 5.8: a wall blocks the ray crossing it).
const PROBES = {
right: cellCentre(67, 64), // [2160,2064]: blocked by the vertical wall at x=2112
left: cellCentre(58, 64), // [1872,2064]: blocked by the closed door at x=1920
below: cellCentre(64, 71), // [2064,2288]: blocked by the one-way wall once its blind side is above
window: [2032, 1920], // the marked window's drawn midpoint
}
function near(actual, expected, tolerance = 12) {
return (
Math.abs(actual.r - expected.r) <= tolerance &&
Math.abs(actual.g - expected.g) <= tolerance &&
Math.abs(actual.b - expected.b) <= tolerance
)
}
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: hello.scene ?? walls.scene }
}
/** A named player with one sighted token: the wall editor's effects have something to change. */
async function worldWithPlayer(origin, gmKey, { tiles = false, stateDir } = {}) {
const gm = await gmWorld(origin, gmKey)
const scene = gm.scene
if (tiles) {
writeTileGrid(stateDir, {
scene: scene.id,
artVersion: scene.art_version,
size: scene.tile_size,
x0: 40,
x1: 87,
y0: 40,
y1: 87,
})
}
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
const token = await gm.ws.request({
t: 'token.create',
scene: scene.id,
kind: 'pc',
pos: CENTRE,
descriptive_name: 'Ann',
actual_name: 'Ann',
controller: player.id,
flags: { vision: true },
vision_radius: 300,
radius: 20,
})
assert.equal(token.ok, true, JSON.stringify(token))
return { gm, player, scene, token: token.id }
}
async function viewOf(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) throw new Error('no canvas')
const rect = canvas.getBoundingClientRect()
const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number)
return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') }
})
}
async function screenOf(page, world) {
const view = await viewOf(page)
return {
x: view.left + world[0] * view.zoom + view.x,
y: view.top + world[1] * view.zoom + view.y,
}
}
async function clickWorld(page, world) {
const point = await screenOf(page, world)
await page.mouse.click(point.x, point.y)
}
async function drawPreset(page, preset, a, b) {
await page.click(`#wall-preset-${preset}`)
await clickWorld(page, a)
await clickWorld(page, b)
}
async function waitWalls(page, count, timeout = 20000) {
await page.waitForFunction(
expected => {
const canvas = document.querySelector('#stage canvas')
return canvas !== null && Number(canvas.dataset.walls ?? '-1') === expected
},
count,
{ timeout },
)
}
async function gmPage(browser, origin, gmKey) {
const { page } = await newPage(browser)
const errors = []
page.on('pageerror', error => errors.push(error.message))
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, gmKey)
await waitForVisible(page, '#stage canvas')
await waitForVisible(page, '#gm-walls')
await waitWalls(page, 0)
return { page, errors }
}
/** A GM-frame wait that returns the wall message, so a test can read the server's record. */
function nextWall(gm, predicate, timeout = 10000) {
return gm.ws.waitFor(message => message.t === 'wall' && predicate(message), timeout)
}
test('GM wall editor: presets, label, door, secret/locked, advanced, undo, drag precedence', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player } = await worldWithPlayer(origin, gmKey)
// A second real player connection: the leak scan's independent witness.
const witness = await openAs(origin, player.key)
await witness.ws.waitText('hello')
const browser = await launchBrowser()
try {
const { page, errors } = await gmPage(browser, origin, gmKey)
// --- wall preset + label -------------------------------------------------------------
await drawPreset(page, 'wall', [2112, 1920], [2112, 2144])
const wall = await nextWall(gm, message => message.a[0] === 2112 && message.b[1] === 2144)
assert.equal(wall.kind, 'wall')
await waitWalls(page, 1)
await waitForVisible(page, '#wall-selected')
await page.fill('#wall-label', 'railing')
await page.click('#wall-label-apply')
await nextWall(gm, message => message.id === wall.id && message.label === 'railing')
assert.equal((await page.textContent('#wall-kind'))?.trim(), 'wall')
// --- door: open/close, locked hint and one-click unlock ------------------------------
await drawPreset(page, 'door', [1920, 1920], [1920, 2144])
const door = await nextWall(gm, message => message.a[0] === 1920 && message.door === true)
assert.equal(door.kind, 'door')
await waitWalls(page, 2)
await page.check('#wall-locked')
await nextWall(gm, message => message.id === door.id && message.locked === true)
await page.click('#wall-open')
await waitForVisible(page, '#wall-hint-locked')
assert.match((await page.textContent('#wall-hint-locked')) ?? '', /locked: unlock first/)
assert.equal(door.open, false)
await page.click('#wall-unlock')
await nextWall(gm, message => message.id === door.id && message.locked === false)
await page.click('#wall-open')
await nextWall(gm, message => message.id === door.id && message.open === true)
await page.click('#wall-open')
await nextWall(gm, message => message.id === door.id && message.open === false)
// Secret is a door checkbox that round-trips; it never reaches the player (leak scan below).
await page.check('#wall-secret')
await nextWall(gm, message => message.id === door.id && message.secret === true)
await page.uncheck('#wall-secret')
await nextWall(gm, message => message.id === door.id && message.secret === false)
// --- window and one-way presets ------------------------------------------------------
await drawPreset(page, 'window', [1984, 1920], [2080, 1920])
const win = await nextWall(gm, message => message.a[1] === 1920 && message.a[0] === 1984)
assert.equal(win.kind, 'window')
assert.equal(win.player_marker, true)
await waitWalls(page, 3)
// The marker switch is authorable on any wall; the window preset turns it on.
assert.equal(await page.isChecked('#wall-player-marker'), true)
await page.uncheck('#wall-player-marker')
await nextWall(gm, message => message.id === win.id && message.player_marker === false)
await page.check('#wall-player-marker')
await nextWall(gm, message => message.id === win.id && message.player_marker === true)
// Round 1 has no thickness, height or position-flip control (ADR-0012).
assert.equal(await page.locator('#wall-thickness').count(), 0)
assert.equal(await page.locator('#wall-height').count(), 0)
await drawPreset(page, 'one_way', [1792, 2208], [2176, 2208])
const oneWay = await nextWall(gm, message => message.a[1] === 2208)
assert.equal(oneWay.kind, 'one_way')
assert.equal(oneWay.sight_dir, 'left')
await waitWalls(page, 4)
// --- advanced switches: an impossible raw combination shows the reason --------------
await page.click('#wall-advanced-toggle')
await page.uncheck('#wall-blocks-sight')
await page.selectOption('#wall-sight-dir', 'left')
await page.click('#wall-adv-apply')
await waitForVisible(page, '#wall-error')
assert.match((await page.textContent('#wall-error')) ?? '', /sight direction/)
// The server still holds the valid one-way wall; the client did not send an invalid patch.
assert.equal(oneWay.blocks_sight, true)
// --- delete then single-step undo ----------------------------------------------------
await page.click('#wall-delete')
await gm.ws.waitFor(message => message.t === 'wall_gone' && message.id === oneWay.id)
await waitWalls(page, 3)
await page.click('#wall-undo')
const restored = await nextWall(gm, message => message.a[1] === 2208 && message.id !== oneWay.id)
assert.equal(restored.kind, 'one_way')
assert.deepEqual([restored.a, restored.b], [oneWay.a, oneWay.b])
await waitWalls(page, 4)
// --- input precedence: a token drag wins over an armed draw --------------------------
await page.click('#wall-preset-wall')
const start = await screenOf(page, CENTRE)
const end = await screenOf(page, [2000, 2112])
await page.mouse.move(start.x, start.y)
await page.mouse.down()
for (let step = 1; step <= 6; step += 1) {
await page.mouse.move(
start.x + ((end.x - start.x) * step) / 6,
start.y + ((end.y - start.y) * step) / 6,
)
await sleep(60)
}
await page.mouse.up()
const moved = await gm.ws.waitFor(
message =>
message.t === 'token' &&
Math.abs(message.pos[0] - 2000) <= 3 &&
Math.abs(message.pos[1] - 2112) <= 3,
10000,
)
assert.deepEqual(moved.pos, [2000, 2112])
// Drawing mode never saw the gesture: no fifth wall and the draw is still armed.
await sleep(300)
assert.equal(await page.getAttribute('#stage canvas', 'data-walls'), '4')
assert.equal(await page.getAttribute('#stage canvas', 'data-wall-draw'), 'first')
await page.keyboard.press('Escape')
// --- player traffic: no wall data beyond the marker (3.1) ---------------------------
const bad = witness.ws.messages.filter(message => {
if (['wall', 'walls', 'wall_gone'].includes(message.t)) return true
if (message.t === 'marker') return false
const banned = [
'blocks_sight',
'blocks_movement',
'sight_dir',
'player_marker',
'thickness',
'position',
'secret',
'locked',
'label',
]
return banned.some(key => Object.prototype.hasOwnProperty.call(message, key))
})
assert.deepEqual(bad, [], `player frames carried wall data: ${JSON.stringify(bad.slice(0, 2))}`)
assert.deepEqual(errors, [])
await page.context().close()
} finally {
await browser.close()
witness.ws.close()
gm.ws.close()
}
})
})
test('GM walls survive a reload and a server restart: drawn, selectable, door toggles',
{ timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir, server }) => {
const { gm } = await worldWithPlayer(origin, gmKey)
const browser = await launchBrowser()
let restarted = null
try {
const { page, errors } = await gmPage(browser, origin, gmKey)
await drawPreset(page, 'wall', [2112, 1920], [2112, 2144])
await nextWall(gm, message => message.a[0] === 2112 && message.b[1] === 2144)
await drawPreset(page, 'door', [1920, 1920], [1920, 2144])
const door = await nextWall(gm, message => message.a[0] === 1920 && message.door === true)
await waitWalls(page, 2)
async function doorStillWorks(client) {
await waitWalls(page, 2)
await clickWorld(page, [1920, 2025])
await waitForText(page, '#wall-kind', /^door$/)
await page.click('#wall-open')
await nextWall(client, message => message.id === door.id && message.open === true)
await page.click('#wall-open')
await nextWall(client, message => message.id === door.id && message.open === false)
}
// Reload is the regression: the GM reconnects and must get the `walls` snapshot back in a
// shape the client accepts (DESIGN 6.1: scene on the frame, entries without it).
await page.reload()
await waitForVisible(page, '#stage canvas')
await waitForVisible(page, '#gm-walls')
await doorStillWorks(gm)
// Restart variant: same state dir, same port, nginx untouched. The client reconnects by
// itself and the same two walls must come back and stay editable.
restarted = await startServer({
stateDir,
port: server.port,
publicOrigin: server.publicOrigin ?? origin,
})
const gmAfter = await openAs(origin, gmKey)
await gmAfter.ws.waitText('hello')
await gmAfter.ws.waitText('walls')
try {
await waitWalls(page, 2, 60000)
await doorStillWorks(gmAfter)
} finally {
gmAfter.ws.close()
}
assert.deepEqual(errors, [])
await page.context().close()
} finally {
if (restarted) await stopServer(restarted)
await browser.close()
gm.ws.close()
}
})
})
async function fogState(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) return null
const data = canvas.dataset
return {
tiles: data.tiles ?? '',
markers: (data.fogMarkers ?? '').split(' ').filter(Boolean),
cells: Number(data.fogCells ?? '-1'),
visionBuilds: Number(data.fogVisionBuilds ?? '-1'),
}
})
}
async function waitFog(page, predicate, timeout = 30000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await fogState(page)
if (last !== null && predicate(last)) return last
await sleep(50)
}
throw new Error(`fog never reached the expected state: ${JSON.stringify(last)}`)
}
async function probeWorld(page, world) {
const point = await screenOf(page, world)
return probe(page, point.x, point.y)
}
async function waitProbe(page, world, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await probeWorld(page, world)
if (predicate(last)) return last
await sleep(100)
}
throw new Error(`pixel at ${world.join(',')} never matched: ${JSON.stringify(last)}`)
}
test('GM walls change the player fog: block, one-way flip, door open/close, marker pixel', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const { gm, player } = await worldWithPlayer(origin, gmKey, { tiles: true, stateDir })
const witness = await openAs(origin, player.key)
await witness.ws.waitText('hello')
const browser = await launchBrowser()
try {
const playerView = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 900, height: 900 },
})
const page = await playerView.newPage()
const errors = []
page.on('pageerror', error => errors.push(error.message))
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#stage canvas')
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout: 30000 },
)
await waitFog(page, state => state.cells > 100)
const rightMap = tileColour(...PROBES.right)
const leftMap = tileColour(...PROBES.left)
const belowMap = tileColour(...PROBES.below)
assert.ok(near(await probeWorld(page, PROBES.right), rightMap), 'right floor starts visible')
assert.ok(near(await probeWorld(page, PROBES.left), leftMap), 'left floor starts visible')
assert.ok(near(await probeWorld(page, PROBES.below), belowMap), 'below floor starts visible')
const gmView = await gmPage(browser, origin, gmKey)
// A drawn solid wall blocks the right floor: visible -> explored-dim without a reload.
await drawPreset(gmView.page, 'wall', [2112, 1920], [2112, 2144])
await nextWall(gm, message => message.a[0] === 2112)
const dimRight = await waitProbe(page, PROBES.right, colour => luminance(colour) < luminance(rightMap) * 0.6)
assert.ok(luminance(dimRight) < luminance(rightMap) * 0.6, 'the wall dimmed the right floor')
// A closed door blocks the left floor.
await drawPreset(gmView.page, 'door', [1920, 1920], [1920, 2144])
const door = await nextWall(gm, message => message.a[0] === 1920 && message.door === true)
const dimLeft = await waitProbe(page, PROBES.left, colour => luminance(colour) < luminance(leftMap) * 0.6)
assert.ok(luminance(dimLeft) < luminance(leftMap) * 0.6, 'the door dimmed the left floor')
// One-way preset: sight_dir "left" names the blind side (below). The player is above, so the
// wall is initially transparent to sight; flipping it to "right" makes the player's side
// blind and dims the floor below.
await drawPreset(gmView.page, 'one_way', [1792, 2208], [2176, 2208])
const oneWay = await nextWall(gm, message => message.a[1] === 2208)
assert.equal(oneWay.sight_dir, 'left')
assert.ok(near(await probeWorld(page, PROBES.below), belowMap), 'the seeing side sees across')
await waitForVisible(gmView.page, '#wall-selected')
await waitForText(gmView.page, '#wall-kind', /^one_way$/)
await gmView.page.click('#wall-flip')
await nextWall(gm, message => message.id === oneWay.id && message.sight_dir === 'right')
const dimBelow = await waitProbe(page, PROBES.below, colour => luminance(colour) < luminance(belowMap) * 0.6)
assert.ok(luminance(dimBelow) < luminance(belowMap) * 0.6, 'the flip moved the blind side to the player')
// Opening the door reveals the left floor; closing it dims it again.
await clickWorld(gmView.page, [1920, 2025])
await waitForText(gmView.page, '#wall-kind', /^door$/)
await gmView.page.click('#wall-open')
await nextWall(gm, message => message.id === door.id && message.open === true)
await waitProbe(page, PROBES.left, colour => near(colour, leftMap))
await gmView.page.click('#wall-open')
await nextWall(gm, message => message.id === door.id && message.open === false)
await waitProbe(page, PROBES.left, colour => luminance(colour) < luminance(leftMap) * 0.6)
// A marked window sends its marker; the player draws it at the wall's drawn midpoint.
await drawPreset(gmView.page, 'window', [1984, 1920], [2080, 1920])
const win = await nextWall(gm, message => message.a[1] === 1920 && message.a[0] === 1984)
assert.equal(win.player_marker, true)
await waitFog(page, state => state.markers.length === 1)
const marker = await probeWorld(page, PROBES.window)
assert.ok(near(marker, { r: 255, g: 204, b: 51 }, 26), `the window marker pixel: ${JSON.stringify(marker)}`)
// The player never received the editor's wall records, even for the secret/locked states.
assert.equal(witness.ws.messages.some(message => ['wall', 'walls', 'wall_gone'].includes(message.t)), false)
assert.deepEqual(errors, [])
await playerView.close()
await gmView.page.context().close()
} finally {
await browser.close()
witness.ws.close()
gm.ws.close()
}
})
})
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>FFF VTT</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1342
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "fff-vtt-client",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "FFF VTT browser client: Vite + TypeScript + PixiJS v8, plain DOM overlay (DESIGN 7).",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"test": "vitest run --reporter=dot"
},
"dependencies": {
"pixi.js": "8.23.0"
},
"devDependencies": {
"playwright-core": "1.65.1",
"typescript": "5.9.3",
"vite": "8.3.8",
"vitest": "5.1.1"
}
}
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# devbox run client-test: the pure reducer/protocol-client seam (TESTING 10.3 "Client reducer",
# spec #63 decision 13). No server, no browser, no GPU: these run in a second.
set -euo pipefail
cd "$(dirname "$0")/.." || exit 1
mkdir -p results
{ [ -d client/node_modules ] || ( cd client && npm ci --no-audit --no-fund ); }
( cd client && npm test ) > results/client-test.log 2>&1
rc=$?
cat results/client-test.log
exit $rc
+35
View File
@@ -0,0 +1,35 @@
// The one way a render module sends an intent (#72). Render modules are mounted by the stage with
// no socket of their own; this module is the tiny, replaceable bridge to the session's protocol
// client. `main.ts` installs the live client on connect and clears it on teardown.
//
// The callback exists because a `token.move` ack is matched by `reqId`, not by token id (6.1):
// the move slice records the `reqId` the socket assigned, then the ack frame finds it. Keeping the
// callback here means the drag module never knows the counter and the protocol client stays pure.
import type { AckFrame } from './protocol.ts'
export type IntentSender = (
t: string,
fields?: Record<string, unknown>,
onReqId?: (reqId: number) => void,
) => Promise<AckFrame>
let sender: IntentSender | null = null
export function setIntentSender(next: IntentSender | null): void {
sender = next
}
/**
* Send one intent, or reject when there is no live session (a drag that raced a disconnect). The
* optional `onReqId` runs only after the frame actually left the socket, so a failed send never
* leaves a pending entry that no ack can settle.
*/
export function sendIntent(
t: string,
fields: Record<string, unknown> = {},
onReqId?: (reqId: number) => void,
): Promise<AckFrame> {
if (!sender) return Promise.reject(new Error('not connected'))
return sender(t, fields, onReqId)
}
+214
View File
@@ -0,0 +1,214 @@
// Client bootstrap: one store, one WS client, one DOM shell, one Pixi stage created only once the
// session is live. Every network/UI decision goes through the pure reducer; this file is wiring.
import './style.css'
import { ProtocolClient } from './ws.ts'
import { Store } from './store.ts'
import { mountShell } from './shell.ts'
import { mountAdminPanel } from './panels/admin.ts'
import { mountCastPanel } from './panels/gmcast.ts'
import type { Stage } from './render/stage.ts'
import { createStage } from './render/stage.ts'
import type { RootState } from './reducer.ts'
import { setIntentSender } from './intents.ts'
import { viewport } from './viewport.ts'
const KEY_REFUSED = 'Key not recognised.'
/**
* A non-secret marker that this browser signed in once. The session cookie is HttpOnly, so the
* client cannot read it; without the marker every cold boot opened `/ws` before a session existed
* and the browser logged the refused upgrade on a perfectly healthy first load (M4 dry-run). The
* marker only decides whether to dial on boot; a stale marker still lands on sign-in as before.
*/
const SESSION_MARKER = 'fff-vtt.session'
function hadSession(): boolean {
try {
return localStorage.getItem(SESSION_MARKER) === '1'
} catch {
return true // storage blocked: keep the old probe rather than break returning sessions
}
}
function markSession(present: boolean): void {
try {
if (present) localStorage.setItem(SESSION_MARKER, '1')
else localStorage.removeItem(SESSION_MARKER)
} catch {
// A blocked localStorage is not worth breaking sign-in over.
}
}
/** Story 6: a refused name is shown with a reason, next to the prompt. */
const NAME_REFUSALS: Record<string, string> = {
'name-taken': 'That name is taken. Choose another.',
invalid: 'Enter a name of 1–32 characters, with no control characters.',
'not-allowed': 'You cannot change your name.',
}
const host = document.querySelector<HTMLElement>('#app')
if (!host) throw new Error('#app is missing')
const store = new Store()
let client: ProtocolClient | null = null
let stage: Stage | null = null
let startingStage: Promise<void> | null = null
const shell = mountShell(host, {
onSubmitKey: key => {
void signIn(key)
},
onSubmitName: name => {
void submitName(name)
},
onReload: () => location.reload(),
})
const stageHost = document.querySelector<HTMLElement>('#stage')
if (!stageHost) throw new Error('#stage is missing')
const stageRoot: HTMLElement = stageHost
// GM panels (T11, #74). A player never sees this section: the panel hides and clears itself unless
// the live session is the GM. Its send callback is the same protocol client as every other intent.
const panelsHost = document.querySelector<HTMLElement>('#panels')
if (!panelsHost) throw new Error('#panels is missing')
const sendIntent = (t: string, fields?: Record<string, unknown>) =>
client ? client.send(t, fields) : Promise.reject(new Error('not connected'))
const adminPanel = mountAdminPanel(panelsHost, {
send: sendIntent,
select: token => store.dispatch({ type: 'admin-select', token }),
})
// T12 (#75): characters, reveals, encountered remove and who-sees-it, beside the #74 panel.
const castPanel = mountCastPanel(panelsHost, { send: sendIntent })
async function signIn(key: string): Promise<void> {
shell.setBusy(true)
let accepted = false
try {
// DESIGN 3.2/6.6: POST /join, key in the body. `redirect: 'manual'` turns the 303 into an
// opaque redirect the client cannot mistake for a body; a 401 (wrong or unknown key alike)
// is a readable same-origin response.
const response = await fetch('/join', {
method: 'POST',
credentials: 'same-origin',
redirect: 'manual',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ key }).toString(),
})
accepted = response.type === 'opaqueredirect' || response.status === 303
} catch {
accepted = false
}
if (!accepted) {
// Story 3: one plain answer, whatever the reason. No key existence oracle.
store.dispatch({ type: 'signin-failed', message: KEY_REFUSED })
return
}
markSession(true)
client?.close()
store.dispatch({ type: 'connecting' })
connect()
}
/**
* Stories 5/6: send `player.setname` once. The server acks before the `hello` + resync (FIXED #33),
* so a refusal is shown on the prompt and an acceptance is followed by the second `hello` the
* reducer already turns into a full reset+resync.
*/
async function submitName(name: string): Promise<void> {
if (!client || store.state.connection.phase !== 'live') return
shell.setNameBusy(true)
let accepted = false
try {
const ack = await client.send('player.setname', { name })
accepted = ack.ok
if (!ack.ok) {
store.dispatch({
type: 'name-failed',
message: NAME_REFUSALS[ack.code ?? ''] ?? 'That name is not available.',
})
}
} catch {
store.dispatch({ type: 'name-failed', message: 'Could not reach the server. Try again.' })
} finally {
if (!accepted) shell.setNameBusy(false)
}
}
function connect(): void {
client = new ProtocolClient({
onEvent: event => {
store.dispatch(event)
},
})
// Render modules (the drag, #72) send through this bridge; it is the same client every other
// intent uses, so `reqId` ordering and the pending map stay in one place.
setIntentSender((t, fields, onReqId) =>
client ? client.send(t, fields, onReqId) : Promise.reject(new Error('not connected')),
)
client.connect()
}
/** A stage exists only for a named live session; a reconnect keeps the last map on screen. */
function syncStage(state: RootState): void {
const named = state.session.me !== null && state.session.me.name !== null
const live = state.connection.phase === 'live' && named
const keep = state.connection.phase === 'reconnecting' && stage !== null
if (!live && !keep) {
stage?.destroy()
stage = null
return
}
if (!live || stage || startingStage) return
startingStage = createStage(stageRoot, store)
.then(created => {
const phase = store.state.connection.phase
if (phase !== 'live' && phase !== 'reconnecting') {
created.destroy()
return
}
stage = created
})
.catch(error => {
console.error('stage init failed', error)
})
.finally(() => {
startingStage = null
})
}
store.subscribe(state => {
// A session the server ended (revoked, evicted) must not make the next cold boot dial `/ws`.
if (state.connection.phase === 'signin') markSession(false)
shell.render(state)
syncStage(state)
adminPanel.render(state)
castPanel.render(state)
})
// The HUD's read-only zoom readout; `viewport` already publishes on every camera change.
shell.setZoom(viewport.state.camera.zoom)
viewport.subscribe(view => shell.setZoom(view.camera.zoom))
// Story 7: the badge distinguishes "no network at all" from "socket is reconnecting". The socket
// retries by itself, but a browser `online` event is the moment to skip the rest of the backoff.
window.addEventListener('offline', () => {
store.dispatch({ type: 'network', online: false })
})
window.addEventListener('online', () => {
store.dispatch({ type: 'network', online: true })
client?.retryNow()
})
// Boot: dial only when this browser may still hold a session; otherwise go straight to the door.
// A visitor without a session is never probed with a WS upgrade, so a healthy fresh load has no
// refused-connection noise in the console. No map data is ever created before a session.
store.dispatch({ type: 'network', online: navigator.onLine })
if (hadSession()) {
store.dispatch({ type: 'connecting' })
shell.render(store.state)
connect()
} else {
store.dispatch({ type: 'signed-out' })
}
+736
View File
@@ -0,0 +1,736 @@
// GM panels (T11, #74): roster + connected state, player keys, and the token panel. Plain DOM and
// `textContent` only (DESIGN 7.1 layer 6, spec #63 decision 15). Mounted under the shell's existing
// `#panels` host; the sign-in flow and HUD are untouched.
//
// SECRETS: a player key lives only in this module's `keys` map and in a `#gm-key-*` <code> element
// inside the GM-only `#gm-panels`. It is never dispatched into the reducer, never sent over the
// socket, never written to the console, and the whole map is dropped the moment the GM session
// leaves the table. This is the "keys exist only in GM DOM" acceptance criterion for #74.
//
// TOKEN SELECTION: this panel dispatches `{type:'admin-select', token}`; the id lives in the
// `admin` slice (`src/slices/admin.ts`), so #71's token renderer and #72's drag module can read the
// same selection later without importing this file.
import type { RootState } from '../reducer.ts'
import type { AckFrame, RosterEntry } from '../protocol.ts'
import { rosterOf } from '../reducer.ts'
import type { AdminToken } from '../slices/admin.ts'
import { adminTokens, selectedTokenId } from '../slices/admin.ts'
import { createVisionFields, updateVisionFields } from '../tokenPanel.ts'
import { viewport, viewportCentre } from '../viewport.ts'
import { panelSection, revealInColumn, setSectionTitle } from './section.ts'
export interface AdminPanelHandlers {
send(t: string, fields?: Record<string, unknown>): Promise<AckFrame>
select(token: string | null): void
}
export interface AdminPanel {
render(state: RootState): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
'cap-reached': 'The table is full (6 players). Remove a player first.',
'not-found': 'That player or token no longer exists.',
'not-allowed': 'The server refused that action.',
invalid: 'That value is not valid.',
'in-use': 'That is still in use.',
}
function describeCode(code: string | undefined): string {
if (code === undefined) return 'The server refused that action.'
return CODE_TEXT[code] ?? `The server refused that action (${code}).`
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function field<K extends keyof HTMLElementTagNameMap>(tag: K, id: string, text?: string) {
const node = element(tag, id, text)
const label = element('label', undefined, text ?? '')
label.htmlFor = id
return { node, label }
}
function playerLabel(entry: RosterEntry): string {
return entry.name ?? `(unnamed ${entry.id})`
}
export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers): AdminPanel {
const root = element('section', 'gm-panels')
root.hidden = true
const heading = element('h2', undefined, 'GM table')
root.append(heading)
// ---- roster and keys -----------------------------------------------------------------------
// Collapsible, open by default: at most six players, so it stays short, but a GM can fold it.
const roster = panelSection('gm-roster', 'Roster', true)
const rosterList = element('ul', 'gm-roster-list')
const keyCreate = element('button', 'gm-key-create', 'Create player key')
keyCreate.type = 'button'
const keyStatus = element('p', 'gm-key-status')
keyStatus.hidden = true
keyStatus.setAttribute('role', 'status')
roster.body.append(rosterList, keyCreate, keyStatus)
// ---- token panel ---------------------------------------------------------------------------
// Layout: the selected token's editor first (selection-driven, see refresh), then the create
// form and the long token list, both collapsed. That keeps the editor near the top of the column
// instead of underneath 50 rows.
const tokenSection = element('section', 'gm-tokens')
const createForm = element('form', 'gm-token-create')
const createSection = panelSection('gm-token-create-section', 'New token')
createSection.body.append(createForm)
const kindInput = field('input', 'token-kind', 'Kind')
kindInput.node.value = 'npc'
kindInput.node.type = 'text'
const nameInput = field('input', 'token-name', 'Descriptive name')
nameInput.node.type = 'text'
const actualInput = field('input', 'token-actual', 'Actual name')
actualInput.node.type = 'text'
const xInput = field('input', 'token-x', 'X')
xInput.node.type = 'number'
xInput.node.value = '400'
const yInput = field('input', 'token-y', 'Y')
yInput.node.type = 'number'
yInput.node.value = '400'
const radiusInput = field('input', 'token-radius', 'Radius (blank = scene default)')
radiusInput.node.type = 'number'
radiusInput.node.min = '0.1'
radiusInput.node.step = 'any'
// DESIGN 8 defaults a new token's `flags` to `{}`: vision is off until the GM turns it on.
const createVision = field('input', 'token-vision', 'Vision')
createVision.node.type = 'checkbox'
const createVisionRadius = field(
'input',
'token-vision-radius',
'Vision radius (blank = scene default)',
)
createVisionRadius.node.type = 'number'
createVisionRadius.node.min = '0.1'
createVisionRadius.node.step = 'any'
const createGmOnly = field('input', 'token-gm-only', 'GM only')
createGmOnly.node.type = 'checkbox'
const createController = field('select', 'token-controller', 'Controller')
const createControllerLabel = createController.label
const createSubmit = element('button', 'token-create-submit', 'Create token')
createSubmit.type = 'submit'
createForm.append(
kindInput.label,
kindInput.node,
nameInput.label,
nameInput.node,
actualInput.label,
actualInput.node,
xInput.label,
xInput.node,
yInput.label,
yInput.node,
radiusInput.label,
radiusInput.node,
createVision.label,
createVision.node,
createVisionRadius.label,
createVisionRadius.node,
createGmOnly.label,
createGmOnly.node,
createControllerLabel,
createController.node,
createSubmit,
)
const tokenList = element('ul', 'gm-token-list')
const listSection = panelSection('gm-token-list-section', 'Tokens')
listSection.body.append(tokenList)
const editor = element('section', 'gm-token-editor')
editor.hidden = true
const editorTitle = element('h4', 'gm-token-editor-title', 'No token selected')
const editName = field('input', 'token-edit-name', 'Descriptive name')
editName.node.type = 'text'
const editActual = field('input', 'token-edit-actual', 'Actual name')
editActual.node.type = 'text'
const editKind = field('input', 'token-edit-kind', 'Kind')
editKind.node.type = 'text'
const editVision = field('input', 'token-edit-vision', 'Vision')
editVision.node.type = 'checkbox'
const editVisionRadius = field(
'input',
'token-edit-vision-radius',
'Vision radius (blank = scene default)',
)
editVisionRadius.node.type = 'number'
editVisionRadius.node.min = '0.1'
editVisionRadius.node.step = 'any'
const editGmOnly = field('input', 'token-edit-gm-only', 'GM only')
editGmOnly.node.type = 'checkbox'
const editController = field('select', 'token-edit-controller', 'Controller')
const save = element('button', 'token-save', 'Save token')
save.type = 'button'
const remove = element('button', 'token-remove', 'Remove token')
remove.type = 'button'
const statusTitle = element('p', 'token-status', 'Statuses: none')
const setStuck = element('button', 'token-status-stuck', 'Add stuck')
setStuck.type = 'button'
const setSqueezed = element('button', 'token-status-squeezed', 'Add squeezed')
setSqueezed.type = 'button'
const clearStuck = element('button', 'token-status-clear-stuck', 'Clear stuck (GM)')
clearStuck.type = 'button'
const clearSqueezed = element('button', 'token-status-clear-squeezed', 'Clear squeezed (GM)')
clearSqueezed.type = 'button'
const clearWalls = element('button', 'token-status-clear-walls', 'Clear stuck (walls)')
clearWalls.type = 'button'
const resizeRadius = field('input', 'token-resize-radius', 'New radius')
resizeRadius.node.type = 'number'
resizeRadius.node.min = '0.1'
resizeRadius.node.step = 'any'
const resize = element('button', 'token-resize', 'Resize')
resize.type = 'button'
const tokenError = element('p', 'gm-token-error')
tokenError.hidden = true
tokenError.setAttribute('role', 'alert')
editor.append(
editorTitle,
editName.label,
editName.node,
editActual.label,
editActual.node,
editKind.label,
editKind.node,
editVision.label,
editVision.node,
editVisionRadius.label,
editVisionRadius.node,
editGmOnly.label,
editGmOnly.node,
editController.label,
editController.node,
save,
remove,
statusTitle,
setStuck,
setSqueezed,
clearStuck,
clearSqueezed,
clearWalls,
resizeRadius.label,
resizeRadius.node,
resize,
)
tokenSection.append(editor, createSection.details, listSection.details, tokenError)
root.append(roster.details, tokenSection)
host.append(root)
// Secrets and local UI state. Never dispatched, never logged.
const keys = new Map<number, string>()
const revealed = new Set<number>()
let keyVersion = 0
let active = false
let rosterSig = ''
let tokenSig = ''
let populatedFor: string | null = null
let lastSelected: string | null = null
let current: RootState | null = null
// The create form follows the viewport centre (#82) until the GM types a position: `autoPos` is
// the pair this module last wrote, so a value the GM edited is never overwritten by a pan.
let autoPos: [number, number] | null = null
function viewportDefaultPosition(): [number, number] | null {
const scene = current?.session.scene
if (!scene) return null
const view = viewport.state
if (view.scene && view.size.width > 1 && view.size.height > 1) {
const [x, y] = viewportCentre(view.camera, view.size)
return [Math.round(x), Math.round(y)]
}
return [Math.round(scene.w / 2), Math.round(scene.h / 2)]
}
function applyPositionDefault(): void {
if (!active) return
const next = viewportDefaultPosition()
if (!next) return
const untouched =
autoPos === null ||
(xInput.node.value === String(autoPos[0]) && yInput.node.value === String(autoPos[1]))
const busy = document.activeElement === xInput.node || document.activeElement === yInput.node
if (untouched && !busy) {
xInput.node.value = String(next[0])
yInput.node.value = String(next[1])
}
autoPos = next
}
const unsubscribeViewport = viewport.subscribe(applyPositionDefault)
function showSecret(entry: RosterEntry): string {
if (!revealed.has(entry.id)) return ''
return keys.get(entry.id) ?? ''
}
function renderControllerOptions(select: HTMLSelectElement, players: RosterEntry[], value: string) {
const signature = players.map(p => `${p.id}:${p.role}`).join(',')
if (select.dataset['options'] === signature) {
select.value = value
return
}
const gm = element('option', undefined, 'GM (no controller)')
gm.value = ''
select.replaceChildren(gm)
for (const entry of players) {
if (entry.role === 'gm') continue
const option = element('option', undefined, playerLabel(entry))
option.value = String(entry.id)
select.append(option)
}
select.dataset['options'] = signature
select.value = value
}
function renderRoster(players: RosterEntry[]): void {
rosterList.replaceChildren(
...players.map(entry => {
const item = element('li')
item.dataset['player'] = String(entry.id)
const name = element('span', undefined, playerLabel(entry))
name.className = 'gm-roster-name'
const state = element('span', undefined, entry.connected ? 'connected' : 'offline')
state.className = 'gm-roster-state'
item.append(name, state)
if (entry.role !== 'gm') {
const keyCode = element('code', `gm-key-${entry.id}`)
keyCode.className = 'gm-key'
keyCode.textContent = showSecret(entry)
keyCode.hidden = keyCode.textContent === ''
const show = element('button', `gm-key-show-${entry.id}`, 'Show')
show.type = 'button'
show.addEventListener('click', () => {
revealed.add(entry.id)
void showKey(entry.id)
})
const hide = element('button', `gm-key-hide-${entry.id}`, 'Hide')
hide.type = 'button'
hide.addEventListener('click', () => {
revealed.delete(entry.id)
refresh()
})
const replace = element('button', `gm-key-replace-${entry.id}`, 'Replace')
replace.type = 'button'
replace.addEventListener('click', () => {
void replaceKey(entry.id)
})
const cut = element('button', `gm-player-remove-${entry.id}`, 'Remove')
cut.type = 'button'
cut.addEventListener('click', () => {
void removePlayer(entry.id)
})
item.append(keyCode, show, hide, replace, cut)
}
return item
}),
)
}
function tokenMeta(token: AdminToken, players: RosterEntry[]): string {
const controller =
token.controller === null
? 'GM'
: (players.find(p => p.id === token.controller)?.name ?? `#${token.controller}`)
const statuses = token.statuses
.map(entry => (entry.source ? `${entry.status}/${entry.source}` : entry.status))
.join(', ')
return [
token.kind ?? '?',
`controller ${controller}`,
token.gmOnly ? 'gm_only' : 'visible',
`r${Math.round(token.radius)}`,
statuses === '' ? 'no status' : statuses,
].join(' · ')
}
function renderTokenList(tokens: AdminToken[], players: RosterEntry[], selected: string | null) {
tokenList.replaceChildren(
...tokens.map(token => {
const item = element('li')
item.dataset['token'] = token.id
if (token.id === selected) item.dataset['selected'] = 'true'
const name = element('span', undefined, token.name)
name.className = 'gm-token-name'
const meta = element('span', undefined, tokenMeta(token, players))
meta.className = 'gm-token-meta'
const pick = element('button', `gm-token-select-${token.id}`, 'Select')
pick.type = 'button'
pick.addEventListener('click', () => handlers.select(token.id))
item.append(name, meta, pick)
return item
}),
)
}
function populateEditor(token: AdminToken | null, players: RosterEntry[]): void {
if (token === null) {
editor.hidden = true
editorTitle.textContent = 'No token selected'
populatedFor = null
return
}
editor.hidden = false
if (populatedFor === token.id) {
renderControllerOptions(
editController.node,
players,
token.controller === null ? '' : String(token.controller),
)
return
}
populatedFor = token.id
editorTitle.textContent = `${token.name} (${token.id})`
editName.node.value = token.descriptiveName ?? token.name
editActual.node.value = token.actualName ?? token.name
editKind.node.value = token.kind ?? ''
editVision.node.checked = token.flags['vision'] === true
editVisionRadius.node.value = token.visionRadius === null ? '' : String(token.visionRadius)
editGmOnly.node.checked = token.gmOnly
renderControllerOptions(
editController.node,
players,
token.controller === null ? '' : String(token.controller),
)
}
function refresh(): void {
const state = current
if (!state || !active) return
const players = rosterOf(state)
const tokens = adminTokens(state)
const selected = selectedTokenId(state)
const nextRosterSig = JSON.stringify(players) + JSON.stringify([...revealed]) + keyVersion
if (nextRosterSig !== rosterSig) {
rosterSig = nextRosterSig
renderRoster(players)
}
const token = tokens.find(entry => entry.id === selected) ?? null
const selectionChanged = selected !== lastSelected
lastSelected = selected
const nextTokenSig = JSON.stringify(tokens) + selected
if (nextTokenSig !== tokenSig) {
tokenSig = nextTokenSig
renderTokenList(tokens, players, selected)
setSectionTitle(listSection, `Tokens (${tokens.length})`)
populateEditor(token, players)
if (token) {
statusTitle.textContent =
token.statuses.length === 0
? 'Statuses: none'
: `Statuses: ${token.statuses
.map(entry => (entry.source ? `${entry.status} (${entry.source})` : entry.status))
.join(', ')}`
resizeRadius.node.placeholder = String(Math.round(token.radius))
}
}
renderControllerOptions(createController.node, players, createController.node.value || '')
applyPositionDefault()
// Selecting a token (in the list or on the board) brings its editor into the column's view;
// the list itself may be collapsed or scrolled far down.
if (token && selectionChanged) revealInColumn(editor)
}
function setError(text: string | null): void {
if (text === null) {
tokenError.textContent = ''
tokenError.hidden = true
} else {
tokenError.textContent = text
tokenError.hidden = false
}
}
function setKeyStatus(text: string): void {
keyStatus.textContent = text
keyStatus.hidden = text === ''
}
function currentSelection(): string | null {
return current ? selectedTokenId(current) : null
}
function currentToken(): AdminToken | null {
const selected = currentSelection()
if (selected === null || !current) return null
return adminTokens(current).find(token => token.id === selected) ?? null
}
async function request(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame | null> {
try {
const ack = await handlers.send(t, fields)
if (!ack.ok) setError(describeCode(ack.code))
return ack
} catch {
setError('Could not reach the server.')
return null
}
}
async function showKey(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.show', { id })
if (ack?.ok && typeof ack.key === 'string') {
keys.set(id, ack.key)
revealed.add(id)
keyVersion += 1
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function replaceKey(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.replace', { id })
if (ack?.ok && typeof ack.key === 'string') {
keys.set(id, ack.key)
revealed.add(id)
keyVersion += 1
setKeyStatus(`New key for player ${id}: ${ack.key}`)
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function removePlayer(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('player.remove', { id })
if (ack?.ok) {
keys.delete(id)
revealed.delete(id)
keyVersion += 1
setKeyStatus(`Player ${id} removed; their key and session are gone.`)
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function createKey(): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.create')
if (ack?.ok) {
const created = ack as { id?: unknown; key?: unknown }
if (typeof created.id === 'number' && typeof created.key === 'string') {
keys.set(created.id, created.key)
revealed.add(created.id)
keyVersion += 1
setKeyStatus(`Key for player ${created.id}: ${created.key}`)
}
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function createToken(): Promise<void> {
setError(null)
const kind = kindInput.node.value.trim()
const name = nameInput.node.value.trim()
const actual = actualInput.node.value.trim()
const fallback = viewportDefaultPosition()
const x = xInput.node.value.trim() === '' && fallback ? fallback[0] : Number(xInput.node.value)
const y = yInput.node.value.trim() === '' && fallback ? fallback[1] : Number(yInput.node.value)
if (kind === '' || name === '' || actual === '' || !Number.isFinite(x) || !Number.isFinite(y)) {
setError('Kind, both names and a numeric position are required.')
return
}
const scene = current?.session.scene?.id
if (scene === undefined) {
setError('No scene yet.')
return
}
const rawRadius = radiusInput.node.value.trim()
const radius = rawRadius === '' ? null : Number(rawRadius)
if (radius !== null && (!Number.isFinite(radius) || radius <= 0)) {
setError('Radius must be a positive number or blank.')
return
}
const vision = createVisionFields(createVision.node.checked, createVisionRadius.node.value)
if (!vision.ok) {
setError(vision.error)
return
}
const controllerValue = createController.node.value
const controller = controllerValue === '' ? null : Number(controllerValue)
const ack = await request('token.create', {
scene,
kind,
pos: [x, y],
descriptive_name: name,
actual_name: actual,
radius,
gm_only: createGmOnly.node.checked,
controller,
...vision.fields,
})
if (ack?.ok) {
const created = ack as { id?: unknown }
if (typeof created.id === 'string') handlers.select(created.id)
}
}
async function saveToken(): Promise<void> {
const token = currentToken()
if (token === null) return
setError(null)
const name = editName.node.value.trim()
const actual = editActual.node.value.trim()
const kind = editKind.node.value.trim()
if (name === '' || actual === '' || kind === '') {
setError('Kind and both names are required.')
return
}
const vision = updateVisionFields(
token.id,
token.flags,
editVision.node.checked,
editVisionRadius.node.value,
)
if (!vision.ok) {
setError(vision.error)
return
}
const controllerValue = editController.node.value
await request('token.update', {
...vision.fields,
kind,
descriptive_name: name,
actual_name: actual,
gm_only: editGmOnly.node.checked,
controller: controllerValue === '' ? null : Number(controllerValue),
})
}
async function removeToken(): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
const ack = await request('token.remove', { id: selected })
if (ack?.ok) handlers.select(null)
}
async function setStatus(status: 'stuck' | 'squeezed'): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
await request('status.set', { id: selected, status })
}
async function clearStatus(status: 'stuck' | 'squeezed', source: 'GM' | 'walls'): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
await request('status.clear', { id: selected, status, source })
}
async function resizeToken(): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
const raw = resizeRadius.node.value.trim()
const radius = raw === '' ? null : Number(raw)
if (radius !== null && (!Number.isFinite(radius) || radius <= 0)) {
setError('Radius must be a positive number or blank for the scene default.')
return
}
await request('token.resize', { id: selected, radius })
}
keyCreate.addEventListener('click', () => {
void createKey()
})
createForm.addEventListener('submit', event => {
event.preventDefault()
void createToken()
})
save.addEventListener('click', () => {
void saveToken()
})
remove.addEventListener('click', () => {
void removeToken()
})
setStuck.addEventListener('click', () => {
void setStatus('stuck')
})
setSqueezed.addEventListener('click', () => {
void setStatus('squeezed')
})
clearStuck.addEventListener('click', () => {
void clearStatus('stuck', 'GM')
})
clearSqueezed.addEventListener('click', () => {
void clearStatus('squeezed', 'GM')
})
clearWalls.addEventListener('click', () => {
void clearStatus('stuck', 'walls')
})
resize.addEventListener('click', () => {
void resizeToken()
})
function render(state: RootState): void {
current = state
const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting'
const gm = state.session.role === 'gm' && state.session.me?.name != null
const nextActive = live && gm
if (!nextActive) {
// Leaving the GM view erases every secret and every server-derived row from the DOM.
active = false
keys.clear()
revealed.clear()
rosterSig = ''
tokenSig = ''
populatedFor = null
lastSelected = null
root.hidden = true
rosterList.replaceChildren()
tokenList.replaceChildren()
editor.hidden = true
setKeyStatus('')
setError(null)
return
}
if (!active) {
active = true
rosterSig = ''
tokenSig = ''
}
root.hidden = false
refresh()
}
return {
render,
destroy() {
unsubscribeViewport()
keys.clear()
revealed.clear()
root.remove()
},
}
}
+489
View File
@@ -0,0 +1,489 @@
// GM cast panels (T12, #75): characters and assignment, name reveals to one player or all, the
// per-player encountered list with its remove action, and the who-sees-it panel. Plain DOM and
// `textContent` only (DESIGN 7.1 layer 6, spec #63 decisions 10/15). Mounted under the shell's
// existing `#panels` host beside the #74 admin panel; the sign-in flow and HUD are untouched.
//
// WHO-SEES-IT: the server computes `seen_by` from each player's existing sight (DESIGN 7.4, #75)
// and sends it on GM `token` frames only. M4 is binary: a token is seen by a player (100 %) or not
// (0 %); the graded fraction waits for wall heights. A player never receives the field.
import type { RootState } from '../reducer.ts'
import type { AckFrame, RosterEntry } from '../protocol.ts'
import { rosterOf } from '../reducer.ts'
import type { AdminToken } from '../slices/admin.ts'
import { adminTokens } from '../slices/admin.ts'
import type { CastCharacter } from '../slices/cast.ts'
import { castCharacters, encounteredOf, seenByOf } from '../slices/cast.ts'
import { panelSection } from './section.ts'
export interface CastPanelHandlers {
send(t: string, fields?: Record<string, unknown>): Promise<AckFrame>
}
export interface CastPanel {
render(state: RootState): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
'cap-reached': 'The table is full (6 players). Remove a player first.',
'not-found': 'That player, character or entry no longer exists.',
'not-allowed': 'The server refused that action.',
invalid: 'That value is not valid.',
'in-use': 'A token still figures that character: unlink or remove the token first.',
}
function describeCode(code: string | undefined): string {
if (code === undefined) return 'The server refused that action.'
return CODE_TEXT[code] ?? `The server refused that action (${code}).`
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function field<K extends keyof HTMLElementTagNameMap>(tag: K, id: string, text?: string) {
const node = element(tag, id, text)
const label = element('label', undefined, text ?? '')
label.htmlFor = id
return { node, label }
}
function playerLabel(entry: RosterEntry): string {
return entry.name ?? `(unnamed ${entry.id})`
}
function nameOf(players: RosterEntry[], id: number): string {
const entry = players.find(player => player.id === id)
return entry ? playerLabel(entry) : `#${id}`
}
export function mountCastPanel(host: HTMLElement, handlers: CastPanelHandlers): CastPanel {
const root = element('section', 'gm-cast')
root.hidden = true
// ---- characters ----------------------------------------------------------------------------
// Long (one editable block per character), so collapsed by default; the list gets its own scroll.
const characters = panelSection('gm-characters', 'Characters')
const createForm = element('form', 'gm-character-create')
const createName = field('input', 'character-name', 'Descriptive name')
createName.node.type = 'text'
const createActual = field('input', 'character-actual', 'Actual name')
createActual.node.type = 'text'
const createOwner = field('select', 'character-owner', 'Owner')
const createSubmit = element('button', 'character-create-submit', 'Create character')
createSubmit.type = 'submit'
createForm.append(
createName.label,
createName.node,
createActual.label,
createActual.node,
createOwner.label,
createOwner.node,
createSubmit,
)
const characterList = element('ul', 'gm-character-list')
const characterStatus = element('p', 'gm-character-status')
characterStatus.hidden = true
characterStatus.setAttribute('role', 'status')
characters.body.append(createForm, characterList, characterStatus)
// ---- encountered ---------------------------------------------------------------------------
// One list per player; collapsed and capped so a busy table cannot bury the rest of the column.
const encountered = panelSection('gm-encountered-section', 'Encountered')
const encounteredBox = element('div', 'gm-encountered')
const encounteredStatus = element('p', 'gm-encountered-status')
encounteredStatus.hidden = true
encounteredStatus.setAttribute('role', 'status')
encountered.body.append(encounteredBox, encounteredStatus)
// ---- who sees it ---------------------------------------------------------------------------
// Open near the top: it is the answer the GM checks most while moving tokens; its own list is
// capped (50 tokens) so it stays a glance, not a wall.
const seenSection = element('section', 'gm-seen')
seenSection.append(element('h3', undefined, 'Who sees it'))
const seenHint = element('p', 'gm-seen-hint', 'M4 is binary per player: 100 % in sight, 0 % not.')
const seenList = element('ul', 'gm-seen-list')
seenSection.append(seenHint, seenList)
root.append(seenSection, characters.details, encountered.details)
host.append(root)
let active = false
let characterSig = ''
let encounteredSig = ''
let seenSig = ''
let current: RootState | null = null
function setCharacterStatus(text: string | null): void {
if (text === null) {
characterStatus.textContent = ''
characterStatus.hidden = true
} else {
characterStatus.textContent = text
characterStatus.hidden = false
}
}
function setEncounteredStatus(text: string | null): void {
if (text === null) {
encounteredStatus.textContent = ''
encounteredStatus.hidden = true
} else {
encounteredStatus.textContent = text
encounteredStatus.hidden = false
}
}
function renderPlayerOptions(
select: HTMLSelectElement,
players: RosterEntry[],
includeGm: boolean,
value: string,
): void {
const wanted = players.filter(entry => includeGm || entry.role !== 'gm')
const signature = wanted.map(entry => `${entry.id}:${entry.role}`).join(',')
if (select.dataset['options'] !== signature) {
select.replaceChildren()
for (const entry of wanted) {
const option = element('option', undefined, playerLabel(entry))
option.value = String(entry.id)
select.append(option)
}
select.dataset['options'] = signature
}
if (value !== '') select.value = value
}
function renderCharacters(characters: CastCharacter[], players: RosterEntry[]): void {
if (characters.length === 0) {
characterList.replaceChildren(element('li', 'gm-character-empty', 'No characters yet.'))
return
}
characterList.replaceChildren(
...characters.map(character => {
const item = element('li')
item.dataset['character'] = character.id
const title = element(
'span',
`gm-character-title-${character.id}`,
`${character.descriptiveName} — ${character.actualName}`,
)
const meta = element(
'span',
`gm-character-meta-${character.id}`,
[
`owner ${nameOf(players, character.owner)}`,
character.revealAll ? 'reveal all' : 'not revealed to all',
character.revealed.length === 0
? 'nobody told'
: `told: ${character.revealed.map(id => nameOf(players, id)).join(', ')}`,
].join(' · '),
)
const dname = field('input', `gm-character-dname-${character.id}`, 'Descriptive')
dname.node.type = 'text'
dname.node.value = character.descriptiveName
const aname = field('input', `gm-character-aname-${character.id}`, 'Actual')
aname.node.type = 'text'
aname.node.value = character.actualName
const rename = element('button', `gm-character-rename-${character.id}`, 'Rename')
rename.type = 'button'
rename.addEventListener('click', () => {
void renameCharacter(character.id, dname.node.value, aname.node.value)
})
const owner = field('select', `gm-character-owner-${character.id}`, 'Owner')
renderPlayerOptions(owner.node, players, true, String(character.owner))
const move = element('button', `gm-character-reassign-${character.id}`, 'Move to owner')
move.type = 'button'
move.addEventListener('click', () => {
void reassignCharacter(character.id, Number(owner.node.value))
})
const revealPlayer = field(
'select',
`gm-character-reveal-player-${character.id}`,
'Reveal actual name to',
)
renderPlayerOptions(revealPlayer.node, players, false, '')
const reveal = element('button', `gm-character-reveal-${character.id}`, 'Reveal')
reveal.type = 'button'
reveal.addEventListener('click', () => {
void revealCharacter(character.id, Number(revealPlayer.node.value))
})
const revealAll = element(
'button',
`gm-character-reveal-all-${character.id}`,
'Reveal to all',
)
revealAll.type = 'button'
revealAll.addEventListener('click', () => {
void revealCharacterAll(character.id)
})
const remove = element('button', `gm-character-remove-${character.id}`, 'Remove')
remove.type = 'button'
remove.addEventListener('click', () => {
void removeCharacter(character.id)
})
item.append(
title,
meta,
dname.label,
dname.node,
aname.label,
aname.node,
rename,
owner.label,
owner.node,
move,
revealPlayer.label,
revealPlayer.node,
reveal,
revealAll,
remove,
)
return item
}),
)
}
function renderEncountered(state: RootState, players: RosterEntry[]): void {
const lists: HTMLElement[] = []
for (const entry of players) {
const list = encounteredOf(state, entry.id)
if (list.length === 0) continue
const playerLabelNode = element('h4', `gm-encountered-title-${entry.id}`, playerLabel(entry))
const ul = element('ul', `gm-encountered-${entry.id}`)
ul.replaceChildren(
...list.map(row => {
const item = element('li')
item.dataset['token'] = row.id
const name = element('span', undefined, row.name)
const memory = element('span', undefined, row.grey ? 'met, not in sight' : 'in sight')
item.append(name, memory)
// A sighting is recorded again on the next refresh while the token is in view, so
// forgetting is only meaningful once the player can no longer see it (DESIGN 8).
if (row.grey) {
const remove = element(
'button',
`gm-encountered-remove-${entry.id}-${row.id}`,
'Forget',
)
remove.type = 'button'
remove.addEventListener('click', () => {
void forgetEncountered(entry.id, row.id)
})
item.append(remove)
}
return item
}),
)
lists.push(playerLabelNode, ul)
}
if (lists.length === 0) {
encounteredBox.replaceChildren(element('p', 'gm-encountered-empty', 'No entry yet.'))
} else {
encounteredBox.replaceChildren(...lists)
}
}
function renderSeen(tokens: AdminToken[], players: RosterEntry[], state: RootState): void {
if (tokens.length === 0) {
seenList.replaceChildren(element('li', 'gm-seen-empty', 'No token yet.'))
return
}
seenList.replaceChildren(
...tokens.map(token => {
const seen = seenByOf(state, token.id)
const watchers = (seen ?? []).map(id => nameOf(players, id))
const percent = watchers.length === 0 ? 0 : 100
const item = element('li')
item.dataset['token'] = token.id
const label = element(
'span',
`gm-seen-${token.id}`,
watchers.length === 0
? `${token.name} — nobody (0 %)`
: `${token.name} — ${watchers.join(', ')} (${percent} %)`,
)
item.append(label)
return item
}),
)
}
function refresh(): void {
const state = current
if (!state || !active) return
const players = rosterOf(state)
const characters = castCharacters(state)
const tokens = adminTokens(state)
const orderedPlayers = [...players].sort((a, b) => a.id - b.id)
const nextCharacterSig = JSON.stringify(characters) + JSON.stringify(players)
if (nextCharacterSig !== characterSig) {
characterSig = nextCharacterSig
renderCharacters(characters, orderedPlayers)
renderPlayerOptions(
createOwner.node,
orderedPlayers,
true,
createOwner.node.value || String(state.session.me?.id ?? ''),
)
}
const encounteredLists = orderedPlayers.map(entry => [entry.id, encounteredOf(state, entry.id)])
const nextEncounteredSig = JSON.stringify(encounteredLists) + JSON.stringify(players)
if (nextEncounteredSig !== encounteredSig) {
encounteredSig = nextEncounteredSig
renderEncountered(state, orderedPlayers)
}
const seenMap = tokens.map(token => [token.id, seenByOf(state, token.id)])
const nextSeenSig =
JSON.stringify(seenMap) + JSON.stringify(tokens.map(t => [t.id, t.name])) + JSON.stringify(players)
if (nextSeenSig !== seenSig) {
seenSig = nextSeenSig
renderSeen(tokens, orderedPlayers, state)
}
}
async function request(
t: string,
fields: Record<string, unknown> = {},
): Promise<AckFrame | null> {
try {
const ack = await handlers.send(t, fields)
if (!ack.ok) setCharacterStatus(describeCode(ack.code))
return ack
} catch {
setCharacterStatus('Could not reach the server.')
return null
}
}
async function createCharacter(): Promise<void> {
setCharacterStatus(null)
const descriptive = createName.node.value.trim()
const actual = createActual.node.value.trim()
if (descriptive === '' || actual === '') {
setCharacterStatus('Both names are required.')
return
}
const owner = createOwner.node.value === '' ? undefined : Number(createOwner.node.value)
const ack = await request('character.create', {
descriptive_name: descriptive,
actual_name: actual,
...(owner === undefined ? {} : { owner }),
})
if (ack?.ok) {
createName.node.value = ''
createActual.node.value = ''
setCharacterStatus('Character created.')
}
}
async function renameCharacter(id: string, descriptive: string, actual: string): Promise<void> {
setCharacterStatus(null)
if (descriptive.trim() === '' || actual.trim() === '') {
setCharacterStatus('Both names are required.')
return
}
const ack = await request('character.update', {
id,
descriptive_name: descriptive.trim(),
actual_name: actual.trim(),
})
if (ack?.ok) setCharacterStatus('Character renamed.')
}
async function reassignCharacter(id: string, owner: number): Promise<void> {
setCharacterStatus(null)
if (!Number.isInteger(owner) || owner <= 0) {
setCharacterStatus('Choose an owner first.')
return
}
const ack = await request('character.reassign', { id, owner })
if (ack?.ok) setCharacterStatus('Character reassigned. Token controllers did not move.')
}
async function revealCharacter(id: string, player: number): Promise<void> {
setCharacterStatus(null)
if (!Number.isInteger(player) || player <= 0) {
setCharacterStatus('Choose a player first.')
return
}
const ack = await request('name.reveal', { subject: 'character', id, player })
if (ack?.ok) setCharacterStatus('Actual name revealed to that player.')
}
async function revealCharacterAll(id: string): Promise<void> {
setCharacterStatus(null)
const ack = await request('name.reveal_all', { subject: 'character', id })
if (ack?.ok) setCharacterStatus('Actual name revealed to everyone.')
}
async function removeCharacter(id: string): Promise<void> {
setCharacterStatus(null)
const ack = await request('character.remove', { id })
if (ack?.ok) setCharacterStatus('Character removed.')
}
async function forgetEncountered(player: number, token: string): Promise<void> {
setEncounteredStatus(null)
try {
const ack = await handlers.send('encountered.remove', { player, id: token })
setEncounteredStatus(ack.ok ? 'Entry forgotten.' : describeCode(ack.code))
} catch {
setEncounteredStatus('Could not reach the server.')
}
}
createForm.addEventListener('submit', event => {
event.preventDefault()
void createCharacter()
})
function render(state: RootState): void {
current = state
const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting'
const gm = state.session.role === 'gm' && state.session.me?.name != null
const nextActive = live && gm
if (!nextActive) {
active = false
characterSig = ''
encounteredSig = ''
seenSig = ''
root.hidden = true
characterList.replaceChildren()
encounteredBox.replaceChildren()
seenList.replaceChildren()
setCharacterStatus(null)
setEncounteredStatus(null)
return
}
if (!active) {
active = true
characterSig = ''
encounteredSig = ''
seenSig = ''
}
root.hidden = false
refresh()
}
return {
render,
destroy() {
root.remove()
},
}
}
+136
View File
@@ -0,0 +1,136 @@
// The lists panel (T8, #71; DESIGN 7.1 layer 6): story 31's own characters and story 32's
// encountered list. Plain DOM, every server string through `textContent` (decision 15): a token
// name can never become markup.
//
// Mounted by `render/modules/lists.ts` under the shell's existing `#panels` host, so the shell's
// sign-in flow is untouched and the panel exists only while a live stage does. The panel is
// pointer-transparent (see style.css): it must never eat a pan or a token drag.
import type { RootState } from '../reducer.ts'
import type { Store } from '../store.ts'
import { ownCharactersOf } from '../slices/characters.ts'
import type { CharacterView } from '../slices/characters.ts'
import { encounteredOf } from '../slices/encountered.ts'
import type { EncounteredEntry } from '../slices/encountered.ts'
import { panelSection } from './section.ts'
const NAME_FALLBACK = '(unnamed)'
function text(tag: keyof HTMLElementTagNameMap, className: string, value: string): HTMLElement {
const node = document.createElement(tag)
node.className = className
node.textContent = value
return node
}
/** A prop value as text: scalars plainly, anything else as bounded JSON. */
function valueText(value: unknown): string {
if (value === null) return 'null'
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
try {
const json = JSON.stringify(value)
return json.length > 80 ? `${json.slice(0, 77)}…` : json
} catch {
return '?'
}
}
/** Story 31: the values this player may read, public first then the owner bucket on top. */
function valuesOf(character: CharacterView): Array<[string, string]> {
const merged: Record<string, unknown> = { ...character.props['public'], ...character.props['owner'] }
return Object.entries(merged).map(([key, value]) => [key, valueText(value)])
}
function characterRow(character: CharacterView): HTMLLIElement {
const item = document.createElement('li')
item.dataset['character'] = character.id
const label = character.descriptiveName.trim() || NAME_FALLBACK
const name = text('span', 'entry-name', label)
if (character.actualName && character.actualName !== character.descriptiveName) {
name.title = character.actualName
}
item.append(name)
const values = valuesOf(character)
if (values.length > 0) {
item.append(text('span', 'entry-values', values.map(([key, value]) => `${key} ${value}`).join(' · ')))
}
return item
}
function encounteredRow(entry: EncounteredEntry): HTMLLIElement {
const item = document.createElement('li')
item.dataset['token'] = entry.id
item.dataset['grey'] = entry.grey ? 'true' : 'false'
item.classList.toggle('grey', entry.grey)
item.append(text('span', 'entry-name', entry.name.trim() || NAME_FALLBACK))
// Greyed means "met before, whereabouts unknown" (story 32); the text says it without colour.
item.append(text('span', 'entry-state', entry.grey ? 'out of sight' : 'in sight'))
return item
}
function listSignature(characters: readonly CharacterView[], encountered: readonly EncounteredEntry[]): string {
return JSON.stringify([
characters.map(character => [
character.id,
character.descriptiveName,
character.actualName,
valuesOf(character),
]),
encountered.map(entry => [entry.id, entry.name, entry.grey]),
])
}
export function mountListsPanel(host: HTMLElement, store: Store): () => void {
const section = document.createElement('section')
section.id = 'lists'
section.hidden = true
// On a phone the HUD column is narrow and tall: both lists start folded so the map stays
// visible, and each list is height-capped with its own scroll when opened. A wide screen has the
// room, so the lists stay open there (the pre-M4 behaviour).
const wide = window.innerWidth >= 640
const charactersSection = panelSection('characters-panel', 'My characters', wide)
const charactersList = document.createElement('ul')
charactersList.id = 'characters'
const charactersEmpty = text('p', 'empty', 'No characters yet.')
charactersSection.body.append(charactersEmpty, charactersList)
const encounteredSection = panelSection('encountered-panel', 'Encountered', wide)
const encounteredList = document.createElement('ul')
encounteredList.id = 'encountered'
const encounteredEmpty = text('p', 'empty', 'Nobody met yet.')
encounteredSection.body.append(encounteredEmpty, encounteredList)
section.append(charactersSection.details, encounteredSection.details)
host.append(section)
let signature = ''
function render(state: RootState): void {
const visible = state.session.role !== null &&
(state.connection.phase === 'live' || state.connection.phase === 'reconnecting')
section.hidden = !visible
if (!visible) return
const characters = ownCharactersOf(state)
const encountered = encounteredOf(state)
const next = listSignature(characters, encountered)
// The lists change on frames, not per frame: rebuild rows only when their content changed.
if (next !== signature) {
signature = next
charactersList.replaceChildren(...characters.map(characterRow))
encounteredList.replaceChildren(...encountered.map(encounteredRow))
charactersEmpty.hidden = characters.length > 0
encounteredEmpty.hidden = encountered.length > 0
}
}
const unsubscribe = store.subscribe(render)
render(store.state)
return () => {
unsubscribe()
section.remove()
}
}
+35
View File
@@ -0,0 +1,35 @@
// A collapsible GM/player panel section (M4 UX): native <details>/<summary>, so a long column
// collapses without custom state, keyboard handling or ARIA. Every string still goes through
// `textContent` (spec #63 decision 15).
//
// The section id stays on the <details> element, so existing selectors (`#gm-roster`, ...) keep
// working and tests can read `.open` or click the summary to toggle.
export interface PanelSection {
details: HTMLDetailsElement
summary: HTMLElement
body: HTMLDivElement
}
export function panelSection(id: string, title: string, open = false): PanelSection {
const details = document.createElement('details')
details.id = id
details.open = open
details.className = 'panel-section'
const summary = document.createElement('summary')
summary.textContent = title
const body = document.createElement('div')
body.className = 'panel-body'
details.append(summary, body)
return { details, summary, body }
}
/** Update a summary without touching the body (the count in "Tokens (50)"). */
export function setSectionTitle(section: PanelSection, title: string): void {
if (section.summary.textContent !== title) section.summary.textContent = title
}
/** The nearest scrollable ancestor's viewport; `scrollIntoView` would also scroll the page. */
export function revealInColumn(node: HTMLElement): void {
node.scrollIntoView({ block: 'nearest', inline: 'nearest' })
}
+39
View File
@@ -0,0 +1,39 @@
// Wall-editor control synchronisation (#73, #76 deflake).
//
// Both a server `wall` frame and the editor's own dispatch (undo bookkeeping after an ack) re-render
// the panel. The panel must copy the server's record into its controls only when that record
// actually changed: the ack dispatch still carries the previous record, so repopulating from it
// would revert the checkbox the GM just toggled for the round trip until the `wall` frame lands.
// That revert is visible on a real connection and, on a slow host, can land before the browser has
// even observed the click (Playwright's `check` then fails as "did not change its state").
//
// Kept pure so the reducer-level test suite can pin it without a DOM.
import type { WallView } from '../slices/walls.ts'
export interface PopulatedWall {
id: number
signature: string
}
/** Every control `populate` writes, in a fixed order: the record, not its object identity. */
export function wallFieldsSignature(wall: WallView): string {
const s = wall.switches
return JSON.stringify([
wall.id,
wall.label,
s.blocksSight,
s.blocksMovement,
s.sightDir,
s.playerMarker,
s.door,
s.open,
s.secret,
s.locked,
])
}
/** True when the panel's controls no longer match the server record and must be repopulated. */
export function shouldPopulate(populated: PopulatedWall | null, wall: WallView): boolean {
return populated === null || populated.id !== wall.id || populated.signature !== wallFieldsSignature(wall)
}
+666
View File
@@ -0,0 +1,666 @@
// GM wall editor panel (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4). Plain DOM and `textContent`
// only. Mounted under the shell's `#panels` host by the wall render module, so a player never gets a
// wall panel and the panel cannot outlive the live stage.
//
// The panel owns the editor's local UI state (the armed preset, the first click, the snap toggle)
// and sends `wall.add` / `wall.update` / `wall.remove` / `door.set` through the session's intent
// bridge. Every payload is built by `src/wallEditor.ts`, which enforces preset XOR raw (an
// `open:false` never rides beside a preset) and never puts `open` in a `wall.update` patch: opening
// and closing a door is the `door.set` intent.
//
// Undo (story 52) is single-step: the panel records the inverse of the last successful edit as a
// wall-slice descriptor, and the Undo button sends that inverse. A new edit replaces it.
import type { ReducerEvent, RootState } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { sendIntent } from '../intents.ts'
import type { WallView } from '../slices/walls.ts'
import { restoreOf, selectedWallOf, undoOf, wallsOf } from '../slices/walls.ts'
import type { SightDir, WallPreset, WallSwitches, WallUndo } from '../wallEditor.ts'
import type { PopulatedWall } from './wallSync.ts'
import { shouldPopulate, wallFieldsSignature } from './wallSync.ts'
import { revealInColumn } from './section.ts'
import {
PRESETS,
buildAddFields,
buildDoorFields,
buildUpdateFields,
flipSightDir,
presetSwitches,
snapPoint,
undoIntent,
validateLabel,
validateSwitches,
} from '../wallEditor.ts'
export interface WallPanel {
render(state: RootState): void
/** The editor is waiting for the two draw points; the renderer must take the gesture. */
readonly armed: boolean
/** The first snapped point of the wall being drawn, or null. */
readonly first: Vec2 | null
/** Snap a world point with the current grid/endpoint settings. */
snap(point: Vec2): Vec2
/** Feed one click while armed; the second one sends `wall.add`. */
drawPoint(point: Vec2): void
cancelDraw(): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
invalid: 'That combination is not valid.',
'not-found': 'That wall no longer exists.',
'not-allowed': 'The server refused that action.',
}
function describeCode(code: string | undefined): string {
if (code === undefined) return 'The server refused that action.'
return CODE_TEXT[code] ?? `The server refused that action (${code}).`
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function field<K extends keyof HTMLElementTagNameMap>(tag: K, id: string, text: string) {
const node = element(tag, id, text)
const label = element('label', undefined, text)
label.htmlFor = id
return { node, label }
}
const PRESET_LABELS: Record<WallPreset, string> = {
wall: 'Wall',
door: 'Door',
window: 'Window',
one_way: 'One-way',
}
export function mountWallPanel(
host: HTMLElement,
dispatch: (event: ReducerEvent) => void,
): WallPanel {
const root = element('section', 'gm-walls')
root.hidden = true
root.append(element('h2', undefined, 'Walls'))
// ---- draw ----------------------------------------------------------------------------------
const drawSection = element('section', 'wall-draw')
drawSection.append(element('h3', undefined, 'Draw'))
const presetRow = element('div', 'wall-presets')
const presetButtons = new Map<WallPreset, HTMLButtonElement>()
for (const preset of PRESETS) {
const button = element('button', `wall-preset-${preset}`, PRESET_LABELS[preset])
button.type = 'button'
button.dataset['preset'] = preset
button.addEventListener('click', () => arm(preset))
presetButtons.set(preset, button)
presetRow.append(button)
}
const snapWrap = field('input', 'wall-snap', 'Snap to grid and endpoints')
snapWrap.node.type = 'checkbox'
snapWrap.node.checked = true
const drawHint = element('p', 'wall-hint', 'Choose a preset, then click two points.')
const drawState = element('p', 'wall-drawing', '')
drawSection.append(presetRow, snapWrap.label, snapWrap.node, drawHint, drawState)
// ---- selected wall -------------------------------------------------------------------------
const selected = element('section', 'wall-selected')
selected.hidden = true
const selectedTitle = element('h3', 'wall-kind', 'No wall selected')
const kindHint = element('p', 'wall-kind-hint', 'Derived kind (server)')
const labelInput = field('input', 'wall-label', 'Private label')
labelInput.node.type = 'text'
labelInput.node.maxLength = 64
const labelApply = element('button', 'wall-label-apply', 'Set label')
labelApply.type = 'button'
const markerWrap = field('input', 'wall-player-marker', 'Players see a marker')
markerWrap.node.type = 'checkbox'
const doorWrap = field('input', 'wall-door', 'Door')
doorWrap.node.type = 'checkbox'
const secretWrap = field('input', 'wall-secret', 'Secret')
secretWrap.node.type = 'checkbox'
const lockedWrap = field('input', 'wall-locked', 'Locked')
lockedWrap.node.type = 'checkbox'
const openButton = element('button', 'wall-open', 'Open door')
openButton.type = 'button'
const flipButton = element('button', 'wall-flip', 'Flip direction')
flipButton.type = 'button'
flipButton.hidden = true
const hintLocked = element('p', 'wall-hint-locked', 'locked: unlock first')
hintLocked.hidden = true
const unlockButton = element('button', 'wall-unlock', 'Unlock')
unlockButton.type = 'button'
unlockButton.hidden = true
const deleteButton = element('button', 'wall-delete', 'Delete wall')
deleteButton.type = 'button'
// ---- advanced raw switches -----------------------------------------------------------------
const advancedToggle = element('button', 'wall-advanced-toggle', 'Advanced switches')
advancedToggle.type = 'button'
const advanced = element('section', 'wall-advanced')
advanced.hidden = true
const advSight = field('input', 'wall-blocks-sight', 'blocks_sight')
advSight.node.type = 'checkbox'
const advMove = field('input', 'wall-blocks-movement', 'blocks_movement')
advMove.node.type = 'checkbox'
const advDir = field('select', 'wall-sight-dir', 'sight_dir')
for (const value of ['both', 'left', 'right'] as const) {
const option = element('option', undefined, value)
option.value = value
advDir.node.append(option)
}
const advMarker = field('input', 'wall-adv-marker', 'player_marker')
advMarker.node.type = 'checkbox'
const advDoor = field('input', 'wall-adv-door', 'door')
advDoor.node.type = 'checkbox'
const advSecret = field('input', 'wall-adv-secret', 'secret')
advSecret.node.type = 'checkbox'
const advLocked = field('input', 'wall-adv-locked', 'locked')
advLocked.node.type = 'checkbox'
const advApply = element('button', 'wall-adv-apply', 'Apply switches')
advApply.type = 'button'
advanced.append(
advSight.label,
advSight.node,
advMove.label,
advMove.node,
advDir.label,
advDir.node,
advMarker.label,
advMarker.node,
advDoor.label,
advDoor.node,
advSecret.label,
advSecret.node,
advLocked.label,
advLocked.node,
advApply,
)
const error = element('p', 'wall-error')
error.hidden = true
error.setAttribute('role', 'alert')
selected.append(
selectedTitle,
kindHint,
labelInput.label,
labelInput.node,
labelApply,
markerWrap.label,
markerWrap.node,
doorWrap.label,
doorWrap.node,
openButton,
secretWrap.label,
secretWrap.node,
lockedWrap.label,
lockedWrap.node,
hintLocked,
unlockButton,
flipButton,
advancedToggle,
advanced,
deleteButton,
error,
)
// ---- undo ----------------------------------------------------------------------------------
const undoButton = element('button', 'wall-undo', 'Undo')
undoButton.type = 'button'
root.append(drawSection, selected, undoButton)
// Walls sit at the top of the column: drawing is the GM's most frequent action and the selected
// wall's editor must be reachable without scrolling past the token/cast lists.
host.prepend(root)
let active = false
let current: RootState | null = null
let preset: WallPreset = 'wall'
let armed = false
let first: Vec2 | null = null
let snapEnabled = true
/** The server record last copied into the controls (id + field signature), or null. */
let populated: PopulatedWall | null = null
let advancedOpen = false
/** The last rendered wall record, so a field edit uses exactly what the GM saw. */
let shown: WallView | null = null
function setError(text: string | null): void {
error.textContent = text ?? ''
error.hidden = text === null
}
function scene(): { id: number; w: number; h: number; grid: number } | null {
const info = current?.session.scene
if (!info) return null
return { id: info.id, w: info.w, h: info.h, grid: info.grid_size }
}
function endpoints(): Vec2[] {
const out: Vec2[] = []
if (!current) return out
for (const wall of wallsOf(current)) out.push(wall.a, wall.b)
return out
}
function clamp(world: Vec2): Vec2 {
const info = scene()
if (!info) return world
return [
Math.min(info.w, Math.max(0, world[0])),
Math.min(info.h, Math.max(0, world[1])),
]
}
function snap(point: Vec2): Vec2 {
const info = scene()
return clamp(
snapPoint(point, {
enabled: snapEnabled,
gridSize: info?.grid ?? 0,
endpoints: endpoints(),
// Endpoint snap is a small pull: 12 world px at the board's 32 px grid.
threshold: 12,
}),
)
}
function updateDrawState(): void {
for (const [value, button] of presetButtons) {
button.setAttribute('aria-pressed', value === preset ? 'true' : 'false')
}
drawState.textContent = armed
? first === null
? `Drawing ${PRESET_LABELS[preset]}: click the first point.`
: `Drawing ${PRESET_LABELS[preset]}: click the second point.`
: 'Not drawing.'
}
function arm(next: WallPreset): void {
preset = next
armed = true
first = null
setError(null)
updateDrawState()
}
function cancelDraw(): void {
armed = false
first = null
updateDrawState()
}
async function send(t: string, fields: Record<string, unknown>): Promise<AckFrame | null> {
try {
const ack = await sendIntent(t, fields)
if (!ack.ok) setError(describeCode(ack.code))
return ack
} catch {
setError('Could not reach the server.')
return null
}
}
function drawPoint(point: Vec2): void {
if (!armed) return
const info = scene()
if (!info) return
const snapped = snap(point)
if (first === null) {
first = snapped
updateDrawState()
return
}
const a = first
first = null
armed = false
updateDrawState()
if (a[0] === snapped[0] && a[1] === snapped[1]) {
setError('A wall needs two different points.')
return
}
const payload = { preset, switches: presetSwitches(preset), label: null }
const fields = buildAddFields(info.id, a, snapped, payload)
void send('wall.add', fields).then(ack => {
if (ack?.ok && typeof ack.id === 'number') {
// Select the new wall so the GM can label it or open it, and make the add undoable.
dispatch({ type: 'wall-select', id: ack.id })
dispatch({ type: 'wall-record-undo', undo: { kind: 'remove', id: ack.id } })
}
})
}
async function patch(fields: Record<string, unknown>, prior: WallView): Promise<boolean> {
const info = scene()
if (!info) return false
const ack = await send('wall.update', { scene: info.id, id: prior.id, ...fields })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
setError(null)
return true
}
return false
}
function mergedSwitches(next: Partial<WallSwitches>): WallSwitches | null {
if (!shown) return null
return { ...shown.switches, ...next }
}
/** Send one checkbox/select field, validating the resulting switch set first. */
async function applySwitch<K extends keyof WallSwitches>(
key: K,
value: WallSwitches[K],
): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
// Clearing `door` is the one patch that also closes/de-secrets server-side (6.1), so it is sent
// alone rather than as a contradictory full switch set.
if (key === 'door' && value === false) {
if (!(await patch({ door: false }, prior))) populate(prior)
return
}
const merged = mergedSwitches({ [key]: value } as Partial<WallSwitches>)
if (!merged) return
const invalid = validateSwitches(merged)
if (invalid !== null) {
setError(invalid)
return
}
const payload = buildUpdateFields(prior.id, { preset: null, switches: merged })
const info = scene()
if (!info) return
const ack = await send('wall.update', { scene: info.id, ...payload })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
} else {
// The server refused: put the control back to the record the GM last saw.
populate(prior)
}
}
// ---- listeners -----------------------------------------------------------------------------
snapWrap.node.addEventListener('change', () => {
snapEnabled = snapWrap.node.checked
})
labelApply.addEventListener('click', () => {
const prior = shown
if (!prior) return
const message = validateLabel(labelInput.node.value)
if (message !== null) {
setError(message)
return
}
const trimmed = labelInput.node.value.trim()
void patch({ label: trimmed === '' ? null : trimmed }, prior)
})
markerWrap.node.addEventListener('change', () => {
void applySwitch('playerMarker', markerWrap.node.checked)
})
doorWrap.node.addEventListener('change', () => {
void applySwitch('door', doorWrap.node.checked)
})
secretWrap.node.addEventListener('change', () => {
void applySwitch('secret', secretWrap.node.checked)
})
lockedWrap.node.addEventListener('change', () => {
void applySwitch('locked', lockedWrap.node.checked)
})
openButton.addEventListener('click', () => {
void toggleDoor()
})
unlockButton.addEventListener('click', () => {
void unlock()
})
flipButton.addEventListener('click', () => {
const prior = shown
if (!prior) return
void applySwitch('sightDir', flipSightDir(prior.switches.sightDir))
})
deleteButton.addEventListener('click', () => {
void deleteWall()
})
advanceButtonSetup()
undoButton.addEventListener('click', () => {
void runUndo()
})
function advanceButtonSetup(): void {
advancedToggle.addEventListener('click', () => {
advancedOpen = !advancedOpen
advanced.hidden = !advancedOpen
advancedToggle.setAttribute('aria-expanded', advancedOpen ? 'true' : 'false')
})
advApply.addEventListener('click', () => {
void applyAdvanced()
})
}
function populate(wall: WallView): void {
const switches = wall.switches
labelInput.node.value = wall.label ?? ''
markerWrap.node.checked = switches.playerMarker
doorWrap.node.checked = switches.door
secretWrap.node.checked = switches.secret
lockedWrap.node.checked = switches.locked
advSight.node.checked = switches.blocksSight
advMove.node.checked = switches.blocksMovement
advDir.node.value = switches.sightDir
advMarker.node.checked = switches.playerMarker
advDoor.node.checked = switches.door
advSecret.node.checked = switches.secret
advLocked.node.checked = switches.locked
}
async function applyAdvanced(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
const switches: WallSwitches = {
...prior.switches,
blocksSight: advSight.node.checked,
blocksMovement: advMove.node.checked,
sightDir: advDir.node.value as SightDir,
playerMarker: advMarker.node.checked,
door: advDoor.node.checked,
secret: advSecret.node.checked,
locked: advLocked.node.checked,
}
const invalid = validateSwitches(switches)
if (invalid !== null) {
setError(invalid)
return
}
await patch({ ...buildUpdateFields(prior.id, { preset: null, switches }) }, prior)
}
async function toggleDoor(): Promise<void> {
const prior = shown
if (!prior || !prior.switches.door) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
if (!prior.switches.open && (prior.switches.locked || prior.switches.secret)) {
// 5.8/6.1: a secret or locked door cannot open; the editor offers the one click that clears
// the block first. No intent is sent, so the server never sees a refused open.
hintLocked.textContent = prior.switches.locked
? 'locked: unlock first'
: 'secret: clear secret first'
hintLocked.hidden = false
unlockButton.textContent = prior.switches.locked ? 'Unlock' : 'Clear secret'
unlockButton.dataset['action'] = prior.switches.locked ? 'locked' : 'secret'
unlockButton.hidden = false
return
}
const info = scene()
if (!info) return
const open = !prior.switches.open
const ack = await send('door.set', buildDoorFields(info.id, prior.id, open))
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: { kind: 'door', id: prior.id, open: prior.switches.open },
})
}
}
async function unlock(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
const field = unlockButton.dataset['action'] === 'secret' ? 'secret' : 'locked'
await applySwitch(field, false)
}
async function deleteWall(): Promise<void> {
const prior = shown
const info = scene()
if (!prior || !info) return
setError(null)
const ack = await send('wall.remove', { scene: info.id, id: prior.id })
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: { kind: 'restore', wall: restoreOf(prior) } })
dispatch({ type: 'wall-select', id: null })
}
}
async function runUndo(): Promise<void> {
if (!current) return
const info = scene()
const undo = undoOf(current)
if (!info || undo === null) return
const intent = undoIntent(info.id, undo)
if (!intent) return
setError(null)
const ack = await send(intent.t, intent.fields)
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: null })
if (intent.t === 'wall.remove') dispatch({ type: 'wall-select', id: null })
}
}
function undoLabel(undo: WallUndo | null): string {
if (undo === null) return 'Undo'
switch (undo.kind) {
case 'remove':
return 'Undo draw'
case 'restore':
return 'Undo delete'
case 'update':
return 'Undo edit'
case 'door':
return 'Undo door'
}
}
function render(state: RootState): void {
current = state
const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting'
const gm = state.session.role === 'gm' && state.session.me?.name != null
const nextActive = live && gm
if (!nextActive) {
active = false
armed = false
first = null
shown = null
populated = null
root.hidden = true
selected.hidden = true
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
updateDrawState()
return
}
if (!active) {
active = true
populated = null
}
root.hidden = false
const wall = selectedWallOf(state)
shown = wall
if (wall === null) {
selected.hidden = true
populated = null
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
return
}
selected.hidden = false
selectedTitle.textContent = `${wall.kind}`
const newlySelected = populated?.id !== wall.id
if (newlySelected) {
populated = null
advancedOpen = false
advanced.hidden = true
advancedToggle.setAttribute('aria-expanded', 'false')
hintLocked.hidden = true
unlockButton.hidden = true
setError(null)
// A click on the board (or a freshly drawn wall) selects it; bring its editor to the top.
revealInColumn(selected)
}
// Repopulate only when the server record changed: an ack dispatch carries the previous record
// and must not undo the switch the GM just made while the authoritative frame is in flight.
// Do not overwrite a field the GM is typing in either; the server's record still drives every
// other control and the derived kind.
if (shouldPopulate(populated, wall) && document.activeElement !== labelInput.node) {
populate(wall)
populated = { id: wall.id, signature: wallFieldsSignature(wall) }
}
kindHint.textContent = `Derived kind: ${wall.kind}`
openButton.textContent = wall.switches.open ? 'Close door' : 'Open door'
openButton.disabled = !wall.switches.door
flipButton.hidden = wall.switches.sightDir === 'both'
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
}
return {
render,
get armed() {
return armed
},
get first() {
return first
},
snap,
drawPoint,
cancelDraw,
destroy() {
root.remove()
},
}
}
+115
View File
@@ -0,0 +1,115 @@
// The opt-in perf overlay's pure half (#82): URL gating, the rolling frame window and the
// percentile/format helpers. No DOM, no Pixi, no socket, so the numbers can be unit-tested.
//
// The overlay is off unless the page is opened with `?perf=1` (or `?perf=on`/`?perf=true`). When
// it is off this module is still imported, but the render module installs no ticker callback and
// creates no DOM node: zero per-frame cost (DESIGN 7.2's "keep the overlay minimal").
/** True when the URL explicitly asks for the overlay; absent and `0`/`false`/`off` mean off. */
export function perfEnabled(search: string): boolean {
let value: string | null = null
try {
value = new URLSearchParams(search).get('perf')
} catch {
return false
}
if (value === null) return false
return ['1', 'true', 'on', 'yes'].includes(value.trim().toLowerCase())
}
/** Nearest-rank percentile of a sample; `null` for an empty sample. `p` is 0..1. */
export function percentile(samples: readonly number[], p: number): number | null {
if (samples.length === 0) return null
const sorted = [...samples].sort((a, b) => a - b)
const rank = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))
return sorted[rank] ?? null
}
export interface FrameSample {
/** Wall-clock time the sample was taken (performance.now()). */
at: number
/** Frame interval in ms (the rAF/ticker delta). */
frame: number
/** Main-thread JS + render submission time for that frame, in ms. */
js: number
}
export interface PerfSnapshot {
/** Frames per second over the window's measured span, or null before two samples. */
fps: number | null
frameP50: number | null
frameP95: number | null
jsP50: number | null
jsP95: number | null
/** How many frames the snapshot is based on. */
samples: number
}
/** A fixed-duration rolling window of frame samples (default: the last 10 s). */
export class PerfWindow {
readonly windowMs: number
#samples: FrameSample[] = []
constructor(windowMs = 10_000) {
this.windowMs = windowMs
}
add(frameMs: number, jsMs: number, now = performance.now()): void {
if (!Number.isFinite(frameMs) || frameMs <= 0) return
this.#samples.push({ at: now, frame: frameMs, js: Number.isFinite(jsMs) ? Math.max(0, jsMs) : 0 })
this.#prune(now)
}
clear(): void {
this.#samples = []
}
snapshot(now = performance.now()): PerfSnapshot {
this.#prune(now)
const frames = this.#samples.map(s => s.frame)
const js = this.#samples.map(s => s.js)
const meanFrame = frames.length > 0 ? frames.reduce((a, b) => a + b, 0) / frames.length : null
const fps = meanFrame !== null && meanFrame > 0 ? 1000 / meanFrame : null
return {
fps,
frameP50: percentile(frames, 0.5),
frameP95: percentile(frames, 0.95),
jsP50: percentile(js, 0.5),
jsP95: percentile(js, 0.95),
samples: frames.length,
}
}
#prune(now: number): void {
const cutoff = now - this.windowMs
let drop = 0
while (drop < this.#samples.length && this.#samples[drop]!.at < cutoff) drop += 1
if (drop > 0) this.#samples.splice(0, drop)
}
}
function number(value: number | null, digits: number): string {
return value === null ? '—' : value.toFixed(digits)
}
/**
* The overlay's one line of text. Everything here is a number or a fixed label.
*
* `tokens visible`/`total` say what the number counts: a player only receives tokens inside their
* sight (the total is then what that client knows), while the GM receives every token. The old bare
* `tokens 50` read as "the scene has 50" even when only two were drawn (M4 dry-run).
*/
export function formatSnapshot(
snapshot: PerfSnapshot,
visibleTokens: number,
totalTokens: number,
zoom: number,
): string {
return [
`fps ${number(snapshot.fps, 1)}`,
`frame p50 ${number(snapshot.frameP50, 1)} p95 ${number(snapshot.frameP95, 1)} ms`,
`JS p50 ${number(snapshot.jsP50, 2)} p95 ${number(snapshot.jsP95, 2)} ms`,
`tokens visible ${visibleTokens} / total ${totalTokens}`,
`zoom ${zoom.toFixed(2)}`,
].join(' · ')
}
+181
View File
@@ -0,0 +1,181 @@
// The wire contract (DESIGN 6). This module is pure: no Pixi, no DOM, no socket. The client speaks
// `proto` 2 (ADR-0011) and ignores unknown server message types and unknown fields (6.2).
/** Compiled into the client exactly as into the server (DESIGN 6.2, ADR-0011). */
export const PROTO = 2
export type Role = 'gm' | 'player'
export type Vec2 = [number, number]
/** `hello.scene` (DESIGN 6.1; views.sceneBlock). No counts, no wall data, no owned ids. */
export interface SceneInfo {
id: number
name: string
w: number
h: number
tile_size: number
cell: number
grid_size: number
vision_radius_default: number
token_radius_default: number
art_version: number
}
export interface RosterEntry {
id: number
name: string | null
role: Role
colour: string
connected: boolean
}
export interface Me {
id: number
name: string | null
}
/** Every server frame carries the per-connection counter `n` (DESIGN 6, 6.4). */
export interface ServerFrame {
t: string
n: number
[field: string]: unknown
}
export interface HelloFrame extends ServerFrame {
t: 'hello'
proto: number
role: Role
me: Me
scene?: SceneInfo
extra?: unknown
}
export interface AckFrame extends ServerFrame {
t: 'ack'
reqId: number
ok: boolean
code?: string
id?: number
key?: string
pos?: Vec2
ts?: number
}
export const CLOSE_REASONS = [
'revoked',
'evicted',
'proto-mismatch',
'malformed-flood',
'server-shutdown',
] as const
export type CloseReason = (typeof CLOSE_REASONS)[number]
export interface ClosingFrame extends ServerFrame {
t: 'closing'
reason: CloseReason
code: number
}
/** What the shell does when a connection outcome arrives (DESIGN 6.5). */
export type CloseOutcome = 'signin' | 'reload' | 'offline'
export function closeOutcome(reason: CloseReason | null): CloseOutcome {
switch (reason) {
case 'revoked':
return 'signin'
case 'proto-mismatch':
return 'reload'
case 'evicted':
case 'malformed-flood':
case 'server-shutdown':
return 'offline'
case null:
return 'offline'
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Parse one text frame into a server envelope. Binary frames and anything that is not a JSON
* object with a string `t` and an integer `n >= 1` are not frames (DESIGN 6: a binary frame counts
* as malformed server input; the client ignores it, exactly as 6.2 says for unknown shapes).
*/
export function parseServerFrame(raw: unknown): ServerFrame | null {
if (typeof raw !== 'string') return null
let value: unknown
try {
value = JSON.parse(raw)
} catch {
return null
}
if (!isRecord(value)) return null
const t = value['t']
const n = value['n']
if (typeof t !== 'string' || t.length === 0) return null
if (typeof n !== 'number' || !Number.isInteger(n) || n < 1) return null
return value as ServerFrame
}
function isRole(value: unknown): value is Role {
return value === 'gm' || value === 'player'
}
function isMe(value: unknown): value is Me {
if (!isRecord(value)) return false
const name = value['name']
return (
typeof value['id'] === 'number' &&
Number.isInteger(value['id']) &&
(name === null || typeof name === 'string')
)
}
export function isHello(frame: ServerFrame): frame is HelloFrame {
if (frame.t !== 'hello') return false
if (typeof frame['proto'] !== 'number' || !Number.isInteger(frame['proto'])) return false
if (!isRole(frame['role'])) return false
if (!isMe(frame['me'])) return false
const scene = frame['scene']
if (scene !== undefined && !isRecord(scene)) return false
return true
}
export function isAck(frame: ServerFrame): frame is AckFrame {
return (
frame.t === 'ack' &&
typeof frame['reqId'] === 'number' &&
Number.isInteger(frame['reqId']) &&
typeof frame['ok'] === 'boolean'
)
}
function isCloseReason(value: unknown): value is CloseReason {
return typeof value === 'string' && (CLOSE_REASONS as readonly string[]).includes(value)
}
export function isClosing(frame: ServerFrame): frame is ClosingFrame {
return (
frame.t === 'closing' &&
isCloseReason(frame['reason']) &&
typeof frame['code'] === 'number' &&
Number.isInteger(frame['code'])
)
}
/**
* Serialise one intent: envelope `t` plus its `reqId` and fields (DESIGN 6 Conventions). The server
* ignores unknown fields (6.2); the client never invents a `t` outside the catalogue.
*/
export function encodeIntent(t: string, reqId: number, fields: Record<string, unknown> = {}): string {
return JSON.stringify({ ...fields, t, reqId })
}
/** The only place the client spells the `proto` parameter (6.2: absent or non-integer is 400). */
export function wsUrl(location: Pick<Location, 'protocol' | 'host'> = window.location): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
return `${scheme}://${location.host}/ws?proto=${PROTO}`
}
+321
View File
@@ -0,0 +1,321 @@
// The client's one pure reducer (DESIGN 7.1, spec #63 decision 11): server frames and connection
// events in, state out. No Pixi import here, ever: this module is the unit-test seam.
//
// Domain slices are *append-only*: every file in ./slices/ that exports `slice` is picked up by the
// build-time glob below and registered automatically, so a later ticket (fog, tokens, walls, GM
// panels) adds one file and touches no other slice. `hello` resets every slice (DESIGN 6.3: a
// reconnect is a full resync), which is why the registry owns the reset rather than each slice.
import type {
CloseReason,
Me,
Role,
RosterEntry,
SceneInfo,
ServerFrame,
Vec2,
} from './protocol.ts'
import { closeOutcome, isClosing, isHello } from './protocol.ts'
import type { WallUndo } from './wallEditor.ts'
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reconnecting' | 'reload' | 'offline'
export type ConnectionBadge = 'connected' | 'reconnecting' | 'offline'
export interface ConnectionState {
phase: Phase
/** Server frames seen on this connection (`n` is per connection, starts at 1). */
frames: number
lastN: number
/** Human text for the shell; never game data. */
notice: string | null
/** Sign-in failure text ("Key not recognised.") or a transport message. */
error: string | null
/** The name the player tried was refused; shown only on the first-sign-in name prompt. */
nameError: string | null
/** Consecutive reconnect attempts since the last live connection (0 when connected). */
attempt: number
/** The delay the socket scheduled for the next attempt, for the badge/notification text. */
retryDelayMs: number | null
/** The browser's own connectivity (story 7: offline when there is no network at all). */
network: 'online' | 'offline'
}
export interface SessionState {
role: Role | null
me: Me | null
proto: number | null
scene: SceneInfo | null
}
export interface RootState {
connection: ConnectionState
session: SessionState
/**
* Append-only domain state, keyed by slice name. Later tickets read `slices.tokens`, `slices.fog`
* and so on; core connection/session/handshake state stays in this file.
*/
slices: Record<string, unknown>
}
export type ReducerEvent =
| { type: 'connecting' }
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
| { type: 'reconnecting'; attempt: number; delay: number }
| { type: 'network'; online: boolean }
| { type: 'signin-failed'; message: string }
| { type: 'name-failed'; message: string }
| { type: 'signed-out' }
/** GM token panel selection (#74); slices own the state, the core just carries the event. */
| { type: 'admin-select'; token: string | null }
/**
* Drag prediction (#72). The drag render module turns pointer input into these events; the move
* slice owns the optimistic position, the pending `reqId` map and the rollback tween. Keeping
* them in the reducer means the token renderer only reads state, and the state machine is tested
* without a DOM or a socket (DESIGN 7.5).
*/
| { type: 'drag-start'; id: string; pos: Vec2 }
| { type: 'drag-move'; id: string; pos: Vec2 }
| { type: 'drag-end'; id: string; pos: Vec2 }
/** One `token.move` intent left the socket; its ack is matched by `reqId` (6.3). */
| { type: 'move-sent'; reqId: number; id: string; pos: Vec2 }
/** The renderer finished the cosmetic rollback tween for this token. */
| { type: 'rollback-done'; id: string; seq: number }
/** GM wall editor selection (#73): the id lives in the wall slice, the core just carries it. */
| { type: 'wall-select'; id: number | null }
/** The last successful wall edit's inverse, for the editor's single-step undo (#73). */
| { type: 'wall-record-undo'; undo: WallUndo | null }
/**
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
* root reducer clones before dispatching, so the previous state is never touched).
*/
export interface Slice<S = unknown> {
readonly name: string
init(): S
reduce(state: S, event: ReducerEvent, root: RootState): void
}
interface SliceModule {
slice: Slice
}
// Build-time registry: no shared import list to merge, so parallel tickets never edit one file.
const modules = import.meta.glob<SliceModule>('./slices/*.ts', { eager: true })
export const SLICES: readonly Slice[] = Object.keys(modules)
.sort()
.map(path => {
const module = modules[path]
if (!module || !module.slice) throw new Error(`slice ${path} has no \`slice\` export`)
return module.slice
})
const sliceNames = new Set(SLICES.map(slice => slice.name))
if (sliceNames.size !== SLICES.length) throw new Error('duplicate slice name')
export function sliceOf<S>(state: RootState, name: string): S {
return state.slices[name] as S
}
function initialConnection(): ConnectionState {
return {
phase: 'boot',
frames: 0,
lastN: 0,
notice: null,
error: null,
nameError: null,
attempt: 0,
retryDelayMs: null,
network: 'online',
}
}
/**
* Story 7's three badge states. The badge is hidden outside the game (boot, sign-in, reload), is
* `offline` whenever the browser has no network even if the socket has not noticed yet, and is
* `reconnecting` while the socket backs off. Pure, so the transition table is unit-tested.
*/
export function connectionBadge(state: RootState): ConnectionBadge | null {
const { phase, network } = state.connection
if (phase === 'boot' || phase === 'connecting' || phase === 'signin' || phase === 'reload') {
return null
}
if (phase === 'offline' || network === 'offline') return 'offline'
if (phase === 'live') return 'connected'
return 'reconnecting'
}
function initialSession(): SessionState {
return { role: null, me: null, proto: null, scene: null }
}
export function initialState(): RootState {
const slices: Record<string, unknown> = {}
for (const slice of SLICES) slices[slice.name] = slice.init()
return { connection: initialConnection(), session: initialSession(), slices }
}
/** Reset everything that came from the server; keep the connection envelope. */
function resetDomain(state: RootState): void {
state.session = initialSession()
const slices: Record<string, unknown> = {}
for (const slice of SLICES) slices[slice.name] = slice.init()
state.slices = slices
}
function onFrame(state: RootState, frame: ServerFrame): void {
state.connection.frames += 1
state.connection.lastN = frame.n
if (isHello(frame)) {
// DESIGN 6.1/6.3: `hello` means "start clean". The resync that follows rebuilds the view; a
// client that kept the previous connection's state would show stale tokens after a reconnect.
resetDomain(state)
state.session.role = frame.role
state.session.me = frame.me
state.session.proto = frame.proto
state.session.scene = frame.scene ?? null
state.connection.phase = 'live'
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
} else if (frame.t === 'roster') {
// The HUD names this connection from `session.me`; a rename arrives as a roster broadcast, so
// keep `me.name` in step or the one visible name goes stale (the roster no longer repeats it).
const players = frame['players']
const me = state.session.me
if (me !== null && Array.isArray(players)) {
const self = (players as RosterEntry[]).find(entry => entry.id === me.id)
if (self && typeof self.name === 'string' && self.name !== me.name) {
state.session.me = { ...me, name: self.name }
}
}
} else if (isClosing(frame)) {
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
const outcome = closeOutcome(frame.reason)
state.connection.notice =
frame.reason === 'revoked'
? 'Your session has ended. Sign in again.'
: frame.reason === 'proto-mismatch'
? 'This client is out of date.'
: frame.reason === 'evicted'
? 'This tab was replaced by a newer connection.'
: 'The connection was closed by the server.'
if (outcome === 'signin') {
resetDomain(state)
state.connection.phase = 'signin'
} else if (outcome === 'reload') {
state.connection.phase = 'reload'
} else {
state.connection.phase = 'offline'
}
}
}
export function reduce(previous: RootState, event: ReducerEvent): RootState {
const state: RootState = {
connection: { ...previous.connection },
session: { ...previous.session },
slices: { ...previous.slices },
}
switch (event.type) {
case 'connecting':
resetDomain(state)
state.connection.phase = 'connecting'
state.connection.frames = 0
state.connection.lastN = 0
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
break
case 'open':
// An open socket is not a view: stay on the boot/connecting screen until `hello` (6.3).
// A new socket also restarts the per-connection frame counter (`n` starts at 1).
state.connection.frames = 0
state.connection.lastN = 0
break
case 'frame':
onFrame(state, event.frame)
break
case 'reconnecting':
// The map stays on screen (stale) with a badge until the resync replaces it; nothing here
// clears state, because `hello` is the reset point (6.3).
state.connection.phase = 'reconnecting'
state.connection.attempt = event.attempt
state.connection.retryDelayMs = event.delay
state.connection.notice = 'Connection lost. Reconnecting…'
break
case 'network':
state.connection.network = event.online ? 'online' : 'offline'
break
case 'close': {
// A `closing` frame already decided the outcome (6.5); a close without one is a transport
// failure. Before the first `hello` that means "no session" (the `/ws` upgrade was refused).
if (state.connection.phase === 'live' || state.connection.phase === 'reconnecting') {
const outcome = closeOutcome(event.reason)
if (outcome === 'signin') {
resetDomain(state)
state.connection.phase = 'signin'
state.connection.notice = 'Your session has ended. Sign in again.'
} else if (outcome === 'reload') {
state.connection.phase = 'reload'
state.connection.notice = 'This client is out of date.'
} else if (event.reason === null) {
// Transport failure: the socket retries by itself; the view stays until the resync.
state.connection.phase = 'reconnecting'
state.connection.notice = 'Connection lost. Reconnecting…'
} else {
state.connection.phase = 'offline'
state.connection.notice = 'Connection lost.'
}
} else if (state.connection.phase === 'connecting' || state.connection.phase === 'boot') {
resetDomain(state)
state.connection.phase = 'signin'
}
break
}
case 'signin-failed':
resetDomain(state)
state.connection.phase = 'signin'
state.connection.error = event.message
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
break
case 'name-failed':
state.connection.nameError = event.message
break
case 'signed-out':
resetDomain(state)
state.connection.phase = 'signin'
state.connection.notice = null
state.connection.error = null
state.connection.nameError = null
state.connection.attempt = 0
state.connection.retryDelayMs = null
break
}
for (const slice of SLICES) {
slice.reduce(state.slices[slice.name], event, state)
}
return state
}
/** `roster` lives in its own slice (append-only), read through here by the shell. */
export interface RosterState {
players: RosterEntry[]
}
export function rosterOf(state: RootState): RosterEntry[] {
return sliceOf<RosterState>(state, 'roster').players
}
+19
View File
@@ -0,0 +1,19 @@
# Render modules: append-only
Every `*.ts` file here that exports `renderModule` is registered by the build-time glob in
`../stage.ts`. Add one file per feature; never edit the registry.
```ts
import type { RenderModule } from '../stage.ts'
export const renderModule: RenderModule = {
name: 'tiles', // unique
mount({ app, world, layers, store }) {
// create your objects in `layers.*`, subscribe to `store` for state changes,
// return a teardown only for global resources you install.
},
}
```
Layers bottom to top: `tiles`, `grid`, `tokens`, `fog`, `gm`, `dom` (DESIGN 7.1). Update only the
entities that changed (DESIGN 7.2); no per-frame full redraw.
+190
View File
@@ -0,0 +1,190 @@
// Pan, zoom and pinch (story 15, spec #63 decision 7; ADR-0013). Hand-rolled DOM pointer events,
// as DESIGN 7.2 keeps Pixi federated events off: the camera is a transform on the world container,
// so a pan is two numbers and never a redraw of the map.
//
// The module also owns the grid toggle button and the small `data-*` view contract the browser e2e
// reads: `data-zoom` (the exact clamped number), `data-camera` (the world container's `x,y`, so a
// test can go screen <- world at any zoom), `data-grid` (on/off) and `data-tiles` (the tile
// module marks `ready` when every wanted tile of the current viewport has settled). Those are UI
// facts, not renderer internals.
import type { RenderModule } from '../stage.ts'
import type { Camera } from '../../viewport.ts'
import { viewport } from '../../viewport.ts'
interface Point {
x: number
y: number
}
function canvasPoint(canvas: HTMLCanvasElement, event: PointerEvent | WheelEvent): Point {
const rect = canvas.getBoundingClientRect()
return { x: event.clientX - rect.left, y: event.clientY - rect.top }
}
function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y)
}
function midpoint(a: Point, b: Point): Point {
return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
}
/** Wheel delta in CSS pixels; Firefox reports lines and pages instead. */
function wheelPixels(event: WheelEvent): number {
if (event.deltaMode === 1) return event.deltaY * 16
if (event.deltaMode === 2) return event.deltaY * 400
return event.deltaY
}
export const renderModule: RenderModule = {
name: 'camera',
mount({ app, world, store }) {
const canvas = app.canvas
canvas.style.touchAction = 'none'
canvas.style.cursor = 'grab'
const size = () => ({ width: app.screen.width, height: app.screen.height })
viewport.reset(store.state.session.scene, store.state.session.role, size())
function apply(): void {
const { camera, grid } = viewport.state
world.scale.set(camera.zoom)
world.position.set(camera.x, camera.y)
canvas.dataset['zoom'] = String(camera.zoom)
// Screen <- world for the browser e2e and drag tests: `screen = world * zoom + x,y`.
canvas.dataset['camera'] = `${camera.x},${camera.y}`
canvas.dataset['grid'] = grid ? 'on' : 'off'
canvas.dataset['view'] = `${viewport.state.size.width}x${viewport.state.size.height}`
}
const unsubscribeViewport = viewport.subscribe(apply)
apply()
// --- session / resize ----------------------------------------------------------------
function syncSession(): void {
const scene = store.state.session.scene
const role = store.state.session.role
if (scene) viewport.setScene(scene)
viewport.setRole(role)
if (store.state.connection.phase === 'live' || store.state.connection.phase === 'reconnecting') {
viewport.setSize(size())
}
}
const unsubscribeStore = store.subscribe(syncSession)
function onResize(): void {
viewport.setSize(size())
}
window.addEventListener('resize', onResize)
// --- grid toggle (story 18) ----------------------------------------------------------
const button = document.createElement('button')
button.id = 'grid-toggle'
button.type = 'button'
button.textContent = 'Grid'
button.hidden = true
button.style.cssText =
'position:fixed;left:12px;bottom:12px;padding:6px 12px;border-radius:6px;' +
'border:1px solid #777;background:rgb(20 20 20 / 85%);color:#eee;font:12px/1.4 ' +
'ui-monospace,monospace;cursor:pointer;z-index:2;pointer-events:auto'
button.addEventListener('click', () => viewport.toggleGrid())
const panels = document.querySelector('#panels') ?? document.body
panels.append(button)
function syncButton(): void {
const phase = store.state.connection.phase
button.hidden = phase !== 'live' && phase !== 'reconnecting'
button.setAttribute('aria-pressed', viewport.state.grid ? 'true' : 'false')
button.style.opacity = viewport.state.grid ? '1' : '0.55'
}
const unsubscribeButton = viewport.subscribe(syncButton)
const unsubscribeButtonStore = store.subscribe(syncButton)
syncButton()
// --- pointer pan / pinch -------------------------------------------------------------
const pointers = new Map<number, Point>()
let drag: Point | null = null
let pinch: { start: Camera; distance: number; midpoint: Point } | null = null
function beginPinch(): void {
const [a, b] = [...pointers.values()]
if (!a || !b) return
drag = null
pinch = { start: viewport.state.camera, distance: distance(a, b), midpoint: midpoint(a, b) }
}
function onPointerDown(event: PointerEvent): void {
if (event.pointerType === 'mouse' && event.button !== 0) return
pointers.set(event.pointerId, canvasPoint(canvas, event))
try {
canvas.setPointerCapture(event.pointerId)
} catch {
// Synthetic pointers (the e2e's touch pinch) are not active pointers to capture.
}
if (pointers.size === 1) {
drag = canvasPoint(canvas, event)
} else if (pointers.size === 2) {
beginPinch()
}
canvas.style.cursor = 'grabbing'
}
function onPointerMove(event: PointerEvent): void {
if (!pointers.has(event.pointerId)) return
const point = canvasPoint(canvas, event)
pointers.set(event.pointerId, point)
if (pinch && pointers.size >= 2) {
const [a, b] = [...pointers.values()]
if (!a || !b) return
viewport.pinch(
pinch.start,
pinch.distance,
distance(a, b),
pinch.midpoint,
midpoint(a, b),
)
return
}
if (drag) {
viewport.pan(point.x - drag.x, point.y - drag.y)
drag = point
}
}
function onPointerUp(event: PointerEvent): void {
pointers.delete(event.pointerId)
if (pointers.size < 2) pinch = null
const [remaining] = [...pointers.values()]
drag = pointers.size === 1 && remaining ? remaining : null
if (pointers.size === 0) canvas.style.cursor = 'grab'
}
function onWheel(event: WheelEvent): void {
event.preventDefault()
const factor = Math.exp(-wheelPixels(event) * 0.0015)
viewport.zoomAt(factor, canvasPoint(canvas, event))
}
canvas.addEventListener('pointerdown', onPointerDown)
canvas.addEventListener('pointermove', onPointerMove)
canvas.addEventListener('pointerup', onPointerUp)
canvas.addEventListener('pointercancel', onPointerUp)
canvas.addEventListener('wheel', onWheel, { passive: false })
return () => {
unsubscribeViewport()
unsubscribeStore()
unsubscribeButton()
unsubscribeButtonStore()
window.removeEventListener('resize', onResize)
canvas.removeEventListener('pointerdown', onPointerDown)
canvas.removeEventListener('pointermove', onPointerMove)
canvas.removeEventListener('pointerup', onPointerUp)
canvas.removeEventListener('pointercancel', onPointerUp)
canvas.removeEventListener('wheel', onWheel)
button.remove()
world.position.set(0, 0)
world.scale.set(1)
}
},
}
+148
View File
@@ -0,0 +1,148 @@
// Drag own tokens with prediction and rollback (T9, #72; DESIGN 7.4 input, 7.5, 5.5, 6.4).
//
// Hand-rolled DOM pointer events on the canvas (DESIGN 7.2: Pixi federated events are off). The
// listener sits on `window` in the capture phase and only starts a drag when the press lands on
// the canvas *and* on a token this session may move. When it does, propagation is stopped, so the
// camera's pan/pinch (#69), which listens at the canvas, never sees the gesture: a token drag takes
// precedence over pan exactly when the pointer starts on a token the user controls.
//
// The module owns input only. Prediction lives in `slices/move.ts` (a `reqId`-keyed pending map and
// the rollback state machine); the token renderer draws the optimistic position. Sends are capped
// at 20 Hz (DESIGN 6.4) plus one final position on release, each through the session's protocol
// client (`intents.ts`) so the ack can be matched by `reqId`.
import type { RenderContext, RenderModule } from '../stage.ts'
import type { Vec2 } from '../../protocol.ts'
import { sendIntent } from '../../intents.ts'
import { dragOf, draggableAt } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
/** 20 Hz while dragging (DESIGN 6.4, FIXED #15); the release always sends. */
export const MOVE_SEND_INTERVAL_MS = 50
interface ActiveDrag {
id: string
pointerId: number
/** `performance.now()` of the last intent; 0 so the first move is sent at once. */
lastSent: number
}
export const renderModule: RenderModule = {
name: 'drag',
mount({ app, layers, store }: RenderContext): () => void {
const canvas = app.canvas
let active: ActiveDrag | null = null
/** Canvas CSS pixels -> the tokens layer's world coordinates (the camera's inverse, #69). */
function worldPointOf(event: PointerEvent): Vec2 {
const rect = canvas.getBoundingClientRect()
const local = layers.tokens.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
return [local.x, local.y]
}
function send(id: string, pos: Vec2): void {
try {
const pending = sendIntent('token.move', { id, pos: [pos[0], pos[1]] }, reqId => {
// The slice records the intent first; the ack frame that follows finds it by `reqId`.
store.dispatch({ type: 'move-sent', reqId, id, pos })
})
// A refused/unreachable send has no pending entry (onReqId never ran) and nothing to undo.
pending.catch(() => undefined)
} catch {
// `sendIntent` rejects rather than throws, but a drag must never break the render loop.
}
}
function detach(): void {
window.removeEventListener('pointermove', onMove, true)
window.removeEventListener('pointerup', onUp, true)
window.removeEventListener('pointercancel', onCancel, true)
window.removeEventListener('blur', onCancel)
}
function stop(): void {
active = null
detach()
}
function onDown(event: PointerEvent): void {
if (active !== null) return
// Only the primary pointer over the canvas itself; DOM panels keep their clicks.
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
const state = store.state
if (state.connection.phase !== 'live') return
const point = worldPointOf(event)
const token = draggableAt(tokensOf(state), state.session.role, point)
if (!token) return
// A token drag wins over pan/pinch (#69): the camera's listener never sees this gesture.
event.preventDefault()
event.stopImmediatePropagation()
active = { id: token.id, pointerId: event.pointerId, lastSent: 0 }
store.dispatch({ type: 'drag-start', id: token.id, pos: token.pos })
window.addEventListener('pointermove', onMove, true)
window.addEventListener('pointerup', onUp, true)
window.addEventListener('pointercancel', onCancel, true)
window.addEventListener('blur', onCancel)
}
function onMove(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
// A reconnect (`hello`/`close`) reset the slice under us: stop sending stale intents.
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
event.preventDefault()
event.stopImmediatePropagation()
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-move', id: drag.id, pos })
const now = performance.now()
if (now - drag.lastSent >= MOVE_SEND_INTERVAL_MS) {
drag.lastSent = now
send(drag.id, pos)
}
}
function onUp(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
event.preventDefault()
event.stopImmediatePropagation()
// A reconnect (or the server dropping the token) already ended this drag: do not send a
// final intent that belongs to the dead connection (6.3).
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-end', id: drag.id, pos })
stop()
// The final position always goes out (6.4); a dud has its own ack and may rate-limit.
send(drag.id, pos)
}
function onCancel(event: Event): void {
const drag = active
if (drag === null) return
if (event.type === 'pointercancel') {
const pointer = event as PointerEvent
if (pointer.pointerId !== drag.pointerId) return
}
const current = dragOf(store.state)
if (current?.id === drag.id) {
store.dispatch({ type: 'drag-end', id: drag.id, pos: current.pos })
}
stop()
}
// Capture on `window` beats every listener attached to the canvas (#69's pan included).
window.addEventListener('pointerdown', onDown, true)
return () => {
window.removeEventListener('pointerdown', onDown, true)
stop()
}
},
}
+320
View File
@@ -0,0 +1,320 @@
// The fog and marker layer (T7, #70; DESIGN 7.1 layer 4, 7.3). Three states from the server's facts:
// never-seen floor is opaque black, explored floor is black at ~0.6 alpha, currently visible floor
// is cut out of the fog so the map shows through.
//
// Mechanism (spec #63 decision 9 leaves the Pixi object to the build):
// - one RGBA canvas at cell resolution (`ceil(w/cell) x ceil(h/cell)`) holds the *explored* state:
// never-seen cells alpha 255, explored cells alpha ~0.6. It is repainted from an `ImageData`
// buffer; a cell diff mutates only the new bytes and uploads only the dirty rectangle, so "only
// changed cells" is the normal path (DESIGN 7.2);
// - a second canvas of the same size is the texture the sprite displays: the explored canvas is
// copied into it and the union of this player's `vision` polygons is cut out with
// `destination-out`, which is the polygon cut-out itself, not a separate stencil pass. It is
// recomposed only when an explored or vision frame arrives; there is no per-frame work here;
// - player markers are small sprites in the same layer, drawn above the fog sprite from the
// `marker` set/del frames, never inferred from tiles or walls (decision 17).
//
// Why no stencil mask: a Graphics stencil mask forces a depth-stencil attachment plus a full-frame
// stencil pass on every frame. Measured on the e2e's software renderer it cost ~350 ms of the
// phone-class viewport-fill budget (test 412x869 dpr 2.625); the baked cut-out keeps the same
// pixels and leaves the fill at the pre-fog baseline. The cut-out is rasterized at cell resolution,
// the same resolution as the explored grid the server sends.
//
// The GM has no fog (story 26): the layer hides and the GM never receives `explored`/`vision`/
// `marker` frames anyway. The counts, timings and ids are published on the canvas dataset; the e2e
// reads them and probes the pixels, so the test never touches renderer internals.
import { Container, Graphics, GraphicsContext, Sprite, Texture } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import type { RootState } from '../../reducer.ts'
import { fogOf } from '../../slices/fog.ts'
import type { FogState, VisionPoly } from '../../slices/fog.ts'
/** Explored-but-not-visible: black at 0.6 alpha, so the map reads dimmed, never hidden. */
export const EXPLORED_ALPHA = 0.6
/** One shared icon context for every marker: a lit window pane with a dark frame. */
const MARKER_ICON = new GraphicsContext()
.roundRect(-7, -7, 14, 14, 2)
.fill(0xffcc33)
.stroke({ width: 2, color: 0x2b1d00 })
export const renderModule: RenderModule = {
name: 'fog',
mount({ app, layers, store }: RenderContext) {
const canvas = app.canvas
// Markers live in their own layer above the fog sprite.
const markerLayer = new Container()
layers.fog.addChild(markerLayer)
let sprite: Sprite | null = null
let texture: Texture | null = null
/** Explored state (`alpha 255` never seen, `alpha 153` explored), at cell resolution. */
let base: HTMLCanvasElement | null = null
let baseContext: CanvasRenderingContext2D | null = null
let baseImage: ImageData | null = null
/** What the sprite shows: `base` with the vision polygons cut out. */
let shown: HTMLCanvasElement | null = null
let shownContext: CanvasRenderingContext2D | null = null
let grid = { cols: 0, rows: 0 }
let cell = 0
let sceneId: number | null = null
/** The union of this player's polygons, kept for every recompose after a cell diff. */
let currentPolys: readonly VisionPoly[] = []
let renderedExplored = -1
let renderedVision = -1
let renderedMarkers = -1
const markerNodes = new Map<string, Graphics>()
// Instrumentation. `cellsPainted` is the cumulative number of cell pixels touched, so a diff
// is visibly cheaper than the snapshot; `fullRedraws` stays at 1 after a connect.
const stats = {
cellsPainted: 0,
fullRedraws: 0,
visionBuilds: 0,
markerUpdates: 0,
lastFresh: 0,
exploredMs: 0,
fullMs: 0,
visionMs: 0,
}
function destroySurface(): void {
sprite?.destroy()
sprite = null
texture?.destroy(true)
texture = null
base = null
baseContext = null
baseImage = null
shown = null
shownContext = null
grid = { cols: 0, rows: 0 }
cell = 0
sceneId = null
renderedExplored = -1
renderedVision = -1
}
function build(fog: FogState, width: number, height: number): void {
const cols = fog.cols
const rows = fog.rows
if (cols <= 0 || rows <= 0) return
base = document.createElement('canvas')
base.width = cols
base.height = rows
const exploredContext = base.getContext('2d')
if (!exploredContext) return
baseContext = exploredContext
baseImage = exploredContext.createImageData(cols, rows)
// Before the first `explored` frame everything is never-seen: opaque black.
exploredContext.fillStyle = '#000'
exploredContext.fillRect(0, 0, cols, rows)
shown = document.createElement('canvas')
shown.width = cols
shown.height = rows
const fogContext = shown.getContext('2d')
if (!fogContext) return
shownContext = fogContext
fogContext.fillStyle = '#000'
fogContext.fillRect(0, 0, cols, rows)
grid = { cols, rows }
cell = fog.cell
texture = Texture.from(shown)
// The cell texture is displayed scaled: smooth beats a pixelated haze at any zoom.
texture.source.scaleMode = 'linear'
sprite = new Sprite(texture)
sprite.width = width
sprite.height = height
sprite.label = 'fog'
layers.fog.addChildAt(sprite, 0)
sceneId = fog.sceneId
renderedExplored = -1
renderedVision = -1
}
/**
* Rebuild the displayed texture from the explored base and the current vision polygons. The
* canvas 2D `destination-out` fill is the polygon cut-out: antialiased at cell resolution and
* one cheap draw, with no mask/stencil state on the render target.
*/
function compose(): number {
if (!shownContext || !base || !shown) return 0
const started = performance.now()
shownContext.globalCompositeOperation = 'copy'
shownContext.drawImage(base, 0, 0)
const polys = currentPolys
if (polys.length > 0 && cell > 0) {
shownContext.globalCompositeOperation = 'destination-out'
shownContext.save()
shownContext.scale(1 / cell, 1 / cell)
// One fill per polygon: overlapping polygons punch the same hole whether their winding
// orders agree or not (a single nonzero fill could cancel an opposite-winding overlap).
for (const poly of polys) {
const [first, ...rest] = poly.pts
if (!first) continue
shownContext.beginPath()
shownContext.moveTo(first[0], first[1])
for (const [x, y] of rest) shownContext.lineTo(x, y)
shownContext.closePath()
shownContext.fill()
}
shownContext.restore()
}
shownContext.globalCompositeOperation = 'source-over'
texture?.source.update()
return performance.now() - started
}
/** Paint the explored state into `base`. Full repaint only for a snapshot or missed revision. */
function paintExplored(fog: FogState): void {
if (!baseContext || !baseImage || !texture || fog.cols !== grid.cols || fog.rows !== grid.rows) {
return
}
const started = performance.now()
const data = baseImage.data
const full = fog.snapshot || fog.exploredVersion !== renderedExplored + 1
const alpha = Math.round(EXPLORED_ALPHA * 255)
if (full) {
for (let i = 3; i < data.length; i += 4) data[i] = 255
for (const index of fog.cells) data[index * 4 + 3] = alpha
baseContext.putImageData(baseImage, 0, 0)
stats.cellsPainted += grid.cols * grid.rows
stats.fullRedraws += 1
} else if (fog.fresh.length > 0) {
let minX = grid.cols
let minY = grid.rows
let maxX = -1
let maxY = -1
for (const index of fog.fresh) {
data[index * 4 + 3] = alpha
const x = index % grid.cols
const y = (index / grid.cols) | 0
if (x < minX) minX = x
if (y < minY) minY = y
if (x > maxX) maxX = x
if (y > maxY) maxY = y
}
stats.cellsPainted += fog.fresh.length
// One write of the dirtied rectangle, not the whole map.
baseContext.putImageData(baseImage, 0, 0, minX, minY, maxX - minX + 1, maxY - minY + 1)
} else {
renderedExplored = fog.exploredVersion
stats.exploredMs = performance.now() - started
return
}
currentPolys = fog.polys
const composeMs = compose()
renderedExplored = fog.exploredVersion
renderedVision = fog.visionVersion
stats.lastFresh = fog.fresh.length
stats.exploredMs = performance.now() - started + composeMs
if (full) stats.fullMs = stats.exploredMs
}
/** Recompose the cut-out; nothing per frame. */
function paintVision(fog: FogState): void {
if (!base) return
currentPolys = fog.polys
stats.visionMs = compose()
renderedVision = fog.visionVersion
stats.visionBuilds += 1
}
/** Apply one `marker` change: only added, removed or moved ids are touched. */
function paintMarkers(fog: FogState): void {
for (const [id, node] of markerNodes) {
if (fog.markers[id] !== undefined) continue
markerLayer.removeChild(node)
node.destroy()
markerNodes.delete(id)
}
for (const [id, pos] of Object.entries(fog.markers)) {
let node = markerNodes.get(id)
if (!node) {
node = new Graphics(MARKER_ICON)
node.label = `marker-${id}`
markerLayer.addChild(node)
markerNodes.set(id, node)
}
if (node.x !== pos[0] || node.y !== pos[1]) node.position.set(pos[0], pos[1])
}
renderedMarkers = fog.markerVersion
stats.markerUpdates += 1
}
function publish(fog: FogState): void {
const datasets = canvas.dataset
const role = store.state.session.role
datasets['fog'] = role === 'gm' ? 'gm' : sceneId === null ? 'idle' : 'player'
datasets['fogCells'] = String(fog.cells.size)
datasets['fogPolys'] = String(fog.polys.length)
datasets['fogMarkers'] = Object.keys(fog.markers).join(' ')
datasets['fogCellsPainted'] = String(stats.cellsPainted)
datasets['fogFullRedraws'] = String(stats.fullRedraws)
datasets['fogVisionBuilds'] = String(stats.visionBuilds)
datasets['fogMarkerUpdates'] = String(stats.markerUpdates)
datasets['fogLastFresh'] = String(stats.lastFresh)
datasets['fogExploredMs'] = stats.exploredMs.toFixed(3)
datasets['fogFullMs'] = stats.fullMs.toFixed(3)
datasets['fogVisionMs'] = stats.visionMs.toFixed(3)
}
function sync(state: RootState): void {
const fog = fogOf(state)
const role = state.session.role
const gm = role === 'gm'
// The GM sees everything: no fog and no marker-only memory (stories 24-26).
if (sprite) sprite.visible = !gm
markerLayer.visible = !gm
if (gm || fog.cols <= 0 || !state.session.scene) {
publish(fog)
return
}
const width = state.session.scene.w
const height = state.session.scene.h
if (sceneId !== fog.sceneId || !sprite) {
destroySurface()
build(fog, width, height)
for (const node of markerNodes.values()) node.destroy()
markerNodes.clear()
} else if (sprite.width !== width || sprite.height !== height) {
sprite.width = width
sprite.height = height
}
if (!sprite) {
publish(fog)
return
}
if (fog.exploredVersion !== renderedExplored) paintExplored(fog)
// A vision frame can arrive before the first explored frame; compose still needs the base.
else if (fog.visionVersion !== renderedVision) paintVision(fog)
if (fog.markerVersion !== renderedMarkers) paintMarkers(fog)
publish(fog)
}
// The stage is created once the session is live, but a resync can beat `app.init`: start from
// whatever the reducer already holds, then follow the event stream.
sync(store.state)
const unsubscribe = store.subscribe(sync)
return () => {
unsubscribe()
for (const node of markerNodes.values()) node.destroy()
markerNodes.clear()
destroySurface()
layers.fog.removeChild(markerLayer)
markerLayer.destroy({ children: true })
}
},
}
+79
View File
@@ -0,0 +1,79 @@
// The grid layer (story 18, DESIGN 7.1 layer 2): one TilingSprite over a tiny cell texture, not a
// per-frame redraw. The texture is `grid_size` world pixels square with a one-pixel line along its
// top/left edge; tiling it across the scene puts a line on every cell boundary.
//
// The toggle is owned by the camera module (`#grid-toggle`); this module only follows
// `viewport.grid` and writes `data-grid` on the canvas so the e2e can prove the state change.
import { Texture, TilingSprite } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import type { SceneInfo } from '../../protocol.ts'
import { viewport } from '../../viewport.ts'
function gridTexture(cell: number): Texture {
const canvas = document.createElement('canvas')
canvas.width = cell
canvas.height = cell
const context = canvas.getContext('2d')
if (context) {
context.strokeStyle = 'rgba(230, 240, 255, 0.30)'
context.lineWidth = 1
context.beginPath()
context.moveTo(0.5, 0)
context.lineTo(0.5, cell)
context.moveTo(0, 0.5)
context.lineTo(cell, 0.5)
context.stroke()
}
const texture = Texture.from(canvas)
texture.source.label = `grid-${cell}`
return texture
}
export const renderModule: RenderModule = {
name: 'grid',
mount({ app, layers }) {
let sprite: TilingSprite | null = null
let texture: Texture | null = null
let sceneId: number | null = null
function build(scene: SceneInfo): void {
const cell = Math.max(4, Math.round(scene.grid_size || scene.tile_size || 32))
texture = gridTexture(cell)
sprite = new TilingSprite({ texture, width: scene.w, height: scene.h })
sprite.label = 'grid'
layers.grid.addChild(sprite)
sceneId = scene.id
}
function sync(): void {
const { scene, grid } = viewport.state
if (!scene) {
if (sprite) sprite.visible = false
return
}
if (scene.id !== sceneId) {
destroy()
build(scene)
}
if (sprite) sprite.visible = grid
app.canvas.dataset['grid'] = grid ? 'on' : 'off'
}
function destroy(): void {
sprite?.destroy()
sprite = null
texture?.destroy(true)
texture = null
sceneId = null
}
const unsubscribe = viewport.subscribe(sync)
sync()
return () => {
unsubscribe()
destroy()
}
},
}
+16
View File
@@ -0,0 +1,16 @@
// Mounts the lists panel under the shell's `#panels` host when the stage comes up (T8, #71). A
// render module rather than a `main.ts` edit: the stage's lifetime is the live session's, so a
// panel cannot outlive a sign-in screen, and parallel tickets add their own panels without touching
// a shared registry.
import type { RenderModule } from '../stage.ts'
import { mountListsPanel } from '../../panels/lists.ts'
export const renderModule: RenderModule = {
name: 'lists',
mount({ store }): (() => void) | void {
const host = document.querySelector<HTMLElement>('#panels')
if (!host) return
return mountListsPanel(host, store)
},
}
+69
View File
@@ -0,0 +1,69 @@
// The opt-in perf overlay (#82): fps, frame p50/p95, JS/render p50/p95, token count and zoom.
// Mounted only when the URL says `?perf=1` (client/src/perf.ts). Off means no DOM node, no ticker
// listener and no per-frame work.
//
// Timing comes from the real Pixi ticker, not a second rAF loop: a listener at INTERACTION runs
// first in the frame and one at UTILITY runs after the render plugin (registered at LOW), so the
// difference is the frame's main-thread JS + render submission time. `ticker.elapsedMS` is the raw
// frame interval (not speed-scaled), which is what the phone's fps readout needs.
import { UPDATE_PRIORITY } from 'pixi.js'
import type { Ticker } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import { viewport } from '../../viewport.ts'
import { adminTokens } from '../../slices/admin.ts'
import { tokensOf } from '../../slices/tokens.ts'
import { formatSnapshot, PerfWindow, perfEnabled } from '../../perf.ts'
const UPDATE_EVERY_MS = 1000
export const renderModule: RenderModule = {
name: 'perf',
mount({ app, store }) {
if (!perfEnabled(window.location.search)) return
const node = document.createElement('div')
node.id = 'perf'
node.setAttribute('role', 'status')
node.setAttribute('aria-live', 'off')
node.style.cssText =
'position:fixed;top:40px;right:12px;z-index:3;padding:6px 10px;border-radius:6px;' +
'border:1px solid #777;background:rgb(0 0 0 / 80%);color:#eee;font:11px/1.5 ' +
'ui-monospace,monospace;pointer-events:none;white-space:nowrap'
node.textContent = 'perf: warming up…'
const host = document.querySelector('#panels') ?? document.body
host.append(node)
const windowStats = new PerfWindow(10_000)
let frameStart = 0
let started = false
let lastUpdate = 0
const begin = (): void => {
frameStart = performance.now()
}
const end = (ticker: Ticker): void => {
const now = performance.now()
if (started && frameStart > 0) windowStats.add(ticker.elapsedMS, now - frameStart, now)
started = true
if (lastUpdate === 0) lastUpdate = now
if (now - lastUpdate < UPDATE_EVERY_MS) return
lastUpdate = now
const snapshot = windowStats.snapshot(now)
const visible = tokensOf(store.state).length
// A player only ever receives tokens in sight, so its total is what it knows. The GM sees
// the whole table in the admin slice, which is the meaningful total there.
const total = store.state.session.role === 'gm' ? adminTokens(store.state).length : visible
node.textContent = formatSnapshot(snapshot, visible, total, viewport.state.camera.zoom)
}
app.ticker.add(begin, undefined, UPDATE_PRIORITY.INTERACTION)
app.ticker.add(end, undefined, UPDATE_PRIORITY.UTILITY)
return () => {
app.ticker.remove(begin)
app.ticker.remove(end)
node.remove()
}
},
}
+216
View File
@@ -0,0 +1,216 @@
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12; #86 tile loading).
//
// Only the viewport plus one tile of margin is requested, nearest the viewport centre first,
// through the TileScheduler's queue. The decoded textures live in a module-level cache keyed by
// URL, so a reconnect (which keeps the stage and only resets the reducer slices) never refetches a
// tile; a new `art_version` changes every URL, so its textures are dropped and refetched.
//
// A `403` from the server is the gate saying "not yours": it is remembered as denied and never
// retried *while its cells stay unexplored*. When the fog slice reports newly explored cells (#70)
// the gate's answer for those tiles changed, so exactly those denied tiles are asked once more.
// A `404`/`5xx`/network failure is transient: the scheduler retries it a bounded number of times
// with backoff, and a reconnect retries every stored failure once more.
//
// The settle path is incremental: a tile that arrives only creates its sprite (or nothing, if the
// window moved on) and updates the readiness flag. Rebuilding the whole wanted list on every
// settle was O(window) per tile — tens of thousands squared while a GM survey view fills.
//
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
// `data-tile-requests` (how many fetches this page ever made) and `data-tile-distinct` (how many
// distinct tile URLs it fetched; the #70 re-ask after newly explored cells is a second request for
// the same URL, so requests may be larger). `ready` means this pass is complete:
// every wanted tile has a terminal answer (`ok`, `denied`, or a stored transient `error` that waits
// for a new window or a reconnect). A stored `error` must not keep `ready` away, or one host hiccup
// would hang the tile-size gate (a) and every e2e readiness wait.
import { Sprite, Texture } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import { viewport, visibleTiles, orderTilesCentreOut } from '../../viewport.ts'
import type { VisibleTile } from '../../viewport.ts'
import { TileScheduler, tilesForCells, tilesInvalidated } from '../../tiles.ts'
import type { TileLoadResult } from '../../tiles.ts'
import { fogOf } from '../../slices/fog.ts'
/** Kept across a reconnect (and even a stage rebuild): URL -> decoded texture. */
const textureCache = new Map<string, Texture>()
/** Fetches made by this page; the cache-survives-reconnect proof reads it. */
let requests = 0
/** Distinct tile URLs fetched. A #70 retry after newly explored cells asks the same URL again, so
* `requests` may exceed this; a duplicate *tile* would not. */
const requestedUrls = new Set<string>()
/**
* One request per tile. `fetch` is used instead of an `<img>` because an image error carries no
* status: asking again with `fetch` to tell 403 from 404 doubled the cost of *every* failure. The
* response is decoded off the main thread by `createImageBitmap`, so the JS path never holds the
* image bytes.
*/
async function fetchTile(url: string): Promise<TileLoadResult> {
requests += 1
requestedUrls.add(url)
let response: Response
try {
response = await fetch(url, { credentials: 'same-origin' })
} catch {
return 'error'
}
if (response.status === 403) return 'denied'
if (!response.ok) return 'error'
try {
const bitmap = await createImageBitmap(await response.blob())
textureCache.set(url, Texture.from(bitmap))
return 'ok'
} catch {
return 'error'
}
}
function clearTextureCache(): void {
for (const texture of textureCache.values()) texture.destroy(true)
textureCache.clear()
}
export const renderModule: RenderModule = {
name: 'tiles',
mount({ app, layers, store }) {
const canvas = app.canvas
const sprites = new Map<string, Sprite>()
/** The current window: url -> tile, so a settle can place its sprite without a rebuild. */
let wanted = new Map<string, VisibleTile>()
/** Wanted urls that have not settled yet this pass; `ready` is `pending.size === 0`. */
let pending = new Set<string>()
let frame = 0
canvas.dataset['tileRequests'] = String(requests)
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
const scheduler = new TileScheduler({
load: fetchTile,
onSettled: settle,
})
function scheduleSync(): void {
if (frame !== 0) return
frame = requestAnimationFrame(() => {
frame = 0
sync()
})
}
function setTilesFlag(): void {
canvas.dataset['tiles'] = wanted.size === 0 ? 'idle' : pending.size > 0 ? 'loading' : 'ready'
canvas.dataset['tileRequests'] = String(requests)
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
canvas.dataset['visibleTiles'] = String(wanted.size)
}
function addSprite(tile: VisibleTile, texture: Texture, tileSize: number): void {
const sprite = new Sprite(texture)
sprite.position.set(tile.x * tileSize, tile.y * tileSize)
sprite.width = tileSize
sprite.height = tileSize
layers.tiles.addChild(sprite)
sprites.set(tile.url, sprite)
}
/** A tile settled: touch only that tile. Runs once per request, not once per window. */
function settle(url: string, result: TileLoadResult): void {
if (result === 'ok') {
const tile = wanted.get(url)
const texture = textureCache.get(url)
const scene = viewport.state.scene
if (tile && texture && scene && !sprites.has(url)) addSprite(tile, texture, scene.tile_size)
}
pending.delete(url)
setTilesFlag()
}
/** The viewport changed (pan/zoom/resize/reconnect): rebuild the window and diff it. */
function sync(): void {
const { scene, camera, size } = viewport.state
if (!scene) {
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
wanted = new Map()
pending = new Set()
canvas.dataset['tiles'] = 'idle'
return
}
const visible = orderTilesCentreOut(visibleTiles(scene, camera, size), scene, camera, size)
const next = new Map(visible.map(tile => [tile.url, tile]))
for (const [url, sprite] of sprites) {
if (next.has(url)) continue
// Left the window (possibly before its bytes arrived): drop it, and let the scheduler
// cancel it if it was only queued.
sprite.destroy()
sprites.delete(url)
}
for (const tile of visible) {
const texture = textureCache.get(tile.url)
if (!texture) continue
scheduler.markLoaded(tile.url)
if (!sprites.has(tile.url)) addSprite(tile, texture, scene.tile_size)
}
wanted = next
scheduler.setDesired(visible.map(tile => tile.url))
pending = new Set()
for (const tile of visible) {
const status = scheduler.status(tile.url)
if (status === undefined || status === 'queued' || status === 'loading') pending.add(tile.url)
}
setTilesFlag()
}
const unsubscribe = viewport.subscribe(scheduleSync)
let lastExplored = -1
let lastScene: { id: number; art_version: number } | null = null
const unsubscribeStore = store.subscribe((state, event) => {
// Newly explored cells can flip a tile's `403` to an allowed tile (#70): retry exactly the
// denied tiles the new cells touch, once. An unexplored 403 stays denied (no retry loop).
const fog = fogOf(state)
if (fog.exploredVersion !== lastExplored) {
lastExplored = fog.exploredVersion
const scene = viewport.state.scene
if (fog.fresh.length > 0 && scene) {
scheduler.retryDenied(tilesForCells(scene, fog, fog.fresh))
scheduleSync()
}
}
// New art is new URLs (`v<art_version>`), so every cached texture and scheduling decision is
// stale. Drop them and refetch the window. A same-version hello (reconnect) keeps the cache.
const scene = state.session.scene
if (scene) {
if (tilesInvalidated(lastScene, scene)) {
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
clearTextureCache()
scheduler.reset()
}
lastScene = { id: scene.id, art_version: scene.art_version }
}
// (No branch for `scene === null`: a reconnect's `connecting` reset clears the session, and
// keeping the last known scene lets a re-import that happened during the reconnect still drop
// the old textures when the new `hello` lands.)
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
if (event.type === 'frame' && event.frame.t === 'hello') {
scheduler.retryFailed()
scheduleSync()
}
})
scheduleSync()
return () => {
unsubscribe()
unsubscribeStore()
scheduler.dispose()
if (frame !== 0) cancelAnimationFrame(frame)
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
}
},
}
+347
View File
@@ -0,0 +1,347 @@
// The token layer (T8, #71; DESIGN 7.1 layer 3, 6.1 `token`/`token_gone`).
//
// Pooled containers in world coordinates on the `tokens` layer: the camera (#69) transforms the
// layer's parent, never the tokens, so pan/zoom composes without this module knowing about it.
// A name is a `BitmapText` from one pre-installed `BitmapFont` (DESIGN 7.2, Q17): atlased once, and
// the text is re-assigned only when the name actually changed, never per frame. Statuses are drawn
// as badges (story 30): a barred ring for `stuck`, inward brackets for `squeezed`.
//
// Everything here is driven by TokenBoard patches, so one changed token touches one container and
// the untouched ones are not visited (DESIGN 7.2). The counts are published on the canvas dataset
// so the browser e2e can prove that rule against the real server (`data-token-updated` etc).
import { BitmapFont, BitmapText, Container, Graphics, GraphicsContext } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import type { RootState } from '../../reducer.ts'
import type { Vec2 } from '../../protocol.ts'
import { TokenBoard } from '../tokenBoard.ts'
import type { TokenPatch } from '../tokenBoard.ts'
import { drawPositionOf, moveOf, rollbacksOf } from '../../slices/move.ts'
import type { RollbackTween } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
import type { TokenView } from '../../slices/tokens.ts'
/** One font for every token label: Latin (incl. accented) and the ASCII the names use. */
const TOKEN_FONT = 'fff-token-label'
const LABEL_SIZE = 16
const GLYPHS: Array<string | [string, string]> = [
[' ', '~'],
['\u00A0', '\u00FF'],
['\u0100', '\u017F'],
'×·—–’‘“”…€£¥°',
]
let fontInstalled = false
function installFont(): void {
if (fontInstalled) return
fontInstalled = true
BitmapFont.install({
name: TOKEN_FONT,
style: {
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: LABEL_SIZE,
fill: 0xffffff,
stroke: { color: 0x000000, width: 3 },
},
chars: GLYPHS,
})
}
/**
* Shared unit-circle contexts, tessellated once and scaled to each token's radius (DESIGN 7.2:
* one GraphicsContext per colour, never one Graphics per token per frame).
*/
const BODY_STYLES = {
mine: new GraphicsContext()
.circle(0, 0, 1)
.fill(0xe8bf4f)
.stroke({ width: 0.09, color: 0xfff3c4 }),
other: new GraphicsContext()
.circle(0, 0, 1)
.fill(0x4f7fbf)
.stroke({ width: 0.09, color: 0xc7dcff }),
gmOnly: new GraphicsContext()
.circle(0, 0, 1)
.fill(0x6d4f86)
.stroke({ width: 0.09, color: 0xc9a5e0 }),
} as const
interface TokenNode {
container: Container
body: Graphics
label: BitmapText
badges: Graphics
/** What this node currently shows, so a patch can skip work that would change nothing. */
shape: 'mine' | 'other' | 'gmOnly' | null
statusKey: string
}
function createNode(radius: number): TokenNode {
const container = new Container()
const body = new Graphics()
const label = new BitmapText({
text: '',
style: { fontFamily: TOKEN_FONT, fontSize: LABEL_SIZE },
roundPixels: true,
})
label.anchor.set(0.5, 0)
label.y = radius + 2
const badges = new Graphics()
badges.visible = false
container.addChild(body, label, badges)
return { container, body, label, badges, shape: null, statusKey: '' }
}
function shapeOf(view: TokenView): 'mine' | 'other' | 'gmOnly' {
if (view.gmOnly) return 'gmOnly'
return view.mine ? 'mine' : 'other'
}
/** The badge glyphs. Two statuses stack; a cause is never drawn (players do not know it, 5.5). */
function drawBadges(graphics: Graphics, radius: number, statuses: readonly string[]): void {
graphics.clear()
if (statuses.length === 0) {
graphics.visible = false
return
}
graphics.visible = true
const size = Math.max(6, Math.min(12, radius * 0.42))
const x = radius * 0.62
let y = -radius * 0.62
for (const status of statuses) {
if (status === 'stuck') {
// A barred ring: the token is held in place.
graphics.circle(x, y, size).fill(0x2a0505).stroke({ width: 2, color: 0xff4d4d })
graphics
.moveTo(x - size * 0.62, y + size * 0.62)
.lineTo(x + size * 0.62, y - size * 0.62)
.stroke({ width: 2, color: 0xff4d4d })
} else if (status === 'squeezed') {
// Two arrows pressing inward: the token has no room.
const half = size * 0.55
graphics.circle(x, y, size).fill(0x2a1a02).stroke({ width: 2, color: 0xffb02e })
graphics
.moveTo(x - half, y)
.lineTo(x - half * 0.2, y)
.moveTo(x + half, y)
.lineTo(x + half * 0.2, y)
.stroke({ width: 2, color: 0xffb02e })
} else {
// A status this client has no badge for still shows that something is wrong.
graphics.circle(x, y, size).fill(0x222222).stroke({ width: 2, color: 0xcccccc })
}
y += size * 2.3
}
}
/**
* Draw one token. `at` is the position to draw at; it is the server's `pos` today, and the drag
* module (#72) passes its optimistic position here while a drag is in flight, so prediction and
* rollback never touch the reducer's authoritative view.
*/
function applyView(
node: TokenNode,
view: TokenView,
stats: { labels: number },
at: readonly [number, number] = view.pos,
): void {
const container = node.container
container.position.set(at[0], at[1])
container.alpha = view.gmOnly ? 0.72 : 1
const shape = shapeOf(view)
if (shape !== node.shape) {
node.body.context = BODY_STYLES[shape]
node.shape = shape
}
// A unit circle scaled to the effective radius: one shared context for every token of a kind.
node.body.scale.set(view.radius)
node.body.visible = true
// The label is built once per name: assigning `text` re-lays out quads, so only do it on a change.
if (node.label.text !== view.name) {
node.label.text = view.name
stats.labels += 1
}
node.label.y = view.radius + 2
// Badge size and place follow the radius, so a resize redraws them too.
const statusKey = `${view.radius}:${view.statuses.join(' ')}`
if (statusKey !== node.statusKey) {
drawBadges(node.badges, view.radius, view.statuses)
node.statusKey = statusKey
}
}
/** Publish the renderer's own counts, so the e2e can observe "only changed entities touched". */
function publish(
canvas: HTMLCanvasElement,
board: TokenBoard,
patch: TokenPatch,
labels: number,
state: RootState,
nodes: ReadonlyMap<string, TokenNode>,
): void {
const datasets = canvas.dataset
datasets['tokens'] = String(board.size)
datasets['tokenEntered'] = String(patch.entered.length)
datasets['tokenUpdated'] = String(patch.updated.length)
datasets['tokenLeft'] = String(patch.left.length)
datasets['tokenLabels'] = String(labels)
datasets['tokenIds'] = [...board.views.keys()].join(' ')
datasets['tokenStatuses'] = [...board.views.values()]
.flatMap(view => view.statuses.map(status => `${view.id}:${status}`))
.join(' ')
// The drag renderer's instrumentation (#72): the drawn position (so the e2e reads what the
// browser shows, not what the reducer predicts) plus the move state machine's counters.
datasets['tokenPositions'] = [...nodes.entries()]
.map(([id, node]) => `${id}:${Math.round(node.container.x)},${Math.round(node.container.y)}`)
.join(' ')
const move = moveOf(state)
datasets['dragId'] = move.drag?.id ?? ''
datasets['dragPos'] = move.drag
? `${Math.round(move.drag.pos[0])},${Math.round(move.drag.pos[1])}`
: ''
datasets['dragPhase'] = move.drag !== null ? 'drag' : Object.keys(move.rollbacks).length > 0 ? 'rollback' : ''
datasets['dragPending'] = String(move.pending.length)
datasets['dragRefused'] = String(move.refused)
datasets['dragRateLimited'] = String(move.rateLimited)
datasets['dragRollbacks'] = String(move.rollbackCount)
datasets['dragDropped'] = String(move.dropped)
}
/** Cosmetic rollback tween (DESIGN 7.5: a short slide back, never a teleport). */
const ROLLBACK_MS = 280
interface ActiveTween {
rb: RollbackTween
from: Vec2
started: number
}
export const renderModule: RenderModule = {
name: 'tokens',
mount(context: RenderContext): (() => void) | void {
installFont()
const { store, app, layers } = context
const canvas = app.canvas
const board = new TokenBoard()
const pool: TokenNode[] = []
const nodes = new Map<string, TokenNode>()
const stats = { labels: 0 }
/** At most one cosmetic rollback per token; keyed by token id, replaced on a newer sequence. */
const tweens = new Map<string, ActiveTween>()
function removeNode(id: string): void {
const node = nodes.get(id)
if (!node) return
tweens.delete(id)
layers.tokens.removeChild(node.container)
node.container.visible = false
nodes.delete(id)
pool.push(node)
}
function atFor(state: RootState, view: TokenView, node: TokenNode): Vec2 {
// A rollback tween owns the sprite position while it runs; a drag/pending prediction owns it
// otherwise (7.5); with neither, the authoritative `token` frame is the truth.
if (tweens.has(view.id)) return [node.container.x, node.container.y]
return drawPositionOf(state, view.id) ?? view.pos
}
function enterNode(view: TokenView, state: RootState): void {
const node = pool.pop() ?? createNode(view.radius)
node.container.visible = true
applyView(node, view, stats, atFor(state, view, node))
layers.tokens.addChild(node.container)
nodes.set(view.id, node)
}
/**
* Apply the reducer's drag/rollback state to the sprites. Touches only a dragged token and the
* tokens with a pending tween, so a pointer move never walks the whole scene (DESIGN 7.2).
*/
function applyMovement(state: RootState, now: number): void {
const move = moveOf(state)
if (move.drag) {
const node = nodes.get(move.drag.id)
if (node) {
tweens.delete(move.drag.id)
node.container.position.set(move.drag.pos[0], move.drag.pos[1])
}
}
const active = rollbacksOf(state)
const current = new Set<string>()
for (const rb of active) {
current.add(rb.id)
const node = nodes.get(rb.id)
if (!node) continue
const existing = tweens.get(rb.id)
if (existing?.rb.seq === rb.seq) continue
tweens.set(rb.id, {
rb,
from: [node.container.x, node.container.y],
started: now,
})
}
// A tween the reducer no longer knows about (a new drag, a reset) is done.
for (const id of [...tweens.keys()]) {
if (!current.has(id) || !nodes.has(id)) tweens.delete(id)
}
}
function tick(): void {
if (tweens.size === 0) return
const now = performance.now()
for (const [id, tween] of tweens) {
const node = nodes.get(id)
if (!node) {
tweens.delete(id)
continue
}
const t = Math.min(1, (now - tween.started) / ROLLBACK_MS)
const eased = 1 - (1 - t) * (1 - t) * (1 - t) // ease-out cubic
node.container.position.set(
tween.from[0] + (tween.rb.to[0] - tween.from[0]) * eased,
tween.from[1] + (tween.rb.to[1] - tween.from[1]) * eased,
)
if (t >= 1) {
tweens.delete(id)
store.dispatch({ type: 'rollback-done', id, seq: tween.rb.seq })
}
}
publish(canvas, board, { reset: false, entered: [], updated: [], left: [] }, stats.labels, store.state, nodes)
}
// The stage is created only once the session is live, but `app.init` is async and the resync
// can beat it: start from whatever the reducer already holds, then follow the event stream.
board.seed(tokensOf(store.state))
let patch = board.drain()
for (const view of patch.entered) enterNode(view, store.state)
publish(canvas, board, patch, stats.labels, store.state, nodes)
app.ticker.add(tick)
const unsubscribe = store.subscribe((state, event) => {
board.apply(event)
patch = board.drain()
if (patch.reset) {
for (const id of [...nodes.keys()]) removeNode(id)
}
for (const id of patch.left) removeNode(id)
for (const view of patch.updated) {
const node = nodes.get(view.id)
if (node) applyView(node, view, stats, atFor(state, view, node))
else enterNode(view, state)
}
for (const view of patch.entered) enterNode(view, state)
applyMovement(state, performance.now())
publish(canvas, board, patch, stats.labels, state, nodes)
})
return () => {
unsubscribe()
app.ticker.remove(tick)
}
},
}
+325
View File
@@ -0,0 +1,325 @@
// GM wall layer and editor input (T10, #73; DESIGN 5.8, 7.4, 7.2). Walls are GM-only, so this module
// draws into the `gm` layer and arms nothing for a player session. It is the Pixi half of the
// editor: the panel (`src/panels/walls.ts`) owns the armed preset and sends the intents, the slice
// (`src/slices/walls.ts`) owns the server's records, and `src/wallEditor.ts` owns the pure rules.
//
// Input precedence (the thing #73 must not break):
// 1. token drag (#72) wins first: its window-capture `pointerdown` runs before this module's and
// stops immediate propagation when the press lands on a token the session may move;
// 2. wall drawing wins next, but only while a preset is armed: the two clicks are consumed and the
// camera never starts a pan;
// 3. otherwise the camera (#69) keeps pan/pinch, and a click (no movement) selects the wall under
// the pointer. A drag that moved more than a few pixels is a pan, not a selection.
// The e2e arms a preset and starts a drag on a token to prove rule 1 still wins.
//
// A one-way wall's arrow points from the seeing side toward the blind side (`sight_dir` names the
// blind side, GLOSSARY "Blind side"): `arrowVector` is the one place that direction is computed.
import { Container, Graphics } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import { dragOf } from '../../slices/move.ts'
import type { WallView } from '../../slices/walls.ts'
import { selectedWallId, undoOf, wallsOf } from '../../slices/walls.ts'
import { arrowVector, distanceToSegment, wallMidpoint } from '../../wallEditor.ts'
import type { Vec2 } from '../../protocol.ts'
import { mountWallPanel } from '../../panels/walls.ts'
const COLORS: Record<string, number> = {
wall: 0xb8c4d0,
door: 0xd19a51,
window: 0x54c7c9,
one_way: 0xb989e0,
custom: 0xd8d8d8,
}
interface WallNode {
container: Container
graphics: Graphics
sig: string
}
function wallSignature(wall: WallView, selected: boolean): string {
const s = wall.switches
return [
wall.id,
wall.a.join(','),
wall.b.join(','),
wall.kind,
s.blocksSight ? 1 : 0,
s.blocksMovement ? 1 : 0,
s.sightDir,
s.playerMarker ? 1 : 0,
s.door ? 1 : 0,
s.open ? 1 : 0,
s.secret ? 1 : 0,
s.locked ? 1 : 0,
selected ? 1 : 0,
].join('|')
}
/** A dashed/dotted stroke, used for an open door (nothing is there) and a secret door (GM view). */
function dashedLine(
graphics: Graphics,
a: Vec2,
b: Vec2,
width: number,
color: number,
dash: number,
gap: number,
alpha: number,
): void {
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const length = Math.hypot(dx, dy)
if (!(length > 0)) return
const ux = dx / length
const uy = dy / length
for (let start = 0; start < length; start += dash + gap) {
const end = Math.min(length, start + dash)
graphics
.moveTo(a[0] + ux * start, a[1] + uy * start)
.lineTo(a[0] + ux * end, a[1] + uy * end)
.stroke({ width, color, alpha })
}
}
function drawWall(graphics: Graphics, wall: WallView, selected: boolean): void {
graphics.clear()
const a = wall.a
const b = wall.b
const color = COLORS[wall.kind] ?? COLORS['custom']!
const width = selected ? 6 : 4
const alpha = selected ? 1 : 0.85
const open = wall.switches.door && wall.switches.open
if (selected) {
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width: width + 6, color: 0x7ee787, alpha: 0.25 })
}
if (open) {
// An open door leaves a gap; the schema keeps the record, the GM sees where it was.
dashedLine(graphics, a, b, width, color, 8, 8, 0.55)
} else if (wall.switches.secret) {
dashedLine(graphics, a, b, width, color, 3, 5, alpha)
} else {
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width, color, alpha })
}
// Endpoint handles while selected: the two authoring points, never moved in round 1.
if (selected) {
for (const point of [a, b]) {
graphics.circle(point[0], point[1], 5).fill(0x0b0b0d).stroke({ width: 2, color: 0x7ee787 })
}
}
// Story 50: the one-way arrow at the wall's middle, toward the blind side.
const direction = arrowVector(a, b, wall.switches.sightDir)
if (direction) {
const [mx, my] = wallMidpoint(a, b)
const tip: Vec2 = [mx + direction[0] * 22, my + direction[1] * 22]
const back: Vec2 = [mx - direction[0] * 8, my - direction[1] * 8]
const px = -direction[1]
const py = direction[0]
graphics
.moveTo(back[0], back[1])
.lineTo(tip[0], tip[1])
.stroke({ width: 3, color: 0xfff3c4, alpha: 0.95 })
graphics
.moveTo(tip[0], tip[1])
.lineTo(tip[0] - direction[0] * 9 + px * 6, tip[1] - direction[1] * 9 + py * 6)
.lineTo(tip[0] - direction[0] * 9 - px * 6, tip[1] - direction[1] * 9 - py * 6)
.closePath()
.fill(0xfff3c4)
}
// Story 48: the GM sees the marker switch. A marked window is the only wall a player learns about.
if (wall.switches.playerMarker) {
const [mx, my] = wallMidpoint(a, b)
if (wall.kind === 'window') {
graphics.circle(mx, my, 6).fill(0xffcc33).stroke({ width: 2, color: 0x2b1d00 })
} else {
graphics.circle(mx, my, 5).stroke({ width: 2, color: 0xffcc33, alpha: 0.7 })
}
}
}
export const renderModule: RenderModule = {
name: 'walls',
mount({ app, layers, store }: RenderContext): () => void {
const canvas = app.canvas
const host = document.querySelector<HTMLElement>('#panels')
const panel = host ? mountWallPanel(host, event => store.dispatch(event)) : null
const container = new Container()
layers.gm.addChild(container)
const preview = new Graphics()
container.addChild(preview)
const nodes = new Map<number, WallNode>()
let hover: Vec2 | null = null
let down: { x: number; y: number; pointerId: number } | null = null
function worldOf(event: PointerEvent): Vec2 {
const rect = canvas.getBoundingClientRect()
const local = layers.gm.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
return [local.x, local.y]
}
function zoom(): number {
const scale = Math.abs(layers.gm.worldTransform.a)
return scale > 0 ? scale : 1
}
function drawPreview(): void {
preview.clear()
if (!panel?.armed || panel.first === null) return
const a = panel.first
const b = hover ?? a
preview
.moveTo(a[0], a[1])
.lineTo(b[0], b[1])
.stroke({ width: 2, color: 0x7ee787, alpha: 0.8 })
preview.circle(a[0], a[1], 4).fill(0x7ee787)
preview.circle(b[0], b[1], 3).stroke({ width: 2, color: 0x7ee787 })
}
function renderWalls(): void {
const state = store.state
const selected = selectedWallId(state)
const walls = wallsOf(state)
const seen = new Set<number>()
for (const wall of walls) {
seen.add(wall.id)
const sig = wallSignature(wall, wall.id === selected)
let node = nodes.get(wall.id)
if (!node) {
const graphics = new Graphics()
const wallContainer = new Container()
wallContainer.addChild(graphics)
container.addChild(wallContainer)
node = { container: wallContainer, graphics, sig: '' }
nodes.set(wall.id, node)
}
if (node.sig !== sig) {
drawWall(node.graphics, wall, wall.id === selected)
node.sig = sig
}
}
for (const [id, node] of nodes) {
if (seen.has(id)) continue
container.removeChild(node.container)
node.container.destroy({ children: true })
nodes.delete(id)
}
}
function publish(): void {
const state = store.state
const walls = wallsOf(state)
const selected = selectedWallId(state)
const dataset = canvas.dataset
dataset['walls'] = String(walls.length)
dataset['wallKinds'] = walls.map(wall => `${wall.id}:${wall.kind}`).join(' ')
dataset['wallSelected'] = selected === null ? '' : String(selected)
dataset['wallArrows'] = walls
.filter(wall => wall.switches.sightDir !== 'both')
.map(wall => `${wall.id}:${wall.switches.sightDir}`)
.join(' ')
dataset['wallMarkers'] = walls
.filter(wall => wall.switches.playerMarker)
.map(wall => String(wall.id))
.join(' ')
dataset['wallDraw'] = panel?.armed ? (panel.first === null ? 'first' : 'second') : 'off'
dataset['wallPreview'] = panel?.first ? panel.first.join(',') : ''
dataset['wallUndo'] = undoOf(state) === null ? 'no' : 'yes'
}
function sync(): void {
renderWalls()
drawPreview()
publish()
}
function onPointerDown(event: PointerEvent): void {
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
const state = store.state
if (state.connection.phase !== 'live' || state.session.role !== 'gm' || !panel) return
if (panel.armed) {
// Drawing takes precedence over pan: consume the gesture and feed the point.
event.preventDefault()
event.stopImmediatePropagation()
hover = worldOf(event)
panel.drawPoint(hover)
sync()
return
}
down = { x: event.clientX, y: event.clientY, pointerId: event.pointerId }
}
function onPointerMove(event: PointerEvent): void {
if (!panel?.armed) return
// A token drag owns its gesture (#72); do not paint a wall preview under it.
if (dragOf(store.state) !== null) return
if (!event.isPrimary) return
hover = worldOf(event)
drawPreview()
}
function onPointerUp(event: PointerEvent): void {
const start = down
down = null
if (!panel || panel.armed) return
if (!start || start.pointerId !== event.pointerId) return
if (event.target !== canvas) return
// A moved pointer was a pan (#69), not a click on a wall.
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) return
if (store.state.session.role !== 'gm') return
const point = worldOf(event)
const tolerance = 8 / zoom()
let hit: WallView | null = null
let best = tolerance
for (const wall of wallsOf(store.state)) {
const distance = distanceToSegment(point, wall.a, wall.b)
if (distance <= best) {
best = distance
hit = wall
}
}
store.dispatch({ type: 'wall-select', id: hit?.id ?? null })
}
function onCancel(): void {
down = null
}
function onKey(event: KeyboardEvent): void {
if (event.key !== 'Escape' || !panel?.armed) return
panel.cancelDraw()
hover = null
sync()
}
const unsubscribe = store.subscribe(() => {
panel?.render(store.state)
sync()
})
panel?.render(store.state)
sync()
window.addEventListener('pointerdown', onPointerDown, true)
window.addEventListener('pointermove', onPointerMove, true)
window.addEventListener('pointerup', onPointerUp, true)
window.addEventListener('pointercancel', onCancel, true)
window.addEventListener('blur', onCancel)
window.addEventListener('keydown', onKey)
return () => {
unsubscribe()
window.removeEventListener('pointerdown', onPointerDown, true)
window.removeEventListener('pointermove', onPointerMove, true)
window.removeEventListener('pointerup', onPointerUp, true)
window.removeEventListener('pointercancel', onCancel, true)
window.removeEventListener('blur', onCancel)
window.removeEventListener('keydown', onKey)
panel?.destroy()
}
},
}
+105
View File
@@ -0,0 +1,105 @@
// The Pixi stage (DESIGN 7.1): one Application, one world container under pan/zoom, fixed layers
// bottom to top. Render modules are append-only, exactly like reducer slices: every file in
// ./modules/ that exports `renderModule` is picked up by the glob, so a later ticket (tiles/grid
// T6, fog T7, tokens T8, walls T10, GM overlays) adds one file and touches no other module.
//
// Pixi is imported here (and in modules/) only. The reducer, the WS client and the DOM shell stay
// Pixi-free so their unit tests run without a GPU or a DOM.
import { Application, Container } from 'pixi.js'
import type { Store } from '../store.ts'
import { PROTO } from '../protocol.ts'
export interface RenderLayers {
tiles: Container
grid: Container
tokens: Container
fog: Container
gm: Container
dom: Container
}
export interface RenderContext {
app: Application
world: Container
layers: RenderLayers
store: Store
}
export interface RenderModule {
readonly name: string
/** Start drawing. Return a teardown for anything global the module installed. */
mount(context: RenderContext): void | (() => void)
}
interface ModuleExport {
renderModule: RenderModule
}
const modules = import.meta.glob<ModuleExport>('./modules/*.ts', { eager: true })
const RENDER_MODULES: readonly RenderModule[] = Object.keys(modules)
.sort()
.map(path => {
const module = modules[path]
if (!module || !module.renderModule) {
throw new Error(`render module ${path} has no \`renderModule\` export`)
}
return module.renderModule
})
const moduleNames = new Set(RENDER_MODULES.map(module => module.name))
if (moduleNames.size !== RENDER_MODULES.length) throw new Error('duplicate render module name')
export interface Stage {
readonly app: Application
readonly context: RenderContext
destroy(): void
}
/**
* Create the stage inside `host`. The caller creates it only when the session is live, so a
* visitor without a session never gets a canvas (story 1). `PROTO` is touched here so the build
* keeps the constant referenced even before an intent module exists.
*/
export async function createStage(host: HTMLElement, store: Store): Promise<Stage> {
const app = new Application()
await app.init({
resizeTo: window,
background: 0x000000,
antialias: true,
autoDensity: true,
resolution: Math.min(window.devicePixelRatio || 1, 2),
preference: 'webgl',
})
app.canvas.id = 'stage-canvas'
app.canvas.dataset['proto'] = String(PROTO)
host.replaceChildren(app.canvas)
const world = new Container()
const layers: RenderLayers = {
tiles: new Container(),
grid: new Container(),
tokens: new Container(),
fog: new Container(),
gm: new Container(),
dom: new Container(),
}
world.addChild(layers.tiles, layers.grid, layers.tokens, layers.fog, layers.gm, layers.dom)
app.stage.addChild(world)
// A v1 scene is large and the camera starts at the origin until T6 adds pan/zoom; scaling the
// world down is not a map feature, so the world simply sits under the camera transform.
const context: RenderContext = { app, world, layers, store }
const teardowns = RENDER_MODULES.map(module => module.mount(context))
return {
app,
context,
destroy() {
for (const teardown of teardowns) teardown?.()
app.destroy(true, { children: true })
host.replaceChildren()
},
}
}
+111
View File
@@ -0,0 +1,111 @@
// The token renderer's pure half (T8, #71). No Pixi import: it turns the store's event stream into
// the exact nodes a renderer must create, update or remove, so the "only changed entities" rule of
// DESIGN 7.2 is observable and unit-tested instead of hidden inside a WebGL module.
//
// It mirrors the token slice's parsing (one wire shape, one parser) but keeps its own view of what
// is currently on screen, which is what a renderer actually needs: a `token_gone` is only a removal
// if a node exists, and a `token` frame for an existing node is an update, not an entry.
import type { ReducerEvent } from '../reducer.ts'
import { isHello } from '../protocol.ts'
import type { TokenView } from '../slices/tokens.ts'
import { tokenViewFromFrame } from '../slices/tokens.ts'
export interface TokenPatch {
/** Everything on screen must go (a `hello` is a full reset, 6.3). */
reset: boolean
entered: TokenView[]
updated: TokenView[]
left: string[]
}
export class TokenBoard {
#views = new Map<string, TokenView>()
#reset = false
#entered = new Map<string, TokenView>()
#updated = new Map<string, TokenView>()
#left = new Set<string>()
get size(): number {
return this.#views.size
}
/** What is on screen now, in entry order. Read-only for the renderer's dataset/teardown. */
get views(): ReadonlyMap<string, TokenView> {
return this.#views
}
/**
* Start from the reducer's current view. The stage is created asynchronously, so the resync may
* have run before a render module mounts; without this a token that arrived during `app.init`
* would stay invisible until it changed. Every seeded token is an entry.
*/
seed(views: readonly TokenView[]): void {
this.#views.clear()
this.#entered.clear()
this.#updated.clear()
this.#left.clear()
this.#reset = false
for (const view of views) {
this.#views.set(view.id, view)
this.#entered.set(view.id, view)
}
}
/** Fold one store event into the pending patch. Nothing is drawn here. */
apply(event: ReducerEvent): void { if (event.type !== 'frame') return
const frame = event.frame
if (isHello(frame)) {
// A `hello` means "start clean" (6.3): the nodes all die, and anything still pending for the
// previous connection is dropped rather than replayed onto the new view.
this.#views.clear()
this.#entered.clear()
this.#updated.clear()
this.#left.clear()
this.#reset = true
return
}
if (frame.t === 'token') {
const view = tokenViewFromFrame(frame)
if (!view) return
const existing = this.#views.has(view.id)
this.#views.set(view.id, view)
if (existing) {
// A token that entered and changed between two drains is still one entry, drawn once.
if (this.#entered.has(view.id)) {
this.#entered.set(view.id, view)
return
}
this.#updated.set(view.id, view)
this.#left.delete(view.id)
} else {
this.#updated.delete(view.id)
this.#entered.set(view.id, view)
}
return
}
if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string' || !this.#views.has(id)) return
this.#views.delete(id)
this.#entered.delete(id)
this.#updated.delete(id)
this.#left.add(id)
}
}
/** Take the pending patch: the renderer touches exactly these entities, then waits. */
drain(): TokenPatch {
const patch: TokenPatch = {
reset: this.#reset,
entered: [...this.#entered.values()],
updated: [...this.#updated.values()],
left: [...this.#left],
}
this.#reset = false
this.#entered.clear()
this.#updated.clear()
this.#left.clear()
return patch
}
}
+290
View File
@@ -0,0 +1,290 @@
// The plain-DOM overlay (DESIGN 7.1 layer 6, spec #63 decision 15). No framework, no `innerHTML`:
// every server-supplied string goes through `textContent`, so a name can never become markup.
//
// The shell is the only module that owns page structure; later panels (roster/keys/tokens T11,
// characters/reveals T12) add their DOM under `#panels` or as their own file next to this one,
// never by rewriting the sign-in flow.
//
// T5 (#68) adds three things here: the first-sign-in name prompt (stories 5, 6), the connection
// badge (story 7) and the `reconnecting` screen state, which keeps the map (stale) on screen while
// the socket backs off instead of dropping the player to a fatal page.
import type { RootState } from './reducer.ts'
import { connectionBadge, rosterOf } from './reducer.ts'
import type { RosterEntry } from './protocol.ts'
export interface ShellHandlers {
onSubmitKey(key: string): void
onSubmitName(name: string): void
onReload(): void
}
export interface Shell {
render(state: RootState): void
setBusy(busy: boolean): void
setNameBusy(busy: boolean): void
/** The read-only zoom readout in the HUD (M4 dry-run: no visible zoom level otherwise). */
setZoom(zoom: number): void
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function rosterName(entry: RosterEntry): string {
return entry.name ?? '(unnamed)'
}
const BADGE_TEXT = {
connected: 'Connected',
reconnecting: 'Reconnecting…',
offline: 'Offline',
} as const
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
const stage = element('div', 'stage')
stage.hidden = true
const boot = element('section', 'boot')
const bootText = element('p', 'boot-text', 'Connecting…')
boot.append(bootText)
const signin = element('section', 'signin')
signin.hidden = true
const title = element('h1', 'signin-title', 'FFF VTT')
const notice = element('p', 'signin-notice')
notice.hidden = true
const form = element('form', 'signin-form')
const label = element('label', 'signin-label', 'Player or GM key')
label.htmlFor = 'key'
const input = element('input', 'key')
input.name = 'key'
input.type = 'text'
input.autocomplete = 'off'
input.autocapitalize = 'characters'
input.spellcheck = false
input.required = true
const submit = element('button', 'signin-submit', 'Sign in')
submit.type = 'submit'
form.append(label, input, submit)
const error = element('p', 'signin-error')
error.hidden = true
error.setAttribute('role', 'alert')
signin.append(title, notice, form, error)
// First-sign-in name prompt (stories 5, 6). Shown while a live session has `me.name === null`;
// the server sends no scene and no game data until the name is accepted (DESIGN 6.1/6.3).
const namePanel = element('section', 'name')
namePanel.hidden = true
const nameTitle = element('h1', 'name-title', 'Choose a display name')
const nameHint = element('p', 'name-hint', 'The rest of the table will see this name.')
const nameForm = element('form', 'name-form')
const nameLabel = element('label', 'name-label', 'Display name')
nameLabel.htmlFor = 'name-input'
const nameInput = element('input', 'name-input')
nameInput.name = 'name'
nameInput.type = 'text'
nameInput.autocomplete = 'off'
nameInput.autocapitalize = 'words'
nameInput.maxLength = 32
nameInput.spellcheck = false
nameInput.required = true
const nameSubmit = element('button', 'name-submit', 'Join the table')
nameSubmit.type = 'submit'
nameForm.append(nameLabel, nameInput, nameSubmit)
const nameError = element('p', 'name-error')
nameError.hidden = true
nameError.setAttribute('role', 'alert')
namePanel.append(nameTitle, nameHint, nameForm, nameError)
const hud = element('header', 'hud')
hud.hidden = true
const role = element('span', 'role')
const scene = element('span', 'scene')
const me = element('span', 'me')
const badge = element('span', 'badge', BADGE_TEXT.connected)
badge.dataset['state'] = 'connected'
const zoom = element('span', 'zoom')
const roster = element('ul', 'roster')
// One line: role, scene, own name, then the other players, then the connection state and zoom.
// The own roster row is omitted (see renderRoster): #me already names this connection.
hud.append(role, scene, me, roster, badge, zoom)
const fatal = element('section', 'fatal')
fatal.hidden = true
const fatalText = element('p', 'fatal-text')
const reload = element('button', 'reload', 'Reload')
reload.type = 'button'
reload.addEventListener('click', () => handlers.onReload())
fatal.append(fatalText, reload)
const panels = element('div', 'panels')
root.replaceChildren(stage, hud, signin, boot, namePanel, fatal, panels)
form.addEventListener('submit', event => {
event.preventDefault()
const key = input.value.trim()
if (key.length === 0) return
handlers.onSubmitKey(key)
})
nameForm.addEventListener('submit', event => {
event.preventDefault()
const name = nameInput.value.trim()
if (name.length === 0) return
handlers.onSubmitName(name)
})
let busy = false
let nameBusy = false
let prevPhase: string | null = null
function setBusy(next: boolean): void {
busy = next
submit.disabled = next
input.disabled = next
bootText.textContent = next ? 'Signing in…' : 'Connecting…'
if (next) showOnly(boot)
}
function setNameBusy(next: boolean): void {
nameBusy = next
nameInput.disabled = next
nameSubmit.disabled = next
nameSubmit.textContent = next ? 'Saving…' : 'Join the table'
}
function showOnly(active: HTMLElement): void {
for (const node of [boot, signin, hud, namePanel, fatal]) node.hidden = node !== active
}
function renderRoster(players: RosterEntry[], meId: number | null): void {
// A roster row for the connection itself duplicated the role/name line on a phone
// ("GM Scene GM Connected GM connected"); the HUD names the viewer once and lists the others.
const others = meId === null ? players : players.filter(entry => entry.id !== meId)
roster.replaceChildren(
...others.map(entry => {
const item = document.createElement('li')
item.dataset['player'] = String(entry.id)
const name = element('span', undefined, rosterName(entry))
name.className = 'roster-name'
const state = element('span', undefined, entry.connected ? 'connected' : 'offline')
state.className = 'roster-state'
item.append(name, state)
return item
}),
)
}
function renderBadge(state: RootState): void {
const current = connectionBadge(state)
badge.hidden = current === null
if (current === null) return
badge.dataset['state'] = current
badge.textContent = BADGE_TEXT[current]
const retry = state.connection.retryDelayMs
badge.title =
current === 'reconnecting' && retry !== null
? `Attempt ${state.connection.attempt}, retrying in ${(retry / 1000).toFixed(1)} s`
: current === 'offline'
? 'No connection. The map is not live.'
: 'The map is live.'
}
function clearHud(): void {
role.textContent = ''
scene.textContent = ''
me.textContent = ''
roster.replaceChildren()
}
function setZoom(value: number): void {
zoom.textContent = `zoom ${value.toFixed(2)}`
}
/** One row: role, scene, this connection's name (once), the other players, badge, zoom. */
function renderHudLine(state: RootState): void {
const roleText = state.session.role === 'gm' ? 'GM' : 'Player'
const name = state.session.me?.name ?? ''
role.textContent = roleText
scene.textContent = state.session.scene?.name ?? ''
me.textContent = name
// "GM … GM" and a player literally named "Player" would say the same thing twice.
me.hidden = name === '' || name === roleText
renderRoster(rosterOf(state), state.session.me?.id ?? null)
}
function render(state: RootState): void {
const phase = state.connection.phase
const phaseChanged = phase !== prevPhase
prevPhase = phase
notice.textContent = state.connection.notice ?? ''
notice.hidden = state.connection.notice === null
error.textContent = state.connection.error ?? ''
error.hidden = state.connection.error === null
stage.hidden = phase !== 'live' && phase !== 'reconnecting'
renderBadge(state)
// Leaving the game clears every server-derived DOM text, so a revoked session cannot leave a
// roster (or names) behind the sign-in page. A reconnect keeps the view: the badge says it is
// stale, and the resync after the next `hello` replaces it.
if (phase === 'signin' || phase === 'offline' || phase === 'reload' || phase === 'boot') {
clearHud()
setNameBusy(false)
}
switch (phase) {
case 'boot':
case 'connecting':
if (!busy) bootText.textContent = 'Connecting…'
showOnly(boot)
break
case 'signin':
busy = false
submit.disabled = false
input.disabled = false
showOnly(signin)
input.focus()
break
case 'live':
busy = false
if (state.session.role === 'player' && state.session.me !== null && state.session.me.name === null) {
// Stories 5/6: ask once, before any game data (the server sends no scene to a nameless
// player). `nameError` is the server's refusal text.
showOnly(namePanel)
nameError.textContent = state.connection.nameError ?? ''
nameError.hidden = state.connection.nameError === null
if (phaseChanged) nameInput.focus()
break
}
setNameBusy(false)
showOnly(hud)
renderHudLine(state)
break
case 'reconnecting':
// Keep the HUD (and the stale map) visible; only the badge changes.
showOnly(hud)
renderHudLine(state)
break
case 'reload':
showOnly(fatal)
fatalText.textContent = 'This client is out of date. Reload the page to get the matching version.'
break
case 'offline':
showOnly(fatal)
fatalText.textContent = state.connection.notice ?? 'Connection lost. Reload to reconnect.'
break
}
}
return { render, setBusy, setNameBusy, setZoom }
}
+158
View File
@@ -0,0 +1,158 @@
// GM admin slice (T11, #74): the GM-only token records the token panel edits, plus the one piece of
// selection state the panel owns. Append-only registration: adding this file was enough; the
// reducer's glob picked it up and `hello` resets it with every other slice.
//
// TOKEN SELECTION FOR #71/#72: the selected token id lives here, not in the panel, so the token
// renderer (#71) and the drag module (#72) can read it without importing the panel. Read it with
// `selectedTokenId(state)` and change it only by dispatching
// `{ type: 'admin-select', token: <id> | null }`. This slice never writes selection from a `token`
// frame; a `token_gone` for the selected id clears it.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame } from '../protocol.ts'
export interface AdminStatus {
status: string
/** GM frames carry the source (`walls`|`GM`); a player frame cannot reach this panel. */
source?: string
}
/** The GM's view of one token frame (DESIGN 6.1 `token`, GM columns). */
export interface AdminToken {
id: string
scene: number
name: string
pos: [number, number]
radius: number
/** GM-only fields; optional so a malformed frame is ignored rather than guessed. */
kind: string | null
controller: number | null
gmOnly: boolean
statuses: AdminStatus[]
descriptiveName: string | null
actualName: string | null
/** Free-form GM flags (DESIGN 8); the panel merges `vision` into this object on save. */
flags: Record<string, unknown>
visionRadius: number | null
radiusOwn: number | null
}
export interface AdminState {
tokens: AdminToken[]
/** Id of the token selected in the GM panel; `null` when nothing is selected. */
selectedToken: string | null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isVec2(value: unknown): value is [number, number] {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function finiteOrNull(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
function flagsObject(value: unknown): Record<string, unknown> {
return isRecord(value) ? { ...value } : {}
}
function parseStatuses(value: unknown): AdminStatus[] {
if (!Array.isArray(value)) return []
const out: AdminStatus[] = []
for (const entry of value) {
if (!isRecord(entry) || typeof entry['status'] !== 'string') continue
const source = entry['source']
out.push(
typeof source === 'string'
? { status: entry['status'], source }
: { status: entry['status'] },
)
}
return out
}
/** Read one GM `token` frame; `null` for a shape the panel cannot edit. */
export function tokenFromFrame(frame: ServerFrame): AdminToken | null {
const id = frame['id']
const scene = frame['scene']
const name = frame['name']
const pos = frame['pos']
const radius = frame['radius']
if (
typeof id !== 'string' ||
id.length === 0 ||
typeof scene !== 'number' ||
!Number.isInteger(scene) ||
typeof name !== 'string' ||
!isVec2(pos) ||
typeof radius !== 'number' ||
!Number.isFinite(radius)
) {
return null
}
return {
id,
scene,
name,
pos: [pos[0], pos[1]],
radius,
kind: typeof frame['kind'] === 'string' ? frame['kind'] : null,
controller: finiteOrNull(frame['controller']),
gmOnly: frame['gm_only'] === true,
statuses: parseStatuses(frame['statuses']),
descriptiveName:
typeof frame['descriptive_name'] === 'string' ? frame['descriptive_name'] : null,
actualName: typeof frame['actual_name'] === 'string' ? frame['actual_name'] : null,
flags: flagsObject(frame['flags']),
visionRadius: finiteOrNull(frame['vision_radius']),
radiusOwn: finiteOrNull(frame['radius_own']),
}
}
function upsert(state: AdminState, token: AdminToken): void {
const index = state.tokens.findIndex(entry => entry.id === token.id)
if (index >= 0) state.tokens[index] = token
else state.tokens.push(token)
}
export const slice: Slice<AdminState> = {
name: 'admin',
init: () => ({ tokens: [], selectedToken: null }),
reduce(state: AdminState, event: ReducerEvent, _root: RootState): void {
if (event.type === 'admin-select') {
state.selectedToken = event.token
return
}
if (event.type !== 'frame') return
const frame = event.frame
if (frame.t === 'token') {
const token = tokenFromFrame(frame)
if (token) upsert(state, token)
} else if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string') return
state.tokens = state.tokens.filter(token => token.id !== id)
if (state.selectedToken === id) state.selectedToken = null
}
},
}
/** The selected token id, owned by this slice for #71/#72 to read. */
export function selectedTokenId(state: RootState): string | null {
return (state.slices['admin'] as AdminState | undefined)?.selectedToken ?? null
}
/** The GM token records, in the order the server sent them. */
export function adminTokens(state: RootState): AdminToken[] {
return (state.slices['admin'] as AdminState | undefined)?.tokens ?? []
}
+171
View File
@@ -0,0 +1,171 @@
// GM cast slice (T12, #75): the character records, the per-player encountered lists and the GM-only
// who-sees-it field of `token` frames. Append-only registration: this file is enough; the reducer's
// glob picks it up and `hello` resets it with every other slice.
//
// This slice is deliberately separate from `slices/admin.ts` (#74, the token editor) so the two
// tickets stay file-disjoint. It only reads frames; the panel in `src/panels/gmcast.ts` sends the
// intents. `seen_by` is a GM-only additive field (DESIGN 6.1/7.4): a player frame never carries it,
// so a player session simply leaves the map empty.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame } from '../protocol.ts'
export interface CastCharacter {
id: string
/** The player who owns the character (the GM owns through its own player id). */
owner: number
descriptiveName: string
actualName: string
revealAll: boolean
/** Players the actual name was revealed to (8); never revoked. */
revealed: number[]
props?: Record<string, unknown>
}
export interface CastEncountered {
id: string
name: string
grey: boolean
}
export interface CastState {
characters: CastCharacter[]
/** playerId -> that player's encountered list, in the order the server sent it. */
encountered: Record<number, CastEncountered[]>
/** tokenId -> the players who see it (GM-only `seen_by`, 0/100 in M4). */
seenBy: Record<string, number[]>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function playerIds(value: unknown): number[] {
if (!Array.isArray(value)) return []
return value.filter(
(entry): entry is number => typeof entry === 'number' && Number.isInteger(entry),
)
}
/** Read one GM `character` frame; `null` for a shape the panel cannot show. */
export function characterFromFrame(frame: ServerFrame): CastCharacter | null {
const id = frame['id']
const owner = frame['owner']
const descriptiveName = frame['descriptive_name']
const actualName = frame['actual_name']
if (
typeof id !== 'string' ||
id.length === 0 ||
typeof owner !== 'number' ||
!Number.isInteger(owner) ||
typeof descriptiveName !== 'string' ||
typeof actualName !== 'string'
) {
return null
}
return {
id,
owner,
descriptiveName,
actualName,
revealAll: frame['reveal_all'] === true,
revealed: playerIds(frame['revealed']),
props: isRecord(frame['props']) ? frame['props'] : undefined,
}
}
function entries(value: unknown): CastEncountered[] | null {
if (!Array.isArray(value)) return null
const out: CastEncountered[] = []
for (const entry of value) {
if (!isRecord(entry) || typeof entry['id'] !== 'string' || typeof entry['name'] !== 'string') {
continue
}
out.push({ id: entry['id'], name: entry['name'], grey: entry['grey'] === true })
}
return out
}
function upsertCharacter(state: CastState, character: CastCharacter): void {
const index = state.characters.findIndex(entry => entry.id === character.id)
if (index >= 0) state.characters[index] = character
else state.characters.push(character)
}
function reduceEncountered(state: CastState, frame: ServerFrame): void {
const player = frame['player']
if (typeof player !== 'number' || !Number.isInteger(player)) return
const set = entries(frame['set'])
if (set === null) return
if (frame['full'] === true) {
state.encountered[player] = set
return
}
const current = state.encountered[player] ?? []
for (const entry of set) {
const index = current.findIndex(row => row.id === entry.id)
if (index >= 0) current[index] = entry
else current.push(entry)
}
const del = frame['del']
if (Array.isArray(del)) {
const gone = new Set(del.filter((id): id is string => typeof id === 'string'))
state.encountered[player] = current.filter(entry => !gone.has(entry.id))
} else {
state.encountered[player] = current
}
}
export const slice: Slice<CastState> = {
name: 'cast',
init: () => ({ characters: [], encountered: {}, seenBy: {} }),
reduce(state: CastState, event: ReducerEvent, _root: RootState): void {
if (event.type !== 'frame') return
const frame = event.frame
switch (frame.t) {
case 'character': {
const character = characterFromFrame(frame)
if (character) upsertCharacter(state, character)
return
}
case 'character_gone': {
const id = frame['id']
if (typeof id !== 'string') return
state.characters = state.characters.filter(entry => entry.id !== id)
return
}
case 'encountered':
reduceEncountered(state, frame)
return
case 'token': {
const id = frame['id']
if (typeof id !== 'string') return
const seen = frame['seen_by']
if (!Array.isArray(seen)) return
state.seenBy[id] = playerIds(seen)
return
}
case 'token_gone': {
const id = frame['id']
if (typeof id !== 'string') return
delete state.seenBy[id]
return
}
}
},
}
export function castCharacters(state: RootState): CastCharacter[] {
return (state.slices['cast'] as CastState | undefined)?.characters ?? []
}
export function encounteredOf(state: RootState, player: number): CastEncountered[] {
return (state.slices['cast'] as CastState | undefined)?.encountered[player] ?? []
}
/** The players who see a token, or `null` when no GM frame has carried it yet. */
export function seenByOf(state: RootState, token: string): number[] | null {
const map = (state.slices['cast'] as CastState | undefined)?.seenBy
const seen = map ? map[token] : undefined
return seen ?? null
}
+93
View File
@@ -0,0 +1,93 @@
// Characters slice (DESIGN 6.1 `character`/`character_gone`, story 31). The server sends a character
// record only to the GM and to the player who owns it, so a player's slice *is* that player's list;
// the GM's slice is the whole cast and the list panel filters it to the GM's own.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame } from '../protocol.ts'
export interface CharacterView {
id: string
/** Absent on the owner's own view (6.1); the GM's copy carries it. */
owner: number | null
descriptiveName: string
actualName: string
props: Record<string, Record<string, unknown>>
}
function own(record: Record<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
export interface CharactersState {
byId: Record<string, CharacterView>
order: string[]
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function propBuckets(value: unknown): Record<string, Record<string, unknown>> {
if (!isRecord(value)) return {}
const buckets: Record<string, Record<string, unknown>> = {}
for (const [bucket, contents] of Object.entries(value)) {
if (isRecord(contents)) buckets[bucket] = contents
}
return buckets
}
export function characterViewFromFrame(frame: ServerFrame): CharacterView | null {
const id = frame['id']
if (typeof id !== 'string' || id.length === 0) return null
if (typeof frame['descriptive_name'] !== 'string') return null
if (typeof frame['actual_name'] !== 'string') return null
const owner = frame['owner']
return {
id,
owner: typeof owner === 'number' && Number.isFinite(owner) ? owner : null,
descriptiveName: frame['descriptive_name'],
actualName: frame['actual_name'],
props: propBuckets(frame['props']),
}
}
export const slice: Slice<CharactersState> = {
name: 'characters',
init: () => ({ byId: {}, order: [] }),
reduce(state: CharactersState, event: ReducerEvent, _root: RootState): void {
if (event.type !== 'frame') return
const frame = event.frame
if (frame.t === 'character') {
const character = characterViewFromFrame(frame)
if (!character) return
if (own(state.byId, character.id) === undefined) state.order.push(character.id)
state.byId = { ...state.byId, [character.id]: character }
} else if (frame.t === 'character_gone') {
const id = frame['id']
if (typeof id !== 'string' || own(state.byId, id) === undefined) return
const byId = { ...state.byId }
delete byId[id]
state.byId = byId
state.order = state.order.filter(entry => entry !== id)
}
},
}
export function charactersOf(state: RootState): CharacterView[] {
const characters = state.slices['characters'] as CharactersState | undefined
if (!characters) return []
return characters.order
.map(id => characters.byId[id])
.filter((character): character is CharacterView => character !== undefined)
}
/** Story 31: the characters this player may call their own. */
export function ownCharactersOf(state: RootState): CharacterView[] {
const me = state.session.me
const characters = charactersOf(state)
// A player only ever receives their own records (6.1), so everything is theirs.
if (state.session.role !== 'gm') return characters
// The GM's copy of the whole cast carries `owner`; the list is the GM's own figures.
if (me === null) return []
return characters.filter(character => character.owner === me.id)
}
+73
View File
@@ -0,0 +1,73 @@
// Encountered slice (DESIGN 6.1 `encountered`, story 32). Per player: the figures that player has
// met, with `grey` marking one that is no longer in view ("met before, whereabouts unknown"). The GM
// receives one message per player; those are not the GM's own list and are ignored here.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame } from '../protocol.ts'
export interface EncounteredEntry {
id: string
name: string
grey: boolean
}
export interface EncounteredState {
entries: EncounteredEntry[]
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function entry(value: unknown): EncounteredEntry | null {
if (!isRecord(value)) return null
const id = value['id']
const name = value['name']
if (typeof id !== 'string' || typeof name !== 'string') return null
return { id, name, grey: value['grey'] === true }
}
function upsert(entries: EncounteredEntry[], next: EncounteredEntry): EncounteredEntry[] {
const index = entries.findIndex(existing => existing.id === next.id)
if (index < 0) return [...entries, next]
const copy = entries.slice()
copy[index] = next
return copy
}
export const slice: Slice<EncounteredState> = {
name: 'encountered',
init: () => ({ entries: [] }),
reduce(state: EncounteredState, event: ReducerEvent, root: RootState): void {
if (event.type !== 'frame') return
const frame: ServerFrame = event.frame
if (frame.t !== 'encountered') return
// The GM's copies carry `player` (6.1): one list per player, never the GM's own.
if (root.session.role === 'gm' || typeof frame['player'] === 'number') return
const set = frame['set']
if (!Array.isArray(set)) return
const incoming: EncounteredEntry[] = []
for (const item of set) {
const parsed = entry(item)
if (!parsed) return
incoming.push(parsed)
}
if (frame['full'] === true) {
state.entries = incoming
return
}
let entries = state.entries
const del = frame['del']
if (Array.isArray(del)) {
const removed = new Set(del.filter((id): id is string => typeof id === 'string'))
if (removed.size > 0) entries = entries.filter(existing => !removed.has(existing.id))
}
for (const item of incoming) entries = upsert(entries, item)
state.entries = entries
},
}
export function encounteredOf(state: RootState): EncounteredEntry[] {
const encountered = state.slices['encountered'] as EncounteredState | undefined
return encountered?.entries ?? []
}
+207
View File
@@ -0,0 +1,207 @@
// Fog slice (T7, #70; DESIGN 6.1 `explored`/`vision`/`marker`, 7.3). Append-only registration: this
// file was enough; the reducer's glob picked it up and `hello` resets it with every other slice.
//
// The server sends derived, per-recipient memory: `explored` (a full RLE snapshot on connect, cell
// diffs after), `vision` (the union of this player's sight polygons, integer px) and `marker`
// (this player's opaque window-marker ids with an anchor). Nothing here is a secret the client
// must enforce; it is only what the server chose to send (DESIGN 7.3, story 27).
//
// The slice keeps the whole explored set, because a reconnect must rebuild the view from a full
// snapshot, plus the *delta* of the last `explored` frame. The renderer uses the delta to touch only
// the new cells (DESIGN 7.2); a snapshot or a missed revision tells it to redraw everything.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { SceneInfo, ServerFrame, Vec2 } from '../protocol.ts'
/** One sight polygon: the token that produced it and its integer-px points (DESIGN 6.1, Q16). */
export interface VisionPoly {
id: string
pts: Vec2[]
}
export interface FogState {
/** The explored cell grid, from `hello.scene`: `cols = ceil(w / cell)`, `rows = ceil(h / cell)`. */
cols: number
rows: number
cell: number
sceneId: number | null
/** Explored cells, row-major (`cy * cols + cx`). Only ever grows between `hello`s. */
cells: Set<number>
/** Cells added by the latest explored update: the only cells a renderer has to touch. */
fresh: number[]
/** The latest explored update was a full `rle` snapshot, not a cell diff. */
snapshot: boolean
/** Bumped when the explored set changes; a renderer tracks what it has already drawn. */
exploredVersion: number
/** This player's current sight polygons (server-clipped already; never another player's). */
polys: VisionPoly[]
/** Bumped when the polygon union changes; the renderer rebuilds the cut-out then. */
visionVersion: number
/** This player's own window markers: opaque id -> integer-px anchor (DESIGN 5.8, 6.1). */
markers: Record<string, Vec2>
/** Bumped when the marker set or an anchor changes. */
markerVersion: number
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isInt(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value)
}
function isVec2(value: unknown): value is Vec2 {
return Array.isArray(value) && value.length === 2 && isInt(value[0]) && isInt(value[1])
}
export function emptyFog(): FogState {
return {
cols: 0,
rows: 0,
cell: 0,
sceneId: null,
cells: new Set<number>(),
fresh: [],
snapshot: false,
exploredVersion: 0,
polys: [],
visionVersion: 0,
markers: {},
markerVersion: 0,
}
}
/** The cell grid of a scene, or zero for a missing/invalid one. */
function gridOf(scene: SceneInfo | null): { cols: number; rows: number; cell: number } {
const cell = scene && scene.cell > 0 ? scene.cell : 0
if (!scene || cell <= 0 || !(scene.w > 0) || !(scene.h > 0)) return { cols: 0, rows: 0, cell: 0 }
return { cols: Math.ceil(scene.w / cell), rows: Math.ceil(scene.h / cell), cell }
}
/** `explored {full:true, rle:[[cy, x0, len, x0, len, ...], ...]}` (DESIGN 6.1). */
function applyFull(state: FogState, rle: unknown): boolean {
if (!Array.isArray(rle)) return false
const cells = new Set<number>()
for (const row of rle) {
if (!Array.isArray(row) || row.length < 3) continue
const cy = row[0]
if (!isInt(cy) || cy < 0 || cy >= state.rows) continue
for (let i = 1; i + 1 < row.length; i += 2) {
const x0 = row[i]
const len = row[i + 1]
if (!isInt(x0) || !isInt(len) || len <= 0) continue
const end = Math.min(state.cols, x0 + len)
for (let cx = Math.max(0, x0); cx < end; cx++) cells.add(cy * state.cols + cx)
}
}
state.cells = cells
state.fresh = [...cells]
state.snapshot = true
state.exploredVersion += 1
return true
}
/** `explored {full:false, cells:[[cx, cy], ...]}` (DESIGN 6.1): monotone additions only. */
function applyFresh(state: FogState, list: unknown): boolean {
if (!Array.isArray(list)) return false
const fresh: number[] = []
for (const entry of list) {
if (!isVec2(entry)) continue
const [cx, cy] = entry
if (cx < 0 || cy < 0 || cx >= state.cols || cy >= state.rows) continue
const index = cy * state.cols + cx
if (state.cells.has(index)) continue
state.cells.add(index)
fresh.push(index)
}
state.fresh = fresh
state.snapshot = false
if (fresh.length > 0) state.exploredVersion += 1
return true
}
/** `vision {polys:[{id, pts:[[x,y],...]}]}` (DESIGN 6.1). Malformed polygons are dropped whole. */
function applyVision(state: FogState, polys: unknown): boolean {
if (!Array.isArray(polys)) return false
const next: VisionPoly[] = []
for (const entry of polys) {
if (!isRecord(entry)) continue
const id = entry['id']
const pts = entry['pts']
if (typeof id !== 'string' || !Array.isArray(pts)) continue
if (pts.length < 3 || !pts.every(isVec2)) continue
next.push({ id, pts: pts as Vec2[] })
}
state.polys = next
state.visionVersion += 1
return true
}
/** `marker {full, set:[{id,pos}], del:[id]}` (DESIGN 6.1). A full frame replaces; a diff retracts. */
function applyMarkers(state: FogState, frame: ServerFrame): boolean {
const set = frame['set']
if (!Array.isArray(set)) return false
const full = frame['full'] === true
const next: Record<string, Vec2> = full ? {} : { ...state.markers }
let changed = full
for (const entry of set) {
if (!isRecord(entry)) continue
const id = entry['id']
const pos = entry['pos']
if (typeof id !== 'string' || !isVec2(pos)) continue
const before = next[id]
if (!before || before[0] !== pos[0] || before[1] !== pos[1]) changed = true
next[id] = [pos[0], pos[1]]
}
if (!full) {
const del = frame['del']
if (Array.isArray(del)) {
for (const id of del) {
if (typeof id !== 'string' || next[id] === undefined) continue
delete next[id]
changed = true
}
}
}
state.markers = next
if (changed) state.markerVersion += 1
return true
}
export const slice: Slice<FogState> = {
name: 'fog',
init: emptyFog,
reduce(state: FogState, event: ReducerEvent, root: RootState): void {
if (event.type !== 'frame') return
const frame = event.frame
switch (frame.t) {
case 'hello': {
// `hello` already reset the slice; the scene (set before the slice loop runs) gives the grid.
const grid = gridOf(root.session.scene)
state.cols = grid.cols
state.rows = grid.rows
state.cell = grid.cell
state.sceneId = root.session.scene?.id ?? null
return
}
case 'explored':
if (state.cols === 0) return
if (frame['full'] === true) applyFull(state, frame['rle'])
else applyFresh(state, frame['cells'])
return
case 'vision':
applyVision(state, frame['polys'])
return
case 'marker':
applyMarkers(state, frame)
return
}
},
}
/** The fog slice of a root state (always registered, always present after `initialState`). */
export function fogOf(state: RootState): FogState {
const fog = state.slices['fog'] as FogState | undefined
return fog ?? emptyFog()
}
+331
View File
@@ -0,0 +1,331 @@
// Move prediction and rollback (T9, #72; DESIGN 7.5, 5.5, 6.4). The pure half of the drag: pointer
// input becomes `drag-*` events, each `token.move` intent is remembered by `reqId`, and the acks
// decide whether the optimistic position stands or slides back. No Pixi, no DOM, no socket.
//
// The contract is DESIGN 7.5:
// - while dragging, the sprite follows the pointer and authoritative positions for that token are
// ignored for drawing (they keep arriving in the tokens slice, unmodified);
// - `ack{ok:true}` confirms the requested position, which the server's `token` frame repeats;
// - the uniform move nack (`ok:false` with `pos`, no `code`) rolls back: at once when idle, on
// release when the finger is still down;
// - `ack{ok:false, code:"rate-limited"}` is dropped quietly: the optimistic position is discarded
// and the next authoritative frame reconciles the view (6.4);
// - pending requests die with the connection (6.3).
//
// Append-only registration: adding this file was enough; the reducer's glob picked it up and
// `hello` resets it with every other slice.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { isAck } from '../protocol.ts'
import type { TokenView } from './tokens.ts'
import { tokensOf } from './tokens.ts'
export interface DragState {
id: string
/** Where the token was when the drag began (the server's last position). */
origin: Vec2
/** The optimistic position under the pointer; the renderer draws here. */
pos: Vec2
}
export interface MovePending {
reqId: number
id: string
pos: Vec2
}
/** A refused move while the finger is still down: snap there on release, never under the finger. */
export interface MoveSnap {
id: string
pos: Vec2
}
export interface RollbackTween {
/** Monotonic id so the renderer can report the exact tween it finished. */
seq: number
id: string
from: Vec2
to: Vec2
}
export interface MoveState {
drag: DragState | null
/** `token.move` intents awaiting their ack, in send order (the server acks in order). */
pending: MovePending[]
snap: MoveSnap | null
/** Cosmetic rollbacks the renderer is sliding; keyed by token id, newest per token wins. */
rollbacks: Record<string, RollbackTween>
/** Confirmed positions kept until the matching `token` frame lands (ack precedes the frame). */
confirmed: Record<string, Vec2>
seq: number
/** Counters for the browser e2e's instrumentation and for the unit tests. */
accepted: number
refused: number
rateLimited: number
/** Pending intents thrown away because the connection closed (6.3). */
dropped: number
rollbackCount: number
}
const EMPTY: MoveState = {
drag: null,
pending: [],
snap: null,
rollbacks: {},
confirmed: {},
seq: 0,
accepted: 0,
refused: 0,
rateLimited: 0,
dropped: 0,
rollbackCount: 0,
}
export function initMove(): MoveState {
return { ...EMPTY, pending: [], rollbacks: {}, confirmed: {} }
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function copy(pos: Vec2): Vec2 {
return [pos[0], pos[1]]
}
/** The newest pending intent for one token, or null. */
function latestPending(state: MoveState, id: string): MovePending | null {
let found: MovePending | null = null
for (const entry of state.pending) {
if (entry.id === id && (found === null || entry.reqId > found.reqId)) found = entry
}
return found
}
function hasNewerPending(state: MoveState, id: string, reqId: number): boolean {
return state.pending.some(entry => entry.id === id && entry.reqId > reqId)
}
function startRollback(state: MoveState, id: string, from: Vec2, to: Vec2): void {
state.seq += 1
state.rollbackCount += 1
state.rollbacks = {
...state.rollbacks,
[id]: { seq: state.seq, id, from: copy(from), to: copy(to) },
}
}
export const slice: Slice<MoveState> = {
name: 'move',
init: initMove,
reduce(state: MoveState, event: ReducerEvent, root: RootState): void {
switch (event.type) {
case 'drag-start': {
// A new drag is a new prediction: any pending snap or tween for this token is obsolete.
state.drag = { id: event.id, origin: copy(event.pos), pos: copy(event.pos) }
state.snap = null
if (state.rollbacks[event.id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
}
delete state.confirmed[event.id]
return
}
case 'drag-move': {
if (state.drag?.id !== event.id) return
state.drag = { ...state.drag, pos: copy(event.pos) }
return
}
case 'drag-end': {
if (state.drag?.id !== event.id) return
state.drag = null
// A refusal seen during the drag is settled on release (7.5): its ack handler starts the
// tween from the released position. Nothing to do here but keep the snap for that ack.
return
}
case 'move-sent': {
state.pending = [
...state.pending.filter(entry => entry.reqId !== event.reqId),
{ reqId: event.reqId, id: event.id, pos: copy(event.pos) },
]
return
}
case 'rollback-done': {
const tween = state.rollbacks[event.id]
if (tween?.seq !== event.seq) return
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
return
}
case 'close': {
// 6.3: pending reqIds are dropped with the connection; no ack will ever arrive.
state.dropped += state.pending.length
state.pending = []
state.drag = null
state.snap = null
state.rollbacks = {}
state.confirmed = {}
return
}
case 'frame': {
const frame = event.frame
if (frame.t === 'token') {
// The server remains the judge (story 39): its frame wins for drawing once no drag or
// pending intent covers the token. Any frame settles a confirmed position.
const id = frame['id']
if (typeof id !== 'string') return
// A frame during a cosmetic rollback does not cancel the tween: the ack that produced it
// already gave the authoritative position, and the renderer only animates the sprite.
delete state.confirmed[id]
return
}
if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string') return
if (state.drag?.id === id) state.drag = null
if (state.snap?.id === id) state.snap = null
state.pending = state.pending.filter(entry => entry.id !== id)
delete state.confirmed[id]
if (state.rollbacks[id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[id]
state.rollbacks = rollbacks
}
return
}
if (isAck(frame)) {
applyAck(root, state, frame)
}
return
}
}
},
}
function applyAck(root: RootState, state: MoveState, frame: AckFrame): void {
const index = state.pending.findIndex(entry => entry.reqId === frame.reqId)
if (index < 0) return // an intent this slice does not own (admin, name, ...)
const entry = state.pending[index]!
// What the sprite shows right now, before the pending entry is removed (7.5 rollback tween).
const shown = drawPositionOf(root, entry.id) ?? entry.pos
const snap = state.snap?.id === entry.id ? state.snap : null
state.pending = state.pending.filter(item => item.reqId !== frame.reqId)
if (frame.ok) {
state.accepted += 1
if (state.snap?.id === entry.id) state.snap = null
// Ack then the token frame (settleLocked); hold the confirmed position for the frame so the
// sprite never blinks back to the pre-move position for one dispatch.
state.confirmed = {
...state.confirmed,
[entry.id]: isVec2(frame.pos) ? copy(frame.pos) : copy(entry.pos),
}
return
}
if (frame.code === 'rate-limited') {
// 6.4: refused by the bucket, never applied, no position to roll back to. Drop quietly and let
// the next frame (or the next drag sample) reconcile; dragging keeps its optimistic position.
state.rateLimited += 1
if (state.snap?.id === entry.id) state.snap = null
if (state.drag?.id !== entry.id) {
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
return
}
if (!isVec2(frame.pos)) return // a malformed nack cannot move the sprite
// A newer intent is already in flight; its ack decides. Acks arrive in order, so ignore this one.
if (hasNewerPending(state, entry.id, entry.reqId)) return
state.refused += 1
if (state.drag?.id === entry.id) {
// 7.5: do not teleport under the finger; snap on release.
state.snap = { id: entry.id, pos: copy(frame.pos) }
return
}
// Idle: slide back from the predicted position to the server's old position (story 40).
startRollback(state, entry.id, snap ? entry.pos : shown, frame.pos)
if (state.snap?.id === entry.id) state.snap = null
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
/** The move slice, or an empty one before the registry has run (unit helpers stay total). */
export function moveOf(state: RootState): MoveState {
return (state.slices['move'] as MoveState | undefined) ?? EMPTY
}
/**
* The position the token renderer must draw at, or null when the authoritative `token` frame is
* the truth. Precedence: under the finger, then the newest pending request, then a confirmed ack
* whose `token` frame has not arrived yet (DESIGN 7.2's `at` parameter, 7.5).
*/
export function drawPositionOf(state: RootState, id: string): Vec2 | null {
const move = moveOf(state)
if (move.drag?.id === id) return move.drag.pos
const pending = latestPending(move, id)
if (pending) return pending.pos
const confirmed = move.confirmed[id]
if (confirmed) return confirmed
return null
}
/** True while the pointer owns this token: its authoritative frames must not move the sprite. */
export function isDragging(state: RootState, id: string): boolean {
return moveOf(state).drag?.id === id
}
/** The rollbacks the renderer should be tweening, newest sequence first. */
export function rollbacksOf(state: RootState): RollbackTween[] {
return Object.values(moveOf(state).rollbacks)
}
/** The active drag (the module's own state machine), if any. */
export function dragOf(state: RootState): DragState | null {
return moveOf(state).drag
}
/**
* O(N) hit test on press only (DESIGN 7.2): the topmost token this recipient may move whose circle
* contains the world point. Players move only their own tokens; the GM moves any token (story 43).
* GM frames say `mine:false`, so the role check is what makes a GM drag work.
*/
export function draggableAt(
tokens: readonly TokenView[],
role: 'gm' | 'player' | null,
point: Vec2,
): TokenView | null {
if (role === null) return null
for (let index = tokens.length - 1; index >= 0; index -= 1) {
const token = tokens[index]
if (!token) continue
if (role !== 'gm' && !token.mine) continue
const dx = point[0] - token.pos[0]
const dy = point[1] - token.pos[1]
if (dx * dx + dy * dy <= token.radius * token.radius) return token
}
return null
}
/** The tokens a drag may start on, for the shell/e2e; not a secrecy filter (the server already is). */
export function draggableTokens(state: RootState): TokenView[] {
const role = state.session.role
if (role === null) return []
return tokensOf(state).filter(token => role === 'gm' || token.mine)
}
+25
View File
@@ -0,0 +1,25 @@
// Roster slice (DESIGN 6.1 `roster`). Append-only registration: adding this file was enough; the
// reducer's glob picked it up and `hello` reset it with every other slice.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { RosterEntry } from '../protocol.ts'
export interface RosterState {
/** Always the full list the server sent; the client never merges (6.1). */
players: RosterEntry[]
}
function rosterList(value: unknown): RosterEntry[] | null {
if (!Array.isArray(value)) return null
return value as RosterEntry[]
}
export const slice: Slice<RosterState> = {
name: 'roster',
init: () => ({ players: [] }),
reduce(state: RosterState, event: ReducerEvent, _root: RootState): void {
if (event.type !== 'frame' || event.frame.t !== 'roster') return
const players = rosterList(event.frame['players'])
if (players) state.players = players
},
}
+152
View File
@@ -0,0 +1,152 @@
// Tokens slice (DESIGN 6.1 `token`/`token_gone`, stories 28-30 and 34). Append-only registration:
// adding this file was enough; the reducer's glob picked it up and `hello` resets it with every
// other slice.
//
// A token frame is *the whole view of one token* for this recipient (6.1), built by the server at
// egress: a player only ever receives tokens they control plus tokens inside their own line of
// sight and not `gm_only`, and the GM receives every token. The client therefore never filters for
// secrecy; it only keeps what arrived and forgets a token on `token_gone` (the server's "you may
// not see it any more", story 29).
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame, Vec2 } from '../protocol.ts'
export interface TokenView {
id: string
scene: number | null
/** The one name this recipient may see (8); never a reveal state. */
name: string
pos: Vec2
/** Effective radius in px (5.6). */
radius: number
/** True when this recipient controls the token (players only; GM frames say false). */
mine: boolean
/** Status names only; the cause (`source`) is GM-only (5.5, 6.1 leak note 6). */
statuses: string[]
/** The prop buckets this recipient may read: public, plus owner for the controller. */
props: Record<string, Record<string, unknown>>
/** GM-only fields (6.1): present on a GM connection, absent for a player. */
gmOnly: boolean
kind: string | null
controller: number | null
characterId: string | null
}
function own(record: Record<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
export interface TokensState {
byId: Record<string, TokenView>
/** Render order: entry order, kept across updates so a token never jumps layers on a move. */
order: string[]
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
typeof value[1] === 'number' &&
Number.isFinite(value[0]) &&
Number.isFinite(value[1])
)
}
function statusNames(value: unknown): string[] | null {
if (!Array.isArray(value)) return null
const names: string[] = []
for (const entry of value) {
if (!isRecord(entry) || typeof entry['status'] !== 'string') return null
// `source` is deliberately not stored: players never receive it, and a GM's own renderer has
// no use for it yet (6.1 leak note 6).
names.push(entry['status'])
}
return names
}
function propBuckets(value: unknown): Record<string, Record<string, unknown>> {
if (!isRecord(value)) return {}
const buckets: Record<string, Record<string, unknown>> = {}
for (const [bucket, contents] of Object.entries(value)) {
if (isRecord(contents)) buckets[bucket] = contents
}
return buckets
}
function optionalString(value: unknown): string | null {
return typeof value === 'string' ? value : null
}
function optionalNumber(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
/**
* One `token` frame as the slice stores it, or null when the frame cannot be that shape. An
* unreadable frame is ignored (6.2: unknown shapes never become state), not half-applied.
*/
export function tokenViewFromFrame(frame: ServerFrame): TokenView | null {
const id = frame['id']
const pos = frame['pos']
const radius = frame['radius']
const statuses = statusNames(frame['statuses'])
if (typeof id !== 'string' || id.length === 0) return null
if (!isVec2(pos)) return null
if (typeof radius !== 'number' || !Number.isFinite(radius)) return null
if (statuses === null) return null
return {
id,
scene: optionalNumber(frame['scene']),
name: typeof frame['name'] === 'string' ? frame['name'] : '',
pos,
radius,
mine: frame['mine'] === true,
statuses,
props: propBuckets(frame['props']),
gmOnly: frame['gm_only'] === true,
kind: optionalString(frame['kind']),
controller: optionalNumber(frame['controller']),
characterId: optionalString(frame['character_id']),
}
}
export const slice: Slice<TokensState> = {
name: 'tokens',
init: () => ({ byId: {}, order: [] }),
reduce(state: TokensState, event: ReducerEvent, _root: RootState): void {
if (event.type !== 'frame') return
const frame = event.frame
if (frame.t === 'token') {
const token = tokenViewFromFrame(frame)
if (!token) return
if (own(state.byId, token.id) === undefined) state.order.push(token.id)
state.byId = { ...state.byId, [token.id]: token }
} else if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string' || own(state.byId, id) === undefined) return
const byId = { ...state.byId }
delete byId[id]
state.byId = byId
state.order = state.order.filter(entry => entry !== id)
}
},
}
/** Every token this recipient may see, in entry order. */
export function tokensOf(state: RootState): TokenView[] {
const tokens = state.slices['tokens'] as TokensState | undefined
if (!tokens) return []
return tokens.order.map(id => tokens.byId[id]).filter((token): token is TokenView => token !== undefined)
}
export function tokenOf(state: RootState, id: string): TokenView | null {
const tokens = state.slices['tokens'] as TokensState | undefined
if (!tokens) return null
const token = own(tokens.byId, id)
return (token as TokenView | undefined) ?? null
}
+245
View File
@@ -0,0 +1,245 @@
// GM wall slice (T10, #73; DESIGN 6.1 `walls`/`wall`/`wall_gone`, 5.8, 7.4). Append-only
// registration: adding this file was enough; the reducer's glob picked it up and `hello` resets it
// with every other slice.
//
// Wall records are GM-only on the wire (3.1). A player connection never receives these frames and a
// player-shaped frame is ignored here too, so a bug on the server side could not quietly turn this
// client into a wall-data renderer. The slice keeps the server's typed record plus the editor's
// selection and its single-step undo descriptor; it never derives or invents a wall field.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { Vec2 } from '../protocol.ts'
import type {
SightDir,
WallKind,
WallPosition,
WallRestore,
WallSwitches,
WallUndo,
} from '../wallEditor.ts'
import { deriveKind } from '../wallEditor.ts'
export interface WallView {
id: number
scene: number
a: Vec2
b: Vec2
thickness: number
position: WallPosition
height: number | null
kind: WallKind
switches: WallSwitches
label: string | null
flags: Record<string, unknown>
}
export interface WallsState {
byId: Record<number, WallView>
order: number[]
/** The wall selected in the GM editor, or null. */
selectedId: number | null
/** The inverse of the last successful edit; single-step undo (story 52). */
undo: WallUndo | null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function own(record: Record<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function isPosition(value: unknown): value is WallPosition {
return value === 'center' || value === 'left' || value === 'right'
}
function isSightDir(value: unknown): value is SightDir {
return value === 'both' || value === 'left' || value === 'right'
}
function isKind(value: unknown): value is WallKind {
return value === 'wall' || value === 'door' || value === 'window' || value === 'one_way' || value === 'custom'
}
function bool(value: unknown): boolean {
return value === true
}
function optionalLabel(value: unknown): string | null {
return typeof value === 'string' ? value : null
}
function flagObject(value: unknown): Record<string, unknown> {
return isRecord(value) ? value : {}
}
/**
* One GM `wall` record as the editor stores it, or null when it cannot be that shape. `kind` is the
* server's derived label; an absent one is derived from the switches so an older-shaped frame still
* shows a label.
*
* DESIGN 6.1 fixes where `scene` lives: a `wall` delta carries it on the frame beside the record,
* while a `walls` entry carries the wall fields only (`{t:"walls", scene, walls:[{id, a, b, ...}]}`).
* `sceneHint` is the enclosing frame's `scene`, so a snapshot entry resolves it the same way a delta
* does. An entry that still carries its own `scene` wins, so older/foreign snapshots stay readable.
*/
export function wallViewFromFrame(
frame: Record<string, unknown>,
sceneHint?: unknown,
): WallView | null {
const id = frame['id']
const ownScene = frame['scene']
const scene = ownScene === undefined ? sceneHint : ownScene
const a = frame['a']
const b = frame['b']
const thickness = frame['thickness']
const position = frame['position']
const sightDir = frame['sight_dir']
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) return null
if (typeof scene !== 'number' || !Number.isInteger(scene)) return null
if (!isVec2(a) || !isVec2(b)) return null
if (typeof thickness !== 'number' || !Number.isFinite(thickness)) return null
if (!isPosition(position) || !isSightDir(sightDir)) return null
const switches: WallSwitches = {
blocksSight: bool(frame['blocks_sight']),
blocksMovement: bool(frame['blocks_movement']),
sightDir,
playerMarker: bool(frame['player_marker']),
door: bool(frame['door']),
open: bool(frame['open']),
secret: bool(frame['secret']),
locked: bool(frame['locked']),
}
const height = frame['height']
const kind = own(frame, 'kind')
const label = own(frame, 'label')
return {
id,
scene,
a: [a[0], a[1]],
b: [b[0], b[1]],
thickness,
position,
height: typeof height === 'number' && Number.isFinite(height) ? height : null,
kind: isKind(kind) ? kind : deriveKind(switches),
switches,
label: optionalLabel(label),
flags: flagObject(frame['flags']),
}
}
function upsert(state: WallsState, wall: WallView): void {
if (state.byId[wall.id] === undefined) state.order = [...state.order, wall.id]
state.byId = { ...state.byId, [wall.id]: wall }
}
function remove(state: WallsState, id: number): void {
if (state.byId[id] === undefined) return
const byId = { ...state.byId }
delete byId[id]
state.byId = byId
state.order = state.order.filter(entry => entry !== id)
if (state.selectedId === id) state.selectedId = null
}
/** The editor's restore payload for one wall: everything `wall.add` needs to bring it back. */
export function restoreOf(wall: WallView): WallRestore {
return {
a: [wall.a[0], wall.a[1]],
b: [wall.b[0], wall.b[1]],
thickness: wall.thickness,
position: wall.position,
height: wall.height,
switches: { ...wall.switches },
label: wall.label,
flags: { ...wall.flags },
}
}
export const slice: Slice<WallsState> = {
name: 'walls',
init: () => ({ byId: {}, order: [], selectedId: null, undo: null }),
reduce(state: WallsState, event: ReducerEvent, root: RootState): void {
if (event.type === 'wall-select') {
state.selectedId = event.id
return
}
if (event.type === 'wall-record-undo') {
state.undo = event.undo
return
}
if (event.type !== 'frame') return
const frame = event.frame
// Wall data is GM-only (DESIGN 3.1); never accept it on a player-shaped session.
if (root.session.role !== 'gm') return
if (frame.t === 'walls') {
const list = frame['walls']
if (!Array.isArray(list)) return
const frameScene = frame['scene']
const byId: Record<number, WallView> = {}
const order: number[] = []
for (const entry of list) {
if (!isRecord(entry)) continue
const wall = wallViewFromFrame(entry, frameScene)
if (!wall) continue
byId[wall.id] = wall
order.push(wall.id)
}
state.byId = byId
state.order = order
if (state.selectedId !== null && byId[state.selectedId] === undefined) {
state.selectedId = null
}
return
}
if (frame.t === 'wall') {
const wall = wallViewFromFrame(frame)
if (wall) upsert(state, wall)
return
}
if (frame.t === 'wall_gone') {
const id = frame['id']
if (typeof id === 'number' && Number.isInteger(id)) remove(state, id)
}
},
}
/** Every wall the GM's connection knows, in the server's id order. */
export function wallsOf(state: RootState): WallView[] {
const walls = state.slices['walls'] as WallsState | undefined
if (!walls) return []
return walls.order
.map(id => walls.byId[id])
.filter((wall): wall is WallView => wall !== undefined)
}
export function wallOf(state: RootState, id: number): WallView | null {
const walls = state.slices['walls'] as WallsState | undefined
if (!walls) return null
return walls.byId[id] ?? null
}
export function selectedWallId(state: RootState): number | null {
return (state.slices['walls'] as WallsState | undefined)?.selectedId ?? null
}
export function selectedWallOf(state: RootState): WallView | null {
const id = selectedWallId(state)
return id === null ? null : wallOf(state, id)
}
export function undoOf(state: RootState): WallUndo | null {
return (state.slices['walls'] as WallsState | undefined)?.undo ?? null
}
+35
View File
@@ -0,0 +1,35 @@
// The store is the tiny bridge between the pure reducer and the renderer/DOM shell. It owns the
// current state and notifies subscribers once per dispatch; render modules update only the
// entities they saw change (DESIGN 7.2), so no module may assume a frame-by-frame redraw.
import type { ReducerEvent, RootState } from './reducer.ts'
import { initialState, reduce } from './reducer.ts'
export type Listener = (state: RootState, event: ReducerEvent) => void
export class Store {
#state: RootState
#listeners = new Set<Listener>()
constructor(state: RootState = initialState()) {
this.#state = state
}
get state(): RootState {
return this.#state
}
dispatch(event: ReducerEvent): RootState {
const next = reduce(this.#state, event)
this.#state = next
for (const listener of this.#listeners) listener(next, event)
return next
}
subscribe(listener: Listener): () => void {
this.#listeners.add(listener)
return () => {
this.#listeners.delete(listener)
}
}
}
+633
View File
@@ -0,0 +1,633 @@
html,
body {
margin: 0;
height: 100%;
overflow: hidden;
background: #000;
color: #eee;
font: 14px/1.4 system-ui, sans-serif;
}
#app {
position: fixed;
inset: 0;
}
[hidden] {
display: none !important;
}
#stage {
position: absolute;
inset: 0;
}
#stage canvas {
display: block;
}
#boot,
#signin,
#name,
#fatal {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 24px;
text-align: center;
}
#signin form,
#name form {
display: flex;
flex-direction: column;
gap: 8px;
width: min(360px, 90vw);
}
#key,
#name-input {
font: inherit;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid #555;
background: #111;
color: inherit;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#name-input {
letter-spacing: normal;
text-transform: none;
}
#signin button,
#name button,
#fatal button {
font: inherit;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid #777;
background: #222;
color: inherit;
}
#signin-error,
#name-error {
color: #ff8a8a;
}
#hud {
position: absolute;
top: 0;
left: 0;
right: 0;
display: flex;
flex-wrap: wrap;
column-gap: 16px;
row-gap: 2px;
align-items: baseline;
padding: 6px 12px;
background: rgb(0 0 0 / 65%);
pointer-events: none;
font: 12px/1.4 ui-monospace, monospace;
box-sizing: border-box;
}
/* The phone dry-run clipped "…Pl…" because the row could not wrap; these children may shrink and
the scene name ellipsises instead of pushing the badge off-screen. */
#hud > * {
min-width: 0;
}
#scene {
max-width: 40vw;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#zoom {
opacity: 0.7;
white-space: nowrap;
}
#roster {
display: flex;
flex-wrap: wrap;
gap: 2px 12px;
margin: 0;
padding: 0;
list-style: none;
min-width: 0;
}
#roster li {
display: flex;
gap: 4px;
min-width: 0;
}
.roster-state {
opacity: 0.6;
}
/* Story 7: connected / reconnecting / offline. The dot carries the state at a glance; the text is
the accessible label. */
#badge {
margin-left: auto;
display: inline-flex;
align-items: center;
gap: 5px;
}
#badge::before {
content: '';
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
}
#badge[data-state='connected'] {
color: #7ee787;
}
#badge[data-state='reconnecting'] {
color: #e3b341;
}
#badge[data-state='offline'] {
color: #ff7b72;
}
/* GM panels (T11, #74): a right-hand column over the canvas. The root is hidden for players and
for every phase outside the table; secrets live only inside it. */
#panels {
position: absolute;
top: 40px;
right: 8px;
bottom: 8px;
width: min(330px, 44vw);
overflow: auto;
pointer-events: none;
}
#gm-panels {
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
border-radius: 8px;
background: rgb(10 10 12 / 88%);
border: 1px solid #333;
pointer-events: auto;
font: 12px/1.4 ui-monospace, monospace;
}
#gm-panels h2,
#gm-panels h3,
#gm-panels h4 {
margin: 0;
font-weight: 600;
}
#gm-panels h2 {
font-size: 14px;
}
#gm-panels h3 {
font-size: 12px;
opacity: 0.8;
}
/* Collapsible sections (M4 UX): native <details>; the summary is the section's only click target,
and an open section's body keeps the column's normal flow. */
.panel-section > summary {
cursor: pointer;
font-weight: 600;
opacity: 0.85;
padding: 2px 0;
}
.panel-section[open] > summary {
margin-bottom: 4px;
}
.panel-section > .panel-body {
display: flex;
flex-direction: column;
gap: 4px;
}
#gm-roster-list,
#gm-token-list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
padding: 0;
list-style: none;
}
/* A long list gets its own scroll instead of stretching the column (50 tokens, a busy cast). */
#gm-token-list {
max-height: 220px;
overflow: auto;
}
#gm-character-list {
max-height: 360px;
overflow: auto;
}
#gm-seen-list {
max-height: 160px;
overflow: auto;
}
#gm-encountered {
max-height: 220px;
overflow: auto;
}
#gm-roster-list li,
#gm-token-list li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 4px;
border-radius: 4px;
background: rgb(255 255 255 / 4%);
}
#gm-token-list li[data-selected='true'] {
outline: 1px solid #7ee787;
}
.gm-roster-state {
opacity: 0.6;
}
.gm-key {
flex-basis: 100%;
color: #e3b341;
word-break: break-all;
}
#gm-panels button {
font: inherit;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid #666;
background: #222;
color: inherit;
}
#gm-panels input,
#gm-panels select {
font: inherit;
padding: 3px 5px;
border-radius: 4px;
border: 1px solid #555;
background: #111;
color: inherit;
width: 100%;
box-sizing: border-box;
}
#gm-panels input[type='checkbox'] {
width: auto;
}
#gm-token-create,
#gm-token-editor {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
}
#gm-token-create label,
#gm-token-editor label {
opacity: 0.7;
}
#gm-key-status,
#gm-token-error {
margin: 4px 0 0;
word-break: break-word;
color: #e3b341;
}
#gm-token-error {
color: #ff8a8a;
}
.gm-token-meta {
flex-basis: 100%;
opacity: 0.7;
word-break: break-word;
}
/* Lists panel (T8, #71): story 31's own characters and story 32's encountered list. Overlaid on the
canvas inside the shared `#panels` column; the pointers stay with the canvas (DESIGN 7.2). */
#lists {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 10px;
border: 1px solid #333;
border-radius: 6px;
background: rgb(0 0 0 / 55%);
font: 12px/1.4 ui-monospace, monospace;
pointer-events: none;
}
#lists summary {
cursor: pointer;
pointer-events: auto;
font: 600 11px/1.2 system-ui, sans-serif;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.65;
}
/* The list itself stays pointer-transparent so it never eats a pan; the body takes pointers only
while open (to scroll a capped list). */
#lists details > .panel-body {
pointer-events: none;
}
#lists details[open] > .panel-body {
pointer-events: auto;
}
#lists ul {
display: flex;
flex-direction: column;
gap: 2px;
margin: 0 0 6px;
padding: 0;
list-style: none;
max-height: 200px;
overflow: auto;
}
#lists li {
display: flex;
gap: 6px;
align-items: baseline;
justify-content: space-between;
}
#lists .entry-values {
font-size: 11px;
opacity: 0.6;
}
#lists .entry-state {
font-size: 10px;
opacity: 0.45;
}
#lists .empty {
margin: 0 0 6px;
opacity: 0.45;
}
/* Story 32: met before, whereabouts unknown. */
#lists li.grey,
#lists li[data-grey='true'] {
opacity: 0.55;
}
#lists li.grey .entry-name {
color: #8f8f8f;
}
/* GM cast panels (T12, #75): characters, reveals, encountered and who-sees-it, below the #74
panel in the same right-hand column. Same secret rules: hidden and cleared unless GM + live. */
#gm-cast {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 10px;
padding: 10px;
border-radius: 8px;
background: rgb(10 10 12 / 88%);
border: 1px solid #333;
pointer-events: auto;
font: 12px/1.4 ui-monospace, monospace;
}
#gm-cast h3,
#gm-cast h4 {
margin: 0;
font-weight: 600;
}
#gm-cast h3 {
font-size: 12px;
opacity: 0.8;
}
#gm-cast ul {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
padding: 0;
list-style: none;
}
#gm-cast li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 4px;
border-radius: 4px;
background: rgb(255 255 255 / 4%);
}
#gm-cast button {
font: inherit;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid #666;
background: #222;
color: inherit;
}
#gm-cast input,
#gm-cast select {
font: inherit;
padding: 3px 5px;
border-radius: 4px;
border: 1px solid #555;
background: #111;
color: inherit;
width: 100%;
box-sizing: border-box;
}
#gm-character-create,
#gm-cast form {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
}
#gm-cast label {
opacity: 0.7;
}
#gm-character-status,
#gm-encountered-status,
#gm-seen-hint {
margin: 4px 0 0;
word-break: break-word;
color: #e3b341;
}
#gm-seen-hint {
opacity: 0.7;
}
/* GM wall editor (T10, #73): draw presets, the selected wall's round-1 fields and single-step undo,
in the same right-hand column. Hidden and inert for players exactly like the other GM panels. */
#gm-walls {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 10px;
padding: 10px;
border-radius: 8px;
background: rgb(10 10 12 / 88%);
border: 1px solid #333;
pointer-events: auto;
font: 12px/1.4 ui-monospace, monospace;
}
#gm-walls h2,
#gm-walls h3 {
margin: 0;
font-weight: 600;
}
#gm-walls h2 {
font-size: 14px;
}
#gm-walls h3 {
font-size: 12px;
opacity: 0.8;
}
#wall-presets {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin: 4px 0;
}
#gm-walls button {
font: inherit;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid #666;
background: #222;
color: inherit;
}
#gm-walls button[aria-pressed='true'] {
outline: 1px solid #7ee787;
background: #1d3322;
}
#gm-walls button:disabled {
opacity: 0.45;
}
#gm-walls input,
#gm-walls select {
font: inherit;
padding: 3px 5px;
border-radius: 4px;
border: 1px solid #555;
background: #111;
color: inherit;
width: 100%;
box-sizing: border-box;
}
#gm-walls input[type='checkbox'] {
width: auto;
}
#wall-selected,
#wall-advanced {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
}
#wall-selected label,
#wall-advanced label {
opacity: 0.7;
}
#wall-kind {
color: #7ee787;
}
#wall-hint,
#wall-drawing,
#wall-kind-hint {
margin: 2px 0;
opacity: 0.7;
word-break: break-word;
}
#wall-hint-locked {
margin: 4px 0 0;
color: #e3b341;
}
#wall-error {
margin: 4px 0 0;
color: #ff8a8a;
word-break: break-word;
}
/* Phone (M4 dry-run, 390 px): the HUD wraps instead of clipping, and the player list column folds
to two summary rows so the map stays visible. The lists are capped and scroll when opened. */
@media (max-width: 640px) {
#hud {
column-gap: 8px;
padding: 4px 8px;
font-size: 11px;
}
#scene {
max-width: 38vw;
}
#panels {
top: 48px;
width: min(300px, 46vw);
}
#lists ul {
max-height: 28vh;
}
}
+313
View File
@@ -0,0 +1,313 @@
// The tile scheduler (#69, spec #63 decision 12; #86 tile-loading). Pure: the loader is injected, so
// the concurrency, cache and retry rules are unit-tested without a browser or a GPU.
//
// Rules encoded here:
// - at most TILE_CONCURRENCY requests in flight (measured knee: a browser decodes and uploads
// faster than one 8-wide queue can keep the server busy on a 16k map, see the issue);
// - the wanted list is the viewport plus one tile of margin, ordered by the caller (the renderer
// asks nearest the viewport centre first);
// - a tile is never fetched twice (a decoded texture is cached by the tile module across a
// reconnect; this scheduler remembers settled URLs too);
// - a `403` is a permanent `denied` answer: never retried in a loop (the server said no). It is
// asked once more only when the fog says its cells just became explored (#70);
// - a `404`/`5xx`/network failure is transient: up to TILE_MAX_ATTEMPTS loads with exponential
// backoff, then a stored `error` that waits for a new window or a reconnect (`retryFailed`) —
// this fixes the black void a missing tile used to leave until a page reload;
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
// prefetches beyond the margin.
import type { SceneInfo } from './protocol.ts'
import { tileUrl } from './viewport.ts'
/**
* Torrent of small tiles is bounded here, not by the server: the gate + nginx sustain ~2.5k
* requests/s, so a narrow client queue is the bottleneck on a survey view. Measured knee on a
* Full HD scene at GM fit / player 0.5 (min-of-3, headless SwiftShader): 8 -> 32 cuts the fill
* 11-29%; 64 is inside the noise and doubles browser decode pressure, so 32 is the cap.
*/
export const TILE_CONCURRENCY = 32
/** Total loads per URL (first try included) before a transient failure is stored as `error`. */
export const TILE_MAX_ATTEMPTS = 3
/** First retry delay; each following retry doubles it (250 ms, 500 ms). */
export const TILE_RETRY_BASE_MS = 250
export type TileLoadResult = 'ok' | 'denied' | 'error'
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
export type RetryScheduler = (run: () => void, ms: number) => () => void
const setTimeoutRetry: RetryScheduler = (run, ms) => {
const timer = setTimeout(run, ms)
return () => clearTimeout(timer)
}
export interface TileSchedulerOptions {
load(url: string): Promise<TileLoadResult>
onSettled?(url: string, result: TileLoadResult): void
onIdle?(): void
concurrency?: number
/** Bounded transient-failure retries (default TILE_MAX_ATTEMPTS, 3). */
maxAttempts?: number
/** First backoff in ms; doubles per attempt (default TILE_RETRY_BASE_MS). */
retryBaseMs?: number
/** Injectable timer, so tests drive backoff without wall-clock waits. */
scheduleRetry?: RetryScheduler
}
function sameList(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
/**
* The tile urls touched by a set of explored cells (fog slice indices, row-major). v1 has
* `cell == tile_size` (DESIGN 8), but the maths keeps a cell-to-tile mapping general.
*/
export function tilesForCells(
scene: Pick<SceneInfo, 'id' | 'art_version' | 'tile_size'>,
grid: { cols: number; cell: number },
cells: Iterable<number>,
): string[] {
const tileSize = scene.tile_size
if (!(tileSize > 0) || grid.cell <= 0 || grid.cols <= 0) return []
const urls = new Set<string>()
for (const index of cells) {
const cx = index % grid.cols
const cy = (index / grid.cols) | 0
const tx = Math.floor((cx * grid.cell) / tileSize)
const ty = Math.floor((cy * grid.cell) / tileSize)
urls.add(tileUrl(scene, tx, ty))
}
return [...urls]
}
/**
* True when a new scene invalidates every cached tile URL: a different scene, or the same scene
* after a re-import (`art_version`). A first scene (no previous) has nothing to invalidate, and a
* reconnect to the same version must keep the decoded cache.
*/
export function tilesInvalidated(
previous: Pick<SceneInfo, 'id' | 'art_version'> | null,
next: Pick<SceneInfo, 'id' | 'art_version'> | null,
): boolean {
if (previous === null || next === null) return false
return previous.id !== next.id || previous.art_version !== next.art_version
}
export class TileScheduler {
readonly #load: (url: string) => Promise<TileLoadResult>
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
readonly #onIdle: (() => void) | undefined
readonly #concurrency: number
readonly #maxAttempts: number
readonly #retryBaseMs: number
readonly #scheduleRetry: RetryScheduler
#states = new Map<string, TileStatus>()
#attempts = new Map<string, number>()
#timers = new Map<string, () => void>()
/** Bumped by `retryFailed`/`reset`: a load that settles after it gets a fresh budget. */
#epoch = 0
#queue: string[] = []
#desired = new Set<string>()
#lastDesired: readonly string[] = []
#active = 0
#idle = true
constructor(options: TileSchedulerOptions) {
this.#load = options.load
this.#onSettled = options.onSettled
this.#onIdle = options.onIdle
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
this.#maxAttempts = Math.max(1, options.maxAttempts ?? TILE_MAX_ATTEMPTS)
this.#retryBaseMs = Math.max(0, options.retryBaseMs ?? TILE_RETRY_BASE_MS)
this.#scheduleRetry = options.scheduleRetry ?? setTimeoutRetry
}
status(url: string): TileStatus | undefined {
return this.#states.get(url)
}
get active(): number {
return this.#active
}
/** What the viewport wants now. `urls` is already in the caller's order (centre-out). */
setDesired(urls: readonly string[]): void {
// A settle calls back into the renderer, which syncs again with the same window; skip the
// O(n) rebuild in that common case. It still pumps, which is what opens the next slot.
if (sameList(urls, this.#lastDesired)) {
this.#pump()
return
}
this.#lastDesired = [...urls]
this.#desired = new Set(urls)
// Keep queued entries that are still wanted, in the new viewport order; forget the rest so a
// later viewport that asks for the tile again can queue it fresh.
const order = new Map(urls.map((url, index) => [url, index]))
const dropped = this.#queue.filter(url => !this.#desired.has(url))
for (const url of dropped) this.#states.delete(url)
this.#queue = this.#queue
.filter(url => this.#desired.has(url))
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
for (const url of urls) {
const existing = this.#states.get(url)
if (existing === 'error') {
// A bounded retry that already used its attempts stays failed until `retryFailed()`; a
// fresh window must not hammer a tile the server keeps 404ing.
if ((this.#attempts.get(url) ?? 0) >= this.#maxAttempts) continue
this.#cancelRetry(url)
this.#states.delete(url)
} else if (existing !== undefined) continue
this.#states.set(url, 'queued')
this.#queue.push(url)
}
this.#pump()
}
/** A texture already in the cache (e.g. a renderer remount) needs no request. */
markLoaded(url: string): void {
if (!this.#states.has(url)) this.#states.set(url, 'ok')
}
/**
* Forget transient failures: the next sync (e.g. after a reconnect) may ask again. The attempt
* budget is reset too, so a reconnect gets the full bounded-retry allowance.
*/
retryFailed(): void {
for (const cancel of this.#timers.values()) cancel()
this.#timers.clear()
this.#epoch += 1
for (const [url, status] of this.#states) {
if (status !== 'error') continue
this.#states.delete(url)
this.#attempts.delete(url)
}
this.#lastDesired = []
}
/**
* Drop every cached decision and pending retry (a new `art_version`: the URLs all changed).
* Loads already in flight settle harmlessly and their results are ignored by the caller.
*/
reset(): void {
for (const cancel of this.#timers.values()) cancel()
this.#timers.clear()
this.#epoch += 1
this.#states.clear()
this.#attempts.clear()
this.#queue = []
this.#desired.clear()
this.#lastDesired = []
}
/** Cancel pending retry timers on teardown; no callback runs after this. */
dispose(): void {
for (const cancel of this.#timers.values()) cancel()
this.#timers.clear()
}
/**
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
* denied urls are forgotten and the next `setDesired` asks for them exactly once more. Nothing
* else is retried: an unexplored 403 stays denied (no retry loop).
*/
retryDenied(urls: Iterable<string>): void {
let changed = false
for (const url of urls) {
if (this.#states.get(url) !== 'denied') continue
this.#states.delete(url)
changed = true
}
// The next setDesired rebuilds the queue, which re-queues the forgotten urls as `queued`.
if (changed) this.#lastDesired = []
}
/**
* True while any wanted tile still has to settle on this pass (queued, loading, or not yet
* asked). A stored `error` is *terminal for this pass*: it is only retried on a new window or
* after `retryFailed()`, so it must not keep a readiness probe waiting forever.
*/
isPending(urls: readonly string[]): boolean {
return urls.some(url => {
const status = this.#states.get(url)
return status === undefined || status === 'queued' || status === 'loading'
})
}
/** True when every wanted tile settled with an `ok` or `denied` answer. */
isComplete(urls: readonly string[]): boolean {
return urls.every(url => {
const status = this.#states.get(url)
return status === 'ok' || status === 'denied'
})
}
#pump(): void {
while (this.#active < this.#concurrency && this.#queue.length > 0) {
const url = this.#queue.shift()
if (url === undefined) break
if (!this.#desired.has(url) || this.#states.get(url) !== 'queued') continue
this.#states.set(url, 'loading')
this.#active += 1
this.#idle = false
const epoch = this.#epoch
void this.#load(url).then(
result => this.#settle(url, result, epoch),
() => this.#settle(url, 'error', epoch),
)
}
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
this.#idle = true
this.#onIdle?.()
}
}
#settle(url: string, result: TileLoadResult, epoch: number): void {
this.#active -= 1
if (result === 'ok' || result === 'denied') {
this.#states.set(url, result)
this.#attempts.delete(url)
this.#cancelRetry(url)
} else {
// Transient: retry with exponential backoff up to `maxAttempts`, then store the failure and
// wait for a new window or `retryFailed()` (reconnect). A 403 is a separate `denied` answer.
// A reconnect (`retryFailed`) during the load resets the budget: a failure that lands after
// it is a fresh first attempt, not the tail of the old one. A tile that left the window
// while loading does not spend the budget: a later window can still try it.
if (!this.#desired.has(url)) {
this.#states.set(url, 'error')
} else {
const attempt = epoch === this.#epoch ? (this.#attempts.get(url) ?? 0) + 1 : 1
this.#attempts.set(url, attempt)
this.#states.set(url, 'error')
if (attempt < this.#maxAttempts) this.#scheduleRetryFor(url, attempt)
}
}
this.#onSettled?.(url, result)
this.#pump()
}
#scheduleRetryFor(url: string, attempt: number): void {
this.#cancelRetry(url)
const delay = this.#retryBaseMs * 2 ** (attempt - 1)
const cancel = this.#scheduleRetry(() => {
this.#timers.delete(url)
// The window may have moved on, or the tile may have been answered meanwhile.
if (this.#states.get(url) !== 'error' || !this.#desired.has(url)) return
this.#states.set(url, 'queued')
this.#queue.push(url)
this.#pump()
}, delay)
this.#timers.set(url, cancel)
}
#cancelRetry(url: string): void {
const cancel = this.#timers.get(url)
if (cancel === undefined) return
cancel()
this.#timers.delete(url)
}
}
+78
View File
@@ -0,0 +1,78 @@
// The GM token panel's pure half (T11/#74, #78): local validation of the vision controls and the
// fields the panel sends for `token.create` / `token.update` (DESIGN 6.1, 8). No DOM, no socket.
//
// `flags` is free-form (DESIGN 8): an edit writes only the `vision` key and copies every other key
// from the current GM `token` frame, so future GM flags survive a save. A new token keeps the
// DESIGN 8 default (`flags: '{}'`): vision off means no `flags` field is sent at all.
//
// `vision_radius` is also the player's move step cap (DESIGN 5.5), so the panel validates it like
// the token radius: blank = scene default (`null`), anything else must be > 0 and finite.
/** The vision part of a `token.create` / `token.update` payload. */
export interface VisionFields {
/** Present only when the panel writes a flag (create with vision on, or any edit). */
flags?: Record<string, unknown>
vision_radius: number | null
}
export type VisionFieldsResult =
| { ok: true; fields: VisionFields }
| { ok: false; error: string }
export type VisionUpdateResult =
| { ok: true; fields: { id: string; flags: Record<string, unknown>; vision_radius: number | null } }
| { ok: false; error: string }
type RadiusResult = { ok: true; value: number | null } | { ok: false; error: string }
/** Blank is the scene default; non-finite and non-positive values are refused before the wire. */
export function parseVisionRadius(raw: string): RadiusResult {
const text = raw.trim()
if (text === '') return { ok: true, value: null }
const value = Number(text)
if (!Number.isFinite(value) || value <= 0) {
return {
ok: false,
error: 'Vision radius must be a positive number or blank for the scene default.',
}
}
return { ok: true, value }
}
/** Copy `flags` and set only `vision`; every other GM flag survives (DESIGN 8). */
export function withVisionFlag(
flags: Record<string, unknown>,
vision: boolean,
): Record<string, unknown> {
return { ...flags, vision }
}
/**
* `token.create` vision fields. Vision off sends no `flags`, so the server keeps its DESIGN 8
* default (`{}`); vision on carries only the one key.
*/
export function createVisionFields(vision: boolean, rawRadius: string): VisionFieldsResult {
const radius = parseVisionRadius(rawRadius)
if (!radius.ok) return radius
return {
ok: true,
fields: vision
? { flags: { vision: true }, vision_radius: radius.value }
: { vision_radius: radius.value },
}
}
/** `token.update` vision fields: the stored flags are the base, never a rebuilt object. */
export function updateVisionFields(
id: string,
flags: Record<string, unknown>,
vision: boolean,
rawRadius: string,
): VisionUpdateResult {
const radius = parseVisionRadius(rawRadius)
if (!radius.ok) return radius
return {
ok: true,
fields: { id, flags: withVisionFlag(flags, vision), vision_radius: radius.value },
}
}
+300
View File
@@ -0,0 +1,300 @@
// Camera, viewport and tile-window maths (#69, DESIGN 7.1/7.2). Pure: no Pixi, no DOM, no socket,
// so it is unit-tested next to the reducer seam. The renderer is the only consumer that turns these
// numbers into a transform and sprites.
//
// Coordinate convention: world pixels are the scene's own (`0..scene.w`, `0..scene.h`). The camera
// is the world container's transform: `screen = world * zoom + (x, y)`. Panning changes x/y;
// zooming around an anchor keeps the world point under that anchor fixed (wheel and pinch).
//
// Zoom bounds are the owner-delegated numbers of spec #63 decision 7: a player stops at 0.5
// (ADR-0013, the cheapest bound on how many tiles a phone can ask for) and both roles stop at 4.0.
// The GM has no low clamp; GM_MIN_ZOOM is only a sanity floor so the transform can never become
// singular (a GM surveying a 16k scene at 0.1 still sees everything they need).
import type { Role, SceneInfo } from './protocol.ts'
export const PLAYER_MIN_ZOOM = 0.5
export const MAX_ZOOM = 4
/** No player-style low clamp for the GM; this only keeps `zoom > 0`. */
export const GM_MIN_ZOOM = 1 / 64
/** The tile window is the viewport plus exactly this many tiles on every side (spec decision 12). */
export const VIEWPORT_MARGIN_TILES = 1
export interface Camera {
/** Screen x of world x = 0, in CSS pixels. */
x: number
/** Screen y of world y = 0, in CSS pixels. */
y: number
zoom: number
}
export interface ViewportSize {
width: number
height: number
}
export interface VisibleTile {
x: number
y: number
url: string
}
export function minZoom(role: Role | null): number {
return role === 'player' ? PLAYER_MIN_ZOOM : GM_MIN_ZOOM
}
export function clampZoom(role: Role | null, zoom: number): number {
if (Number.isNaN(zoom)) return 1
if (zoom === Number.POSITIVE_INFINITY) return MAX_ZOOM
if (zoom === Number.NEGATIVE_INFINITY) return minZoom(role)
return Math.min(MAX_ZOOM, Math.max(minZoom(role), zoom))
}
/** The starting view: the whole scene centred in the viewport at zoom 1. */
export function centredCamera(scene: SceneInfo, size: ViewportSize, zoom = 1): Camera {
return {
x: size.width / 2 - (scene.w / 2) * zoom,
y: size.height / 2 - (scene.h / 2) * zoom,
zoom,
}
}
export function screenToWorld(camera: Camera, screenX: number, screenY: number): [number, number] {
return [(screenX - camera.x) / camera.zoom, (screenY - camera.y) / camera.zoom]
}
export function worldToScreen(camera: Camera, worldX: number, worldY: number): [number, number] {
return [worldX * camera.zoom + camera.x, worldY * camera.zoom + camera.y]
}
export function panCamera(camera: Camera, dx: number, dy: number): Camera {
return { ...camera, x: camera.x + dx, y: camera.y + dy }
}
/** The world point at the centre of the viewport: the default position for a new token (#82). */
export function viewportCentre(camera: Camera, size: ViewportSize): [number, number] {
return screenToWorld(camera, size.width / 2, size.height / 2)
}
/**
* Multiply the zoom by `factor` around a screen anchor: the world point under the anchor does not
* move, which is what a wheel over the pointer or a pinch between two fingers must feel like.
*/
export function zoomCamera(
role: Role | null,
camera: Camera,
factor: number,
anchor: { x: number; y: number },
): Camera {
return zoomCameraTo(role, camera, camera.zoom * factor, anchor)
}
export function zoomCameraTo(
role: Role | null,
camera: Camera,
zoom: number,
anchor: { x: number; y: number },
): Camera {
const next = clampZoom(role, zoom)
const [worldX, worldY] = screenToWorld(camera, anchor.x, anchor.y)
return { x: anchor.x - worldX * next, y: anchor.y - worldY * next, zoom: next }
}
/**
* Two-finger pinch: the world point under the starting midpoint stays under the (possibly moved)
* midpoint, scaled by how far apart the fingers are now.
*/
export function pinchCamera(
role: Role | null,
start: Camera,
startDistance: number,
distance: number,
startMidpoint: { x: number; y: number },
midpoint: { x: number; y: number },
): Camera {
const safeStart = startDistance > 0 ? startDistance : 1
const [worldX, worldY] = screenToWorld(start, startMidpoint.x, startMidpoint.y)
const zoom = clampZoom(role, start.zoom * (distance / safeStart))
return { x: midpoint.x - worldX * zoom, y: midpoint.y - worldY * zoom, zoom }
}
/**
* The tiles a viewport needs: every tile intersecting the viewport, plus `VIEWPORT_MARGIN_TILES`
* on each side, clamped to the scene grid and returned in viewport order (row-major, top-left to
* bottom-right). Never a tile beyond that margin, so the client cannot prefetch the map.
*/
export function visibleTiles(
scene: SceneInfo,
camera: Camera,
size: ViewportSize,
marginTiles = VIEWPORT_MARGIN_TILES,
): VisibleTile[] {
const tileSize = scene.tile_size
if (!(tileSize > 0)) return []
const columns = Math.ceil(scene.w / tileSize)
const rows = Math.ceil(scene.h / tileSize)
if (columns <= 0 || rows <= 0) return []
const [worldLeft, worldTop] = screenToWorld(camera, 0, 0)
const [worldRight, worldBottom] = screenToWorld(camera, size.width, size.height)
const margin = marginTiles * tileSize
const x0 = Math.max(0, Math.floor((worldLeft - margin) / tileSize))
const y0 = Math.max(0, Math.floor((worldTop - margin) / tileSize))
const x1 = Math.min(columns - 1, Math.ceil((worldRight + margin) / tileSize) - 1)
const y1 = Math.min(rows - 1, Math.ceil((worldBottom + margin) / tileSize) - 1)
const tiles: VisibleTile[] = []
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) tiles.push({ x, y, url: tileUrl(scene, x, y) })
}
return tiles
}
/**
* Order tiles nearest the viewport centre first (the tile layer's request order). At a GM survey
* zoom a 16k scene is tens of thousands of tiles, and the fill should grow out of what the eye is
* on, not from the top-left corner. Ties keep the incoming (row-major) order, so it is stable.
*/
export function orderTilesCentreOut(
tiles: readonly VisibleTile[],
scene: Pick<SceneInfo, 'tile_size'>,
camera: Camera,
size: ViewportSize,
): VisibleTile[] {
const tileSize = scene.tile_size
if (!(tileSize > 0)) return [...tiles]
const [cx, cy] = screenToWorld(camera, size.width / 2, size.height / 2)
const distance = (tile: VisibleTile): number => {
const dx = (tile.x + 0.5) * tileSize - cx
const dy = (tile.y + 0.5) * tileSize - cy
return dx * dx + dy * dy
}
return [...tiles].sort((a, b) => distance(a) - distance(b))
}
/** The canonical tile URL of DESIGN 3.3: digits only, no leading zeros, `v` + art_version. */
export function tileUrl(scene: Pick<SceneInfo, 'id' | 'art_version'>, x: number, y: number): string {
return `/tiles/${scene.id}/v${scene.art_version}/${x}_${y}.png`
}
// ---------------------------------------------------------------------------------------------
// The renderer's viewport model. It lives outside `slices/` on purpose: camera and grid are local
// UI state, not server-derived state, so a `hello` reset must not move the player's view. The
// renderer remounts it when a new stage is created; a reconnect keeps the stage, so it also keeps
// the camera (and the tile cache).
export interface ViewportState {
scene: SceneInfo | null
role: Role | null
size: ViewportSize
camera: Camera
/** Grid defaults to on; players and the GM toggle it with the same button (story 18). */
grid: boolean
}
export type ViewportListener = (state: ViewportState) => void
const EMPTY_SIZE: ViewportSize = { width: 1, height: 1 }
export class ViewportModel {
#state: ViewportState = {
scene: null,
role: null,
size: EMPTY_SIZE,
camera: { x: 0, y: 0, zoom: 1 },
grid: true,
}
#listeners = new Set<ViewportListener>()
get state(): ViewportState {
return this.#state
}
subscribe(listener: ViewportListener): () => void {
this.#listeners.add(listener)
return () => {
this.#listeners.delete(listener)
}
}
/** A fresh stage: start from the scene centre at zoom 1 with the grid on. */
reset(scene: SceneInfo | null, role: Role | null, size: ViewportSize): void {
this.#state = {
scene,
role,
size,
camera: scene ? centredCamera(scene, size) : { x: 0, y: 0, zoom: 1 },
grid: true,
}
this.#emit()
}
setSize(size: ViewportSize): void {
if (size.width === this.#state.size.width && size.height === this.#state.size.height) return
this.#state = { ...this.#state, size }
this.#emit()
}
/** The role decides the clamp; a downgrade to player immediately lifts zoom to 0.5. */
setRole(role: Role | null): void {
if (role === this.#state.role) return
const zoom = clampZoom(role, this.#state.camera.zoom)
this.#state = { ...this.#state, role, camera: { ...this.#state.camera, zoom } }
this.#emit()
}
setScene(scene: SceneInfo | null): void {
if (scene?.id === this.#state.scene?.id) {
if (scene === this.#state.scene) return
// Same scene, new object (a reconnect `hello`, or a re-import with a new art_version). Keep
// the camera, but notify: the tile layer must rebuild its window and drop stale textures.
this.#state = { ...this.#state, scene }
this.#emit()
return
}
this.reset(scene, this.#state.role, this.#state.size)
}
pan(dx: number, dy: number): void {
this.#state = { ...this.#state, camera: panCamera(this.#state.camera, dx, dy) }
this.#emit()
}
zoomAt(factor: number, anchor: { x: number; y: number }): void {
const camera = zoomCamera(this.#state.role, this.#state.camera, factor, anchor)
const current = this.#state.camera
if (camera.zoom === current.zoom && camera.x === current.x && camera.y === current.y) return
this.#state = { ...this.#state, camera }
this.#emit()
}
pinch(
start: Camera,
startDistance: number,
distance: number,
startMidpoint: { x: number; y: number },
midpoint: { x: number; y: number },
): void {
const camera = pinchCamera(this.#state.role, start, startDistance, distance, startMidpoint, midpoint)
this.#state = { ...this.#state, camera }
this.#emit()
}
setGrid(visible: boolean): void {
if (visible === this.#state.grid) return
this.#state = { ...this.#state, grid: visible }
this.#emit()
}
toggleGrid(): void {
this.setGrid(!this.#state.grid)
}
#emit(): void {
for (const listener of this.#listeners) listener(this.#state)
}
}
/** The single viewport the render modules share. */
export const viewport = new ViewportModel()
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+344
View File
@@ -0,0 +1,344 @@
// The wall editor's pure half (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4 GM editor). No Pixi, no
// DOM, no socket: presets and derived kinds, the preset-XOR-raw payload rules, local validation
// before an intent leaves the client, grid/endpoint snapping, the one-way arrow side and the undo
// intent. `slices/walls.ts` holds the server's wall records; this module turns editor state into
// exactly the fields DESIGN 6.1 accepts.
//
// Round 1 deliberately has no thickness, height or position control (ADR-0012, spec #63 decision 3):
// the geometry fields stay at the server defaults and `open` is never a `wall.update` patch field
// (it belongs to `door.set`, 6.1 FIXED #49).
import type { Vec2 } from './protocol.ts'
export type WallPreset = 'wall' | 'door' | 'window' | 'one_way'
export type WallKind = 'wall' | 'door' | 'window' | 'one_way' | 'custom'
export type SightDir = 'both' | 'left' | 'right'
export type WallPosition = 'center' | 'left' | 'right'
/** The v1 switches (DESIGN 5.8, 6.1). `open` is a stored door state, not a switch patch. */
export interface WallSwitches {
blocksSight: boolean
blocksMovement: boolean
sightDir: SightDir
playerMarker: boolean
door: boolean
open: boolean
secret: boolean
locked: boolean
}
export const PRESETS: readonly WallPreset[] = ['wall', 'door', 'window', 'one_way']
/**
* The four preset expansions of DESIGN 5.8's table. `window` is the opening form: see-through while
* closed, passable once opened, and it is the only preset that turns `player_marker` on. A preset
* never implies thickness, position or height (6.1).
*/
export function presetSwitches(preset: WallPreset): WallSwitches {
switch (preset) {
case 'door':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'both',
playerMarker: false,
door: true,
open: false,
secret: false,
locked: false,
}
case 'window':
return {
blocksSight: false,
blocksMovement: true,
sightDir: 'both',
playerMarker: true,
door: true,
open: false,
secret: false,
locked: false,
}
case 'one_way':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'left',
playerMarker: false,
door: false,
open: false,
secret: false,
locked: false,
}
case 'wall':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'both',
playerMarker: false,
door: false,
open: false,
secret: false,
locked: false,
}
}
}
/** The 5.8 derived shape label: output only, never stored and never accepted as input. */
export function deriveKind(switches: WallSwitches): WallKind {
if (!switches.blocksSight && switches.blocksMovement) return 'window'
if (switches.blocksSight && switches.sightDir !== 'both') return 'one_way'
if (switches.blocksSight && switches.blocksMovement && switches.door) return 'door'
if (
switches.blocksSight &&
switches.blocksMovement &&
!switches.door &&
switches.sightDir === 'both'
) {
return 'wall'
}
return 'custom'
}
export function flipSightDir(sightDir: SightDir): SightDir {
if (sightDir === 'left') return 'right'
if (sightDir === 'right') return 'left'
return 'both'
}
/**
* The direction the GM's one-way arrow points: from the seeing side toward the watched (blind)
* side. `sight_dir` names the BLIND side (GLOSSARY "Blind side", DESIGN 5.8): `left` is the
* `(-dy, dx)` normal of `a -> b`. Null for a two-way wall (no arrow).
*/
export function arrowVector(a: Vec2, b: Vec2, sightDir: SightDir): Vec2 | null {
if (sightDir === 'both') return null
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const length = Math.hypot(dx, dy)
if (!(length > 0)) return null
if (sightDir === 'left') return normalize([-dy, dx])
return normalize([dy, -dx])
}
function normalize([x, y]: Vec2): Vec2 {
const length = Math.hypot(x, y)
if (!(length > 0)) return [0, 0]
return [x / length === 0 ? 0 : x / length, y / length === 0 ? 0 : y / length]
}
/** The arrow's midpoint: the wall's drawn midpoint, the same anchor a player marker uses (5.8). */
export function wallMidpoint(a: Vec2, b: Vec2): Vec2 {
return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
}
export interface SnapOptions {
enabled: boolean
gridSize: number
endpoints: readonly Vec2[]
/** Endpoint snap radius in world px; it wins over the grid when both are in reach. */
threshold: number
}
/**
* Story 45: optional grid and endpoint snap while drawing. Endpoint snap is tried first (the GM is
* extending a wall), then the grid; disabled means the raw pointer position. Values stay in world
* px and are clamped by the caller to the scene.
*/
export function snapPoint(point: Vec2, options: SnapOptions): Vec2 {
if (!options.enabled) return [point[0], point[1]]
let best: Vec2 | null = null
let bestDistance = options.threshold
for (const endpoint of options.endpoints) {
const distance = Math.hypot(endpoint[0] - point[0], endpoint[1] - point[1])
if (distance <= bestDistance) {
bestDistance = distance
best = endpoint
}
}
if (best) return [best[0], best[1]]
const size = options.gridSize
if (!(size > 0)) return [point[0], point[1]]
return [Math.round(point[0] / size) * size, Math.round(point[1] / size) * size]
}
/** Distance from a point to a segment, for choosing the wall under a click. */
export function distanceToSegment(point: Vec2, a: Vec2, b: Vec2): number {
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const lengthSq = dx * dx + dy * dy
if (lengthSq <= 0) return Math.hypot(point[0] - a[0], point[1] - a[1])
let t = ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / lengthSq
t = Math.min(1, Math.max(0, t))
return Math.hypot(point[0] - (a[0] + t * dx), point[1] - (a[1] + t * dy))
}
/** DESIGN 6.5's text rule for a wall label: 1..64 code points, trimmed, no control characters. */
export function validateLabel(label: string): string | null {
const trimmed = label.trim()
if (trimmed.length === 0) return null
if ([...trimmed].length > 64) return 'The label must be at most 64 characters.'
if (/[\u0000-\u001f\u007f]/.test(trimmed)) return 'The label cannot contain control characters.'
return null
}
/**
* The server's 5.8/6.1 switch rules, checked before an intent leaves the client so the editor can
* show the reason. The server remains the validator; this is the same rule read locally.
*/
export function validateSwitches(switches: WallSwitches): string | null {
if (!switches.blocksSight && switches.sightDir !== 'both') {
return 'invalid: a sight direction needs blocks_sight.'
}
if ((switches.open || switches.secret || switches.locked) && !switches.door) {
return 'invalid: open, secret and locked need a door.'
}
if (switches.secret) {
if (switches.open) return 'invalid: a secret door is always closed.'
if (switches.sightDir !== 'both') return 'invalid: a secret door is always two-way.'
if (!switches.blocksSight || !switches.blocksMovement) {
return 'invalid: a secret door is opaque and solid.'
}
}
if (switches.open && switches.locked) return 'invalid: a locked door cannot open.'
return null
}
/** What a preset payload or a raw-switch payload carries; never both (6.1, preset XOR raw). */
export interface WallPayload {
/** A preset name, or null for the raw switches. */
preset: WallPreset | null
switches: WallSwitches
/** `undefined` leaves it alone; `null` clears it; a string sets it. */
label?: string | null
}
function labelFields(label: string | null | undefined): Record<string, unknown> {
return label === undefined ? {} : { label }
}
/**
* `wall.add` fields for the editor's one-drag default. A preset payload carries ONLY `preset` (plus
* the label): no raw switch may sit beside it, `open:false` included (DESIGN 6.1 FIXED #49). A raw
* payload names every switch; `wall.add` accepts `open` on a new door.
*/
export function buildAddFields(
scene: number,
a: Vec2,
b: Vec2,
payload: WallPayload,
): Record<string, unknown> {
const label = payload.label === null || payload.label === undefined ? {} : { label: payload.label }
if (payload.preset !== null) {
return { scene, a: [a[0], a[1]], b: [b[0], b[1]], preset: payload.preset, ...label }
}
const s = payload.switches
return {
scene,
a: [a[0], a[1]],
b: [b[0], b[1]],
blocks_sight: s.blocksSight,
blocks_movement: s.blocksMovement,
sight_dir: s.sightDir,
player_marker: s.playerMarker,
door: s.door,
open: s.open,
secret: s.secret,
locked: s.locked,
...label,
}
}
/**
* `wall.update` fields. `open` is not a patch field (it belongs to `door.set`): even an editor that
* holds a full switch set must drop it here. A preset replaces the whole switch set; a raw patch
* names every switch it holds except `open`.
*/
export function buildUpdateFields(id: number, payload: WallPayload): Record<string, unknown> {
const label = labelFields(payload.label)
if (payload.preset !== null) return { id, preset: payload.preset, ...label }
const s = payload.switches
return {
id,
blocks_sight: s.blocksSight,
blocks_movement: s.blocksMovement,
sight_dir: s.sightDir,
player_marker: s.playerMarker,
door: s.door,
secret: s.secret,
locked: s.locked,
...label,
}
}
/** `door.set` is the only way to open or close a door (6.1): `open` is a door intent, not a patch. */
export function buildDoorFields(scene: number, id: number, open: boolean): Record<string, unknown> {
return { scene, id, open }
}
/** The restore payload for undoing a delete: the whole wall, switches and label included. */
export interface WallRestore {
a: Vec2
b: Vec2
thickness: number
position: WallPosition
height: number | null
switches: WallSwitches
label: string | null
flags: Record<string, unknown>
}
export type WallUndo =
| { kind: 'remove'; id: number }
| { kind: 'restore'; wall: WallRestore }
| { kind: 'update'; id: number; switches: WallSwitches; label: string | null; flags: Record<string, unknown> }
| { kind: 'door'; id: number; open: boolean }
/** The inverse intent of the last edit, or null when there is nothing to undo. */
export function undoIntent(
scene: number,
undo: WallUndo | null,
): { t: string; fields: Record<string, unknown> } | null {
if (undo === null) return null
switch (undo.kind) {
case 'remove':
return { t: 'wall.remove', fields: { scene, id: undo.id } }
case 'restore': {
const wall = undo.wall
return {
t: 'wall.add',
fields: {
scene,
a: [wall.a[0], wall.a[1]],
b: [wall.b[0], wall.b[1]],
thickness: wall.thickness,
position: wall.position,
height: wall.height,
blocks_sight: wall.switches.blocksSight,
blocks_movement: wall.switches.blocksMovement,
sight_dir: wall.switches.sightDir,
player_marker: wall.switches.playerMarker,
door: wall.switches.door,
open: wall.switches.open,
secret: wall.switches.secret,
locked: wall.switches.locked,
label: wall.label,
flags: wall.flags,
},
}
}
case 'update':
return {
t: 'wall.update',
fields: {
...buildUpdateFields(undo.id, {
preset: null,
switches: undo.switches,
label: undo.label,
}),
flags: undo.flags,
},
}
case 'door':
return { t: 'door.set', fields: buildDoorFields(scene, undo.id, undo.open) }
}
}
+260
View File
@@ -0,0 +1,260 @@
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
// counter, the pending-request map and the reconnect schedule; it emits reducer events and never
// touches the DOM. The socket factory, the clock and the random source are injectable, so the
// backoff and the retry state machine are unit-testable without a browser and without waiting.
//
// Close mapping (6.5, FIXED #18): a server-initiated close is `closing {reason, code}` and then a
// close frame the browser reports as 1005, so the reason always comes from the last `closing` frame.
// `revoked` and `proto-mismatch` are terminal (the reducer goes to the sign-in page / reload and
// this client stops). A close with no `closing` frame is a transport failure: the socket retries
// with exponential backoff and jitter, because a flaky phone network must recover without a reload
// (stories 7, 8). Pending reqIds are dropped with every connection (6.3); a `hello` on a live
// connection does not drop them.
import type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
export interface SocketLike {
send(data: string): void
close(code?: number, reason?: string): void
onopen: (() => void) | null
onmessage: ((event: { data: unknown }) => void) | null
onclose: ((event: { code: number; reason: string }) => void) | null
onerror: ((event: unknown) => void) | null
}
export type ClientEvent =
| { type: 'open' }
| { type: 'frame'; frame: ServerFrame }
| { type: 'close'; reason: CloseReason | null; code: number | null }
| { type: 'reconnecting'; attempt: number; delay: number }
/** The reconnect delays of DESIGN 6.3: 1/2/4/8/10 s, then the cap. Attempts are 1-based. */
export const RECONNECT_BASE_DELAYS_MS = [1000, 2000, 4000, 8000, 10000] as const
/** Jitter is +/- this fraction of the base delay (story 8: "growing, jittered delays"). */
export const RECONNECT_JITTER = 0.2
/** The un-jittered delay for a 1-based attempt number; past the last entry the cap holds. */
export function reconnectBaseMs(attempt: number): number {
const index = Math.min(Math.max(Math.floor(attempt), 1), RECONNECT_BASE_DELAYS_MS.length) - 1
return RECONNECT_BASE_DELAYS_MS[index] ?? RECONNECT_BASE_DELAYS_MS[RECONNECT_BASE_DELAYS_MS.length - 1]!
}
/** The next retry delay: the base schedule times a random factor in [1-jitter, 1+jitter). */
export function backoffDelay(attempt: number, random: () => number = Math.random): number {
const base = reconnectBaseMs(attempt)
const factor = 1 - RECONNECT_JITTER + clamp(random()) * 2 * RECONNECT_JITTER
return Math.round(base * factor)
}
function clamp(value: number): number {
if (!Number.isFinite(value)) return 0.5
return Math.min(Math.max(value, 0), 1)
}
/** `setTimeout`'s handle in the browser; tests substitute their own clock behind this type. */
export type TimerHandle = number
export interface Timers {
setTimeout(fn: () => void, ms: number): TimerHandle
clearTimeout(handle: TimerHandle): void
}
const defaultTimers: Timers = {
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms) as unknown as TimerHandle,
clearTimeout: handle => globalThis.clearTimeout(handle),
}
export interface ProtocolClientOptions {
url?: string
createSocket?: (url: string) => SocketLike
onEvent: (event: ClientEvent) => void
/** Transport failures retry by default (DESIGN 6.3); a terminal server outcome never does. */
autoReconnect?: boolean
random?: () => number
timers?: Timers
}
type Pending = {
resolve: (ack: AckFrame) => void
reject: (error: Error) => void
}
function defaultSocket(url: string): SocketLike {
return new WebSocket(url) as unknown as SocketLike
}
export class ProtocolClient {
#url: string
#createSocket: (url: string) => SocketLike
#onEvent: (event: ClientEvent) => void
#autoReconnect: boolean
#random: () => number
#timers: Timers
#socket: SocketLike | null = null
#nextReqId = 1
#pending = new Map<number, Pending>()
#lastClosing: { reason: CloseReason; code: number } | null = null
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
/** A socket has opened at least once: only then can a transport close be a lost session. */
#everOpened = false
#attempt = 0
#retryTimer: TimerHandle | null = null
constructor(options: ProtocolClientOptions) {
this.#url = options.url ?? wsUrl()
this.#createSocket = options.createSocket ?? defaultSocket
this.#onEvent = options.onEvent
this.#autoReconnect = options.autoReconnect ?? true
this.#random = options.random ?? Math.random
this.#timers = options.timers ?? defaultTimers
}
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
return this.#state
}
get pendingCount(): number {
return this.#pending.size
}
/** The number of consecutive retries scheduled/failed since the last successful open. */
get attempt(): number {
return this.#attempt
}
connect(): void {
if (this.#state !== 'idle') return
this.#state = 'connecting'
this.#lastClosing = null
let socket: SocketLike
try {
socket = this.#createSocket(this.#url)
} catch {
// A socket that cannot even be constructed is a failed upgrade, not a lost session: the
// reducer sends a visitor with no session to the sign-in page (6.5 row 2).
this.#state = 'closed'
this.#onEvent({ type: 'close', reason: null, code: null })
return
}
this.#socket = socket
socket.onopen = () => {
if (this.#state !== 'connecting') return
this.#state = 'open'
this.#everOpened = true
this.#attempt = 0
this.#onEvent({ type: 'open' })
}
socket.onmessage = event => {
if (this.#state === 'closed') return // a frame in flight after the client closed
const frame = parseServerFrame(event.data)
if (!frame) return // binary or unreadable: 6.2 says ignore what cannot be read
if (isClosing(frame)) this.#lastClosing = { reason: frame.reason, code: frame.code }
if (isAck(frame)) {
const pending = this.#pending.get(frame.reqId)
if (pending) {
this.#pending.delete(frame.reqId)
pending.resolve(frame)
}
}
this.#onEvent({ type: 'frame', frame })
}
socket.onerror = () => {
// The browser follows an error with a close; mapping the outcome there keeps it single.
}
socket.onclose = event => {
if (this.#state === 'closed') return
const reason = this.#lastClosing?.reason ?? null
const code = this.#lastClosing?.code ?? event.code ?? null
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
// A named reason always came from a `closing` frame: it is an application outcome, and
// 6.5 says the client must stop for revoked/proto-mismatch/evicted/flood. Only a bare
// transport close (reason null) is retried, and only after this client was live once.
if (reason === null && this.#autoReconnect && this.#everOpened) {
this.#onEvent({ type: 'close', reason, code })
this.#scheduleRetry()
return
}
this.#state = 'closed'
this.#onEvent({ type: 'close', reason, code })
}
}
/**
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
* `hello` on a live connection does not drop them.
*
* `onReqId` is told the request id once the frame has left the socket, so a caller that must
* match the ack itself (the drag's `token.move`, #72) can record it before the reply can arrive.
*/
send(
t: string,
fields: Record<string, unknown> = {},
onReqId?: (reqId: number) => void,
): Promise<AckFrame> {
const socket = this.#socket
if (this.#state !== 'open' || !socket) {
return Promise.reject(new Error('not connected'))
}
const reqId = this.#nextReqId++
const frame = encodeIntent(t, reqId, fields)
return new Promise<AckFrame>((resolve, reject) => {
this.#pending.set(reqId, { resolve, reject })
try {
socket.send(frame)
onReqId?.(reqId)
} catch (error) {
this.#pending.delete(reqId)
reject(error instanceof Error ? error : new Error(String(error)))
}
})
}
/** Retry at once instead of waiting out the backoff (used when the browser goes online). */
retryNow(): void {
if (this.#retryTimer === null) return
this.#timers.clearTimeout(this.#retryTimer)
this.#retryTimer = null
this.connect()
}
close(): void {
this.#cancelRetry()
if (this.#state === 'closed') return
this.#state = 'closed'
try {
this.#socket?.close()
} catch {
// A socket that is already gone is the outcome we wanted.
}
this.#failPending(new Error('connection closed by the client'))
}
#scheduleRetry(): void {
this.#attempt += 1
const delay = backoffDelay(this.#attempt, this.#random)
this.#state = 'idle' // connect() may run again; the view stays in the reducer meanwhile
this.#socket = null
this.#onEvent({ type: 'reconnecting', attempt: this.#attempt, delay })
this.#retryTimer = this.#timers.setTimeout(() => {
this.#retryTimer = null
this.connect()
}, delay)
}
#cancelRetry(): void {
if (this.#retryTimer === null) return
this.#timers.clearTimeout(this.#retryTimer)
this.#retryTimer = null
}
#failPending(error: Error): void {
const pending = [...this.#pending.values()]
this.#pending.clear()
for (const entry of pending) entry.reject(error)
}
}
+173
View File
@@ -0,0 +1,173 @@
// T11 (#74) reducer seam: the GM admin slice consumes `token`/`token_gone` frames and owns the
// token selection that #71/#72 will read. Pure, no DOM and no socket.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import type { AdminToken } from '../src/slices/admin.ts'
import { adminTokens, selectedTokenId } from '../src/slices/admin.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number): ReducerEvent =>
frame({
t: 'hello',
n,
proto: 2,
role: 'gm',
me: { id: 1, name: 'GM' },
scene: {
id: 1,
name: 'Cellar',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
},
})
const gmToken = (id: string, patch: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n: 3,
id,
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [{ status: 'stuck', source: 'walls' }],
props: {},
kind: 'npc',
controller: null,
gm_only: false,
flags: {},
vision_radius: null,
radius_own: null,
character_id: null,
descriptive_name: 'Rat',
actual_name: 'Giant Rat',
reveal_all: false,
revealed: [],
...patch,
})
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
const tokenOf = (state: RootState, id: string): AdminToken | undefined =>
adminTokens(state).find(token => token.id === id)
describe('GM token records', () => {
it('upserts the GM fields of a `token` frame and replaces on a later frame', () => {
const first = run({ type: 'connecting' }, hello(1), gmToken('abc'))
expect(adminTokens(first)).toHaveLength(1)
expect(tokenOf(first, 'abc')).toMatchObject({
id: 'abc',
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
kind: 'npc',
controller: null,
gmOnly: false,
statuses: [{ status: 'stuck', source: 'walls' }],
descriptiveName: 'Rat',
actualName: 'Giant Rat',
flags: {},
visionRadius: null,
})
const changed = reduce(
first,
gmToken('abc', {
name: 'Big Rat',
pos: [420, 400],
radius: 30,
gm_only: true,
controller: 2,
statuses: [{ status: 'squeezed', source: 'GM' }],
}),
)
expect(adminTokens(changed)).toHaveLength(1)
expect(tokenOf(changed, 'abc')).toMatchObject({
name: 'Big Rat',
pos: [420, 400],
radius: 30,
gmOnly: true,
controller: 2,
statuses: [{ status: 'squeezed', source: 'GM' }],
})
})
it('keeps the free-form flags and the vision radius the panel edits (#78)', () => {
const state = run(
{ type: 'connecting' },
hello(1),
gmToken('abc', { flags: { vision: true, note: 'kept' }, vision_radius: 300 }),
)
expect(tokenOf(state, 'abc')).toMatchObject({
flags: { vision: true, note: 'kept' },
visionRadius: 300,
})
const changed = reduce(state, gmToken('abc', { flags: { vision: false }, vision_radius: null }))
expect(tokenOf(changed, 'abc')).toMatchObject({
flags: { vision: false },
visionRadius: null,
})
})
it('ignores a malformed token frame instead of inventing a row', () => {
const state = run({ type: 'connecting' }, hello(1), frame({ t: 'token', n: 2, id: 7 }))
expect(adminTokens(state)).toEqual([])
})
it('removes the row on token_gone and clears a selection that pointed at it', () => {
const selected = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
{ type: 'admin-select', token: 'abc' },
frame({ t: 'token_gone', n: 4, id: 'abc' }),
)
expect(adminTokens(selected)).toEqual([])
expect(selectedTokenId(selected)).toBeNull()
})
it('hello resets the token list and the selection with every other slice', () => {
const live = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
{ type: 'admin-select', token: 'abc' },
)
expect(selectedTokenId(live)).toBe('abc')
const reset = reduce(live, hello(9))
expect(adminTokens(reset)).toEqual([])
expect(selectedTokenId(reset)).toBeNull()
})
})
describe('token selection (#71/#72 hook)', () => {
it('is slice state, changed only by the admin-select event', () => {
const state = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
gmToken('def'),
{ type: 'admin-select', token: 'def' },
)
expect(selectedTokenId(state)).toBe('def')
expect(adminTokens(state).map(token => token.id)).toEqual(['abc', 'def'])
expect(selectedTokenId(reduce(state, { type: 'admin-select', token: null }))).toBeNull()
})
})
+148
View File
@@ -0,0 +1,148 @@
// T12 (#75) reducer seam: the GM cast slice consumes `character`, `encountered` and the GM-only
// `seen_by` field of `token` frames. Pure, no DOM and no socket.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { castCharacters, encounteredOf, seenByOf } from '../src/slices/cast.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number): ReducerEvent =>
frame({
t: 'hello',
n,
proto: 2,
role: 'gm',
me: { id: 1, name: 'GM' },
})
const character = (id: string, patch: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'character',
n: 2,
id,
owner: 2,
descriptive_name: 'a cloaked figure',
actual_name: 'Lord Vex',
reveal_all: false,
revealed: [],
props: { public: {}, owner: {}, gm: {} },
...patch,
})
const encountered = (player: number, patch: Record<string, unknown> = {}): ReducerEvent =>
frame({ t: 'encountered', n: 3, player, full: false, set: [], del: [], ...patch })
const token = (id: string, seenBy: number[]): ReducerEvent =>
frame({
t: 'token',
n: 4,
id,
scene: 1,
name: 'a cloaked figure',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [],
props: {},
seen_by: seenBy,
})
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
describe('GM cast slice', () => {
it('upserts character frames, keeps the reveal list and replaces on a later frame', () => {
const first = run({ type: 'connecting' }, hello(1), character('c1'))
expect(castCharacters(first)).toEqual([
expect.objectContaining({
id: 'c1',
owner: 2,
descriptiveName: 'a cloaked figure',
actualName: 'Lord Vex',
revealAll: false,
revealed: [],
}),
])
const changed = reduce(
first,
character('c1', { owner: 3, actual_name: 'The Duke', reveal_all: true, revealed: [2, 3] }),
)
expect(castCharacters(changed)).toEqual([
expect.objectContaining({
id: 'c1',
owner: 3,
actualName: 'The Duke',
revealAll: true,
revealed: [2, 3],
}),
])
})
it('removes a character on character_gone and ignores a malformed record', () => {
const state = run(
{ type: 'connecting' },
hello(1),
character('c1'),
frame({ t: 'character', n: 3, id: 7 }),
frame({ t: 'character_gone', n: 4, id: 'c1' }),
)
expect(castCharacters(state)).toEqual([])
})
it('keeps one encountered list per player: full replaces, a diff upserts, del removes', () => {
const full = run(
{ type: 'connecting' },
hello(1),
encountered(2, {
full: true,
set: [
{ id: 't1', name: 'Rat', grey: false },
{ id: 't2', name: 'Bat', grey: true },
],
}),
)
expect(encounteredOf(full, 2)).toEqual([
{ id: 't1', name: 'Rat', grey: false },
{ id: 't2', name: 'Bat', grey: true },
])
const diff = reduce(
full,
encountered(2, { set: [{ id: 't2', name: 'Giant Bat', grey: false }], del: ['t1'] }),
)
expect(encounteredOf(diff, 2)).toEqual([{ id: 't2', name: 'Giant Bat', grey: false }])
expect(encounteredOf(diff, 3)).toEqual([])
})
it('records seen_by from GM token frames and drops it on token_gone', () => {
const state = run(
{ type: 'connecting' },
hello(1),
token('t1', [2, 3]),
token('t2', []),
)
expect(seenByOf(state, 't1')).toEqual([2, 3])
expect(seenByOf(state, 't2')).toEqual([])
expect(seenByOf(reduce(state, frame({ t: 'token_gone', n: 5, id: 't1' })), 't1')).toBeNull()
})
it('hello resets every list and the seen_by map with every other slice', () => {
const live = run(
{ type: 'connecting' },
hello(1),
character('c1'),
encountered(2, { full: true, set: [{ id: 't1', name: 'Rat', grey: false }] }),
token('t1', [2]),
)
const reset = reduce(live, hello(9))
expect(castCharacters(reset)).toEqual([])
expect(encounteredOf(reset, 2)).toEqual([])
expect(seenByOf(reset, 't1')).toBeNull()
})
})
+202
View File
@@ -0,0 +1,202 @@
// The fog slice (T7, #70; DESIGN 6.1 `explored`/`vision`/`marker`, 7.3). These are reducer-seam
// tests: server frames in, state out. The pixels themselves are proven in the browser e2e
// (`client/e2e/fog.test.mjs`), not here.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { fogOf } from '../src/slices/fog.ts'
import type { FogState } from '../src/slices/fog.ts'
const scene = {
id: 1,
name: 'Cellar',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
}
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' }, scene })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
const fogAfter = (...events: ReducerEvent[]): FogState => fogOf(run(hello(1), ...events))
describe('the explored grid comes from hello.scene (6.1)', () => {
it('is empty until hello, then sized in cells', () => {
const before = fogOf(initialState())
expect(before.cols).toBe(0)
expect(before.sceneId).toBeNull()
const fog = fogAfter()
expect(fog.cols).toBe(128)
expect(fog.rows).toBe(128)
expect(fog.cell).toBe(32)
expect(fog.sceneId).toBe(1)
expect(fog.cells.size).toBe(0)
expect(fog.exploredVersion).toBe(0)
})
})
describe('explored full and diff frames (6.1)', () => {
it('a full RLE snapshot answers every explored cell and marks the update a snapshot', () => {
// Row cy=2: x=5..7 and x=10..11 (runs are [x0, len] pairs).
const fog = fogAfter(frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 3, 10, 2]] }))
const base = 2 * 128
expect([...fog.cells].sort((a, b) => a - b)).toEqual([
base + 5,
base + 6,
base + 7,
base + 10,
base + 11,
])
expect(fog.fresh).toHaveLength(5)
expect(fog.snapshot).toBe(true)
expect(fog.exploredVersion).toBe(1)
})
it('a diff adds only new cells and reports exactly those as fresh', () => {
const fog = fogAfter(
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
frame({
t: 'explored',
n: 3,
full: false,
cells: [
[5, 2], // explored already: not fresh again
[6, 2], // explored already
[7, 2], // new
],
}),
)
expect(fog.cells.size).toBe(3)
expect(fog.fresh).toEqual([2 * 128 + 7])
expect(fog.snapshot).toBe(false)
expect(fog.exploredVersion).toBe(2)
})
it('a diff with nothing new changes no version and reports no fresh cells', () => {
const fog = fogAfter(
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
frame({ t: 'explored', n: 3, full: false, cells: [[5, 2], [6, 2]] }),
)
expect(fog.cells.size).toBe(2)
expect(fog.fresh).toEqual([])
expect(fog.exploredVersion).toBe(1)
})
it('ignores cells outside the grid and malformed frames without half-applying them', () => {
const fog = fogAfter(
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2], [999, 0, 3], [3, -4, 2]] }),
frame({ t: 'explored', n: 3, full: false, cells: [[-1, 0], [128, 0], [0, 128], ['x', 0]] }),
frame({ t: 'explored', n: 4, full: false, cells: 'nope' }),
)
expect(fog.cells.size).toBe(2)
expect(fog.exploredVersion).toBe(1)
})
})
describe('vision polygons (6.1)', () => {
it('keeps this player\'s polygons and drops malformed ones whole', () => {
const fog = fogAfter(
frame({
t: 'vision',
n: 2,
polys: [
{ id: 'tok-1', pts: [[10, 10], [20, 10], [20, 20]] },
{ id: 'short', pts: [[0, 0], [1, 1]] },
{ id: 'bad-point', pts: [[0, 0], [1, 'x'], [2, 2]] },
{ pts: [[0, 0], [1, 1], [2, 0]] },
],
}),
)
expect(fog.polys).toEqual([{ id: 'tok-1', pts: [[10, 10], [20, 10], [20, 20]] }])
expect(fog.visionVersion).toBe(1)
})
it('a later vision frame replaces the union (a token leaving sight is gone)', () => {
const fog = fogAfter(
frame({ t: 'vision', n: 2, polys: [{ id: 'a', pts: [[0, 0], [9, 0], [9, 9]] }] }),
frame({ t: 'vision', n: 3, polys: [] }),
)
expect(fog.polys).toEqual([])
expect(fog.visionVersion).toBe(2)
})
})
describe('player markers (5.8, 6.1)', () => {
it('a full set replaces the whole memory', () => {
const fog = fogAfter(
frame({ t: 'marker', n: 2, full: true, set: [{ id: 'm1', pos: [100, 200] }] }),
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm2', pos: [300, 400] }] }),
frame({ t: 'marker', n: 4, full: true, set: [{ id: 'm3', pos: [500, 600] }] }),
)
expect(fog.markers).toEqual({ m3: [500, 600] })
})
it('a diff adds and retracts by id; an anchor change moves the same id', () => {
const fog = fogAfter(
frame({ t: 'marker', n: 2, full: true, set: [{ id: 'm1', pos: [100, 200] }] }),
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm2', pos: [300, 400] }] }),
frame({ t: 'marker', n: 4, full: false, set: [{ id: 'm1', pos: [110, 200] }] }),
frame({ t: 'marker', n: 5, full: false, set: [], del: ['m2', 'never-seen'] }),
)
expect(fog.markers).toEqual({ m1: [110, 200] })
expect(fog.markerVersion).toBe(4)
})
it('a diff that changes nothing does not bump the version', () => {
const fog = fogAfter(
frame({ t: 'marker', n: 2, full: false, set: [{ id: 'm1', pos: [100, 200] }] }),
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm1', pos: [100, 200] }] }),
frame({ t: 'marker', n: 4, full: false, set: [], del: [] }),
)
expect(fog.markerVersion).toBe(1)
})
})
describe('reset and the GM (6.3)', () => {
it('a second hello clears explored, vision and markers and rebuilds the grid', () => {
const reset = run(
hello(1),
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
frame({ t: 'vision', n: 3, polys: [{ id: 'a', pts: [[0, 0], [9, 0], [9, 9]] }] }),
frame({ t: 'marker', n: 4, full: true, set: [{ id: 'm1', pos: [1, 2] }] }),
hello(1),
)
const fog = fogOf(reset)
expect(fog.cols).toBe(128)
expect(fog.cells.size).toBe(0)
expect(fog.fresh).toEqual([])
expect(fog.polys).toEqual([])
expect(fog.markers).toEqual({})
expect(fog.exploredVersion).toBe(0)
expect(fog.visionVersion).toBe(0)
expect(fog.markerVersion).toBe(0)
})
it('a GM connection receives no fog frames, so its fog state stays empty', () => {
const state = run(
frame({ t: 'hello', n: 1, proto: 2, role: 'gm', me: { id: 1, name: 'GM' }, scene }),
frame({ t: 'roster', n: 2, players: [] }),
)
const fog = fogOf(state)
expect(fog.cols).toBe(128)
expect(fog.cells.size).toBe(0)
expect(fog.polys).toEqual([])
expect(fog.markers).toEqual({})
})
})
+149
View File
@@ -0,0 +1,149 @@
// T8 (#71): the lists' reducer seam. Story 31 (my characters with my own values) and story 32 (an
// encountered list with greyed entries). `character`/`character_gone` and `encountered` in, the
// two lists out; `hello` resets both with every other slice.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { charactersOf, ownCharactersOf } from '../src/slices/characters.ts'
import { encounteredOf } from '../src/slices/encountered.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number, role: 'gm' | 'player' = 'player', id = 2): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role, me: { id, name: role === 'gm' ? 'GM' : 'Ann' } })
/** The owner's view has no `owner`/`reveal_all`/`revealed` field (6.1). */
const ownerCharacter = (n: number, id: string, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'character',
n,
id,
descriptive_name: 'Ann',
actual_name: 'Ann of the Vale',
props: { public: {}, owner: { hp: 12 } },
...overrides,
})
const gmCharacter = (n: number, id: string, owner: number, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'character',
n,
id,
owner,
descriptive_name: 'Ann',
actual_name: 'Ann of the Vale',
reveal_all: false,
revealed: [],
props: { public: {}, owner: { hp: 12 }, gm: { secret: true } },
...overrides,
})
const encountered = (n: number, body: Record<string, unknown>): ReducerEvent =>
frame({ t: 'encountered', n, ...body })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
describe('my characters (story 31)', () => {
it('lists the characters the server sent the owner, with their own values', () => {
const state = run({ type: 'connecting' }, hello(1), ownerCharacter(2, 'char1'))
expect(charactersOf(state)).toHaveLength(1)
expect(ownCharactersOf(state)).toEqual([
expect.objectContaining({
id: 'char1',
descriptiveName: 'Ann',
actualName: 'Ann of the Vale',
props: { public: {}, owner: { hp: 12 } },
}),
])
})
it('replaces a character on a later frame and drops it on character_gone', () => {
const state = run(
{ type: 'connecting' },
hello(1),
ownerCharacter(2, 'char1'),
ownerCharacter(3, 'char1', { descriptive_name: 'Ann the Bold' }),
)
expect(ownCharactersOf(state)).toEqual([expect.objectContaining({ descriptiveName: 'Ann the Bold' })])
const gone = reduce(state, frame({ t: 'character_gone', n: 4, id: 'char1' }))
expect(ownCharactersOf(gone)).toEqual([])
expect(charactersOf(gone)).toEqual([])
})
it('shows a GM only the characters that GM owns, never the whole cast', () => {
const state = run(
{ type: 'connecting' },
hello(1, 'gm', 1),
gmCharacter(2, 'char1', 2),
gmCharacter(3, 'char2', 1),
)
expect(ownCharactersOf(state).map(character => character.id)).toEqual(['char2'])
})
it('clears the list on hello', () => {
const state = run({ type: 'connecting' }, hello(1), ownerCharacter(2, 'char1'), hello(3))
expect(ownCharactersOf(state)).toEqual([])
})
})
describe('encountered list (story 32)', () => {
it('replaces the whole list on full:true and keeps the grey flag', () => {
const state = run(
{ type: 'connecting' },
hello(1),
encountered(2, {
full: true,
set: [
{ id: 'aaa', name: 'Rat', grey: false },
{ id: 'bbb', name: 'Bat', grey: true },
],
}),
)
expect(encounteredOf(state)).toEqual([
{ id: 'aaa', name: 'Rat', grey: false },
{ id: 'bbb', name: 'Bat', grey: true },
])
})
it('applies a diff: set upserts and del removes, without touching anything else', () => {
const state = run(
{ type: 'connecting' },
hello(1),
encountered(2, {
full: true,
set: [
{ id: 'aaa', name: 'Rat', grey: false },
{ id: 'bbb', name: 'Bat', grey: false },
],
}),
encountered(3, { full: false, set: [{ id: 'aaa', name: 'Rat', grey: true }], del: ['bbb'] }),
)
expect(encounteredOf(state)).toEqual([{ id: 'aaa', name: 'Rat', grey: true }])
})
it('ignores the GM copy, which is one message per player and not the GM own list', () => {
const state = run(
{ type: 'connecting' },
hello(1, 'gm', 1),
encountered(2, { full: true, set: [{ id: 'aaa', name: 'Rat', grey: false }], player: 2 }),
)
expect(encounteredOf(state)).toEqual([])
})
it('clears on hello', () => {
const state = run(
{ type: 'connecting' },
hello(1),
encountered(2, { full: true, set: [{ id: 'aaa', name: 'Rat', grey: false }] }),
hello(3),
)
expect(encounteredOf(state)).toEqual([])
})
})
+284
View File
@@ -0,0 +1,284 @@
// T9 (#72): the drag state machine at the reducer seam (DESIGN 7.5, 5.5, 6.4). Every test drives
// the same events the drag render module and the socket produce, then reads what the token renderer
// would draw. No DOM, no GPU, no socket.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { tokenOf, tokensOf } from '../src/slices/tokens.ts'
import type { TokenView } from '../src/slices/tokens.ts'
import {
draggableAt,
draggableTokens,
dragOf,
drawPositionOf,
moveOf,
} from '../src/slices/move.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n = 1): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } })
const token = (n: number, id: string, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n,
id,
scene: 1,
name: 'Ann',
pos: [400, 400],
radius: 20,
mine: true,
statuses: [],
props: {},
...overrides,
})
const ack = (n: number, reqId: number, ok: boolean, extra: Record<string, unknown> = {}): ReducerEvent =>
frame({ t: 'ack', n, reqId, ok, ...extra })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
/** The initial live view: one controlled token at 400,400 and one another player controls. */
const live = (): ReducerEvent[] => [
{ type: 'connecting' },
hello(),
token(2, 'own'),
token(3, 'other', { mine: false, pos: [800, 400] }),
]
describe('optimistic drag (stories 38, 39, 41)', () => {
it('draws the token under the pointer and ignores authoritative frames while dragging', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [450, 430] })
expect(drawPositionOf(state, 'own')).toEqual([450, 430])
expect(dragOf(state)?.id).toBe('own')
// Story 41: a slow ack/authoritative frame must not move the sprite under the finger.
state = reduce(state, token(4, 'own', { pos: [400, 400] }))
expect(drawPositionOf(state, 'own')).toEqual([450, 430])
// The reducer still keeps what the server said; only drawing is overridden.
expect(tokenOf(state, 'own')?.pos).toEqual([400, 400])
})
it('tracks the last pointer position; the input module decides which tokens may start a drag', () => {
let state = run(...live())
// The slice is a mechanical state machine: `draggableAt` (tested below) is the permission gate,
// and the server still refuses a move of someone else's token (story 39) with a nack.
expect(draggableAt(tokensOf(state), 'player', [800, 400])).toBeNull()
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [410, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [420, 410] })
expect(drawPositionOf(state, 'own')).toEqual([420, 410])
// A drag-move for another id is ignored while this drag is active.
state = reduce(state, { type: 'drag-move', id: 'other', pos: [820, 400] })
expect(dragOf(state)?.id).toBe('own')
expect(drawPositionOf(state, 'other')).toBeNull()
})
})
describe('ack reconciliation and rollback (stories 39, 40, 42)', () => {
it('holds the predicted position until the authoritative frame after an ok ack', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [460, 400] })
state = reduce(state, { type: 'move-sent', reqId: 7, id: 'own', pos: [460, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [460, 400] })
expect(dragOf(state)).toBeNull()
expect(drawPositionOf(state, 'own')).toEqual([460, 400])
// The ack precedes the token frame (settleLocked): keep drawing the confirmed position.
state = reduce(state, ack(5, 7, true, { pos: [460, 400] }))
expect(moveOf(state).pending).toEqual([])
expect(drawPositionOf(state, 'own')).toEqual([460, 400])
expect(moveOf(state).accepted).toBe(1)
expect(moveOf(state).rollbacks).toEqual({})
// The frame lands: the prediction is no longer needed.
state = reduce(state, token(6, 'own', { pos: [460, 400] }))
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('rolls back a uniform nack while idle, and clears the tween when the renderer is done', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [640, 400] })
state = reduce(state, { type: 'move-sent', reqId: 8, id: 'own', pos: [640, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [640, 400] })
// The uniform nack (5.5): ok:false, the old position, no code.
state = reduce(state, ack(5, 8, false, { pos: [400, 400] }))
const move = moveOf(state)
expect(move.pending).toEqual([])
expect(move.refused).toBe(1)
expect(move.rollbackCount).toBe(1)
const rollback = move.rollbacks['own']
expect(rollback).toBeDefined()
expect(rollback).toMatchObject({ id: 'own', from: [640, 400], to: [400, 400] })
// No pending intent remains, so the draw falls through to the authoritative frame.
expect(drawPositionOf(state, 'own')).toBeNull()
state = reduce(state, { type: 'rollback-done', id: 'own', seq: rollback!.seq })
expect(moveOf(state).rollbacks).toEqual({})
// A stale completion cannot clear a newer tween.
state = reduce(state, ack(6, 8, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks).toEqual({})
})
it('does not snap under the finger: a nack while dragging rolls back on release', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [600, 400] })
state = reduce(state, { type: 'move-sent', reqId: 9, id: 'own', pos: [600, 400] })
state = reduce(state, ack(5, 9, false, { pos: [400, 400] }))
// Still under the pointer, still at the pointer; the snap is remembered for release.
expect(drawPositionOf(state, 'own')).toEqual([600, 400])
expect(moveOf(state).snap).toEqual({ id: 'own', pos: [400, 400] })
expect(moveOf(state).rollbacks).toEqual({})
state = reduce(state, { type: 'drag-move', id: 'own', pos: [610, 410] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [610, 410] })
// The release sends the final position; its nack starts the tween from where the finger was.
state = reduce(state, { type: 'move-sent', reqId: 10, id: 'own', pos: [610, 410] })
state = reduce(state, ack(6, 10, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks['own']).toMatchObject({
from: [610, 410],
to: [400, 400],
})
expect(moveOf(state).snap).toBeNull()
})
it('lets a later accepted intent win over an earlier refusal', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [800, 400] })
state = reduce(state, { type: 'move-sent', reqId: 11, id: 'own', pos: [800, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [500, 400] })
state = reduce(state, { type: 'move-sent', reqId: 12, id: 'own', pos: [500, 400] })
// The first (over-cap) intent is refused while the second is in flight: no tween yet.
state = reduce(state, ack(5, 11, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks).toEqual({})
expect(moveOf(state).snap).toBeNull()
expect(drawPositionOf(state, 'own')).toEqual([500, 400])
state = reduce(state, ack(6, 12, true, { pos: [500, 400] }))
expect(moveOf(state).accepted).toBe(1)
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).rollbacks).toEqual({})
})
it('drops a rate-limited intent quietly and reconciles with the next frame (story 42)', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'move-sent', reqId: 13, id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [430, 400] })
// 6.4: refused by the bucket, no position, no rollback, connection stays open.
state = reduce(state, ack(5, 13, false, { code: 'rate-limited' }))
expect(moveOf(state).rateLimited).toBe(1)
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).rollbacks).toEqual({})
expect(drawPositionOf(state, 'own')).toBeNull()
// The next authoritative frame is the reconciliation; a drag continues from it, not from a
// corrupted map.
state = reduce(state, token(6, 'own', { pos: [420, 400] }))
expect(tokenOf(state, 'own')?.pos).toEqual([420, 400])
state = reduce(state, { type: 'drag-start', id: 'own', pos: [420, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [440, 400] })
expect(drawPositionOf(state, 'own')).toEqual([440, 400])
})
it('ignores acks for intents this slice does not own', () => {
let state = run(...live())
state = reduce(state, ack(5, 99, false, { pos: [1, 1] }))
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).pending).toEqual([])
})
})
describe('pending map lifecycle (6.3)', () => {
it('drops every pending reqId, drag and tween when the connection closes', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'move-sent', reqId: 20, id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'move-sent', reqId: 21, id: 'own', pos: [440, 400] })
expect(moveOf(state).pending).toHaveLength(2)
state = reduce(state, { type: 'close', reason: null, code: 1006 })
const move = moveOf(state)
expect(move.pending).toEqual([])
expect(move.dropped).toBe(2)
expect(move.drag).toBeNull()
expect(move.rollbacks).toEqual({})
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('drops pending intents on hello (the full resync resets every slice)', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'move-sent', reqId: 30, id: 'own', pos: [430, 400] })
state = reduce(state, hello(10))
expect(moveOf(state).pending).toEqual([])
expect(moveOf(state).drag).toBeNull()
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('stops a drag when its token leaves the view', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, frame({ t: 'token_gone', n: 4, id: 'own' }))
expect(moveOf(state).drag).toBeNull()
expect(drawPositionOf(state, 'own')).toBeNull()
})
})
describe('hit test and permission (stories 38, 43)', () => {
const view = (id: string, mine: boolean, pos: [number, number]): TokenView => ({
id,
scene: 1,
name: id,
pos,
radius: 20,
mine,
statuses: [],
props: {},
gmOnly: false,
kind: null,
controller: null,
characterId: null,
})
const views = [view('a', true, [100, 100]), view('b', false, [200, 100])]
it('picks the topmost token under the pointer that the role may move', () => {
expect(draggableAt(views, 'player', [100, 100])?.id).toBe('a')
expect(draggableAt(views, 'player', [200, 100])).toBeNull()
expect(draggableAt(views, 'gm', [200, 100])?.id).toBe('b')
expect(draggableAt(views, 'player', [150, 150])).toBeNull()
expect(draggableAt(views, null, [100, 100])).toBeNull()
})
it('lists what the session may drag: its own tokens, or every token for the GM', () => {
let state = run(...live())
expect(draggableTokens(state).map(item => item.id)).toEqual(['own'])
state = run(
{ type: 'connecting' },
frame({ t: 'hello', n: 1, proto: 2, role: 'gm', me: { id: 1, name: 'GM' } }),
token(2, 'own', { mine: false }),
token(3, 'other', { mine: false }),
)
expect(tokensOf(state)).toHaveLength(2)
expect(draggableTokens(state).map(item => item.id)).toEqual(['own', 'other'])
})
})
+68
View File
@@ -0,0 +1,68 @@
// #82 perf overlay seam: URL gating, the rolling window's percentiles and the one-line format.
// Pure (no DOM/Pixi), so the numbers the phone reads are pinned without a browser.
import { describe, expect, it } from 'vitest'
import { PerfWindow, formatSnapshot, percentile, perfEnabled } from '../src/perf.ts'
describe('URL gate', () => {
it('is off when the query is absent, empty or explicitly false', () => {
for (const search of ['', '?x=1', '?perf=', '?perf=0', '?perf=false', '?perf=off', '?perf=no']) {
expect(perfEnabled(search), search).toBe(false)
}
})
it('is on for 1/true/on/yes, case-insensitively', () => {
for (const search of ['?perf=1', '?perf=true', '?perf=TRUE', '?perf=on', '?perf=yes', '?a=b&perf=1']) {
expect(perfEnabled(search), search).toBe(true)
}
})
})
describe('percentile', () => {
it('is null for an empty sample and nearest-rank otherwise', () => {
expect(percentile([], 0.5)).toBeNull()
expect(percentile([16, 17, 18, 19, 20], 0.5)).toBe(18)
expect(percentile([20, 16, 20, 18, 16], 0.95)).toBe(20)
expect(percentile([16], 0.95)).toBe(16)
})
})
describe('rolling window', () => {
it('reports fps from the mean frame interval and p50/p95 of frames and JS', () => {
const window = new PerfWindow(1000)
// Five 16 ms frames at exactly 1 s span: 62.5 fps, p50 16, p95 20.
for (let i = 0; i < 5; i += 1) window.add(i === 4 ? 20 : 16, i + 0.5, 1000 + i * 16)
const snapshot = window.snapshot(1100)
expect(snapshot.samples).toBe(5)
expect(snapshot.fps).toBeCloseTo(59.52, 2)
expect(snapshot.frameP50).toBe(16)
expect(snapshot.frameP95).toBe(20)
expect(snapshot.jsP50).toBe(2.5)
expect(snapshot.jsP95).toBe(4.5)
})
it('drops samples older than the window and ignores a non-positive frame', () => {
const window = new PerfWindow(1000)
window.add(16, 1, 1000)
window.add(0, 1, 1000)
window.add(-1, 1, 1000)
window.add(16, 1, 2500)
const snapshot = window.snapshot(2600)
expect(snapshot.samples).toBe(1)
expect(snapshot.fps).toBeCloseTo(62.5, 5)
})
it('has no fps before a sample and formats a missing JS measure as an em dash', () => {
expect(new PerfWindow().snapshot(0).fps).toBeNull()
const text = formatSnapshot(
{ fps: 59.9, frameP50: 16.7, frameP95: 17.1, jsP50: null, jsP95: null, samples: 600 },
50,
50,
1.25,
)
expect(text).toContain('fps 59.9')
expect(text).toContain('frame p50 16.7 p95 17.1 ms')
expect(text).toContain('JS p50 — p95 — ms')
expect(text).toContain('tokens visible 50 / total 50')
expect(text).toContain('zoom 1.25')
})
})
+137
View File
@@ -0,0 +1,137 @@
import { describe, expect, it } from 'vitest'
import {
CLOSE_REASONS,
PROTO,
closeOutcome,
encodeIntent,
isAck,
isClosing,
isHello,
parseServerFrame,
wsUrl,
} from '../src/protocol.ts'
const scene = {
id: 1,
name: 'Cellar',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
}
describe('server envelope', () => {
it('parses a JSON object with a string t and an integer n >= 1', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'roster', n: 3, players: [] }))
expect(frame).toEqual({ t: 'roster', n: 3, players: [] })
})
it('ignores unknown frame types without dropping them (6.2: additive only)', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'future_frame', n: 2, x: 1 }))
expect(frame?.t).toBe('future_frame')
})
it.each([
['binary', new Uint8Array([1, 2, 3])],
['non-JSON', '{not json'],
['array', '[]'],
['null', 'null'],
['no t', JSON.stringify({ n: 1 })],
['empty t', JSON.stringify({ t: '', n: 1 })],
['no n', JSON.stringify({ t: 'hello' })],
['n = 0', JSON.stringify({ t: 'hello', n: 0 })],
['fractional n', JSON.stringify({ t: 'hello', n: 1.5 })],
['string n', JSON.stringify({ t: 'hello', n: '1' })],
])('rejects %s', (_name, raw) => {
expect(parseServerFrame(raw)).toBeNull()
})
})
describe('hello', () => {
it('accepts the DESIGN 6.1 shape and carries the scene block', () => {
const frame = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: 'Ann' }, scene }),
)
expect(frame && isHello(frame)).toBe(true)
if (frame && isHello(frame)) {
expect(frame.proto).toBe(2)
expect(frame.scene?.w).toBe(4096)
}
})
it('accepts the unnamed-player minimum (proto, role, me only)', () => {
const frame = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: null } }),
)
expect(frame && isHello(frame)).toBe(true)
})
it('rejects a wrong role or proto', () => {
const badRole = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'admin', me: { id: 1, name: null } }),
)
const badProto = parseServerFrame(
JSON.stringify({ t: 'hello', n: 1, proto: '2', role: 'gm', me: { id: 1, name: null } }),
)
expect(badRole && isHello(badRole)).toBe(false)
expect(badProto && isHello(badProto)).toBe(false)
})
})
describe('ack', () => {
it('is the envelope plus reqId and ok', () => {
const frame = parseServerFrame(JSON.stringify({ t: 'ack', n: 2, reqId: 7, ok: true, pos: [1, 2] }))
expect(frame && isAck(frame)).toBe(true)
if (frame && isAck(frame)) expect(frame.pos).toEqual([1, 2])
})
it('is not an ack without an integer reqId or a boolean ok', () => {
for (const body of [
{ t: 'ack', n: 1, ok: true },
{ t: 'ack', n: 1, reqId: '7', ok: true },
{ t: 'ack', n: 1, reqId: 7, ok: 'yes' },
]) {
const frame = parseServerFrame(JSON.stringify(body))
expect(frame && isAck(frame)).toBe(false)
}
})
})
describe('closing and outcomes', () => {
it('accepts every static reason of DESIGN 6.5', () => {
for (const reason of CLOSE_REASONS) {
const frame = parseServerFrame(
JSON.stringify({ t: 'closing', n: 9, reason, code: 4001 }),
)
expect(frame && isClosing(frame)).toBe(true)
}
})
it('maps reasons to the shell outcome', () => {
expect(closeOutcome('proto-mismatch')).toBe('reload')
expect(closeOutcome('revoked')).toBe('signin')
expect(closeOutcome('evicted')).toBe('offline')
expect(closeOutcome('malformed-flood')).toBe('offline')
expect(closeOutcome(null)).toBe('offline')
})
})
describe('intents', () => {
it('always carry t and reqId and nothing secret', () => {
const raw = encodeIntent('conn.ping', 3, { ts: 99 })
expect(JSON.parse(raw)).toEqual({ t: 'conn.ping', reqId: 3, ts: 99 })
})
it('builds the /ws URL with the required proto parameter', () => {
expect(wsUrl({ protocol: 'https:', host: 'table.example' })).toBe(
`wss://table.example/ws?proto=${PROTO}`,
)
expect(wsUrl({ protocol: 'http:', host: '127.0.0.1:8080' })).toBe(
`ws://127.0.0.1:8080/ws?proto=${PROTO}`,
)
})
})
+305
View File
@@ -0,0 +1,305 @@
import { describe, expect, it } from 'vitest'
import { SLICES, connectionBadge, initialState, reduce, rosterOf } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import type { RosterEntry } from '../src/protocol.ts'
const scene = (name: string) => ({
id: 1,
name,
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
})
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number, extra: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'hello',
n,
proto: 2,
role: 'player',
me: { id: 2, name: 'Ann' },
scene: scene('Cellar'),
...extra,
})
const roster = (n: number, players: RosterEntry[]): ReducerEvent =>
frame({ t: 'roster', n, players })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
describe('hello resets the whole view (6.1/6.3)', () => {
it('clears every slice and replaces session fields on a second hello', () => {
const first = run(
{ type: 'connecting' },
hello(1),
roster(2, [
{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true },
{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true },
]),
)
expect(first.connection.phase).toBe('live')
expect(first.session.role).toBe('player')
expect(first.session.me).toEqual({ id: 2, name: 'Ann' })
expect(first.session.scene?.name).toBe('Cellar')
expect(rosterOf(first)).toHaveLength(2)
// Reconnect: the server sends hello first, then the resync. Nothing from the old connection
// may survive, otherwise a token that left the view would stay on screen.
const second = reduce(first, hello(9, { role: 'gm', me: { id: 1, name: 'GM' }, scene: scene('Attic') }))
expect(rosterOf(second)).toEqual([])
expect(second.session.role).toBe('gm')
expect(second.session.scene?.name).toBe('Attic')
expect(second.connection.phase).toBe('live')
expect(second.connection.frames).toBe(3)
expect(second.connection.lastN).toBe(9)
})
it('stays on the other slices while a hello resets them', () => {
const state = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
hello(3),
)
expect(Object.keys(state.slices).sort()).toEqual(SLICES.map(slice => slice.name).sort())
expect(rosterOf(state)).toEqual([])
})
})
describe('no data before join', () => {
it('connecting clears session and slices, so a stranger is shown nothing', () => {
const live = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]),
)
const cleared = reduce(live, { type: 'connecting' })
expect(cleared.connection.phase).toBe('connecting')
expect(cleared.session).toEqual({ role: null, me: null, proto: null, scene: null })
expect(rosterOf(cleared)).toEqual([])
})
it('a refused upgrade (close before hello) lands on sign-in', () => {
const state = run({ type: 'connecting' }, { type: 'close', reason: null, code: 1006 })
expect(state.connection.phase).toBe('signin')
expect(state.session.me).toBeNull()
})
it('a failed key shows a sign-in error and no session', () => {
const state = run({ type: 'connecting' }, { type: 'signin-failed', message: 'Key not recognised.' })
expect(state.connection.phase).toBe('signin')
expect(state.connection.error).toBe('Key not recognised.')
expect(state.session.me).toBeNull()
})
})
describe('connection outcomes (6.5)', () => {
it('proto-mismatch asks for a reload', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'closing', n: 2, reason: 'proto-mismatch', code: 4003 }),
{ type: 'close', reason: 'proto-mismatch', code: 4003 },
)
expect(state.connection.phase).toBe('reload')
})
it('revoked returns to sign-in and clears the view', () => {
const state = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
frame({ t: 'closing', n: 3, reason: 'revoked', code: 4001 }),
{ type: 'close', reason: 'revoked', code: 4001 },
)
expect(state.connection.phase).toBe('signin')
expect(state.connection.notice).toMatch(/session has ended/i)
expect(state.session.me).toBeNull()
expect(rosterOf(state)).toEqual([])
})
it('evicted goes offline but keeps the tab usable', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'closing', n: 2, reason: 'evicted', code: 4002 }),
)
expect(state.connection.phase).toBe('offline')
})
it('a transport close while live is reconnecting, not a silent sign-out', () => {
const state = run({ type: 'connecting' }, hello(1), { type: 'close', reason: null, code: 1006 })
expect(state.connection.phase).toBe('reconnecting')
expect(connectionBadge(state)).toBe('reconnecting')
})
})
describe('frames', () => {
it('ignores an unknown server message type (6.2) without touching the view', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'future_frame', n: 2, payload: 42 }),
)
expect(state.connection.phase).toBe('live')
expect(state.connection.lastN).toBe(2)
})
it('a roster frame replaces the list instead of merging', () => {
const a: RosterEntry = { id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }
const b: RosterEntry = { id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }
const state = run({ type: 'connecting' }, hello(1), roster(2, [a, b]), roster(3, [b]))
expect(rosterOf(state)).toEqual([b])
})
it('keeps the session intact when a non-hello frame arrives', () => {
const state = run({ type: 'connecting' }, hello(1), frame({ t: 'error', n: 2, code: 'malformed' }))
expect(state.session.me).toEqual({ id: 2, name: 'Ann' })
})
})
describe('registry', () => {
it('registers the roster slice without an import list', () => {
expect(SLICES.map(slice => slice.name)).toContain('roster')
})
it('rotates every server frame through the slice too', () => {
const state = run({ type: 'connecting' }, hello(1))
const withRoster = reduce(state, roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]))
expect(rosterOf(withRoster)).toHaveLength(1)
})
})
// ---------------------------------------------------------------------------------------------
// T5 (#68): the connection slice — badge, backoff display, name prompt errors, reconnect reset.
const named = (): RootState =>
run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
)
describe('connection badge (story 7)', () => {
it('is connected while live, hidden at the sign-in door and on boot', () => {
expect(connectionBadge(named())).toBe('connected')
expect(connectionBadge(initialState())).toBeNull()
expect(connectionBadge(run({ type: 'connecting' }))).toBeNull()
expect(
connectionBadge(run({ type: 'connecting' }, { type: 'signin-failed', message: 'Key not recognised.' })),
).toBeNull()
})
it('is reconnecting after a transport close and keeps showing the last view', () => {
const state = reduce(named(), { type: 'close', reason: null, code: 1006 })
expect(state.connection.phase).toBe('reconnecting')
expect(connectionBadge(state)).toBe('reconnecting')
expect(state.connection.notice).toMatch(/reconnect/i)
// The map is stale but stays on screen until the resync replaces it (no blank flash).
expect(state.session.me).toEqual({ id: 2, name: 'Ann' })
expect(rosterOf(state)).toHaveLength(1)
})
it('records the attempt and delay the socket scheduled', () => {
const state = reduce(named(), { type: 'reconnecting', attempt: 3, delay: 4400 })
expect(state.connection.phase).toBe('reconnecting')
expect(state.connection.attempt).toBe(3)
expect(state.connection.retryDelayMs).toBe(4400)
expect(state.connection.notice).toMatch(/reconnect/i)
})
it('is offline when the browser reports no network, and connected again when it returns', () => {
const offline = reduce(named(), { type: 'network', online: false })
expect(connectionBadge(offline)).toBe('offline')
expect(offline.session.me).toEqual({ id: 2, name: 'Ann' })
const online = reduce(offline, { type: 'network', online: true })
expect(connectionBadge(online)).toBe('connected')
})
it('is offline for a terminal outcome (evicted) even while a retry was in flight', () => {
const reconnecting = reduce(named(), { type: 'close', reason: null, code: 1006 })
const state = reduce(reconnecting, { type: 'close', reason: 'evicted', code: 4002 })
expect(state.connection.phase).toBe('offline')
expect(connectionBadge(state)).toBe('offline')
})
it('a reconnect keeps the view until hello, then reset+resync rebuilds it', () => {
const reconnecting = run(
{ type: 'connecting' },
hello(1),
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
{ type: 'close', reason: null, code: 1006 },
{ type: 'reconnecting', attempt: 2, delay: 2200 },
)
expect(connectionBadge(reconnecting)).toBe('reconnecting')
expect(rosterOf(reconnecting)).toHaveLength(1)
const back = reduce(reconnecting, { type: 'open' })
expect(back.connection.frames).toBe(0)
expect(rosterOf(back)).toHaveLength(1)
const resynced = reduce(back, hello(1))
expect(resynced.connection.phase).toBe('live')
expect(resynced.connection.attempt).toBe(0)
expect(resynced.connection.retryDelayMs).toBeNull()
expect(connectionBadge(resynced)).toBe('connected')
// `hello` cleared the old view; the resync frames after it refill it.
expect(rosterOf(resynced)).toEqual([])
const filled = reduce(
resynced,
roster(2, [
{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true },
{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true },
]),
)
expect(rosterOf(filled)).toHaveLength(2)
})
})
describe('name prompt (stories 5, 6)', () => {
const unnamed = (): RootState =>
run({ type: 'connecting' }, frame({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 5, name: null } }))
it('an unnamed player is live with a null name and no scene', () => {
const state = unnamed()
expect(state.connection.phase).toBe('live')
expect(state.session.me).toEqual({ id: 5, name: null })
expect(state.session.scene).toBeNull()
expect(state.connection.nameError).toBeNull()
})
it('a taken name keeps the connection live and carries the visible reason', () => {
const state = reduce(unnamed(), { type: 'name-failed', message: 'That name is taken.' })
expect(state.connection.phase).toBe('live')
expect(state.connection.nameError).toBe('That name is taken.')
expect(state.session.me?.name).toBeNull()
})
it('the second hello (me.name set) clears the name error and starts the resync', () => {
const failed = reduce(unnamed(), { type: 'name-failed', message: 'That name is taken.' })
const state = reduce(failed, hello(2, { me: { id: 5, name: 'Bob' }, scene: scene('Cellar') }))
expect(state.connection.nameError).toBeNull()
expect(state.session.me).toEqual({ id: 5, name: 'Bob' })
expect(state.session.scene?.name).toBe('Cellar')
})
it('signing out or reconnecting clears a stale name error', () => {
const failed = reduce(unnamed(), { type: 'name-failed', message: 'Enter a name.' })
expect(reduce(failed, { type: 'connecting' }).connection.nameError).toBeNull()
expect(reduce(failed, { type: 'signed-out' }).connection.nameError).toBeNull()
})
})
+347
View File
@@ -0,0 +1,347 @@
// The tile scheduler (#69, spec #63 decision 12; #86 tile loading): viewport-order requests, a
// bounded concurrency of 32, a decoded-texture cache the tile module keeps across reconnect, no
// duplicate in-flight fetch, a denied 403 remembered (no loop) and transient failures retried with
// bounded backoff.
import { describe, expect, it } from 'vitest'
import { TILE_CONCURRENCY, TileScheduler, tilesForCells, tilesInvalidated } from '../src/tiles.ts'
import type { TileLoadResult } from '../src/tiles.ts'
interface Harness {
scheduler: TileScheduler
calls: string[]
maxActive: number
settle(url: string, result: TileLoadResult): void
settleAll(result: TileLoadResult): void
/** Delays of the retry timers currently scheduled, in schedule order. */
retryDelays(): number[]
/** Fire every live retry timer (the hidden/vitest-free fake of `setTimeout`). */
fireRetries(): void
idle: number
}
function harness(concurrency = TILE_CONCURRENCY): Harness {
const calls: string[] = []
const pending = new Map<string, (result: TileLoadResult) => void>()
interface Retry {
run: () => void
delay: number
cancelled: boolean
}
const retries: Retry[] = []
let active = 0
let maxActive = 0
const state = { idle: 0 }
const scheduler = new TileScheduler({
concurrency,
load: url => {
calls.push(url)
active += 1
maxActive = Math.max(maxActive, active)
return new Promise<TileLoadResult>(resolve => {
pending.set(url, result => {
active -= 1
pending.delete(url)
resolve(result)
})
})
},
scheduleRetry: (run, delay) => {
const retry: Retry = { run, delay, cancelled: false }
retries.push(retry)
return () => {
retry.cancelled = true
}
},
onIdle: () => {
state.idle += 1
},
})
return {
scheduler,
calls,
get maxActive() {
return maxActive
},
settle(url, result) {
const resolve = pending.get(url)
if (!resolve) throw new Error(`no pending load for ${url}`)
resolve(result)
},
settleAll(result) {
for (const url of [...pending.keys()]) {
pending.get(url)?.(result)
pending.delete(url)
}
},
retryDelays() {
return retries.filter(retry => !retry.cancelled).map(retry => retry.delay)
},
fireRetries() {
for (const retry of retries.splice(0)) if (!retry.cancelled) retry.run()
},
get idle() {
return state.idle
},
}
}
function urls(count: number): string[] {
return Array.from({ length: count }, (_, index) => `/tiles/1/v1/${index}_0.png`)
}
/** Let every queued promise callback and the next pump round run. */
async function flush(): Promise<void> {
for (let i = 0; i < 20; i++) await Promise.resolve()
}
describe('TileScheduler', () => {
it('starts at most TILE_CONCURRENCY loads at once, in the order asked', async () => {
expect(TILE_CONCURRENCY).toBe(32)
const h = harness()
const list = urls(80)
h.scheduler.setDesired(list)
expect(h.calls).toEqual(list.slice(0, 32))
expect(h.maxActive).toBe(32)
h.settle(list[0] as string, 'ok')
await flush()
expect(h.calls[32]).toBe(list[32])
expect(h.maxActive).toBe(32)
// Each settle opens a slot for the next queued tile; drain every round.
for (let round = 0; round < 4 && h.calls.length < 80; round++) {
h.settleAll('ok')
await flush()
}
expect(h.calls.length).toBe(80)
expect(h.maxActive).toBe(32)
})
it('never asks twice for the same tile', () => {
const h = harness()
const list = urls(4)
h.scheduler.setDesired(list)
h.scheduler.setDesired(list)
expect(h.calls).toEqual(list)
})
it('remembers a denied tile and never retries it', async () => {
const h = harness()
const list = urls(1)
h.scheduler.setDesired(list)
h.settle(list[0] as string, 'denied')
await flush()
expect(h.scheduler.status(list[0] as string)).toBe('denied')
h.scheduler.setDesired(list)
h.scheduler.setDesired(list)
expect(h.calls).toEqual(list)
})
it('reports idle once when every wanted tile is settled', async () => {
const h = harness()
const list = urls(3)
h.scheduler.setDesired(list)
h.settleAll('ok')
await flush()
expect(h.scheduler.isComplete(list)).toBe(true)
expect(h.idle).toBe(1)
})
it('drops queued work that left the viewport (no prefetch beyond the margin)', async () => {
const h = harness()
const list = urls(80)
h.scheduler.setDesired(list)
expect(h.calls.length).toBe(32)
h.scheduler.setDesired([list[0] as string])
h.settleAll('ok')
await flush()
// Only the first TILE_CONCURRENCY were ever started; the rest were cancelled.
expect(h.calls.length).toBe(32)
expect(h.scheduler.status(list[79] as string)).toBeUndefined()
})
it('does not retry a failed tile on the same window, only on a new one', async () => {
const h = harness()
const list = urls(2)
h.scheduler.setDesired([list[0] as string])
h.settle(list[0] as string, 'error')
await flush()
expect(h.scheduler.isComplete([list[0] as string])).toBe(false)
expect(h.calls).toEqual([list[0]])
// Same window: the rAF sync after the failure must not hammer the server (only the scheduled
// backoff does, which is not a window sync).
h.scheduler.setDesired([list[0] as string])
expect(h.calls).toEqual([list[0]])
// A new window that still wants the tile asks once more, and cancels the pending backoff.
h.scheduler.setDesired(list)
expect(h.retryDelays()).toEqual([])
expect(h.calls).toEqual([list[0], list[0], list[1]])
})
it('retries a transient failure with exponential backoff, up to the budget', async () => {
const h = harness()
const [url] = urls(1) as [string]
h.scheduler.setDesired([url])
h.settle(url, 'error')
await flush()
expect(h.retryDelays()).toEqual([250])
h.fireRetries()
expect(h.calls).toEqual([url, url])
h.settle(url, 'error')
await flush()
expect(h.retryDelays()).toEqual([500])
h.fireRetries()
expect(h.calls).toEqual([url, url, url])
// Third (last) attempt fails: stored error, no more timers until a reconnect.
h.settle(url, 'error')
await flush()
expect(h.retryDelays()).toEqual([])
expect(h.scheduler.isPending([url])).toBe(false)
expect(h.scheduler.isComplete([url])).toBe(false)
})
it('a failure after the tile left the window does not spend the retry budget', async () => {
const h = harness()
const [url] = urls(1) as [string]
h.scheduler.setDesired([url])
h.scheduler.setDesired([])
h.settle(url, 'error')
await flush()
expect(h.retryDelays()).toEqual([])
h.scheduler.setDesired([url])
expect(h.calls).toEqual([url, url])
})
it('a retry that fires after the window moved on does not request the tile', async () => {
const h = harness()
const [url] = urls(1) as [string]
h.scheduler.setDesired([url])
h.settle(url, 'error')
await flush()
h.scheduler.setDesired([])
h.fireRetries()
expect(h.calls).toEqual([url])
})
it('a failure that settles after retryFailed gets a fresh budget', async () => {
const h = harness()
const [url] = urls(1) as [string]
h.scheduler.setDesired([url])
// The reconnect happens while the load is in flight: its failure must not exhaust the old run.
h.scheduler.retryFailed()
h.settle(url, 'error')
await flush()
expect(h.retryDelays()).toEqual([250])
expect(h.calls).toEqual([url])
})
it('retryFailed resets the budget so a reconnect can recover a 404', async () => {
const h = harness()
const [url] = urls(1) as [string]
h.scheduler.setDesired([url])
for (let attempt = 0; attempt < 3; attempt++) {
h.settle(url, 'error')
await flush()
h.fireRetries()
}
expect(h.calls).toHaveLength(3)
h.scheduler.retryFailed()
h.scheduler.setDesired([url])
expect(h.calls).toHaveLength(4)
})
it('reset forgets every decision (a new art_version)', async () => {
const h = harness()
const list = urls(2)
h.scheduler.setDesired(list)
expect(h.calls).toEqual(list)
h.settle(list[0] as string, 'error')
await flush()
h.scheduler.reset()
expect(h.retryDelays()).toEqual([])
expect(h.scheduler.status(list[0] as string)).toBeUndefined()
h.scheduler.setDesired(list)
// Both urls are queued again: the new art_version's URLs are different ones in production.
expect(h.calls).toEqual([...list, ...list])
})
it('is not pending once a transient failure has settled this pass', async () => {
const h = harness()
const list = urls(2)
h.scheduler.setDesired(list)
expect(h.scheduler.isPending(list)).toBe(true) // both in flight
h.settle(list[0] as string, 'error')
h.settle(list[1] as string, 'ok')
await flush()
// The stored error is terminal until a new window or a reconnect: readiness must not wait on it.
expect(h.scheduler.isPending(list)).toBe(false)
expect(h.scheduler.isComplete(list)).toBe(false)
})
it('markLoaded satisfies a tile from the texture cache without a request', () => {
const h = harness()
const list = urls(1)
h.scheduler.markLoaded(list[0] as string)
h.scheduler.setDesired(list)
expect(h.calls).toEqual([])
expect(h.scheduler.isComplete(list)).toBe(true)
})
it('retryFailed makes a transient failure askable again after a reconnect', async () => {
const h = harness()
const list = urls(1)
h.scheduler.setDesired(list)
h.settle(list[0] as string, 'error')
await flush()
h.scheduler.retryFailed()
h.scheduler.setDesired(list)
expect(h.calls).toEqual([list[0], list[0]])
})
})
describe('art_version invalidation', () => {
it('drops the cache on a new art_version or scene, never on a reconnect', () => {
expect(tilesInvalidated(null, { id: 1, art_version: 1 })).toBe(false)
expect(tilesInvalidated({ id: 1, art_version: 1 }, { id: 1, art_version: 1 })).toBe(false)
expect(tilesInvalidated({ id: 1, art_version: 1 }, { id: 1, art_version: 2 })).toBe(true)
expect(tilesInvalidated({ id: 1, art_version: 2 }, { id: 2, art_version: 2 })).toBe(true)
expect(tilesInvalidated({ id: 1, art_version: 1 }, null)).toBe(false)
})
})
describe('fog-driven denied retry (#70)', () => {
it('re-asks a denied tile exactly once after its cells became explored', async () => {
const h = harness()
const list = urls(2)
h.scheduler.setDesired(list)
h.settle(list[0] as string, 'denied')
h.settle(list[1] as string, 'ok')
await flush()
expect(h.calls).toEqual(list)
// The fog says cells under the first tile became explored: only that denied tile is stale.
h.scheduler.retryDenied([list[0] as string])
h.scheduler.setDesired(list)
expect(h.calls).toEqual([...list, list[0]])
h.settleAll('ok')
await flush()
// A plain re-sync (no new cells) must not ask again: the denial is still remembered.
h.scheduler.setDesired(list)
h.scheduler.retryDenied([])
h.scheduler.setDesired(list)
expect(h.calls).toEqual([...list, list[0]])
})
it('maps explored cells to the tiles they touch', () => {
const scene = { id: 3, art_version: 7, tile_size: 32 }
const grid = { cols: 4, cell: 32 }
// Cells (1,0) -> tile (1,0), (1,1) -> tile (1,1), (3,1) -> tile (3,1).
expect(tilesForCells(scene, grid, [1, 5, 7])).toEqual([
'/tiles/3/v7/1_0.png',
'/tiles/3/v7/1_1.png',
'/tiles/3/v7/3_1.png',
])
// Two cells in one tile are one url; a smaller cell than a tile still maps correctly.
expect(tilesForCells(scene, { cols: 16, cell: 8 }, [0, 1, 2])).toEqual(['/tiles/3/v7/0_0.png'])
expect(tilesForCells(scene, { cols: 0, cell: 0 }, [1])).toEqual([])
})
})
+177
View File
@@ -0,0 +1,177 @@
// T8 (#71): the token renderer's pure seam. The board turns store events into the exact set of
// entities a renderer has to touch — entered, updated, left — so a frame that moves one token costs
// one node update, never a full redraw (DESIGN 7.2, spec #63 decision 11).
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { TokenBoard } from '../src/render/tokenBoard.ts'
import { tokenViewFromFrame } from '../src/slices/tokens.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n = 1): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } })
const token = (n: number, id: string, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n,
id,
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [],
props: {},
...overrides,
})
/** Apply every event, draining after each one the way the renderer does. */
function feed(board: TokenBoard, events: ReducerEvent[]) {
const patches = []
for (const event of events) {
board.apply(event)
patches.push(board.drain())
}
return patches
}
describe('the token board (stories 28, 29; DESIGN 7.2)', () => {
it('reports one entity entered per new token', () => {
const board = new TokenBoard()
const patches = feed(board, [hello(), token(2, 'aaa'), token(3, 'bbb')])
expect(patches[0]).toMatchObject({ reset: true, entered: [], updated: [], left: [] })
expect(patches[1]?.entered.map(view => view.id)).toEqual(['aaa'])
expect(patches[1]?.updated).toEqual([])
// The second token arrives on its own frame; nothing earlier is re-entered.
expect(board.size).toBe(2)
})
it('moves only the changed token, never the whole set (the instrumented count)', () => {
const board = new TokenBoard()
const events: ReducerEvent[] = [hello()]
for (let i = 0; i < 50; i += 1) events.push(token(2 + i, `t${i}`))
feed(board, events)
expect(board.size).toBe(50)
board.apply(token(100, 't7', { pos: [420, 400] }))
const patch = board.drain()
// One token moved -> one entity updated. 49 untouched tokens are not touched again.
expect(patch.updated.map(view => view.id)).toEqual(['t7'])
expect(patch.entered).toEqual([])
expect(patch.left).toEqual([])
expect(board.size).toBe(50)
})
it('reports a token leaving once, with no stale entered entry', () => {
const board = new TokenBoard()
feed(board, [hello(), token(2, 'aaa'), token(3, 'bbb')])
board.apply(frame({ t: 'token_gone', n: 4, id: 'aaa' }))
const patch = board.drain()
expect(patch.left).toEqual(['aaa'])
expect(patch.entered).toEqual([])
expect(patch.updated).toEqual([])
expect(board.size).toBe(1)
})
it('never both enters and leaves one token between drains', () => {
const board = new TokenBoard()
board.apply(hello())
board.drain()
board.apply(token(2, 'aaa'))
board.apply(frame({ t: 'token_gone', n: 3, id: 'aaa' }))
const patch = board.drain()
expect(patch.entered).toEqual([])
expect(patch.updated).toEqual([])
expect(patch.left).toEqual(['aaa'])
expect(board.size).toBe(0)
})
it('asks for a reset on hello, and clears anything still pending', () => {
const board = new TokenBoard()
feed(board, [hello(), token(2, 'aaa')])
board.apply(token(3, 'bbb'))
board.apply(hello(4))
const patch = board.drain()
expect(patch.reset).toBe(true)
expect(patch.entered).toEqual([])
expect(patch.updated).toEqual([])
expect(patch.left).toEqual([])
expect(board.size).toBe(0)
})
it('ignores a close: the map stays on screen, the resync arrives after the next hello', () => {
const board = new TokenBoard()
feed(board, [hello(), token(2, 'aaa')])
board.apply({ type: 'close', reason: null, code: 1006 })
const patch = board.drain()
expect(patch).toMatchObject({ reset: false, entered: [], updated: [], left: [] })
expect(board.size).toBe(1)
})
it('keeps the view an entity was last given, for the renderer to compare against', () => { const board = new TokenBoard()
board.apply(hello())
board.apply(token(2, 'aaa', { name: 'Rat' }))
expect(board.views.get('aaa')?.name).toBe('Rat')
board.apply(token(3, 'aaa', { name: 'Giant Rat' }))
expect(board.views.get('aaa')?.name).toBe('Giant Rat')
})
it('seeds the current state when a stage mounts after the resync', () => {
const board = new TokenBoard()
const view = parseServerFrame(
JSON.stringify({
t: 'token',
n: 1,
id: 'aaa',
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [],
props: {},
}),
)
if (!view) throw new Error('bad test frame')
const parsed = tokenViewFromFrame(view)
if (!parsed) throw new Error('bad test token')
board.seed([parsed])
const patch = board.drain()
expect(patch.entered.map(entry => entry.id)).toEqual(['aaa'])
expect(patch.reset).toBe(false)
expect(board.size).toBe(1)
})
it('is a pure reader of reducer state too: the slice agrees with the board', () => {
let state = reduce(initialState(), { type: 'connecting' })
const board = new TokenBoard()
for (const event of [hello(), token(2, 'aaa'), token(3, 'bbb')]) {
state = reduce(state, event)
board.apply(event)
board.drain()
}
expect([...board.views.keys()]).toEqual(['aaa', 'bbb'])
expect(state.slices['tokens']).toBeDefined()
})
})
describe('the token board keeps one pending entry per entity', () => {
it('draws a token once when it enters and changes before the drain', () => {
const board = new TokenBoard()
board.apply(hello())
board.drain()
board.apply(token(2, 'aaa', { name: 'Rat' }))
board.apply(token(3, 'aaa', { name: 'Giant Rat' }))
const patch = board.drain()
expect(patch.entered.map(view => [view.id, view.name])).toEqual([['aaa', 'Giant Rat']])
expect(patch.updated).toEqual([])
expect(board.size).toBe(1)
})
})
+79
View File
@@ -0,0 +1,79 @@
// #78 token panel seam: the vision controls' local rules and the exact `flags`/`vision_radius`
// fields the panel sends. Pure, no DOM, no socket. `flags` is free-form (DESIGN 8), so an edit must
// copy the stored object and change only `vision`; a new token keeps the `{}` default.
import { describe, expect, it } from 'vitest'
import {
createVisionFields,
parseVisionRadius,
updateVisionFields,
withVisionFlag,
} from '../src/tokenPanel.ts'
describe('vision radius', () => {
it('treats blank as the scene default and accepts any finite positive number', () => {
expect(parseVisionRadius('')).toEqual({ ok: true, value: null })
expect(parseVisionRadius(' ')).toEqual({ ok: true, value: null })
expect(parseVisionRadius('300')).toEqual({ ok: true, value: 300 })
expect(parseVisionRadius(' 12.5 ')).toEqual({ ok: true, value: 12.5 })
})
it('refuses zero, negative, non-finite and non-numeric values like the radius field', () => {
for (const raw of ['0', '-1', 'abc', 'Infinity', 'NaN']) {
const result = parseVisionRadius(raw)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.error).toMatch(/positive number or blank/)
}
})
})
describe('create fields', () => {
it('sends only the vision key when vision is on, plus the radius', () => {
expect(createVisionFields(true, '300')).toEqual({
ok: true,
fields: { flags: { vision: true }, vision_radius: 300 },
})
expect(createVisionFields(true, '')).toEqual({
ok: true,
fields: { flags: { vision: true }, vision_radius: null },
})
})
it('sends no flags when vision is off, keeping the DESIGN 8 `{}` default', () => {
expect(createVisionFields(false, '')).toEqual({
ok: true,
fields: { vision_radius: null },
})
})
it('refuses a bad radius before the intent leaves the client', () => {
const result = createVisionFields(true, '0')
expect(result.ok).toBe(false)
})
})
describe('update fields', () => {
it('copies the stored flags and writes only vision, so other GM flags survive', () => {
expect(updateVisionFields('abc', { blocks_move: true, note: 'x' }, false, '250')).toEqual({
ok: true,
fields: {
id: 'abc',
flags: { blocks_move: true, note: 'x', vision: false },
vision_radius: 250,
},
})
expect(withVisionFlag({ vision: true, other: 1 }, true)).toEqual({ vision: true, other: 1 })
})
it('clears the radius back to the scene default with null', () => {
expect(updateVisionFields('abc', { vision: true }, true, '')).toEqual({
ok: true,
fields: { id: 'abc', flags: { vision: true }, vision_radius: null },
})
})
it('refuses a non-positive radius on edit too', () => {
const result = updateVisionFields('abc', {}, true, '-5')
expect(result.ok).toBe(false)
})
})
+142
View File
@@ -0,0 +1,142 @@
// T8 (#71): the token slice is the reducer seam for stories 28-30 and 34. Server frames in, the
// token view out; `token` upserts one token, `token_gone` removes it, `hello` resets the view.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { tokenOf, tokensOf } from '../src/slices/tokens.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } })
/** A player-shaped token frame: `statuses` are names only, no `source` (6.1 leak note 6). */
const playerToken = (n: number, id: string, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n,
id,
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [],
props: { public: {}, cprops: { public: {} } },
...overrides,
})
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
describe('token enters, updates and leaves (stories 28, 29)', () => {
it('enters on a token frame and replaces the whole view on a later one', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa'),
playerToken(3, 'bbb'),
)
expect(tokensOf(state).map(token => token.id)).toEqual(['aaa', 'bbb'])
// 6.1: every `token` message is the whole view of one token; a later one replaces it in place.
const moved = reduce(state, playerToken(4, 'aaa', { pos: [420, 400], radius: 26, name: 'Giant Rat' }))
expect(tokensOf(moved)).toHaveLength(2)
expect(tokensOf(moved).map(token => token.id)).toEqual(['aaa', 'bbb'])
expect(tokenOf(moved, 'aaa')).toMatchObject({ name: 'Giant Rat', pos: [420, 400], radius: 26 })
expect(tokenOf(moved, 'bbb')).toMatchObject({ name: 'Rat', pos: [400, 400] })
})
it('removes a token on token_gone, and a later frame re-enters it', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa'),
playerToken(3, 'bbb'),
frame({ t: 'token_gone', n: 4, id: 'aaa' }),
)
expect(tokensOf(state).map(token => token.id)).toEqual(['bbb'])
expect(tokenOf(state, 'aaa')).toBeNull()
const back = reduce(state, playerToken(5, 'aaa'))
expect(tokensOf(back).map(token => token.id)).toEqual(['bbb', 'aaa'])
})
it('clears every token on hello: a token that left the view must not survive a reconnect', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa'),
playerToken(3, 'bbb'),
hello(4),
)
expect(tokensOf(state)).toEqual([])
})
it('keeps the status names and drops the GM-only source (6.1 leak note 6)', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa', { statuses: [{ status: 'stuck', source: 'walls' }] }),
)
expect(tokenOf(state, 'aaa')?.statuses).toEqual(['stuck'])
})
it('keeps the GM-only fields when the server sends them (story 34)', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa', {
statuses: [{ status: 'stuck', source: 'walls' }, { status: 'squeezed', source: 'GM' }],
gm_only: true,
kind: 'npc',
controller: null,
character_id: 'char1',
flags: {},
vision_radius: 320,
radius_own: null,
}),
)
const token = tokenOf(state, 'aaa')
expect(token).toMatchObject({
gmOnly: true,
kind: 'npc',
controller: null,
characterId: 'char1',
statuses: ['stuck', 'squeezed'],
})
})
it('marks the tokens the recipient controls (mine)', () => {
const state = run(
{ type: 'connecting' },
hello(1),
playerToken(2, 'aaa', { mine: true }),
playerToken(3, 'bbb'),
)
expect(tokensOf(state).filter(token => token.mine).map(token => token.id)).toEqual(['aaa'])
})
it('ignores a malformed token frame instead of inventing a token (6.2)', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'token', n: 2, id: 'aaa', name: 'Rat' }),
)
expect(tokensOf(state)).toEqual([])
})
it('does not let a token_gone for an unknown id create anything', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'token_gone', n: 2, id: 'nope' }),
)
expect(tokensOf(state)).toEqual([])
})
})
+229
View File
@@ -0,0 +1,229 @@
// Camera and viewport maths (#69, DESIGN 7.1/7.2, ADR-0013). Pure: no Pixi, no DOM, so this is
// the same cheap seam as the reducer. The numbers here are the contract: players clamp at 0.5 and
// the GM has no low clamp; both stop at 4.0; a viewport asks for its tiles plus exactly one tile of
// margin, clamped to the scene.
import { describe, expect, it } from 'vitest'
import type { SceneInfo } from '../src/protocol.ts'
import {
GM_MIN_ZOOM,
MAX_ZOOM,
PLAYER_MIN_ZOOM,
VIEWPORT_MARGIN_TILES,
ViewportModel,
clampZoom,
centredCamera,
orderTilesCentreOut,
pinchCamera,
screenToWorld,
tileUrl,
viewportCentre,
visibleTiles,
worldToScreen,
zoomCamera,
} from '../src/viewport.ts'
const scene: SceneInfo = {
id: 1,
name: 'Scene',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 32,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
}
const size = { width: 320, height: 320 }
describe('zoom clamps (ADR-0013, spec #63 decision 7)', () => {
it('a player stops exactly at 0.5 and 4.0', () => {
expect(PLAYER_MIN_ZOOM).toBe(0.5)
expect(MAX_ZOOM).toBe(4)
expect(clampZoom('player', 0.4)).toBe(0.5)
expect(clampZoom('player', 0.5)).toBe(0.5)
expect(clampZoom('player', 1)).toBe(1)
expect(clampZoom('player', 4)).toBe(4)
expect(clampZoom('player', 4.1)).toBe(4)
})
it('the GM has no player low clamp, but the same 4.0 ceiling', () => {
expect(GM_MIN_ZOOM).toBeLessThan(0.5)
expect(clampZoom('gm', 0.25)).toBe(0.25)
expect(clampZoom('gm', 0.1)).toBe(0.1)
expect(clampZoom('gm', GM_MIN_ZOOM)).toBe(GM_MIN_ZOOM)
expect(clampZoom('gm', 0.0001)).toBe(GM_MIN_ZOOM)
expect(clampZoom('gm', 4.1)).toBe(4)
})
it('an unknown or non-finite zoom falls back to 1', () => {
expect(clampZoom(null, Number.NaN)).toBe(1)
expect(clampZoom('player', Number.POSITIVE_INFINITY)).toBe(4)
})
})
describe('camera', () => {
it('centres on the scene at zoom 1', () => {
const camera = centredCamera(scene, size)
expect(camera.zoom).toBe(1)
expect(camera.x + (scene.w / 2) * camera.zoom).toBe(size.width / 2)
expect(camera.y + (scene.h / 2) * camera.zoom).toBe(size.height / 2)
})
it('screenToWorld and worldToScreen are inverses', () => {
const camera = { x: -100, y: -200, zoom: 2 }
const world = screenToWorld(camera, 40, 80)
expect(world).toEqual([70, 140])
const screen = worldToScreen(camera, world[0], world[1])
expect(screen[0]).toBeCloseTo(40, 10)
expect(screen[1]).toBeCloseTo(80, 10)
})
it('viewportCentre is the world point under the middle of the screen (#82)', () => {
expect(viewportCentre(centredCamera(scene, size), size)).toEqual([2048, 2048])
expect(viewportCentre({ x: -100, y: -200, zoom: 2 }, size)).toEqual([130, 180])
})
it('zoomCamera keeps the world point under the anchor fixed and clamps', () => {
const camera = { x: -1000, y: -800, zoom: 1 }
const anchor = { x: 120, y: 200 }
const before = screenToWorld(camera, anchor.x, anchor.y)
const zoomed = zoomCamera('player', camera, 0.1, anchor)
expect(zoomed.zoom).toBe(0.5)
const after = screenToWorld(zoomed, anchor.x, anchor.y)
expect(after[0]).toBeCloseTo(before[0], 10)
expect(after[1]).toBeCloseTo(before[1], 10)
expect(zoomCamera('player', camera, 100, anchor).zoom).toBe(4)
})
it('pinch zooms around the starting midpoint and follows it as it moves', () => {
const start = { x: -1000, y: -800, zoom: 1 }
const startMid = { x: 100, y: 100 }
const world = screenToWorld(start, startMid.x, startMid.y)
const movedMid = { x: 140, y: 120 }
const pinched = pinchCamera('player', start, 100, 200, startMid, movedMid)
expect(pinched.zoom).toBe(2)
const atMoved = screenToWorld(pinched, movedMid.x, movedMid.y)
expect(atMoved[0]).toBeCloseTo(world[0], 10)
expect(atMoved[1]).toBeCloseTo(world[1], 10)
expect(pinchCamera('player', start, 100, 1, startMid, startMid).zoom).toBe(0.5)
})
})
describe('ViewportModel (the render layer\'s UI state)', () => {
it('pans, toggles the grid and re-clamps when the role becomes a player', () => {
const model = new ViewportModel()
model.reset(scene, 'gm', size)
model.pan(10, -20)
expect(model.state.camera.x).toBe(centredCamera(scene, size).x + 10)
expect(model.state.camera.y).toBe(centredCamera(scene, size).y - 20)
expect(model.state.grid).toBe(true)
model.toggleGrid()
expect(model.state.grid).toBe(false)
// A GM zoomed to 0.25; the same view cannot stay below the player floor.
model.zoomAt(0.25, { x: 0, y: 0 })
expect(model.state.camera.zoom).toBe(0.25)
model.setRole('player')
expect(model.state.camera.zoom).toBe(0.5)
})
it('keeps the camera across a same-scene resync and resets for a new scene', () => {
const model = new ViewportModel()
model.reset(scene, 'player', size)
model.pan(-40, 0)
const panned = model.state.camera
model.setScene({ ...scene })
expect(model.state.camera).toBe(panned)
model.setScene({ ...scene, id: 2 })
expect(model.state.camera).toEqual(centredCamera({ ...scene, id: 2 }, size))
})
it('emits on a same-scene resync so a new art_version is not swallowed (#86)', () => {
const model = new ViewportModel()
let seen = 0
model.reset(scene, 'player', size)
model.subscribe(() => {
seen += 1
})
const panned = model.state.camera
model.setScene({ ...scene, art_version: 2 })
expect(seen).toBe(1)
expect(model.state.scene?.art_version).toBe(2)
expect(model.state.camera).toBe(panned)
// The same object again is not a change: no extra notification.
model.setScene(model.state.scene)
expect(seen).toBe(1)
})
})
describe('centre-out tile order (#86)', () => {
it('asks for the tile under the viewport centre first, growing outwards', () => {
const camera = centredCamera(scene, size)
const tiles = orderTilesCentreOut(visibleTiles(scene, camera, size), scene, camera, size)
// 320x320 viewport at zoom 1 centred on world (2048,2048): the four middle tiles tie.
expect(tiles.length).toBe(12 * 12)
const distance = (tile: { x: number; y: number }) =>
Math.hypot((tile.x + 0.5) * scene.tile_size - 2048, (tile.y + 0.5) * scene.tile_size - 2048)
const distances = tiles.map(distance)
expect(distances).toEqual([...distances].sort((a, b) => a - b))
expect(Math.abs((tiles[0]?.x ?? -1) - 63)).toBeLessThanOrEqual(1)
expect(Math.abs((tiles[0]?.y ?? -1) - 63)).toBeLessThanOrEqual(1)
// It is a permutation of the row-major window, not a different window.
expect(new Set(tiles.map(tile => tile.url)).size).toBe(12 * 12)
})
})
describe('visible tiles', () => {
it('returns the viewport plus one tile of margin, row-major, inside the scene', () => {
const camera = centredCamera(scene, size)
const tiles = visibleTiles(scene, camera, size)
// 320 px at zoom 1 is 10 tiles; one margin on each side is 12 x 12.
expect(tiles.length).toBe(12 * 12)
expect(tiles[0]).toMatchObject({ x: 58, y: 58 })
expect(tiles[tiles.length - 1]).toMatchObject({ x: 69, y: 69 })
expect(tiles[0]?.url).toBe('/tiles/1/v1/58_58.png')
expect(tiles.every(tile => tile.x >= 0 && tile.x < 128 && tile.y >= 0 && tile.y < 128)).toBe(true)
// row-major: every tile of a row comes before the next row.
const ys = tiles.map(tile => tile.y)
expect(ys).toEqual([...ys].sort((a, b) => a - b))
})
it('clamps the margin at the scene edges', () => {
const camera = { x: 0, y: 0, zoom: 1 }
const tiles = visibleTiles(scene, camera, size)
expect(tiles[0]).toMatchObject({ x: 0, y: 0 })
// 320 px + one tile margin to the right/down => 0..10 inclusive.
expect(Math.max(...tiles.map(tile => tile.x))).toBe(10)
expect(Math.max(...tiles.map(tile => tile.y))).toBe(10)
})
it('scales with zoom (out asks for more, in for fewer)', () => {
const out = visibleTiles(scene, centredCamera(scene, size, 0.5), size)
const inn = visibleTiles(scene, centredCamera(scene, size, 4), size)
expect(out.length).toBeGreaterThan(inn.length)
// At 0.5 a 320 px viewport is 640 world px: 20 tiles + 2 margin = 22 per axis.
expect(out.length).toBe(22 * 22)
})
it('never prefetches beyond the margin', () => {
const camera = centredCamera(scene, size)
const tiles = visibleTiles(scene, camera, size)
const maxX = Math.max(...tiles.map(tile => tile.x))
const minX = Math.min(...tiles.map(tile => tile.x))
const viewport = visibleTiles(scene, camera, { width: 320, height: 320 })
// Calling twice is deterministic; the margin is exactly one tile (VIEWPORT_MARGIN_TILES).
expect(VIEWPORT_MARGIN_TILES).toBe(1)
expect(maxX - minX).toBe(11)
expect(viewport.length).toBe(tiles.length)
})
it('returns nothing when the camera looks outside the map', () => {
expect(visibleTiles(scene, { x: 100000, y: 100000, zoom: 1 }, size)).toEqual([])
})
it('builds the canonical tile URL', () => {
expect(tileUrl(scene, 0, 0)).toBe('/tiles/1/v1/0_0.png')
expect(tileUrl(scene, 127, 3)).toBe('/tiles/1/v1/127_3.png')
})
})
+359
View File
@@ -0,0 +1,359 @@
// T10 (#73): the wall slice and the wall editor's pure rules are the reducer seam. Server GM frames
// in, the wall view out; presets expand to the 5.8 table; `kind` is derived in the fixed order; the
// one-way arrow points at the blind side; a payload is preset XOR raw, and `open` never rides in a
// `wall.update`. No DOM, no Pixi, no socket.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import type { Vec2 } from '../src/protocol.ts'
import { selectedWallId, wallOf, wallViewFromFrame, wallsOf } from '../src/slices/walls.ts'
import { shouldPopulate, wallFieldsSignature } from '../src/panels/wallSync.ts'
import type { SightDir, WallPreset, WallSwitches } from '../src/wallEditor.ts'
import {
PRESETS,
arrowVector,
buildAddFields,
buildDoorFields,
buildUpdateFields,
deriveKind,
flipSightDir,
presetSwitches,
snapPoint,
undoIntent,
validateLabel,
validateSwitches,
} from '../src/wallEditor.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n: number, role: 'gm' | 'player' = 'gm'): ReducerEvent =>
frame({
t: 'hello',
n,
proto: 2,
role,
me: { id: role === 'gm' ? 1 : 2, name: role === 'gm' ? 'GM' : 'Ann' },
...(role === 'player' ? {} : { scene: { id: 1, name: 'S', w: 4096, h: 4096, tile_size: 32, cell: 32, grid_size: 32, vision_radius_default: 300, token_radius_default: 20, art_version: 1 } }),
})
const wallBody = (id: number, overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
id,
scene: 1,
a: [100, 100],
b: [300, 100],
thickness: 0,
position: 'center',
height: null,
kind: 'wall',
blocks_sight: true,
blocks_movement: true,
sight_dir: 'both',
player_marker: false,
door: false,
open: false,
secret: false,
locked: false,
label: null,
flags: {},
...overrides,
})
// DESIGN 6.1: a `walls` snapshot entry carries the wall fields only; `scene` is on the frame.
const snapBody = (id: number, overrides: Record<string, unknown> = {}): Record<string, unknown> => {
const { scene: _scene, ...entry } = wallBody(id, overrides)
return entry
}
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
const switches = (overrides: Partial<WallSwitches> = {}): WallSwitches => ({
...presetSwitches('wall'),
...overrides,
})
describe('wall slice (DESIGN 6.1, GM only)', () => {
it('loads the walls snapshot, upserts a wall and removes one', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'walls', n: 2, scene: 1, walls: [snapBody(1), snapBody(2, { a: [100, 200], b: [100, 400] })] }),
)
expect(wallsOf(state).map(wall => wall.id)).toEqual([1, 2])
expect(wallOf(state, 1)?.kind).toBe('wall')
const moved = reduce(state, frame({ t: 'wall', n: 3, ...wallBody(1, { kind: 'door', door: true, a: [120, 100] }) }))
expect(wallsOf(moved)).toHaveLength(2)
expect(wallOf(moved, 1)).toMatchObject({ kind: 'door', a: [120, 100] })
const gone = reduce(moved, frame({ t: 'wall_gone', n: 4, scene: 1, id: 2 }))
expect(wallsOf(gone).map(wall => wall.id)).toEqual([1])
})
it('loads a real `walls` snapshot: scene on the frame, entries without scene (6.1)', () => {
// The server's snapshot frame is `{t:'walls', scene, walls:[{id, a, b, ...}]}`; a delta is
// `{t:'wall', scene, id, a, b, ...}`. This is the reload regression: the reducer must read the
// frame's scene for every entry, not require `scene` on the entry itself.
const snapshot = frame({
t: 'walls',
n: 2,
scene: 7,
walls: [snapBody(1), snapBody(2, { a: [100, 200], b: [100, 400] })],
})
const state = run({ type: 'connecting' }, hello(1), snapshot)
expect(wallsOf(state).map(wall => wall.id)).toEqual([1, 2])
expect(wallOf(state, 1)?.scene).toBe(7)
expect(wallOf(state, 2)?.scene).toBe(7)
// An entry that still carries its own scene (an older/foreign snapshot) is tolerated.
const explicit = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'walls', n: 2, scene: 7, walls: [wallBody(3, { scene: 3 })] }),
)
expect(wallOf(explicit, 3)?.scene).toBe(3)
expect(wallOf(explicit, 3)).not.toBeNull()
})
it('keeps selection while the wall exists and clears it on wall_gone or a snapshot without it', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({ t: 'wall', n: 2, ...wallBody(7) }),
{ type: 'wall-select', id: 7 },
)
expect(selectedWallId(state)).toBe(7)
expect(selectedWallId(reduce(state, frame({ t: 'wall_gone', n: 3, id: 7 })))).toBeNull()
expect(
selectedWallId(reduce(state, frame({ t: 'walls', n: 4, scene: 1, walls: [] }))),
).toBeNull()
})
it('resets on hello and ignores wall frames on a player-shaped session (3.1)', () => {
const gm = run({ type: 'connecting' }, hello(1), frame({ t: 'wall', n: 2, ...wallBody(1) }))
expect(wallsOf(reduce(gm, hello(3)))).toEqual([])
const player = run({ type: 'connecting' }, hello(1, 'player'), frame({ t: 'wall', n: 2, ...wallBody(1) }))
expect(wallsOf(player)).toEqual([])
})
it('derives `kind` when the server frame omits it', () => {
const state = run(
{ type: 'connecting' },
hello(1),
frame({
t: 'wall',
n: 2,
...wallBody(1, { kind: undefined, blocks_sight: false, blocks_movement: true, door: true }),
}),
)
expect(wallOf(state, 1)?.kind).toBe('window')
})
})
describe('presets, derived kind and the arrow (5.8)', () => {
it('expands the four presets exactly as the 5.8 table says', () => {
expect(PRESETS).toEqual(['wall', 'door', 'window', 'one_way'])
expect(presetSwitches('wall')).toEqual({
blocksSight: true,
blocksMovement: true,
sightDir: 'both',
playerMarker: false,
door: false,
open: false,
secret: false,
locked: false,
})
expect(presetSwitches('door')).toMatchObject({ door: true, open: false, playerMarker: false })
expect(presetSwitches('window')).toMatchObject({
blocksSight: false,
blocksMovement: true,
door: true,
playerMarker: true,
})
expect(presetSwitches('one_way')).toMatchObject({ sightDir: 'left', blocksSight: true, door: false })
})
it('derives kind in the fixed order: window, one_way, door, wall, else custom', () => {
expect(deriveKind(switches({ blocksSight: false }))).toBe('window')
expect(deriveKind(switches({ sightDir: 'left' }))).toBe('one_way')
expect(deriveKind(switches({ door: true }))).toBe('door')
expect(deriveKind(switches())).toBe('wall')
expect(deriveKind(switches({ blocksMovement: false }))).toBe('custom')
// A one-way door is labelled one_way, and secret/locked never change the label.
expect(deriveKind(switches({ door: true, sightDir: 'right' }))).toBe('one_way')
expect(deriveKind(switches({ door: true, secret: true, locked: true }))).toBe('door')
})
it('points the arrow at the blind side named by sight_dir, and flips left/right only', () => {
const a: Vec2 = [0, 0]
const b: Vec2 = [100, 0]
// a -> b runs +x; left is (-dy, dx) = +y, so sight_dir:"left" means the +y side is blind.
expect(arrowVector(a, b, 'left')).toEqual([0, 1])
expect(arrowVector(a, b, 'right')).toEqual([0, -1])
expect(arrowVector(a, b, 'both')).toBeNull()
expect(flipSightDir('left')).toBe('right')
expect(flipSightDir('right')).toBe('left')
expect(flipSightDir('both')).toBe('both')
})
})
describe('snap while drawing (story 45)', () => {
it('prefers an endpoint inside the threshold, else rounds to the grid, and does nothing when off', () => {
const endpoints = [([100, 100] as Vec2), ([300, 200] as Vec2)]
expect(snapPoint([105, 97], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([100, 100])
expect(snapPoint([143, 154], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([128, 160])
expect(snapPoint([143, 154], { enabled: false, gridSize: 32, endpoints, threshold: 12 })).toEqual([143, 154])
// An endpoint outside the threshold loses to the grid.
expect(snapPoint([130, 130], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([128, 128])
})
})
describe('payload rules (6.1): preset XOR raw, and open is a door intent', () => {
it('sends only `preset` beside a preset, never a raw switch such as open:false', () => {
const fields = buildAddFields(1, [0, 0], [100, 0], { preset: 'door', switches: presetSwitches('door'), label: null })
expect(fields).toEqual({ scene: 1, a: [0, 0], b: [100, 0], preset: 'door' })
for (const key of ['open', 'blocks_sight', 'blocks_movement', 'sight_dir', 'player_marker', 'door', 'secret', 'locked']) {
expect(fields).not.toHaveProperty(key)
}
})
it('sends every raw switch on a raw add and a label only when given', () => {
const fields = buildAddFields(1, [0, 0], [100, 0], {
preset: null,
switches: switches({ sightDir: 'left' }),
label: 'railing',
})
expect(fields).toMatchObject({
blocks_sight: true,
blocks_movement: true,
sight_dir: 'left',
player_marker: false,
door: false,
open: false,
secret: false,
locked: false,
label: 'railing',
})
})
it('never puts `open` in a wall.update patch, preset or raw', () => {
const raw = buildUpdateFields(9, { preset: null, switches: switches({ open: true }), label: null })
expect(raw).toEqual({
id: 9,
blocks_sight: true,
blocks_movement: true,
sight_dir: 'both',
player_marker: false,
door: false,
secret: false,
locked: false,
label: null,
})
expect(raw).not.toHaveProperty('open')
const preset = buildUpdateFields(9, { preset: 'window', switches: presetSwitches('window') })
expect(preset).toEqual({ id: 9, preset: 'window' })
expect(buildDoorFields(1, 9, true)).toEqual({ scene: 1, id: 9, open: true })
})
it('builds the inverse of each edit for single-step undo', () => {
expect(undoIntent(1, { kind: 'remove', id: 4 })).toEqual({
t: 'wall.remove',
fields: { scene: 1, id: 4 },
})
expect(undoIntent(1, { kind: 'door', id: 4, open: true })).toEqual({
t: 'door.set',
fields: { scene: 1, id: 4, open: true },
})
const update = undoIntent(1, {
kind: 'update',
id: 4,
switches: switches({ sightDir: 'right' }),
label: 'x',
flags: { a: 1 },
})
expect(update?.t).toBe('wall.update')
expect(update?.fields).toMatchObject({ id: 4, sight_dir: 'right', label: 'x', flags: { a: 1 } })
expect(update?.fields).not.toHaveProperty('open')
const restore = undoIntent(1, {
kind: 'restore',
wall: {
a: [0, 0],
b: [100, 0],
thickness: 0,
position: 'center',
height: null,
switches: switches({ open: true, door: true }),
label: 'door',
flags: {},
},
})
expect(restore?.t).toBe('wall.add')
expect(restore?.fields).toMatchObject({ door: true, open: true, label: 'door', height: null })
})
})
describe('local validation mirrors the server rules (5.8, 6.1)', () => {
it('rejects a sight direction with nothing to block', () => {
expect(validateSwitches(switches({ blocksSight: false, sightDir: 'left' }))).toContain('sight direction')
expect(validateSwitches(switches({ blocksSight: false, sightDir: 'both' }))).toBeNull()
})
it('rejects door settings without a door and impossible secret/locked doors', () => {
expect(validateSwitches(switches({ locked: true }))).toContain('need a door')
expect(validateSwitches(switches({ door: true, secret: true, open: true }))).toContain('always closed')
expect(validateSwitches(switches({ door: true, secret: true, sightDir: 'left' }))).toContain('two-way')
expect(validateSwitches(switches({ door: true, secret: true, blocksMovement: false }))).toContain('opaque')
expect(validateSwitches(switches({ door: true, open: true, locked: true }))).toContain('locked')
expect(validateSwitches(switches({ door: true, secret: true, locked: true }))).toBeNull()
expect(validateSwitches(switches({ door: true, open: true }))).toBeNull()
})
it('accepts 1..64 trimmed code points with no control characters', () => {
expect(validateLabel(' railing ')).toBeNull()
expect(validateLabel('')).toBeNull()
expect(validateLabel('x'.repeat(65))).toContain('64')
expect(validateLabel('a\nb')).toContain('control')
expect(validateLabel('😀'.repeat(64))).toBeNull()
})
it('treats a preset and raw switches as one draft mode', () => {
// The editor's preset draft never carries a raw switch; the type is the guard.
const preset: WallPreset = 'wall'
const fields = buildAddFields(1, [0, 0], [1, 1], { preset, switches: switches(), label: null })
expect(fields).toHaveProperty('preset', 'wall')
expect(fields).not.toHaveProperty('open')
const dir: SightDir = 'left'
expect(validateSwitches(switches({ sightDir: dir }))).toBeNull()
})
})
describe('panel synchronisation (#76): an ack render never undoes a toggle', () => {
const view = (id = 1, overrides: Record<string, unknown> = {}) => {
const wall = wallViewFromFrame(wallBody(id, overrides))
if (!wall) throw new Error('bad wall body')
return wall
}
it('populates a newly selected wall, then leaves an identical record alone', () => {
const wall = view()
expect(shouldPopulate(null, wall)).toBe(true)
const populated = { id: wall.id, signature: wallFieldsSignature(wall) }
// The editor's own ack dispatch re-renders with the previous record (same fields, usually the
// same object): repopulating here is what reverted the GM's just-toggled checkbox.
expect(shouldPopulate(populated, view())).toBe(false)
})
it('repopulates when the server record or the selection changes', () => {
const wall = view()
const populated = { id: wall.id, signature: wallFieldsSignature(wall) }
expect(shouldPopulate(populated, view(1, { locked: true, door: true, kind: 'door' }))).toBe(true)
expect(shouldPopulate(populated, view(1, { label: 'railing' }))).toBe(true)
expect(shouldPopulate(populated, view(2))).toBe(true)
})
})
+370
View File
@@ -0,0 +1,370 @@
import { describe, expect, it } from 'vitest'
import {
RECONNECT_BASE_DELAYS_MS,
RECONNECT_JITTER,
ProtocolClient,
backoffDelay,
reconnectBaseMs,
} from '../src/ws.ts'
import type { ClientEvent, SocketLike, Timers } from '../src/ws.ts'
class FakeSocket implements SocketLike {
onopen: (() => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onclose: ((event: { code: number; reason: string }) => void) | null = null
onerror: ((event: unknown) => void) | null = null
sent: string[] = []
closed = false
send(data: string): void {
if (this.closed) throw new Error('socket is closed')
this.sent.push(data)
}
close(): void {
this.closed = true
}
open(): void {
this.onopen?.()
}
receive(body: unknown): void {
this.onmessage?.({ data: typeof body === 'string' ? body : JSON.stringify(body) })
}
serverClose(code = 1005, reason = ''): void {
this.closed = true
this.onclose?.({ code, reason })
}
}
function connect(): {
client: ProtocolClient
socket: FakeSocket
events: ClientEvent[]
} {
const socket = new FakeSocket()
const events: ClientEvent[] = []
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: event => events.push(event),
})
client.connect()
socket.open()
return { client, socket, events }
}
describe('protocol client', () => {
it('parses text frames and ignores binary or unreadable ones', () => {
const { socket, events } = connect()
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
socket.receive('not json')
socket.onmessage?.({ data: new Uint8Array([1, 2]) })
expect(events.filter(event => event.type === 'frame')).toHaveLength(1)
})
it('correlates one ack per reqId and ignores an unknown ack', async () => {
const { client, socket } = connect()
const first = client.send('conn.ping', { ts: 11 })
const second = client.send('conn.ping', { ts: 12 })
expect(client.pendingCount).toBe(2)
const sent = socket.sent.map(raw => JSON.parse(raw) as { t: string; reqId: number; ts: number })
expect(sent.map(intent => intent.t)).toEqual(['conn.ping', 'conn.ping'])
expect(sent[0]?.reqId).toBe(1)
expect(sent[1]?.reqId).toBe(2)
socket.receive({ t: 'ack', n: 1, reqId: 2, ok: true, ts: 12 })
socket.receive({ t: 'ack', n: 2, reqId: 99, ok: true })
expect(client.pendingCount).toBe(1)
await expect(second).resolves.toMatchObject({ reqId: 2, ok: true })
socket.receive({ t: 'ack', n: 3, reqId: 1, ok: false, code: 'invalid' })
await expect(first).resolves.toMatchObject({ reqId: 1, ok: false, code: 'invalid' })
expect(client.pendingCount).toBe(0)
})
it('tells the caller the reqId after the frame left the socket (#72)', async () => {
const { client, socket } = connect()
const seen: number[] = []
const pending = client.send('token.move', { id: 'aaa', pos: [10, 20] }, reqId => {
// The callback runs only once the frame is on the wire, so recording it cannot outrun send.
expect(socket.sent).toHaveLength(1)
seen.push(reqId)
})
expect(seen).toEqual([1])
expect(JSON.parse(socket.sent[0] ?? '{}')).toMatchObject({
t: 'token.move',
reqId: 1,
id: 'aaa',
pos: [10, 20],
})
socket.receive({ t: 'ack', n: 1, reqId: 1, ok: true, pos: [10, 20] })
await expect(pending).resolves.toMatchObject({ ok: true })
})
it('keeps pending requests across a hello on a live connection (6.3)', async () => {
const { client, socket } = connect()
const pending = client.send('player.setname', { name: 'Ann' })
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } })
expect(client.pendingCount).toBe(1)
socket.receive({ t: 'ack', n: 2, reqId: 1, ok: true })
await expect(pending).resolves.toMatchObject({ ok: true })
})
it('drops pending requests with the connection (6.3)', async () => {
const { client, socket } = connect()
const pending = client.send('conn.ping', { ts: 1 })
socket.serverClose(1006)
expect(client.pendingCount).toBe(0)
await expect(pending).rejects.toThrow(/closed/)
})
it('reads a server close reason from the last closing frame (6.5, FIXED #18)', () => {
const { socket, events } = connect()
socket.receive({ t: 'closing', n: 2, reason: 'revoked', code: 4001 })
socket.serverClose(1005)
expect(events.at(-1)).toEqual({ type: 'close', reason: 'revoked', code: 4001 })
})
it('treats a close without a closing frame as a transport failure', () => {
const { client, sockets, events, timers } = reconnectingClient()
client.connect()
sockets[0]!.open()
sockets[0]!.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
sockets[0]!.serverClose(1006)
expect(events.find(event => event.type === 'close')).toEqual({
type: 'close',
reason: null,
code: 1006,
})
// It is a transport failure, so the client also schedules a retry (T5, #68).
expect(events.some(event => event.type === 'reconnecting')).toBe(true)
expect(timers.size).toBe(1)
client.close()
})
it('does not reconnect to a terminal outcome (single connect)', () => {
const socket = new FakeSocket()
const sockets: FakeSocket[] = [socket]
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: () => {},
})
client.connect()
socket.open()
socket.receive({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 })
socket.serverClose(1005)
client.connect() // a no-op once closed
expect(sockets).toHaveLength(1)
expect(client.state).toBe('closed')
})
it('ignores a frame that arrives after the client closed the socket', () => {
const { client, socket, events } = connect()
client.close()
const before = events.length
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
expect(events).toHaveLength(before)
})
it('refuses to send before the socket opens', async () => {
const socket = new FakeSocket()
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => socket,
onEvent: () => {},
})
client.connect()
await expect(client.send('conn.ping', { ts: 1 })).rejects.toThrow(/not connected/)
})
})
// ---------------------------------------------------------------------------------------------
// T5 (#68): reconnect with a growing, jittered delay.
/** A clock the test advances by hand: no real timers, so the schedule is exact. */
class ManualTimers implements Timers {
#next = 1
pending = new Map<number, { fn: () => void; ms: number }>()
setTimeout(fn: () => void, ms: number): number {
const id = this.#next++
this.pending.set(id, { fn, ms })
return id
}
clearTimeout(handle: number): void {
this.pending.delete(handle)
}
get size(): number {
return this.pending.size
}
nextDelay(): number | null {
const first = this.pending.values().next()
return first.done ? null : first.value.ms
}
runNext(): void {
const first = this.pending.entries().next()
if (first.done) throw new Error('no scheduled timer')
this.pending.delete(first.value[0])
first.value[1].fn()
}
}
function reconnectingClient(options: { autoReconnect?: boolean; random?: () => number } = {}): {
client: ProtocolClient
sockets: FakeSocket[]
events: ClientEvent[]
timers: ManualTimers
} {
const sockets: FakeSocket[] = []
const events: ClientEvent[] = []
const timers = new ManualTimers()
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => {
const socket = new FakeSocket()
sockets.push(socket)
return socket
},
onEvent: event => events.push(event),
timers,
random: options.random ?? (() => 0.5),
...(options.autoReconnect === undefined ? {} : { autoReconnect: options.autoReconnect }),
})
return { client, sockets, events, timers }
}
const helloFrame = { t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } }
describe('reconnect backoff (6.3, story 8)', () => {
it('uses the 1/2/4/8/10 s base schedule with bounded jitter', () => {
expect(RECONNECT_BASE_DELAYS_MS).toEqual([1000, 2000, 4000, 8000, 10000])
expect([1, 2, 3, 4, 5, 6, 99].map(reconnectBaseMs)).toEqual([
1000, 2000, 4000, 8000, 10000, 10000, 10000,
])
for (let attempt = 1; attempt <= 6; attempt += 1) {
const base = reconnectBaseMs(attempt)
expect(backoffDelay(attempt, () => 0.5)).toBe(base)
expect(backoffDelay(attempt, () => 0)).toBe(base - base * RECONNECT_JITTER)
expect(backoffDelay(attempt, () => 0.999999)).toBeLessThanOrEqual(
Math.round(base * (1 + RECONNECT_JITTER)),
)
}
// Jitter is real, not cosmetic: two random draws give different delays, and the cap still holds.
expect(backoffDelay(1, () => 0)).not.toBe(backoffDelay(1, () => 0.9))
expect(backoffDelay(99, () => 0.999999)).toBeLessThanOrEqual(
Math.round(10000 * (1 + RECONNECT_JITTER)),
)
})
it('reconnects after a transport close and drops the pending reqIds with it', async () => {
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
const pending = client.send('conn.ping', { ts: 1 })
expect(client.pendingCount).toBe(1)
sockets[0]!.serverClose(1006)
expect(client.pendingCount).toBe(0)
await expect(pending).rejects.toThrow(/closed/)
expect(events.filter(event => event.type === 'close')).toEqual([
{ type: 'close', reason: null, code: 1006 },
])
const reconnecting = events.filter(event => event.type === 'reconnecting')
expect(reconnecting).toEqual([{ type: 'reconnecting', attempt: 1, delay: 1000 }])
expect(timers.size).toBe(1)
timers.runNext()
expect(sockets).toHaveLength(2)
sockets[1]!.open()
sockets[1]!.receive(helloFrame)
expect(events.filter(event => event.type === 'open')).toHaveLength(2)
// The backoff resets after a successful reconnect: the next drop starts again at 1 s.
sockets[1]!.serverClose(1006)
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toEqual({
type: 'reconnecting',
attempt: 1,
delay: 1000,
})
})
it('grows the delay while attempts keep failing', () => {
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
for (const attempt of [1, 2, 3, 4, 5]) {
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
attempt,
delay: reconnectBaseMs(attempt),
})
timers.runNext()
sockets.at(-1)!.serverClose(1006) // the retry never got a hello
}
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
attempt: 6,
delay: 10000,
})
})
it('does not reconnect after a terminal server outcome', () => {
for (const reason of ['revoked', 'proto-mismatch', 'evicted', 'malformed-flood'] as const) {
const { client, sockets, events, timers } = reconnectingClient()
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.receive({ t: 'closing', n: 2, reason, code: 4000 })
sockets[0]!.serverClose(1005)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
expect(client.state).toBe('closed')
}
})
it('does not reconnect before the first open (a refused upgrade)', () => {
const { client, sockets, events, timers } = reconnectingClient()
client.connect()
sockets[0]!.serverClose(1006)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
})
it('does not reconnect when autoReconnect is off', () => {
const { client, sockets, events, timers } = reconnectingClient({ autoReconnect: false })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
})
it('retryNow skips the wait and a manual close cancels the retry', () => {
const { client, sockets, timers } = reconnectingClient()
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
expect(timers.size).toBe(1)
client.retryNow()
expect(timers.size).toBe(0)
expect(sockets).toHaveLength(2)
sockets[1]!.serverClose(1006)
expect(timers.size).toBe(1)
client.close()
expect(timers.size).toBe(0)
expect(client.state).toBe('closed')
})
})
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"allowImportingTsExtensions": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"types": ["vite/client"]
},
"include": ["src", "test"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vitest/config'
// The client is served from `/` by the nginx vhost (DESIGN 11.1, #66), so assets are absolute
// (`/assets/...`) and content-hashed. Tests are pure modules (no DOM): the reducer seam has no
// Pixi import, so Vitest needs no browser environment.
export default defineConfig({
base: '/',
build: { target: 'es2022' },
test: {
include: ['test/**/*.test.ts'],
environment: 'node',
},
})
+24 -3
View File
@@ -15,7 +15,10 @@
"bin"
]
},
"nginx": "latest"
"nginx": "latest",
"openssl": "latest",
"chromium": "latest",
"imagemagick": "latest"
},
"shell": {
"init_hook": [],
@@ -23,11 +26,29 @@
"test": [
"tools/test.sh"
],
"e2e": [
"client/e2e/run.sh"
],
"client-test": [
"client/run-tests.sh"
],
"serve": [
"tools/serve.sh \"$@\""
],
"seed": [
"node tools/seed.mjs \"$@\""
],
"mutation": [
"tools/mutation.sh"
"tools/mutation.sh \"$@\""
],
"bench": [
"mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc"
"mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim \"$@\" > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc"
],
"import-scale": [
"mkdir -p results; IMPORT_SCALE=1 node --test --test-concurrency=1 --test-reporter=spec tools/importscale.test.mjs \"$@\" > results/import-scale.log 2>&1; rc=$?; cat results/import-scale.log; exit $rc"
],
"fogbench": [
"mkdir -p results; nim c -d:release --hints:off -o:run/test/fogbench tools/fogbench.nim > results/m4-fog-bench.log 2>&1 && ./run/test/fogbench \"$@\" >> results/m4-fog-bench.log 2>&1; rc=$?; cat results/m4-fog-bench.log; exit $rc"
]
}
},
+222
View File
@@ -1,6 +1,42 @@
{
"lockfile_version": "1",
"packages": {
"chromium@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#chromium",
"source": "devbox-search",
"version": "155.0.8059.39",
"systems": {
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/a1w34yg08mvma03xps5dsy8vw5hrdy9w-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/5hpd396v5byrfp1vnw7zmpfscqd3b1zv-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39"
}
}
},
"coreutils@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#coreutils",
@@ -420,6 +456,68 @@
}
}
},
"imagemagick@latest": {
"last_modified": "2026-10-07T09:43:42Z",
"resolved": "github:NixOS/nixpkgs/39ad350a0602fa0a58a544344e3e9187526ea45c#imagemagick",
"source": "devbox-search",
"version": "7.1.2-31",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/w943n99gba8wqiznbvl3v1a5bz1aj1hs-imagemagick-7.1.2-31",
"default": true
},
{
"name": "dev",
"path": "/nix/store/h5381l00wa4a8l42d5wf20f1i6nzsbdi-imagemagick-7.1.2-31-dev"
},
{
"name": "doc",
"path": "/nix/store/rqwrgqsbh8jgximpzd8cnixhpfscss1k-imagemagick-7.1.2-31-doc"
}
],
"store_path": "/nix/store/w943n99gba8wqiznbvl3v1a5bz1aj1hs-imagemagick-7.1.2-31"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/jwa4dla37chizyjlhafhq5dz4bkfchgq-imagemagick-7.1.2-31",
"default": true
},
{
"name": "dev",
"path": "/nix/store/mpd89rd3lxyjc4fpb9jzqr55ik57r8nk-imagemagick-7.1.2-31-dev"
},
{
"name": "doc",
"path": "/nix/store/8bm6yz8yy86sai52vnfcd4a6n7z7adnf-imagemagick-7.1.2-31-doc"
}
],
"store_path": "/nix/store/jwa4dla37chizyjlhafhq5dz4bkfchgq-imagemagick-7.1.2-31"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/s13s3r3pi67vj27s6ca7pbrxs2z4zjf6-imagemagick-7.1.2-31",
"default": true
},
{
"name": "dev",
"path": "/nix/store/6b18lsv6dy2vss0adl6n9zrjgx1r3ixg-imagemagick-7.1.2-31-dev"
},
{
"name": "doc",
"path": "/nix/store/pjx3bsd4p2qssg4gaph70x7qz9vzzb9p-imagemagick-7.1.2-31-doc"
}
],
"store_path": "/nix/store/s13s3r3pi67vj27s6ca7pbrxs2z4zjf6-imagemagick-7.1.2-31"
}
}
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
@@ -586,6 +684,130 @@
}
}
},
"openssl@latest": {
"last_modified": "2025-12-05T06:24:47Z",
"resolved": "github:NixOS/nixpkgs/42e29df35be6ef54091d3a3b4e97056ce0a98ce8#openssl",
"source": "devbox-search",
"version": "3.6.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/z9prisxci5h5lsk3rdknd4jzq7k9q13d-openssl-3.6.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/ii9mnzr3i92mgk9dkgg65739mavd0j6f-openssl-3.6.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/h0qgqik0mk0wn7rmm2kk3grfi1wzly74-openssl-3.6.0-dev"
},
{
"name": "doc",
"path": "/nix/store/yx3ip21fdaaxpjn5fbir02mqnaw9cm4f-openssl-3.6.0-doc"
},
{
"name": "out",
"path": "/nix/store/3z54dgks2mz3dhwddj158sdibll8xmq5-openssl-3.6.0"
}
],
"store_path": "/nix/store/z9prisxci5h5lsk3rdknd4jzq7k9q13d-openssl-3.6.0-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/wb6q44n9kcb5acmaa4rgqsajadx1fhhl-openssl-3.6.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/c9n1alb7ypzjvzd47m16fiwfczz23qs3-openssl-3.6.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/ci6d4k1sj4bnr892lsrqqmjiihqsk0bl-openssl-3.6.0-debug"
},
{
"name": "dev",
"path": "/nix/store/pq8b7fb3282g68pmk14mbyi20qn6chid-openssl-3.6.0-dev"
},
{
"name": "doc",
"path": "/nix/store/vaplp6w56dyz38986bgkf0pbg3r486b2-openssl-3.6.0-doc"
},
{
"name": "out",
"path": "/nix/store/nj50gkyx813dxvfmsg1q8m330hmf3h86-openssl-3.6.0"
}
],
"store_path": "/nix/store/wb6q44n9kcb5acmaa4rgqsajadx1fhhl-openssl-3.6.0-bin"
},
"x86_64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/m3xwn9n0jypwjgi256idfzs979g30j29-openssl-3.6.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/hw43f3y1vl7ydrd4samnwnrwqqwkpisv-openssl-3.6.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/dirjrfjk8jgsbdpslgb51cav6qaxn2vm-openssl-3.6.0-dev"
},
{
"name": "doc",
"path": "/nix/store/va1zhkz0nfmycvd0h239hi4w40qgaxcx-openssl-3.6.0-doc"
},
{
"name": "out",
"path": "/nix/store/q9a4wssx24xsy28w8kifdqizc01fh7sc-openssl-3.6.0"
}
],
"store_path": "/nix/store/m3xwn9n0jypwjgi256idfzs979g30j29-openssl-3.6.0-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/k0gl1zc7f5hk87lylxwbipb0b870bcmk-openssl-3.6.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/a9jdl6xq9fc98ykpvqmc9kf0b0j9y8wh-openssl-3.6.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/sqv8kbdgfxlr2d6nysr8c2715qpsi6f5-openssl-3.6.0-debug"
},
{
"name": "dev",
"path": "/nix/store/ydrckgnllgg8nmhdwni81h7xhcpnrlhd-openssl-3.6.0-dev"
},
{
"name": "doc",
"path": "/nix/store/cgp9ig35iwicfb9spcrgyg2m5dmlcgrv-openssl-3.6.0-doc"
},
{
"name": "out",
"path": "/nix/store/61i74yjkj9p1qphfl7018ja4sdwkipx0-openssl-3.6.0"
}
],
"store_path": "/nix/store/k0gl1zc7f5hk87lylxwbipb0b870bcmk-openssl-3.6.0-bin"
}
}
},
"sqlite@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite",
+110
View File
@@ -0,0 +1,110 @@
# Review of `docs/ANALYSIS.md`
Reviewed by the owner with the agent on 2026-11-17, against `main` at `287859d` (after #49/#50).
`docs/ANALYSIS.md` was written against `409d2c8` / DESIGN v0.27 and is kept unchanged. This file
records the decisions, the corrections to the analysis, and the technical items adopted into the
build list.
## 1. Owner decisions (FIXED, 2026-11-17)
### D1 - Build order: playable M4 first; walls/height logic after the playtest
Thick walls (#45/#50) and wall/token heights + see-over (#41/#44) stay **FIXED design** and are
not cut. They are **built after the first playable M4 client and a phone playtest**. The v1-first
build is thin walls with the 5.8 switches, doors, secret/locked, windows, one-way and player
markers.
The #49 schema still lands **complete now**: `thickness`, `position` and `height` columns with
"as today" defaults (`0`, `center`, `NULL`) and the #49 migration. The later build therefore adds
behaviour, not a migration.
ANALYSIS ref: §1.1, §4.5, §7 item 2. Recorded in DESIGN §1, §13.
### D2 - Split DESIGN.md before `/to-spec` - DONE 2026-11-17
The current spec (`docs/DESIGN.md`), 22 ADRs in `docs/adr/`, and the non-normative history
(`docs/DESIGN-history.md`) are split; verification in `docs/research/design-split-check.md`.
Tracking issue: #51 "Design doc split: current spec + ADRs + history".
ANALYSIS ref: §1.3, §4.6, §7 item 8.
### D3 - Minimum zoom 0.5 for players
v1 clamps player zoom-out at 0.5. That bounds the visible tile count (about 1.3k tiles at 0.5,
about 5k at 0.25), which is the cheapest bound on phone tile requests. A per-player
explored-masked overview image is a **possible later** feature, not v1.
ANALYSIS ref: §4.8, §6.6.
### D4 - Walls-sourced `stuck`/`squeezed` visible to players: accepted
A player seeing a `walls`-sourced status learns that some blocking wall touches that token. This
is an **accepted, documented effect**: a refused move already reveals the same fact through the
uniform nack. Leak note 6 (6.1) is **closed as accepted**; no source-free status is added.
ANALYSIS ref: §4.7.
## 2. Corrections to ANALYSIS
- **§4.5 is stale on #49/#50.** It says #49 (wire/schema/migration) and #50 (thick doors and
push) are still open. Both are decided on `main` (#49 in v0.29, #50 in v0.28); thickness,
height and the door leaf are settled design.
- **§4.5, heights in the polygon: wrong.** Height never enters the sight polygon. DESIGN 5.9
keeps the polygon strict and applies height as a **per-target predicate** (`visibleTo` =
`insideAny or predicate`); 5.10 evaluates it at every crossed face. The oracle-burden point
(leakcheck needs its own height test, band cells are oracle-*maybe*) stands.
- **§4.5, one-way "expensive in the ray fan": overstated/wrong.** #47 chose a per-viewer **sign
test on the hoisted, viewer-independent face list** inside the fan: one cross-product sign per
one-way wall per viewer, no per-viewer copy, no geometry. #43 measured the filter at
+0.15 ms/polygon on 5k sparse (2.8x thin, 0.24 vs 0.08 ms) and 1.1x dense; it is a small
inline predicate, not a fan rework. No separate one-way build item is needed.
- **§6.2, "near-face variant costs about the same as thin walls [measured]": INCORRECT as
applied.** Research §2.2's one-face row (0.174 ms sparse) includes building 5000 offset
segments **inside the timed call** and is an approximation that leaves the far half of the
band visible-ish; hoisted it is thin-like, but it is not the model DESIGN 5.10 needs. The
decided near+caps silhouette has three faces, is observer-dependent and **cannot be hoisted**;
`prototype-wall-sight/cost.txt` (branch `prototype/wall-sight`) measures:
- 5k sparse: thin 0.083 ms; 3-face silhouette per query **0.699 ms (8.4x)**;
4-face quad per query 0.943 ms (11.3x), hoisted 0.263 ms (3.2x);
- 5k dense: thin 1.254 ms; silhouette per query 7.851 ms (6.3x);
4-face quad per query 13.229 ms (10.6x), hoisted 12.721 ms (10.2x).
So the near-face route is not thin-priced; the quad is affordable only when hoisted.
DESIGN 5.10's citation "0.26 vs 0.94 ms on 5k sparse" compares hoisted vs per-query **4-face
quad**; the 3-face silhouette is 0.70 ms. The citation is corrected in 5.10 to name the rows.
- **§6.7, thick dense 6-token party 75.6 ms: correct.** Research §2.3: six thick polygons in
one dense recompute = 75.6 ms vs 7.7 ms thin [MEASURED, #39] (about 6 x 12.8 ms quad per
query vs 6 x 1.28 ms thin). The figure is per-query (not hoisted) and it is the stress layout,
as stated.
- Everything else checked against the tree (race §4.1, global lock/transactions §4.2, egress
§4.4, leakcheck non-independence §4.7, tile count §4.8) still holds at `287859d`. Note that
§4.1's quick fix is done, merged `c5ec25e`.
## 3. Adopted technical items - build list
Sizes are S/M/L. "When" uses the owner order: before-M4 / M4 / M5; decisions and later work are
marked.
| # | Item | Gist | ANALYSIS | Size | When |
|---|---|---|---|---|---|
| 1 | JsonNode race fix + small fixed `workerThreads` | Own/copy intent JSON before it enters the world; build referencing frames under the lock; pin a small worker pool instead of mummy's `10 x cores`. Done, merged `c5ec25e`. | §4.1, §7.1 | S | before-M4 |
| 2 | Circle-segment-per-sector ray test | Each ray tests only the 64-gon segment in its sector; same polygon, same tests. | §4.3, §6.2(1) | S | before-M4 |
| 3 | Per-token polygon cache keyed `(pos, range, wallsVersion)` | A move recomputes one token's polygon, not the player's party; wall edits bump the version. | §4.3, §6.2(4) | M | M4 |
| 4 | Incremental wall-edit refresh by bbox | Recompute only tokens whose vision circle overlaps the edited wall's bbox. | §4.3, §6.2(5) | S | M4 |
| 5 | Angular sweep; keep the old ray fan as oracle | O(n log n) sweep for polygons; the old fan stays in leakcheck as an independent oracle, fixing §4.7's non-independence. | §4.3, §6.2(2-3), §4.7 | M | M5 |
| 6 | Session cache + tile gate off the global lock; explored as bitmap | In-memory session table and per-player explored bitmap snapshot; no DB/SHA-256 per tile request; explored is the on-disk bitmap, not a `HashSet`. | §4.2, §4.3, §6.2(7), §6.6 | S/M | before-M4 |
| 7 | World thread + group commit | One thread owns all ref-managed state; workers pass plain strings; one SQLite transaction per batch. Removes the race class and the M5 ordering work. | §4.1, §4.2, §6.1 | L | M5 |
| 8 | Integer/fixed-point wire coords; per-entity version diffs; affected-recipient egress | Quantised coordinates; diff by versions, not JSON trees; build each frame once and visit only affected recipients. | §4.4, §6.3 | M | M5 |
| 9 | Slow client: stop feeding + resync on pong lag | Stop feeding a lagging client and resync from `Known` on recovery; replaces "close when lag exceeds a bound" (impossible at the mummy pin). | §4.3, §6.4, §5 | S | M5 |
| 10 | Table-driven intent schema | One field table (name, type, required, range) replaces hand-written validation per intent. | §4.7 | M | M5 |
| 11 | Durability: one setting, measure first | Drop the FULL/NORMAL toggle if measurement shows no benefit; one setting for the home server. | §4.7, §5, §6.5 | S | M5 |
| 12 | Verify nginx HTTP/2 before the phone gate | HTTP/2 must be live end-to-end before the Note 10 gate; HTTP/1.1 caps six connections per host. | §6.6 | S | before-M4 |
| 13 | Thin sqlite3 binding replacing `db_connector` | **PROPOSED.** Prepared-statement cache, real NULL binding, `busy_timeout`, one transaction helper. Touches a [FIXED] stack item, so the owner decides at `/to-spec`. | §4.7, §5, §6.5 | M | at `/to-spec`, if accepted |
Related to D3: the 0.5 minimum zoom is client work in M4; the explored-masked overview image is a
possible later (post-M5) item and is not on this list.
## 4. Consequence for tickets
Build tickets are generated from the split current spec at `/to-spec`, not from this review.
Thick walls and heights get build tickets only after the M4 playtest (D1). No issue is created
from the build list here; the only new tracker issue is the DESIGN split.
+405
View File
@@ -0,0 +1,405 @@
# FFF_vtt: an outside analysis of requirements, design and engine
Written 2026-11-17 against `main` at `409d2c8` (DESIGN draft v0.27, M1 to M3 done, M4 client not
started). I read the design, glossary, research notes, prototype reports and the whole server, and
skimmed the tests, tools and committed gate logs. I did not run anything. The numbers come from
the committed logs in `results/` and from the research notes.
Evidence tags used below:
- **[measured]**: a number from a committed log or research note.
- **[read]**: I saw it in the code or the docs.
- **[inferred]**: my estimate. Treat it as a hypothesis to measure, not a fact.
---
## 1. Verdict in one page
**The core idea is right, and it is rare.** "The server alone decides what each player sees", with
one egress path and typed per-recipient views, is the correct architecture for a VTT that really
hides information. Most VTTs send everything and hide it in the client. This project doesn't, and
it has built the tests to prove it: an independent leak checker, fault-injection builds and 63
mutations. That is the strongest part of the project, and it is better engineered than most
commercial VTTs on this specific point.
**The compute engine is not the problem.** One visibility polygon costs about 0.04 ms, and a whole
mutation about 0.7 ms [measured]. One GM and six players produce a few intents per second. The CPU
has a margin of three to four orders of magnitude. For this load, "the most efficient engine" does
not mean faster geometry. It means:
1. lower tail latency (the slowest acks come from SQLite COMMIT and lock queueing, not from vision),
2. fewer wire bytes and fewer tile requests on a phone,
3. no latent concurrency bugs,
4. less code and fewer documents for one person to carry.
**The three biggest problems, in order:**
1. **There is still no client, and the design keeps growing.** Six milestones of server work, then
eight design decisions (#41 to #48: heights, thick walls, one-way walls, windows, presets,
markers) were added before anyone has played a session in a browser. The riskiest unknowns are
all on the client side: cold tile load on the phone, iOS Safari, real map sizes. None of them is
retired.
2. **A real data race in the threading model** (section 4.1). The server runs mummy's worker
threads over shared ORC-managed `JsonNode`s that are not protected by the lock. Reference counts
in Nim's ORC are not atomic, so this can corrupt memory. It is rare and hard to reproduce, and it
is exactly the kind of bug that shows up once in a live session and never in tests.
3. **The design document has outgrown its author.** `docs/DESIGN.md` is 270 KB of layered,
partly superseded decisions, with no ADRs. It is now the main cost of every change, and that
includes changes made by agents.
**My recommendation, short form:** freeze the wall-feature scope at what thin-segment geometry can
do cheaply. Fix the threading model by moving to a single world thread. Make the vision pass
incremental and cheaper using the known algorithmic fixes. Then build the M4 client and measure on
the phone before designing anything else.
---
## 2. What the project is, as I understand the requirements
- Self-hosted browser VTT for **one table**: 1 GM and up to 6 players, one scene in v1.
- **Server-authoritative sight.** Walls and doors are GM-only data. Each player receives only the
tokens inside their vision polygons, their own polygons, and their own explored cells. Map art is
served as 32 px tiles, gated per player by explored cells. No secret ever reaches a client
"hidden".
- Movement is validated on the server (swept circle, step cap, uniform nack) so that players cannot
map walls by probing.
- Stack, marked [FIXED] in the design: Nim 2.2 + mummy 0.4.8 + db_connector/SQLite WAL on the
server; TypeScript + PixiJS v8 on the client; nginx in front (TLS, `X-Accel-Redirect` tiles);
NixOS/devbox.
- The target device includes a 5-year-old Android phone (Note 10), which sets the client budget.
These requirements are coherent. The single-table scale is the most important one and it should
drive every trade-off. Several parts of the design read as if they were sized for a bigger system
than this.
---
## 3. What is good (keep it)
| Idea | Why it is good |
|---|---|
| **Single egress, typed views** (`views.nim`: `GmView`/`PlayerView`, the `Known` diff) | A forbidden field cannot leak because it does not exist in the player type. This is the right way to enforce "the server decides". |
| **State-based diffs, not event replay** | Frames describe the current state, so reordering, dropped frames and a resync all converge. This choice already saves the current threading model from its ordering gaps (section 4.2). |
| **Independent leak checker + fault builds + mutation testing** | Proof that the rule holds, not just a belief. Fault injection is compiled out of shipped binaries. Few projects of any size do this. |
| **Measured-evidence discipline** ([MEASURED]/[INFERRED] tags, prototypes, research notes) | Decisions are traceable. Several research notes caught real errors in the design. |
| **Uniform move nack + step cap** | Closes the "probe the walls with moves" channel at low cost. 24/24 probing runs are identical [measured]. |
| **Explored stored as 64×64-cell chunk bitmaps** | Compact, bounded writes, simple to restore. |
| **Random 72-bit token ids** | Counted ids would leak hidden tokens through the gaps. A small detail, and it is right. |
| **Scanline `cellsTouched`** | About 10× faster than the prototype and differential-tested against it [measured]. |
| **Switch-based wall model (#42/#48)** backed by a survey of other VTTs | The model is right. The scope built on top of it is the problem (section 5). |
| **nginx serves tile bytes, Nim only authorises** | Correct split. Nim never reads image files. |
| **Glossary** | Short, precise, useful. Keep it as the vocabulary anchor. |
---
## 4. What is bad or risky (the critique)
Ordered by how much it matters, not by how easy it is to fix.
### 4.1 Data race: shared `JsonNode`s across mummy worker threads [read, not reproduced]
`main.nim` casts the `App` out of a raw pointer so that mummy's worker-thread handlers count as
`{.gcsafe.}`. That silences the compiler check that would have caught the following.
In `wall.add` (`server/main.nim:1846-1872`):
- `flags` is a subtree of `env.node`, the JSON parsed on the worker thread.
- Under the lock, it is stored into `app.scene.walls`, so the global world now references that
node.
- After the lock is released, `wallObjectOf(added.get)` builds a frame that references the same
`flags` node (reference count +1). At the end of `dispatch`, `env`, `candidate` and `added` are
destroyed (reference count −1). Both happen **outside the lock**.
- At the same time, another worker thread can be inside the lock, walking `app.scene.walls` for a
GM resync or `wallsSnapshot`, which touches the same node's reference count.
With `--mm:orc` (`nim.cfg`), reference counting is **not atomic**. Atomic counts exist only under
`--mm:atomicArc`. Two threads updating the same count without synchronisation can lose an update.
The result is a premature free (use-after-free) or a leak. The same pattern applies to `token.*`
flags and props, `scene.set` `extra`, and any `JsonNode` from an intent that ends up in the world.
The probability is low (GM edits are rare and the windows are short). The cost when it happens is a
crash or silent corruption mid-session that no test reproduces. **Fix options**, from quickest to
best:
- Quick: `copy()` every `JsonNode` taken from an intent before it enters the world, and build every
frame that references world state inside the lock.
- Cheap and broad: compile with `--mm:atomicArc`. `JsonNodeObj` is `{.acyclic.}`, so ORC's cycle
collector gives nothing here. Measure the cost first; it is probably small at this load
[inferred].
- Structural (recommended, section 6.1): one world thread owns all ref-managed state, and worker
threads pass it only plain strings.
Related: mummy defaults to `10 × CPU cores` worker threads (`mummy.nim:1476`), and `newServer` is
called without `workerThreads`. On a 16-core machine that is 160 threads competing for one global
lock to serve seven people.
### 4.2 One global lock, two critical sections, two to three transactions per mutation [read]
A mutation runs the handler under `withLock app.dbLock`, releases it, then `settle` takes it again
for encounters, the ack and egress. Between the two sections, another mutation can run in full.
Each section opens its own transactions (`persistExplored`, `recordEncounters`, the row write).
Correctness is saved by the state-based diff, and the design admits the exact ordering is deferred
to the M5 outbox.
- The measured tail is intent→ack p99 4.58 ms, worst ~20 ms, with an unexplained 583 ms spike
earlier [measured]. The research attributes the tail to COMMIT and queueing, not to compute.
- More transactions mean more fsync-shaped tail. One mutation should be one transaction.
- `tileGate` takes the **same global lock** and runs a SQLite session lookup plus SHA-256 **per
tile request** (`main.nim:614-625`). A connect burst is 292 tile requests [measured]. Each one
competes with gameplay mutations for the lock.
- Several paths query the DB under the lock for data that is already in memory (`rosterFrames` →
`allPlayers`, `resyncEveryone` → `playerById`).
### 4.3 The vision pass does far more work than it needs to [read + measured]
None of this matters for latency today (0.27 ms for six polygons [measured]). It matters for thick
walls and dense maps, where the research measured **12.8 ms per polygon and 75.6 ms for a six-token
party** with thick walls on a dense scene [measured].
- **Every ray is tested against all 64 circle segments as well as the walls**
(`geometry.nim:46-68`). The ray's angle tells you which single segment of the 64-gon it can hit,
so one test is enough. That gives the same output and removes most of the work on sparse scenes.
The research estimated a 5-9× saving [inferred there].
- The algorithm is **rays × segments**: 3 rays per endpoint × all walls in the box. Thick walls
multiply both factors (4 edges each), which is why they blow up. An **angular sweep** (sort
endpoints, keep the active walls ordered by distance) is O(n log n) and is the standard solution.
For the dense case (~200 walls in the box) I would expect about 0.1 ms instead of 1.3 ms
[inferred].
- **No caching.** `vision.refresh` recomputes **every** polygon of the player and re-rasterises all
of them, even if only one token moved. `geometryWalls(sc)` copies all walls on every
`computePolys`. `moveScene` copies all walls and tokens on every move and wall edit [read].
- **A wall edit refreshes everyone.** `refreshAll()` recomputes every token of every player,
including tokens 3000 px away from the edited wall.
- Explored is an in-memory `HashSet[int]`, although it is persisted as bitmaps. The tile gate's
"is any cell explored" check would be one bit test on a bitmap.
### 4.4 Egress rebuilds everything, every time [read]
`egressAll` rebuilds the full typed view and every JSON frame for every connection on every
mutation. It compares `JsonNode` trees against `Known`, compares vision as a serialised string, and
resends the **full polygon** on any change (3.4-3.7 KB per move [measured]). `withN` deep-copies
each frame per connection.
At seven users this is affordable. It is still the main cost after COMMIT, and it grows with thick
walls (2.5-3.7× more polygon vertices [measured]). The cheap wins:
- Send integer coordinates (or 0.1 px fixed point), not 17-digit floats. That cuts vision frames
roughly 3-4× [inferred].
- Diff on typed values or a per-entity version counter, not on JSON trees.
- Recompute only the recipients the mutation can affect.
### 4.5 Scope grew before the product exists [read]
v1 started with `wall` | `door`. Decisions #41-#48 add wall heights with see-over, a switch-based
wall model with presets, thick walls, secret and locked doors, windows, one-way walls and player
markers. #49 (wire/schema/migration) and #50 (thick doors and push) are still open.
My honest opinion, per feature:
| Feature | Opinion |
|---|---|
| Secret / locked doors (#46) | **Good.** Cheap (a flag plus the egress rule) and high table value. |
| Windows, one-way walls (#47) | **Good and cheap, if** the vision code is a sweep: they become per-wall predicates (blocks sight from this side / blocks movement but not sight). Expensive in the current ray fan. |
| Presets / switch model (#42/#48) | **Good** as the data model. Keep the preset list short. |
| Player marker | Fine. |
| Thick walls (#45) | **Doubtful for v1.** Highest cost in algorithm, wire bytes and leak-checker rework (its zero-width `clearLine` oracle does not cover thick walls). Most tables are served by thin walls that follow the art. If kept, model them as closed polygons inside a sweep, not as four independent segments in a ray fan. |
| Heights / see-over low walls (#41) | **Bad idea for v1.** No surveyed VTT puts wall height into the sight polygon (Foundry explicitly refused it in core), the semantics are disputed at the table, it needs UI on a phone, and it doubles the leak-oracle burden. Defer it until people have played without it and asked for it. |
UVTT 0.3 import cannot express movement blocking, secret, locked, one-way or windows [read], so
every advanced feature is GM hand-authoring on a phone or desktop client that does not exist yet.
### 4.6 The design document [read]
`docs/DESIGN.md` is 270 KB, draft v0.27. It has lines over 4000 characters, superseded decisions
kept inline next to their replacements, and no `docs/adr/` directory although the agent docs
expect one. The research notes found factual errors in it (mummy "has no upstream tags", and
"close when lag exceeds bound" is impossible at the pin). A document this large is no longer
reliably read in full, by a person or by an agent. That defeats its purpose as the source of truth.
### 4.7 Smaller issues [read]
- **`db_connector` limitations leak into the code:** no NULL binding (so `sqlLitId`/`sqlLit` build
SQL literals, guarded by an alphabet check), no prepared-statement reuse, no transaction API. A
~200-line wrapper over the sqlite3 C API (bind_null, a cached statement table, busy_timeout)
would remove the literals and save CPU on every write.
- **`PRAGMA synchronous` toggled FULL↔NORMAL around each authoring transaction.** It is defensible,
but it adds code and tests for a small difference: in WAL mode, NORMAL only risks the last commits
on power loss, not on a process crash. Low priority. Consider simply FULL everywhere and measure.
- **`dispatch` is one ~1300-line `case`** with field validation written by hand for each intent. A
table-driven schema (field name, type, required, range) would remove most of it and the class of
bugs where one intent forgets a check.
- **The leak checker is less independent than it says.** Its polygon "truth" calls the server's own
`visibilityPolygon`, and its explored check calls the server's `cellsTouched`. Only the
clear-segment sanity check is independent. A wrong polygon would agree with itself. (Section 6.2
turns this into an opportunity.)
- **`walls`-sourced statuses** tell a player that a wall touches a token (leak note 6, still open).
It is minor, but it is a leak by the project's own definition, so either accept it explicitly or
show players a source-free status.
- **mummy 0.4.8:** unbounded send queue, no backpressure, no close codes, no timeouts. The design
knows this; M5 must handle it (section 6.4).
- **Unknowns not retired:** phone cold viewport < 1 s at zoom 1 (unproven; the worst measured cold
load is 3.3 s at zoom 0.5 over HTTP/1.1 [measured]), iOS Safari, real map size and wall count
(Q2), the 583 ms spike, the T11 timing/size side channel (accepted, untested), and where the FFF
rules engine will live.
### 4.8 Tiles at zoom-out [read + measured]
The 32 px tile is the right leak granularity: tile = cell, so an allowed tile shows exactly
explored ground. But the request count grows with 1/zoom²: about 1.3k tiles at zoom 0.5 and about
5k at zoom 0.25 [inferred from the measured 1.3k]. A 16384 px map is 262,144 files, about 1.06 GB
[measured]. There is no lower-resolution pyramid, and a normal one would leak, because a coarse
tile would cover unexplored cells.
---
## 5. Requirements I would challenge
- **"Thick walls and heights in v1"**: covered in 4.5. Defer them.
- **"Close a slow client when lag exceeds a bound"**: impossible as an immediate close at the mummy
pin [research]. Replace it with "stop feeding, then resync" (section 6.4), which the state-based
diff makes easy.
- **"Durability FULL for authoring, NORMAL for the rest"**: correct in spirit, but the
implementation cost is out of proportion to the risk for a home server. Make it one setting.
- **mummy and db_connector as [FIXED]**: keep mummy, since replacing the HTTP layer gains little.
db_connector is worth replacing with a thin direct binding (4.7). Flagging this because it
touches a [FIXED] item.
---
## 6. The engine I would build
This is not a rewrite. Most of the modules are good: `moverules`, `views`, `explored`, `tiles`,
`characters`, `tokens`, `world`. What changes is the plumbing around them in `main.nim`, the vision
algorithm, and how state is published to the tile gate.
### 6.1 Concurrency: one world thread, no global lock
```
mummy workers (few: 4-8) world thread (owns ALL game state)
───────────────────────── ──────────────────────────────────────────────
ws text ─► rate limit ─► (connId, raw string) ──► inbox (MPSC channel, plain strings)
│
├─ parse + validate (table-driven schema)
├─ apply to in-memory world (moverules, …)
├─ ONE SQLite transaction for the whole batch
├─ incremental vision + explored (6.2)
├─ egress diff per affected recipient (6.3)
└─ ws.send(bytes) per connection outbox (6.4)
tile gate (worker) ─► session cache + per-player explored bitmap snapshot
(plain bits, no refs; published by the world thread under a tiny lock
or as an immutable seq swapped atomically)
```
Why this design:
- **No shared refs between threads.** Workers hand over only `string`s. Every `JsonNode` lives and
dies on the world thread. The data race in 4.1 disappears as a category, not as one patched
instance.
- **Ordering is exact by construction.** One thread applies one intent after another, so the M5
"exact per-connection ordering" problem goes away.
- **Group commit.** Intents that arrive while a COMMIT is running are applied together and
committed in one transaction. This attacks the measured tail (COMMIT + queueing) directly. Under a
burst, several acks share one fsync.
- **The tile gate never touches the world or the DB.** It reads a bitmap and an in-memory session
table. Revocation updates the cache from the world thread.
- **The mutation path is easier to reason about**: one loop instead of two critical sections, three
transactions and a borrow-the-world context.
Cost: rewriting `settle`/`egressAll`/`dispatch` plumbing in `main.nim`. Handler bodies move almost
unchanged. Nim's built-in `Channel[string]` or `threading/channels` is enough for the inbox, and
mummy's `ws.send` can be called from any thread.
### 6.2 Vision: sweep, cache, incremental
1. **Now, same output:** test each ray against only the one circle segment in its sector. All
existing geometry tests and the bench still apply unchanged.
2. **Angular sweep** replacing the ray fan: O(n log n) in walls in range. Windows, one-way walls and
secret doors become a per-wall predicate inside the sweep. If thick walls survive, they enter as
closed polygons (only the near face matters for sight, and the research found the near-face
variant costs about the same as thin walls [measured]).
3. **Keep the old ray fan as the leak checker's oracle.** That turns the checker's weakness in 4.7
into real independence: two different algorithms must agree. A single change both speeds up the
engine and strengthens the proof.
4. **Cache per token:** polygon and cell set keyed by `(pos, range, wallsVersion)`. A move
recomputes one polygon, not the player's whole party.
5. **Incremental wall edits:** recompute only tokens whose vision circle overlaps the edited wall's
bounding box.
6. **Uniform grid for walls** (for example 256 px buckets) only if Q2 says maps exceed about 1000
walls. Below that, the bbox cull is enough [measured: 5k sparse is 0.08 ms].
7. **Explored as the bitmap it already is on disk**, not a `HashSet[int]`. Restore is a memcpy, the
tile check is a bit test, and dirty-chunk tracking falls out naturally.
### 6.3 Egress: smaller, cheaper frames
- Integer or fixed-point coordinates on the wire.
- Per-entity version counters. Diff by comparing versions, build JSON only for what changed, and
build each shared frame once, not once per connection.
- Vision: keep full-polygon replacement (it is simple and safe) but quantised. A delta encoding is
not worth the complexity at this scale.
- Only recipients whose view the mutation can affect are visited: the mover's player plus anyone
who could see the token's old or new position.
### 6.4 Slow clients (M5)
mummy gives no queue depth. Use **pong lag** (already recorded) as the signal. When a connection's
lag exceeds a bound, **stop feeding it** and mark it dirty. When it recovers, send `hello` and a
full resync from its `Known` reset. The state-based diff makes the dropped frames harmless. This is
simpler than any outbox with byte accounting and fits the pin's limits.
### 6.5 Persistence
- A thin direct SQLite binding: prepared-statement cache, real NULL binding, `busy_timeout`, one
`transaction` helper.
- One transaction per batch (6.1), and one durability setting.
- Session lookups served from memory, written through.
### 6.6 Tiles
- Keep 32 px tiles and the explored gate.
- **Clamp the minimum zoom in v1** (for example 0.5). That alone bounds the request count.
- Later, if needed: a **per-player overview image** (for example 512 px for a 4096 px map), rendered
from the art and masked by that player's explored bitmap, regenerated when explored grows by more
than N cells. It is leak-free by construction and turns thousands of requests into one.
- Make sure nginx actually runs HTTP/2 to the browser before the phone gate. The h2 benefit is only
inferred so far, and HTTP/1.1 limits a browser to six connections per host.
### 6.7 Expected effect [all inferred, to be measured]
| Metric | Today | After |
|---|---|---|
| Ack p99 | 4.6 ms (worst ~20 ms) | ≈ one COMMIT; bursts share it |
| Polygon, dense 5k | 1.28 ms | ~0.1 ms (sweep) |
| Thick, dense, 6-token party | 75.6 ms | a few ms (sweep, near faces) |
| Vision frame per move | 3.4-3.7 KB | ~1 KB (quantised) |
| Tile request cost | global lock + DB + SHA-256 | `dbLock`-free map lookup + bit test (private mutex) |
| Data-race class | present | gone |
---
## 7. What I would do next, in order
| # | Action | Why now | Size |
|---|---|---|---|
| 1 | Patch the `JsonNode` race: `copy()` intent JSON before storing it, and build frames under the lock (or `--mm:atomicArc`). Set `workerThreads` small. | Memory safety, cheap | S |
| 2 | **Freeze wall scope:** keep secret/locked doors, windows and one-way walls. Defer heights (#41) and thick walls (#45, #50) to after M4 playtests. | Stop growth before the client | decision |
| 3 | Circle-segment fix plus per-token polygon cache. | Same output, big cut | S |
| 4 | Session cache; tile gate off the global lock. | Connect burst vs gameplay | S |
| 5 | **Build M4 client**; run the phone and iOS gates over real nginx h2; clamp the minimum zoom. | Biggest unretired risk | L |
| 6 | World-thread refactor with group commit. | Tail latency, ordering, removes M5 ordering work | M |
| 7 | Angular sweep; keep the ray fan as the leak-checker oracle. | Needed if windows/one-way stay; makes thick walls possible later | M |
| 8 | Split DESIGN.md: a short current spec, ADRs for decisions, and history moved out. | Every future change gets cheaper | M |
| 9 | Thin SQLite binding; table-driven intent schema. | Removes workarounds and repeated validation | M |
| 10 | Slow-client "stop feeding + resync" (M5). | Robustness | S |
---
## 8. Final honest opinion
This is a serious, carefully built server, more rigorous about information leaks than the VTTs
people pay for. The author's instinct to measure before deciding is the project's greatest asset.
The weakness is the mirror image of that strength. Rigor is applied to the server and the design
document, while the thing that decides whether the project succeeds, a playable client on a real
phone at a real table, has not been started. Every week spent designing wall heights or thick-wall
push rules is a week of decisions made without player feedback. Every decision also lands in a
document that is already too large to hold in one head.
The engine needs no heroic optimisation. It needs one structural fix (the world thread, which also
removes a real memory-safety bug), three or four textbook algorithmic fixes it already knows about,
and a scope freeze. After that, the fastest way to make it better is to play with it.
+977
View File
@@ -0,0 +1,977 @@
# FFF_vtt design history
**Not normative.** Nothing in this file is binding. The current rules are in
[`docs/DESIGN.md`](DESIGN.md); the reasoning behind the durable decisions is in
[`docs/adr/`](adr/). This file preserves, verbatim and for reference only:
- A. the v0.4-v0.30 change log that used to be the status line of `DESIGN.md`;
- B. the HANDOFF traceability table (old DESIGN §12);
- C. the dated owner-decision log (old DESIGN §14), Q1-Q24;
- D. the superseded statements that were removed from the current spec, with the
surviving rule named.
Split made on 2026-11-17 under issue #51 (`docs/ANALYSIS-review.md` D2). Section
numbers cited below are the old DESIGN v0.30 numbers; the current spec keeps the
same numbering.
## A. Change log (old status line, v0.4-v0.30)
- v0.4 records Q4 (tile_size 32 px), the outbox lock invariant (4.2, 4.3), and the follow-ups in
3.4, 8, 11.1, 12, 13
- v0.5 records the M2 move-rule decisions in 5.5 and updates 3.4, 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3,
12, 13
- v0.6 records #14 (characters and player data) in 3.1, 3.4, 4.1, 4.4, 6.1, 8, 9, 10.3, 13, 14
- v0.7 records #6 (players and invites) in 3.1, 3.2, 3.4, 4.4, 6.1, 8, 12, 13, 14
- v0.8 records #7 (map tiles) in 3.3, 3.4, 11.1, 13, 14
- v0.9 records #9 (test tools) in 2, 10.4, 13, 14
- v0.10 records #12 (what M3 done means) in 13, 14
- v0.11 records #15 (M3 limits) in 4.3, 6.4, 10.1, 13, 14
- v0.12 records #11 (M3 message list) in 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13, 14
- v0.13 records the owner review of #11 flags in 1, 3.1, 5.5, 6.1, 8, 14
- v0.14 records #17 (getting in: keys, sessions, the auth slice) in 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13,
14
- v0.15 records #18 (talking safely: the protocol shell and the `closing` close-reason message) in
3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3, 13, 14
- v0.16 records #19 (walls and doors: the scene/wall schema, the wall payload rules and the slice-4
rollout) in 4.4, 6.1, 8, 13, 14
- v0.17 records #20 (tokens and sight: the `entity` step, the typed views and the single egress,
vision and explored, and the slice-5 rollout) in 4.4, 6.1, 6.3, 8, 10.3, 13, 14
- v0.18 records #23 (characters and names: the `character`/`name_reveal`/`encountered` step, the
name rule, the players' names and the `roster` frame, and the four name/character fault classes)
in 4.1, 4.4, 6.1, 6.3, 6.4, 6.5, 8, 10.3, 13, 14
- v0.19 records the owner confirmation of the #22 property-schema registry (keep the empty registry
with the permissive fallback in v1; strict mode comes with the FFF seam, post-v1) in 6.1, 14
- v0.20 records the #27-#31 correctness and cost fixes (per-player reveal persistence, one
encountered rewrite path, link-by-update, the borrowed egress context, one scene read per request)
in 4.3, 6.1, 10.3, 14
- v0.21 records #41 (the height model: metres, `height` and `eye_height` as GM-only registered props
with a token override, eye height 93% by default, walls full height unless the GM gives a height)
in 5.7, 6.1, 8, 9, 14
- v0.22 records #42 (the wall model: independent sight/movement switches with door settings and a
sight-only direction, kinds as presets, a derived `kind` label, the v1 preset table, and
secret/locked unobservable to players) in 1, 3.1, 5.1, 5.5, 5.8, 6.1, 7.4, 8, 14
- v0.23 records #44 (low walls: see-over as a per-target predicate over the strict fog polygon,
movement blind to height, the floor behind a low wall left unexplored, and the GM-only who-sees-it
view) in 5.7, 5.8, 5.9, 7.4, 14
- v0.24 records #46 (secret and locked doors: doors stay GM-only in v1, a locked door refuses to
open, and the differential door-equivalence oracle with its fault, leakcheck and tile sweeps) in
1, 3.4, 5.8, 6.1, 6.5, 7.4, 10.3, 14
- v0.25 records #45 (thick walls: the rectangular body and its placement, the shared sight/collider
rectangle with square ends, see-over at every crossed face, no push on a wall edit, and the shape
seam) in 1, 5.1, 5.3, 5.5, 5.7, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 13, 14
- v0.26 records #47 (windows as see-through wall pieces with no sill or top and the `window` preset,
one-way direction wording, the body opaque from both sides, and the one-way oracle and fault
class) in 1, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3, 14
- v0.27 records #48 (`terrain` dropped, four presets, the `player_marker` switch and its player-wire
exception, the GM-only wall `label`, and the "fewest things" principle) in 1, 3.1, 3.4, 5.1, 5.8,
5.9, 5.10, 6.1, 7.4, 8, 10.3, 14
- v0.28 records #50 (door geometry: the door leaf is the wall's own body, an open door is only a
gap, and the thick-door push geometry) in 5.4, 5.5, 5.8, 5.10, 10.3, 14
- v0.29 records #49 (the wall record's wire fields, typed columns with CHECK constraints, migration
step 8 with the legacy `kind` dropped and `marker_seen` added, existing heights backfilled to 1.8
m, the player `marker` message, and `proto` 2) in 3.1, 4.4, 5.7, 5.8, 5.9, 5.10, 6.1, 6.2, 6.3, 8,
10.3, 14
- v0.30 records the 2026-11-17 review of `docs/ANALYSIS.md` (build order after the M4 phone
playtest, minimum zoom 0.5, walls statuses accepted, slow-client close superseded by stop-feed +
resync, and the DESIGN split note) in 1, 4.3, 5.10, 6.1, 7.4, 13, 14
- v0.31 records #32 (the dispatch guard: the `internal` refusal code and unconditional rollback on
every unwind path) in 4.2, 6.2, 6.5, 14
- v0.32 records #35 (the opaque-object caps on wall `flags` and scene `extra`: 8 KB, 64 keys per
object, depth 8) in 6.1, 14
All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN.
## B. HANDOFF traceability (old DESIGN §12)
Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries). Every
row is resolved; the current rules are in the sections each row names.
<!-- BEGIN old section 12 verbatim -->
## 12. HANDOFF items -> decisions / open questions
Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries).
| # | Item | Decision / open | Milestone |
|---|---|---|---|
| H1 | Port geometry + tests as-is | Decision: port `geometry.nim`, `tgeometry.nim`, mutation check, leak harness first | M1 |
| H2 | Token on a wall can't leave (inclusive `segsCross`); closing a door or editing a wall on a token | Decision [FIXED, Q14; door case revised by owner 2026-11-08]: wall add/edit on a token gives it `stuck` (player moves refused, GM moves allowed); a door closing on a token pushes it aside instead (5.5; `squeezed` only if no side is valid; status names per #4, was `blocked`). Set/Keep/Clear per 5.5: stays while any blocking wall overlaps; clears on wall removal or door open only if no other wall overlaps, on a GM move to a free spot, or on GM clear; GM placements/moves onto a wall set it. Trigger = circle overlap [FIXED, owner]; escape + capsule rule [FIXED, accepted default]; both in 5.5. Pin tests replaced in M2. | M2 |
| H3 | O(rays x walls) vision | Decision: radius-bbox cull now; uniform spatial grid over walls only if the 5k-wall bench misses target (5.5) | M2 |
| H4 | `cellsTouched` ~12x polygon | Decision: scanline rasterization, differential test vs ported version | M2 |
| H5 | Shared-endpoint test gap | Decision: port with a test that fails if either arm is removed; new mutation (d) | M1 |
| H6 | Single machine, loopback, power-save timings | Decision: keep as baseline only; real-network run required | M7 |
| H7 | Boundary epsilon ambiguity | Decision: keep `RayEps`, 0.5 px tolerance in checkers; documented | M1 |
| H8 | Tile leak: whole 256 px tile | Decision [FIXED, Q4]: `tile_size` = explored cell = 32 px; residual leak <= one cell, never revoked; no server masking; M4 gates (headless mobile-emulation + phone run); fallback 64 px per-scene config | M4 |
| H9 | Prototype secret = cookie = permanent bearer, no expiry, binds 0.0.0.0, needs HTTPS | Decision: session != key, key replace (GM, live), remove player, log redaction, bind 127.0.0.1, HTTPS via nginx. Sessions never expire; one player key usable across devices (Q10 FIXED); keys plaintext (Q11 FIXED); no key-entry rate limit (owner, #6) | M3 |
| H10 | Move collision: centre path + dest circle, not swept circle | Decision: capsule (swept-circle) check + escape rule, 5.5; step cap = effective vision radius, 5.5 (T8) | M2 |
| H11 | Leak test explored/tile checks self-consistent | Decision: add independent explored oracle | M2 |
| H12 | Full vision polygon (~3 KB) per player move | Decision [FIXED, Q16]: full polygon, integer px, only on change; delta/binary post-v1 | M3 |
| H13 | Explored sent whole + one SQLite row per cell | Decision: chunked bitmaps in DB; RLE on connect | M3 |
| H14 | No SIGTERM handler | Decision: add; durability independent of it | M5 |
| H15 | `synchronous=NORMAL` vs FULL | Decision [FIXED, Q12]: NORMAL; FULL around GM authoring transactions | M3 |
| H16 | Timing instrumentation unbounded and under lock | Decision: do not port; ring buffer/histogram, snapshot outside lock | M5 |
| H17 | 583 ms spike unexplained | Open: not reproduced; production SLOW logging to catch recurrence | M5/M7 |
| H18 | mummy: unbounded send queue, no backpressure | Decision [FIXED (owner decision), Q13]: app-level bounded per-client outbox, coalescing, WS Ping(seq)/Pong lag tracking, stop feeding + full resync; no mummy patch; fork is fallback only (4.3) | M5 |
| H19 | `WebSocket` keyed by raw bytes | Decision: app `connId` table (not raw bytes; `WebSocket` has field-wise `==`/hash at pin, Q13 research) + layout test | M3 |
| H20 | Fog masks Graphics grow unbounded | Decision: fixed-size baked fog texture (7.3) | M4 |
| H21 | Pixi `Text` per token heavy | Decision: BitmapText; glyph set Latin incl. accents + Nerd Font icons (Q17 FIXED) | M4 |
| H22 | Browser rendering never verified | Decision: headless browser e2e | M4 |
| H23 | Tiles don't update on door change | Decision: by design (static art); doors never part of art | -- |
| H24 | Prototype `gmOnly` unused (my finding, not in HANDOFF) | Decision: enforce + fault class | M3 |
| H25 | Player-visible `gseq` side channel (my finding) | Decision: per-connection counter | M3 |
| H26 | Move-validation wall-probing oracle (my finding) | Decision: step cap + rate limit + uniform nack + test (in-process M2, over WS M3; 5.5) | M2/M3 |
---
<!-- END old section 12 -->
## C. Dated owner-decision log (old DESIGN §14)
<!-- BEGIN old section 14 verbatim -->
## 14. Open questions for the owner
1. Q1 - Table size and device mix: how many players max, and which devices (phones, tablets, iOS)?
Drives iOS testing priority and token/message budgets. **RESOLVED [FIXED (owner decision),
2026-11-08]:** devices are phones, tablets and laptops. Max players: 6 [FIXED, owner decision
2026-11-08] (section 1). Connection cap 8 (6 players + GM + headroom) stays [PROPOSED] (sections
4.3, 13).
2. Q2 - Largest map you plan to use (px), and typical wall count per scene? Drives tile size,
spatial grid priority and explored chunking. **DEFERRED [FIXED (owner decision), 2026-11-08]:**
owner does not know yet. 16384 px map and 5k walls stay [PROPOSED] test targets; revisit with real
maps. **Map size RESOLVED 2026-11-21 [FIXED (owner decision), #85]:** images are capped at Full HD
(at most 1920 px long side, 1080 px short side) and the import shrinks larger sources; the largest
scene is 60x34 cells at cell 32. 5k walls remains a PROPOSED server stress target only. See current
3.3, 5.3, 8, 11.1, 13 and ADR-0023.
3. Q3 - Multiple scenes in v1 (GM switches the active scene, per-scene explored grids), or exactly
one scene per table to start? **RESOLVED [FIXED (owner decision), 2026-11-08]:** exactly one scene
in v1; schema may stay `scene_id`-keyed.
4. Q4 - Tile-edge leak: accept as documented, or reduce it (smaller tiles = more requests; gate
tiles only when explored cells cover a minimum fraction; or server-side masked tiles at the cost
of image processing in Nim)? What detail do you paint in map art that must stay secret? **RESOLVED
[FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is
at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to
~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual
phone run; fallback 64 px (per-scene config). Evidence: `docs/archive/prototypes/tile-leak/README.md`. Applied
in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6).
5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start?
**RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is
post-v1.
6. Q6 - Wall/door authoring: is an in-browser GM wall editor required in v1 (no generator feeds in),
or is hand-edited/imported wall data acceptable at first? What other wall kinds are needed soon
(windows, one-way, secret doors, locked doors)? **RESOLVED [FIXED (owner decision), 2026-11-08]:**
in-browser GM wall editor in v1; wall kinds `wall` and `door` only. **Kind set SUPERSEDED [FIXED
(owner decision), 2026-11-15, #42]** by 5.8: a wall's behaviour is independent switches and named
kinds are presets; v1 presets are `wall`, `door`, `secret door`, `locked door`, `terrain` and
`one-way wall`, and `window` was added by #47 (2026-11-16) as a see-through opening, its fixed
form being `terrain`. **Preset list SUPERSEDED AGAIN [FIXED (owner decision), 2026-11-16, #48]:**
there are four presets (`wall`, `door`, `window`, `one-way`), `secret` and `locked` are checkboxes
on any door rather than presets, and `terrain` is dropped entirely (the name, the preset and the
kind); the derived kinds are `wall`, `door`, `window`, `one_way`, `custom`. The editor requirement
is unchanged.
7. Q7 - Vision model: single radius per token or per-token property from day one? Is any
"darkvision/light" concept needed before FFF? **RESOLVED [FIXED (owner decision), 2026-11-08]:**
per-entity numeric `vision_radius` plus scene default; no light sources or darkvision.
8. Q8 - Which "table convenience" features come first after v1, if any: freehand drawing (exists in
the perf prototype), pings, ruler, chat, dice, token images/portraits, initiative tracker?
**DEFERRED [FIXED (owner decision), 2026-11-08]:** decided at M7.
9. Q9 - Should players see each other's names/presence, and should party members share vision
(shared explored/LOS) or is it strictly per player? **RESOLVED [FIXED (owner decision),
2026-11-08]:** vision and explored strictly per player; player names visible to all.
10. Q10 - Session lifetime and invite policy: session expiry, how often invites rotate, single-use
vs reusable invite links, can one player use multiple devices at once? **RESOLVED [FIXED (owner
decision), 2026-11-08]:** sessions never expire; one player key is usable on multiple devices
(wording amended #6: was invite link).
11. Q11 - Invite secrets: stored hashed (shown once, GM regenerates to re-share) or stored plaintext
so the GM can re-copy a link? **RESOLVED [FIXED (owner decision), 2026-11-08]:** player and GM key
secrets stored plaintext so the GM can re-show them (wording amended #6: was invite secrets).
12. Q12 - Durability: is `synchronous=NORMAL` (can lose the last few commits on power loss/OS crash,
never corrupts) acceptable, or should it be FULL for some or all writes? **RESOLVED [FIXED (owner
decision), 2026-11-08]:** `synchronous=NORMAL`; `FULL` around GM authoring transactions.
13. Q13 - Slow/dead client policy: acceptable to disconnect clients that fall behind? Willing to
patch/fork the pinned mummy commit if per-socket queue depth cannot be read from outside?
**RESOLVED [FIXED (owner decision), 2026-11-08]:** option A: app-level bounded per-client outbox,
latest-state-wins coalescing per key (MQTT-retained-like), diff at flush time, server
Ping(seq)/Pong ack tracking for lag, stop feeding lagging clients + full resync on recovery; no
mummy patch. Dead/stuck peers closed by nginx proxy timeouts (mechanism PROPOSED; verify WS goes
through nginx in M5). Fork of mummy (option B) is fallback only, not planned. Research:
`docs/research/q13-mummy-slow-clients.md`; detail in 4.3.
14. Q14 - Moving tokens when walls change: what should happen if the GM closes a door (or edits a
wall) on top of a token? Allow the token to walk out, auto-nudge it, or refuse the edit?
**RESOLVED [FIXED (owner decision), 2026-11-08]:** a GM edit that lands on a token gives it status
`blocked`: server refuses that token's player moves; GM can still move it; status clears when the
wall is removed or the door opened, or when the GM clears it. **Door case revised [FIXED (owner
decision), 2026-11-08]:** spell walls and wall edits stay stuck; a door closing on a token pushes
the token aside (5.5), stuck only if neither side is valid. Status names superseded by #4
(2026-11-10): `blocked` is now `stuck`/`squeezed` (5.5); door-push failure is `squeezed`.
15. Q15 - Reconnect: is a full resync on every reconnect fine up to what explored/state size, or do
you want `resume since N` later? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full resync on
every reconnect; revisit if a measured snapshot exceeds ~100 KB.
16. Q16 - Vision payload: OK with full polygon per move (~3.4-3.7 KB per mover delivery, measured on
loopback) for v1, or do you want deltas/binary earlier (e.g. for mobile data plans)? **RESOLVED
[FIXED (owner decision), 2026-11-08]:** full vision polygon, integer px, sent only on change;
deltas post-v1.
17. Q17 - Names/labels: which character sets must labels support (Latin only, accents, non-Latin,
emoji)? Affects BitmapText glyph atlas vs Text/HTMLText. **RESOLVED [FIXED (owner decision),
2026-11-08]:** labels in Latin incl. accented characters plus Nerd Font icon glyphs.
18. Q18 - Grid and movement: snap to grid on drop? Any server-side speed/distance limit per move,
given there are no rules yet? **RESOLVED [FIXED (owner decision), 2026-11-08]:** grid snap off by
default (client option); server step cap = token vision radius.
19. Q19 - FFF engine: implementation language/runtime, current maturity, and whether it should run
inside the VTT server process, as a sidecar, or in the browser for display only? Does it need
hidden/secret state beyond the three property buckets (public / owner / GM)? **RESOLVED for hidden
state [FIXED (owner decision), 2026-11-08]:** no hidden state beyond the `public`/`owner`/`gm`
buckets and `gm_only` flag in v1; revisit when FFF starts (schema change accepted then). Engine
language, runtime and location: **DEFERRED** to FFF start (section 9 options a/b/c; no decision
now).
20. Q20 - Nix packaging: how do you want the Nim server built (nimble lock + `buildNimPackage` or a
vendored deps approach), and which repo hosts the NixOS module (this repo or your
nixos-configuration repo)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `buildNimPackage`
with a committed `nix/lock.json` (`nim_lk` JSON lock). `nix/package.nix` and `nix/module.nix`
(`services.fffVtt`) live in this repo and are imported from the owner's server NixOS config, like
`foundryvtt.nix`. nixpkgs input pinned to match devbox Nim (2.2.12). Fallback: vendored deps if
`nim_lk` cannot resolve the mummy pin. `nix/` un-ignored in `.gitignore` when M6 starts, not now.
mummy pinned to tag `0.4.8` (same `src/` as `01deb1ff`). Research:
`docs/research/q20-nix-packaging.md`; detail in 11.1.
21. Q21 - Backups: where should off-box backups go (existing mechanism on the server?), and how many
dated copies to keep? **RESOLVED [FIXED (owner decision), 2026-11-08]:** v1 backups go to a backup
folder the server creates under its data root; off-box backups out of v1 scope.
22. Q22 - Observability: journald lines only, or also an internal metrics endpoint scraped by
something you run? **RESOLVED [FIXED (owner decision), 2026-11-08]:** journald lines only;
`/healthz` stays.
23. Q23 - Public exposure: reachable from the internet (domain, rate-limiting, fail2ban
expectations) or LAN/VPN only? **RESOLVED [FIXED (owner decision), 2026-11-08]:** network exposure
and access are out of project scope (owner handles reachability). Built-in protections stay
(127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening
(fail2ban etc.) not in scope.
24. Q24 - Repo conventions: should this design live in `docs/DESIGN.md` plus ADRs under `docs/adr/`
and a `GLOSSARY.md` (AGENTS.md references both, neither exists yet)? Should prototypes remain
in-tree or move to an archive branch once ported? **RESOLVED [FIXED (owner decision),
2026-11-08]:** `GLOSSARY.md` and `docs/adr/` per AGENTS.md; prototypes stay in-tree until the M4
client port, then archived.
Owner also decided 2026-11-08 [FIXED (owner decision)]: restore drill belongs in M6 (sections 11.2,
13).
Owner also decided 2026-11-08 (M2): move rules, `blocked` trigger and GM move bypass are recorded in
5.5; M2 scope and accept criteria in 13.
Owner also decided 2026-11-10 [FIXED (owner decision), #14]: characters are separate records from
tokens (one owner: a player or the GM; a token may link to one character; token controller is
independent of the character owner); character holds identity, token holds the state of the figure;
descriptive and actual names, revealed per player or to all; per-player encountered list, persisted,
removed only by the GM; storage on the server only (SQLite). Character export/import as a file is
future, not M3. See 3.1, 4.4, 8.
Owner also decided 2026-11-10 [FIXED (owner decision), #6]: one shared site link (alone it shows
only the sign-in page); each player has a personal player key, generated by the GM with no name,
identifying the player and granting access to their data. The player types their display name at
first sign-in; names are unique among players; the GM can rename. The GM signs in the same way with
a GM key printed by `fff-vtt gm-key` (replaces `gm-link`, #5; rest of #5 unchanged). The GM can
replace a player's key at any time while the server runs: old key invalid, all that player's
sessions revoked, live connections closed; identity, characters and encountered list kept; no name
re-prompt. Removing a player: key invalid, sessions revoked, connections closed; their characters
and controlled tokens pass to the GM; name and slot freed; encountered list deleted. Defaults
accepted: one key on many devices; sessions never expire; keys stored plaintext; 20-character key in
groups of 4 with dashes, no look-alikes, CSPRNG (~100 bits); 6-player cap counts unused keys;
sign-in sets the session cookie as in 3.2. No rate limit or lockout on key entry (owner rejected
guessing protection). Rejected: per-person invite links; GM types the name at key creation;
delete-and-reinvite only; deleting characters with the player; shared-link visit creates a player;
separate GM link path. Terms: "player key" and "GM key"; "token" stays reserved for map figures.
Message names: #11.
Owner also decided 2026-11-14 [FIXED (owner decision), #7]: map tiles in M3. The tile gate
(`/tiles/`, Nim, `X-Accel-Redirect`) and a minimal local test nginx with generated 32 px fixture
tiles are M3 scope; tile import CLI and the production nginx vhost stay M6. Tile URLs carry
`art_version` from M3 (always 1 in M3); responses are `Cache-Control: private`; malformed or
out-of-range paths get 404, unexplored tiles 403. The gate reuses the server's explored-area logic,
checked against the independent oracle (10.2). On-disk layout
`<state>/tiles/<scene>/v<art_version>/` fixed in M3. See 3.3, 11.1, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #9]: test tools. Black-box WS/HTTP harnesses
are Node 26 only (repo-root `tools/`, built-ins and `node:net` for raw frames, `node:test`, no npm
deps), ported from the prototype; no Nim rewrite. In-process tests stay Nim. Root devbox pins nodejs
26; `devbox run test` runs Nim then Node. Browser e2e details stay open (M4). See 2, 10.4, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #12]: what M3 done means. Done = `devbox run
test` green on a clean checkout, with the nine named groups in 13 (M3 Accept), each pointing to its
details in 10.3, 3.4, 5.5 and 6. Concurrency moves to M5 and the 127.0.0.1 bind check to M6 deploy.
Protocol limits (frame size, intent rate, connection caps) are a separate open card, "M3 limits",
not decided here. See 10.3, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #15)]: M3 limits. The owner
delegated the numbers to the agent and accepted the set. Max inbound WS message 64 KB (mummy
default; inbound only; no config). Intent rate: token bucket per connection, 30/s sustained, burst
100, same for GM and players; excess refused with `rate limited`, no rollback (each intent atomic),
connection stays open. Connections: 4 per player (a 5th closes the oldest), 16 total (the 17th is
refused); replaces the PROPOSED cap of 8. Consequence: the M5 concurrency port spreads load across
connections (10.1). See 4.3, 6.4, 10.1, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #11)]: M3 message list. The owner
delegated the wire shapes; the set is the complete M3 catalogue in 6 (29 client intents, 14 server
messages, 15 with #18's `closing`). Client `t` is `<noun>.<verb>` (GLOSSARY nouns: `token`, never
"entity"), server `t` is a dotless state noun, so they never collide. Every intent carries `reqId`
and gets exactly one `ack` (`ok`, new `id`, `pos` for moves); a refused player move stays the
uniform nack (old position, no code), every other refusal has a static code (`rate-limited`,
`not-allowed`, `not-found`, `invalid`, `name-taken`, `cap-reached`, `in-use`, `no-rules`,
`unknown-type`); frames without a readable `reqId` get `error` (`malformed`, `rate-limited`).
`invite.*`, `gmClearBlocked` and `blocked` are retired: `key.*`/`player.*` for player keys and
players, `status.set`/`status.clear` and `token.resize` for #4. Connection outcomes: HTTP 403
(Origin), 401 (no session), 400, 503 (17th connection); WS close 4001 revoked, 4002 evicted (5th
connection), 4003 proto mismatch, 1008 malformed flood; oversize closes TCP with no frame. `POST
/join` is HTTP (6.6). Server `door` is folded into `wall`; `presence` into `roster`; `pong` into the
ping `ack`. See 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13.
Owner also decided 2026-11-14 (review of #11 flags) [FIXED (owner decision)]: (1) players cannot
create or edit characters or props in v1 (GM only); opening that later is a permission change on the
existing intents, not a redesign (1). (2) A revealed name cannot be un-revealed: no un-reveal intent
(8, 6.1). (3) `character.remove` is refused with `in-use` while tokens link the character (6.1,
6.5). (4) Encountered stays encountered: a `gm_only` flip leaves the entry, greyed (8, 6.1). (5)
Status markers do not reveal their cause to non-GM viewers: `statuses[].source` goes to the GM only
(3.1, 5.5, 6.1; amends #4). The controlling owner is not given `source` either, as the doc has no
owner-view rule for statuses; revisit if wanted.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #17)]: M3 slice 2 ("getting in").
Storage is migration step 2 (`auth`): `player`, `player_key`, `session`, a single-GM partial unique
index, cascading deletes (4.4). Players/keys/sessions: 3.2 and 8. Cookie `fff_session`, `POST /join`
as in 6.6. `fff-vtt gm-key [--new]` and the `<stateDir>/instance.lock` fcntl lock with exit 3 are
recorded in 3.2/11.1. Slice 2 implements only the three GM intents auth needs (`key.create`,
`key.replace`, `player.remove`) with the 6.1 ack shape; the rest of the envelope, error frames, rate
limits and unknown-type answers stay slice 3 (#18). The application close codes of 6.5 are not
expressible at the mummy pin (3.2); slice 3 decides. See 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13.
Owner also decided 2026-11-15 [FIXED (owner decision), #18]: close codes at the mummy pin, option A.
Mummy 0.4.8 cannot send an application close code (`close(ws)` -> an empty close frame -> the
browser sees 1005); mummy is not forked or patched for it. Every server-initiated close is preceded
by exactly one `closing {reason, code}` message carrying the reason of 6.5, then the close frame; a
client treats 1005 plus that last message as the reason. `closing` is a catalogue message (server ->
client, dotless noun) and the catalogue count is 15. Slice 2's eviction and revocation paths send
it. Also recorded FIXED here: the server Ping interval (20 s, plus one right after `hello`; lag
enforcement stays M5), the per-connection `n` rule (server frames only, no number for Ping/Pong, no
global counter), the own `maxMessageLen` (64 KB) rather than mummy's default, and the slice-3
rollout note that catalogue intents whose slice has not landed answer `unknown-type`. See 3.2, 4.3,
6, 6.1, 6.2, 6.4, 6.5, 10.3.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #19)]: walls and doors (M3 slice
4). Schema is migration step 3 (`world`): `scene` and `wall`, with the single v1 scene seeded at `id
1` (4096x4096, tile 32 = cell 32, no grid, vision 400, token radius 20, art_version 1,
`next_wall_id` 1) (4.4). Wall ids are per scene from `next_wall_id`, monotonic and never reused
across removal or restart (#3). The four intents `wall.add`/`wall.update`/`wall.remove`/`door.set`
are GM-only and answer the 6.1 acks; the payload rules 6.1 left open are fixed there: integer
`scene` (else `not-found`), `a`/`b` finite and in bounds with `a != b`, `open` boolean and never
true on a plain wall, `flags` an object (default `{}`), `wall.update` patches only
`a`/`b`/`kind`/`flags` and needs at least one, `door.set` on a non-door is `invalid`, fields before
lookup. Effects: `wall`/`wall_gone` to every GM connection only, and a `walls` snapshot right after
`hello` on a GM connection; players never receive wall data in any message (3.1, T2). Every wall
write is one transaction with `synchronous=FULL` (Q12) and memory follows COMMIT, so a restart
reloads exactly what was acked. See 4.4, 6.1, 6.3, 8, 10.3.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #16)]: M3 slice 1 groundwork
("bare server"). Config keys, defaults, precedence and the canonical origin: 11.1. Migration history
DDL, the agreement/contiguity rule and one-transaction-per-step: 4.4. Secret redaction (value
registry plus sensitive field names, minimum secret length 8): 11.3. `GET /healthz` answers `200
{"status":"ok"}` from slice 1; the lock-bounded health check stays M5: 6.6, 11.3. `devbox run test`
runs `nimble test` first and only then `node --test tools/*.test.mjs` (10.4); both logs land in
`results/`. The server's listen address is the constant `config.BindAddress` = `127.0.0.1`, not a
config key (T15). Dependencies: `fff_vtt.nimble` requires `mummy == 0.4.8` and `db_connector ==
0.1.0`; devbox adds nodejs 26 and sqlite (`out`+`bin`, with
`LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib` for the dlopen). Node 26 `{headers}` re-check: 10.4.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #20)]: tokens and sight (M3 slice
5). Schema is migration step 4 (`tokens`): `entity` as listed in 4.4, no
`radius`/props/`character_id` columns yet (slices 7-8 add them, `entity_status` with slice 7,
`explored_chunk` with slice 6). Token ids are 12 random characters from `[A-Za-z0-9_-]` (a 64-symbol
alphabet, so 6 uniform bits per character, 72 bits) from `std/sysrand`, collision-checked against
every loaded token. The token payload rules 6.1 left open are fixed in 6.1 ("Token payload rules");
the load-bearing ones are: plain tokens only, `radius`/`props`/`character_id` refused `invalid`
rather than dropped, effective radius = the scene default, the wire `name` is always the descriptive
name, `controller: null` is the only GM spelling, and `explored` on connect is RLE rows.
**Modules**: `server/tokens.nim` (records, validation, write-through persistence with FULL for GM
authoring and NORMAL for moves), `server/vision.nim` (per-player polygons, explored set, the one
copy of the visibility rule), `server/views.nim` (the single egress: typed `GmView`/`PlayerView`,
then frames, then the per-connection diff), `server/worldmap.nim` (records -> geometry/move-rule
inputs), `server/faults.nim` (test-only hook). `main.nim` holds the state (`tokens`, `visions` per
player, `known` per connection keyed by app connId) and never builds a state frame itself, so raw
world state has no path to a socket outside the egress (2, 10.1). **Egress timing**: a mutation's
ack and its per-recipient diffs are enqueued under the global lock, in that order, and every frame
is built from the state at enqueue time (mummy's `send` only appends to its deque, 4.3). Exact
per-connection ordering between two concurrent mutations, and the coalescing that keeps that cheap,
stay the M5 outbox. **Runtime rules**: polygons exist only for tokens a player controls that carry
the `vision` flag, with the token's `vision_radius` or the scene default; only their token centres
count for visibility; explored is the union of `cellsTouched` over history, only grows, drops cells
outside the world, and the `fresh` set is cleared after one egress fan-out. A door closing pushes
tokens aside (5.5) and persists the new positions; `stuck`/`squeezed` are slice 7's status model, so
a failed push leaves the token overlapped and unflagged for now. `token.move` maps the move rules to
the wire exactly: `ack {pos}`, the uniform nack for locked/over-cap/collision and for an
out-of-bounds GM move, and `not-allowed` (players, one code for unknown and not-yours) or
`not-found` (GM) before any geometry runs; accepted moves are persisted with NORMAL durability.
`hello` carries the scene block for every named recipient and `extra` for the GM; an unnamed player
still gets only `proto, role, me` and is not fed any state at all (6.3), so slice 5's player-side
acceptance is reached through a harness fixture that writes the name into the DB before connecting:
`player.setname` is slice 8 (#23) and the unnamed gate itself is pinned by `tools/tokens.test.mjs`.
**Tests** (10.1, 10.3): `tools/leak.mjs` builds a 27-group scene over the real wire (enter/leave by
movement, a closed door, create/remove, `gm_only`, a controller hand-over, another player walking in
and out, a wall added and removed, a door push) and records every frame; `tools/leakcheck.nim`
replays it with the GM socket as truth, recomputes polygons from `geometry.nim`, and checks explored
against both that recomputation and an independent clear-segment sampler; A and B both pass with
zero failures. `tools/fault.test.mjs` catches `hidden`, `gmOnly`, `walls`, `withhold`, `otherOwner`,
`otherVision`, `otherExplored`, `noremove` and `explored` under their exact class sets and asserts
the shipped binary contains no `LEAK_FAULT` string. `tools/probing.test.mjs` re-runs T8/H26 over WS:
over-cap probes give the one uniform nack, two scenes differing only beyond cap + token radius
produce identical reply sequences over 90 hostile probes inside the 6.4 burst, and a wall inside
that bound does change the replies. Nim units: `tests/ttokens.nim`, `tests/tvision.nim`,
`tests/tviews.nim`. Mutations aa-af pin the view rule, the egress `token_gone`, the absence of
GM-only fields in a player frame and the "explored only grows" rule.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #22)]: token details (M3 slice
7). Schema is migration step 6 (`token details`): the three prop buckets on `entity` and
`entity_status` (4.4). Intents: `token.resize`, `status.set`, `status.clear`, `prop.set`,
`prop.unset`, all GM-only in v1 (6.1; owner-bucket writes by players come with FFF actions, 9, and
are a permission change, not a redesign). The payload rules 6.1 left open are fixed in 6.1: the
status set and its `source`, the three-bucket caps (64 keys, 1..64-char keys, 8 KB values, per
bucket), the property-schema registry (empty at start with a permissive fallback, so v1 accepts any
key in any bucket because 8 says the server never interprets props; a registered key is enforced)
and the grow-push search. **Modules**: `server/props.nim` (buckets, caps, registry, parsing),
`server/moverules.nim` (the status model replaces the M2 `blocked` bool:
`stuckWalls`/`squeezedWalls` are the `walls` source, `locked` is the caller's "any entry" bit,
per-token radius everywhere, `resizeToken` with the grow search, `placeToken` for GM
placement/move), `server/text.nim` (the one copy of the 6.5 text rule, shared by names and prop
keys), `server/tokens.nim` (statuses and props on the record and in the row), `server/worldmap.nim`
(`ruleToken`/`ruleWall`/`applyOutcome`/`wallsStatuses`: the bridge between the record's entry set
and the rules' two booleans), `server/views.nim` (typed per-recipient statuses and buckets). **One
rule, one place**: every wall/door edit and every resize runs the pure rules on a snapshot taken
*before* the write, then the write, then `applyRuleOutcome` (positions and `walls` statuses in one
`NORMAL` transaction, memory after COMMIT); `token.create` computes the placement status before
writing the row, so a new token is born with `stuck` if it lands on a wall. Status sources are owned
by different layers on purpose: the rules never see `GM` entries, the record never derives `walls`
entries. **Tests** (10.1, 10.3): `tests/tprops.nim` (caps, key/value rules, registry enforcement,
set/unset, clone isolation), `tests/ttokens.nim` (radius, buckets, statuses round trip, the FK
cascade), `tests/tmoverules.nim` (per-token radius, shrink/grow/squeeze, the no-crossing rule, the
source independence), `tests/tviews.nim` (bucket and source filtering, one `token` frame per
change), `tools/details.test.mjs` (the five intents' acks and codes, grow push and squeeze,
stuck/clear, prop caps, who reads which bucket, restart equality), plus the leak scenario's
prop/status groups and the `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE` faults. Mutations am-au pin the
bucket filter, the per-bucket cap, the status set/clear, the shrink/grow rules and the push. See
4.4, 5.5, 5.6, 6.1, 8, 10.3.
Owner also decided 2026-11-15 [FIXED (owner decision), #22]: the property-schema registry of 6.1 is
confirmed as the agent specified it — v1 ships the registry **empty with a permissive fallback**
(`pkAny`), so any key is accepted in any bucket and only a registered key is enforced, which matches
8's "the server never interprets props in v1". **Strict mode comes with the FFF seam (post-v1)**,
where the rules module registers every key it uses; flipping the fallback is a one-line change and
no v1 payload, wire shape or test changes. **[amended 2026-11-15, #41: the v1 registry is no longer
empty — `height` and `eye_height` are registered (`number`, `gm`, 5.7); the rest of this entry
stands]**. The rest of the #22 token-details decisions stay owner-delegated.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #23)]: characters and names (M3
slice 8). Schema is migration step 7 (`characters`, 4.4): `character`, `name_reveal`, `encountered`,
plus `entity.character_id` and `entity.reveal_all`. The decisions 4.4 leaves open are recorded there
and the wire rules in 6.1 ("Character and name payload rules"): one id namespace for tokens and
characters, an owner that never dangles (`player.remove` transfers to the GM first), an encountered
entry with no FK that outlives everything, a linked token that stores `''` names, and
`character_id`/`cprops` on the token frame with the ownership rules of 6.1 leak notes 2-3.
**Modules**: `server/characters.nim` (records, the name rule, the reveal set, the encountered
snapshots, their rows), `server/views.nim` (the typed character and encountered views plus the
token-frame additions), `server/tokens.nim` (`characterId`/`revealAll`, the linked-token validation
and `sqlLitId`), `server/text.nim` (`normalizedPlayerName`, `validPlayerName`, `sameName`),
`server/auth.nim` (`allPlayers`, `nameTaken`, `setName`, `renamePlayer`), `server/main.nim`
(`recordEncounters` in every mutation path before the ack, the roster fan-out, `sendHello`/`resync`
for `player.setname`). Also fixed here: `protocol.withN` deep-copies before stamping `n`, because
the stored diff base was being mutated and every state frame was re-sent on every mutation.
**Tests** (10.1, 10.3): `tests/tcharacters.nim` (the name rule, the reveal set, the encounter
snapshot, validation, persistence incl. the GM transfer and the `in-use` count), `tests/tviews.nim`
(character frames, the owner/non-owner split, `cprops`, `character_gone`, the encountered diff),
`tools/characters.test.mjs` (the acceptance group of 13), the leak scenario's ten
character/name/encountered groups and the `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`,
`CHAR_OWNER_PROP` faults. Mutations av-b4 pin the name rule, the encountered snapshot, the
linked-token validation, `in-use`, the GM transfer, the snapshot rename and the `cprops` bucket. See
3.1, 4.1, 4.4, 6.1, 6.3, 6.4, 6.5, 8, 10.3, 13.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #21)]: explored persistence (M3
slice 6). Schema is migration step 5 (`explored`): `explored_chunk` keyed by `(player_id, scene_id,
cx, cy)` with a 512-byte blob, both FKs cascading (4.4). Chunk format and size are fixed at 64x64
cells = 512 B, row-major LSB-first bits, `(cx, cy)` = chunk coordinates; the layout is pinned by
tests and re-read independently by the Node harness. **Write timing**: a mutation writes only the
chunks its refresh dirtied, each encoded from the whole explored set, with `NORMAL` durability; a
move writes position and chunks in one transaction, a GM authoring write adds a second `NORMAL`
chunk transaction under the same lock, both before the ack — the two commits are deliberately not
atomic with each other, and the only loss they can cause after a crash is cells no client was acked
about, which the next refresh re-adds. Measured: 0.015 ms avg / 0.035 ms p99 per chunk write, 0.7 ms
avg / 1-2 ms p99 per move ack (4.3's budget is untouched). **Load**: `explored.restore` fills every
player's set at startup from the chunk rows and logs `explored_loaded players= chunks=`; polygons
stay recomputed (8). **Tests** (10.1, 10.3): `tests/texplored.nim` (format, whole-chunk encoding,
upsert replacement, per-player keying, restore, cost) and `tools/persistence.test.mjs` (fresh-resync
round trip, per-player isolation, SIGTERM and SIGKILL restart equality, wall-removal cells surviving
after the wall returns, chunk rows decoded independently, move-ack timing, and a schema-4 fixture DB
migrated by the real binary). Mutations ag-al pin the bit layout, the chunk coordinate, the restore,
the per-player key, the upsert and the dirty-chunk dedupe. See 4.4, 8, 10.3.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #27-#31)]: five M3 correctness
and cost fixes found by review, all owner-authorized to land on `main` with a regression test each.
(1) **`name.reveal` is per player on disk too** (#27): the persisted snapshot write took only the
subject, so every player who had met the subject got the actual name in their `encountered` row and
saw it only after a restart; the write is now scoped by `player_id` and a reveal to one player
changes exactly one row. `name.reveal_all` keeps all-players scope through the same helper. (2)
**`token.update {character_id}` links a plain token** (#29): the link patch now drops the token's
own two names, so the candidate satisfies `validToken`; names supplied *with* a link stay `invalid`,
unlinking still needs both names (6.1). (3) **One encountered rewrite path** (#30):
`characters.rewriteEncountered` takes the subject's `SubjectNames` plus the reveal set and rewrites
every matching snapshot in SQLite *and* in `app.encountered` from the 8 name rule, so a rename, a
link change and an owner change reach the live list immediately and the DB never disagrees with the
wire. The old DB-only `renameEncountered*`/`revealEncountered*` helpers are gone, which is what let
the two stores drift. (4) **Egress borrows the world** (#28): `views.Context` now holds six pointers
(`contextOf`/`borrow`) instead of owning copies of `scene`, `tokens`, `characters`, `reveals`,
`encountered` and `visions`, `playerView`/`gmView` read a `ptr PlayerVision` instead of
`getOrDefault`, and a view computes each player's visible-id set once per frame so `grey` is a set
test rather than a token scan plus a `PlayerVision` copy per encountered entry. Measured on this
build's types (debug, 6 players, 40 encountered entries, 40 world tokens): context construction
0.227 ms / 4.87 ms at 16384 / 262144 explored cells before, 0.008 us after; one `getOrDefault` of a
`PlayerVision` 28.8 us / 591 us before (gone); a GM egress pass 8.0 ms / 142.8 ms before, 0.79 ms /
0.80 ms after; a player pass 1.45 ms / 25.7 ms before, 0.32 ms after. Behaviour is unchanged and
pinned by `tests/tviews.nim` (identity: a borrow sees a later in-place mutation; six pointers, no
container; both sizes inside the M5 7.5 ms budget) plus the unchanged leak/fault suites. (5) **One
scene read per request** (#31): `tileGate` reads `app.scene` once under `dbLock` and uses that local
for the URL parse, the explored check and the redirect; `checkScene` reads the scene id under the
lock; `scene.set` patches under the lock; the wall/door handlers capture `sceneId` inside their lock
for the log and the effect frame. `tests/ttiles.nim` pins that one record gives one whole answer,
and `tools/tiles.test.mjs` pins the handler shape (source scan) and interleaves 20 `scene.set` +
wall edits with 200 tile fetches (only whole tiles, no crash). **Tests added**:
`tests/tcharacters.nim` (per-player reveal row, one rewrite path, link handover),
`tests/ttokens.nim`-style `patched` unit (in `tcharacters.nim`), `tools/characters.test.mjs` (link
via update end to end), `tools/restart.test.mjs` (three named players + per-player reveals across
SIGTERM/SIGKILL, with a direct `encountered` row assertion and a name oracle; a mid-session rename
for a plain token and a character), `tools/leak.mjs`/`leakcheck.nim` (a second player meets the same
subject; `STALE_NAME` pins each entry's expected name), `tests/tviews.nim` and `tests/ttiles.nim` as
above. Mutations e1-e3 and the repointed b2 pin the reveal scope, the live snapshot update and the
link handover.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #25)]: the M3 finish line.
`scene.set` is built as the 29th and last catalogue intent; its payload rules are in 6.1 ("Scene
payload rules"), with the decision that `hello` also resets the server-side per-connection diff base
(otherwise a resync after `hello` would skip state the client just reset). The two missing accept
groups are built: **restart** = `tools/restart.test.mjs` (full 6.3 resync equality over SIGTERM and
SIGKILL, every CRUD path) and **logs** = `tools/logs.test.mjs` (every key, session cookie and
session hash absent from both runs' log, with a `LEAK_FAULT=keylog` negative control).
`tools/groups.mjs` + `tools/groups.test.mjs` map the nine groups of 13 to their named proving tests,
so the checklist cannot silently go stale. Fixture clean-up (acceptance 5):
`tests/fixtures/scene.json` loses the stale `tileSize: 256`, the scene-wide `tokenRadius` (now a
fixture constant, the server has per-token radius, #4) and its index token ids (`A`/`M1`); the
geometry/corpus fixture keeps its walls, radii and positions. The `blocked` boolean is already gone
from code (`stuck`/`squeezed`, #4). **M3 acceptance checklist (all nine groups, `devbox run test`,
measured on the final tree):**
| # | group (13 M3 Accept) | proving test | status |
|---|---|---|---|
| 1 | leak+fault | `tools/leak.test.mjs` (leak A/B), `tools/fault.test.mjs` (exact class sets incl. `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`) | pass |
| 2 | tiles | `tools/tiles.test.mjs` (oracle sweep through the test nginx, refusal/path matrix, no committed PNG) | pass |
| 3 | probing | `tools/probing.test.mjs` (hostile client over WS, bounded replies) | pass |
| 4 | protocol | `tools/protocol.test.mjs` (proto, unknown type, envelope, flood, rate limit, 64 KB, cap, closing) | pass |
| 5 | auth | `tools/auth.test.mjs` (cookie flags, Origin, devices, key replace, remove, gm-key) | pass |
| 6 | characters and names | `tools/characters.test.mjs` (names, reveals, reassign, in-use, encountered, status source) | pass |
| 7 | restart | `tools/restart.test.mjs` (full state, all CRUD, SIGTERM and SIGKILL) | pass |
| 8 | persistence | `tools/persistence.test.mjs` (chunk round trip, migration, restart, write cost) | pass |
| 9 | logs | `tools/logs.test.mjs` (keys/sessions/hashes across two runs, `keylog` control) | pass |
Out of M3 accept, unchanged: concurrency (M5) and the 127.0.0.1 bind check (M6 deploy) [FIXED, #12].
**Measured 2026-11-15 on the final tree:** `devbox run test` exit 0 (Nim suite all pass; 103 Node
harness tests, 0 fail) and `devbox run mutation` exit 0 (control passes, all 63 mutations fail >= 1
expected test, the new `d3` included; log `results/mutation.log`). See 6.1, 10.3, 10.4, 13.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #41]: the height model. Heights
are metres, decimal; map distances stay px and no map scale is introduced, because see-over compares
heights with heights (research #39 3.3). `height` and `eye_height` are properties, not fields: a
character carries the base value, a plain token must carry its own (`token.create` without one is
refused), a linked token uses the character's value and may carry a temporary on-map override that
never writes the character. Effective token height = token override, else character, else the plain
token's own. Eye height follows the same pattern; if nobody set one by hand anywhere it is 93% of
the effective token height and follows changes live [93% FIXED (owner-delegated)]. A wall is full
height (nobody sees over it) unless the GM gives it one in metres; existing walls are unchanged.
Both keys live in the `gm` bucket, so players see only the outcome, their sight. They are the first
two keys of the property-schema registry (`number`, `gm`), so "the server never interprets props in
v1" becomes "the server interprets only registered keys used by core sight rules". Limits [FIXED
(owner-delegated)]: all heights > 0; `height` <= 100 m; `eye_height` <= 100 m and may exceed
`height`; a wall's height > 0 and <= 100 m. Deferred: the target's height in see-over (#44) and the
height existing tokens and characters get at migration (#49); wall kinds were settled afterwards by
#42 (5.8, v0.22), and what a low wall hides (#44) and thickness (#45) were settled afterwards in 5.9
and 5.10. See 5.7, 6.1, 8, 9.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #42]: the wall model. A wall's
behaviour is **independent switches**, and a named kind is only a **preset** over them: never a
fixed kind enum in the record, and never client-interpreted free flags (the client may send a preset
name; the server expands and validates it). v1 switches are `blocks_sight` and `blocks_movement`
plus the door settings `door`, `open`, `secret`, `locked` and one direction field `sight_dir`
(`both|left|right`); no light or sound axis. Direction is **sight only**: movement is two-way
governed by its switch. A door is a wall with `door` set and independent `open`/`secret`/`locked`
settings, not a separate kind or a state enum, and `door.set` keeps working as "set `open`". The
switches describe the closed wall: an open door blocks neither sight nor movement. A secret door is
always closed and two-way (`open:true` or `sight_dir != both` on it is `invalid`), so it can look
exactly like a solid wall. `secret` and `locked` are GM-only and never observable to a player in any
form; the obligations are byte-identical player frames and refusals for a closed secret door against
a solid wall, and one uniform move nack. v1 presets (one-drag editor defaults and the GM's label)
are `wall` (default), `door`, `secret door`, `locked door`, `terrain` (blocks movement, not sight:
railing, bushes) and `one-way wall`; windows were left to #47, which added the `window` preset
(2026-11-16), and "blocks nothing" is not a preset. The record stores the switches; `kind` survives
on the wire as a derived read-only label (exact preset match, else `custom`), never an input and
never the authority [FIXED (owner-delegated)]. The switches are typed validated fields on the record
and in the payloads, not entries in the never-interpreted `flags`; columns vs one validated object,
and the existing-row migration, are #49's [FIXED (owner-delegated)]. The GM editor has a preset row
plus an **advanced** toggle that exposes the raw switches [FIXED (owner decision)]. Thickness and
height compose through the switches (a wall with `blocks_sight=false` never reaches the sight
predicate) and are decided in 5.10 and 5.9. See 1, 3.1, 5.1, 5.5, 5.8, 6.1, 7.4, 8, 14.
**[Superseded 2026-11-16, Q6/#48: the preset list is `wall`|`door`|`window`|`one_way`, `terrain` is
dropped, and `kind` is derived by shape rather than by exact preset match; the switch model itself
stands.]**
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #44]: low walls. A token is
visible iff **its top clears every sight wall the line from the viewer's eye crosses**, strictly:
the sight line's height at the wall (`h_e + (h_t - h_e)·d_W/d_T`) must exceed the wall's height, and
one failing wall hides it. The target's own height therefore matters (a giant's head over a fence, a
crouched figure hidden next to the wall it would clear from further away); there is no
adjacent-visible exception and no distance rule. The visibility polygon stays **strict**, so the
floor behind a low wall stays unexplored and black, no tile is sent, and a visible token may stand
on a black cell; no per-cell height is tested anywhere. Movement never reads height:
`blocks_movement` alone decides, so a knee-high wall with the switch on stops a walker. Players get
a binary answer and the whole token, with no clipping and no cover percentages (a rules-engine
judgement, still a non-goal). The GM gets a GM-only **who-sees-it** view: per token, which
player(s)/characters see it and its visible fraction (the share of its height above the highest
blocking sight line, 100 % unobstructed), derived from data the GM already receives, never on a
player wire, its panel shape M4's. Knobs delegated: strict comparison with equality hidden,
evaluated at the wall near face (a thick wall: every crossed face, 5.10, #45); every crossed wall
must clear; the hook sits at `visibleTo` as `insideAny or predicate` with heights never entering
`visibilityPolygon`; no "see-over" switch on the wall; the hidden band's cells and tiles are
oracle-*maybe*, a band-hidden token gives no frame, name or churn, and the leak checker's clear-line
oracle gets its own height test. See 5.7, 5.8, 5.9, 7.4.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #46]: secret and locked doors.
(1) **Player door opening is out of v1** [FIXED (owner decision)]: only the GM opens or closes a
door; `door.set` stays G-only and a player sender is `not-allowed` at the role step (6.5) whatever
the door's settings. Player-opened doors, lock refusals addressed to players and player discovery of
secret doors (searching, revealing, finding a way in) are future effort, not v1 and not this map;
the lock is GM authoring state. (2) **A locked door does not open** [FIXED (owner decision)]:
`door.set open:true` on a door with `locked` is `invalid`, exactly like a secret door, and the GM
unlocks first (editor hint "locked: unlock first"); any write that would store `open:true` with
`locked` or `secret` — `wall.add`, `wall.update`, a preset expansion — is `invalid`; closing a
locked door is allowed. Otherwise a locked door is an ordinary closed door. (3) **The equivalence
oracle** [FIXED (owner-delegated)]: `tools/doors.test.mjs` is a new Node accept group (built-ins
only, 10.4) in the shape of `tools/probing.test.mjs` — two servers, fresh state, one identical
script, scenes differing only in one segment (solid wall vs secret door; solid wall vs
secret+locked; closed door vs locked closed door), player frames and per-tile statuses identical
after canonicalisation with **no** normalisation; the positive control is the same script against an
open door, which must differ; the negative control is `LEAK_FAULT=secretgap` (a secret door not
blocking the player-facing computation), which must fail the doors group while a clean build passes
and ships no fault string; `tools/leakcheck.nim`'s banned-key scan grows `secret`, `locked`, `door`,
`blocks_sight`, `blocks_movement`, `sight_dir` (and #49's names) into `WALLDATA`, with a new fault
leaking one door setting key and asserting exactly `WALLDATA`; a GM `door.set` on a secret or locked
door is `invalid` and a player `door.set` is `not-allowed` for every door; timing and size side
channels (T11) stay accepted and untested. See 1, 3.4, 5.8, 6.1, 6.5, 7.4, 10.3.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #45]: thick walls. (1)
**Placement** [FIXED (owner decision)]: `position` is `center` (default), `left` or `right` of the
drawn `a -> b` line, using 5.8's side convention; the line is the room's interior, the body grows
outward, and a flip changes only the body, never `a`/`b`. (2) **Body** [FIXED (owner decision)]: a
rectangle `|ab|` x `thickness` with square ends, offset per `position`; `thickness: 0` is today
exactly and every existing wall migrates to zero and unchanged. It is opaque floor: never in a
player polygon, never newly explored, no tile newly revealed under it. (3) **One shape** [FIXED
(owner decision)]: sight footprint and movement collider are the same exact rectangle, sight as the
4-face quad hoisted per wall edit (#43 measured) and movement as exact circle-vs-rectangle distance
with a centre inside the body counting as overlap; one rectangle-distance primitive serves
`pathClear`, the overlap/`stuck` check, the door push, `pushOutOfWalls` and resize; a
`blocks_sight:false` wall contributes nothing to sight, body included, while its collider keeps the
thickness. (4) **Default thickness** [FIXED (owner decision)]: a new wall starts at the GM's
last-used thickness, 0 in a fresh editor. (5) **See-over** [FIXED (owner decision)]: 5.9's line must
clear **every crossed face** of the body, near and far, strictly; the faces coincide at zero
thickness, so 5.9 stands. (6) **Edits never push** [FIXED (owner decision)]: a thickness change,
flip or move that covers a token leaves it in place and `stuck`; only a door close pushes. (7) **A
viewer inside a sight-blocking body sees nothing** [FIXED (owner decision)]: empty polygon until it
leaves. (8) **No dead end** [FIXED (owner decision)]: v1 walls stay straight rectangles (a cave is a
chain of walls; joints overlap with a small outer notch and no crack), the shape sits behind one
seam, and curved/freeform walls and tracing walls from a map image are future effort. Delegated: px
thickness `0..256`; the `(-dy, dx)` side formula; joints by overlap, no mitre; field names
`thickness` and `position`; the last-used default as editor state. Downstream: thick doors and push
geometry #50, one-way body occlusion #47, wire/schema/migration #49. See 1, 5.1, 5.3, 5.5, 5.7, 5.8,
5.9, 5.10, 6.1, 7.4, 8, 13.
Owner also decided 2026-11-16 [FIXED (owner decision), 2026-11-16, #47]: windows and one-way walls.
(1) **Window** [FIXED (owner decision)]: v1 has no sill and no top — a window is see-through along
its whole drawn length, height unused, drawn as its own wall piece inside a wall (`wall | window |
wall`, like a door), with two forms: fixed (no pass) and opening (door settings; pass when open).
The editor gets a `window` preset. No distance-limited window. (2) **One-way** [FIXED (owner
decision)]: a thick one-way wall's body is opaque floor from **both** sides — no player polygon,
never explored, no tile — and only pass-through past the wall is directional; explored cells and
tiles differ per side with no new mechanism (per-viewer sight), and explored only grows, so a flip
never takes anything back. (3) **Editor** [FIXED (owner decision)]: a one-way wall shows an arrow at
its middle pointing the way the view goes (from the seeing side toward the watched side) plus a flip
that swaps `sight_dir` without moving `a`/`b`; GM-only, never on a player wire. (4) **`left`
wording** [FIXED (owner-delegated)]: `sight_dir:"left"` means a viewer on the left side — the `(-dy,
dx)` normal of `a -> b`, the same side as `position` — cannot see across; a viewer on the right sees
across. The one-way preset defaults to `left`; `sight_dir != "both"` with `blocks_sight:false` is
`invalid`; `left` and `right` both derive `one_way`. (5) **Filter shape** [FIXED (owner-delegated)]:
hoisted viewer-independent faces plus one sign test per one-way wall per viewer inline in the fan,
no per-viewer list copy (the prototype's ~0.15 ms per viewer per frame, times tokens, rejected). (6)
**Windows as a kind** [FIXED (owner-delegated)]: the `window` preset is the opening form and derives
`window`; the fixed form's switches are `terrain`'s and derive `terrain` (the rules are identical),
with no second preset and no new kind — the editor may hint at it. Downstream: the
wire/schema/migration and the preset list are #49; terrain stays #48. Out of scope for v1: windows
with a real sill and top height, and light through windows (future effort with lighting). See 1,
5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3, 14. **[Superseded 2026-11-16, #48: `terrain` is dropped, the
fixed form is a window, and the presets are four.]**
Owner also decided 2026-11-16 [FIXED (owner decision), 2026-11-16, #48]: terrain walls, and the
principle behind the answer. (1) **`terrain` is dropped, everywhere** [FIXED (owner decision)]: no
preset, no derived kind and no stored name. The switch set `blocks_sight:false`,
`blocks_movement:true`, no door, is a **fixed window** and derives `kind:"window"`. A railing, a
bush, a pit edge and a fixed window are one object with one switch set; they differ only in the GM's
`label`. This supersedes #42's and #47's `terrain` preset/kind (and #47's fixed-form wording) and is
itself an application of the new principle. (2) **Principle** [FIXED (owner decision)]: "Do the most
with the fewest things: one object, switches on top, names are only labels" — recorded in §1 and to
be applied to future cards. (3) **Four editor presets** [FIXED (owner decision)]: `wall` (default),
`door`, `window`, `one_way`; `secret` and `locked` are checkboxes on any door, including an opening
window (`door` + `blocks_sight:false`), and keep #46's semantics (GM-only, a locked door refuses to
open until the GM unlocks, never observable to a player). (4) **Preset names and kinds resolved**
[FIXED (owner-delegated)]: `secret_door` and `locked_door` are **removed** as wire preset names (the
wire takes `wall|door|window|one_way`; #49 implements), and the derived kind list is `wall`, `door`,
`window`, `one_way`, else `custom`, derived by shape (window first, then one-way, then door, then
wall) with `secret`/`locked` as flags that never change the label. A secret door also requires both
block switches on and `sight_dir:"both"` (a secret window would show itself); a locked window is
allowed. (5) **Player marker** [FIXED (owner decision); name and shape delegated]: a new wall switch
`player_marker`, on by default for the `window` preset and off for every other preset (GM may toggle
it on any wall); an invisible barrier is simply a window with the marker off. It is the **first and
only wall-derived data on a player wire**, an exact exception to 3.1: once any point of the wall's
visible extent has entered that player's vision polygon, the player receives an anchor (the wall's
drawn midpoint; a thick wall's midpoint is inside its own opaque body, so the gate is the visible
extent, not the midpoint in the polygon) and its own opaque marker id, and **nothing else** — no
type, kind, open/closed, direction, label, thickness, height or wall id; the client draws the window
icon. The marker is per-player memory like explored: persisted, survives disconnect, never lost to
LOS or a door, and retracted only when the GM removes the wall, clears `player_marker`, makes it not
a window, or moves its geometry; a moved wall re-earns its marker only when the new geometry is
seen. (6) **Wall `label`** [FIXED (owner-delegated)]: every wall may carry an optional GM-only
free-text `label`, at most 64 code points (the 6.5 text rule), no behaviour, never on a player wire
and in `BannedAlways` (`WALLDATA`). (7) **No other hint** [FIXED (owner decision)]: players get no
other sign of a barrier; a refused move stays the uniform nack. (8) **Out of scope** [FIXED (owner
decision)]: per-wall material (stone, wood, glass) waits for the lighting effort, alongside sill/top
and light through windows; difficult terrain, movement cost and pit/fall semantics are rules-engine
work, not wall behaviour. Downstream: the preset set, `player_marker`, `label` and the player
`marker` message are inputs to #49 (wire/schema/migration); locked/secret as door checkboxes and
window doors are inputs to #50. See 1, 3.1, 3.4, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3.
Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, #50]: door geometry. (1) **The
door leaf is the wall's own body** [FIXED (owner decision)]: a door is a wall like any other, and
its leaf is the 5.10 body rectangle with the same `thickness` and `position` fields — no separate
leaf inside a deep opening, no clamp to the neighbouring pieces. The jambs are ordinary walls, so
the doorway is the gap between wall pieces. A thick door bulges out of its doorway or leaves a step
behind the jambs, exactly as drawn (authoring, not a rule), and a deep opening between thick jambs
keeps the tunnel/keyhole view accepted in #43. Opening and closing add and remove that body and
nothing else: no swing, no slide, no hinge, no arc, and an open door is absent from sight and
movement as today. (2) **The close push** [FIXED (owner decision)]: each token whose centre is
within `r` of the door's **body** is pushed out of the side its centre is on, by the minimal
distance that ends `>= r` from the body (+ `PushEps`); a centre inside the body takes the side of
`prev` (its position before the most recent move or push), and the left side of `a -> b` when that
is undetermined; if the first side's position is invalid (out of bounds or within `r` of any
blocking body) the other side is tried; if both are invalid the token stays and gets `squeezed`, and
the door still closes. No axial slide, no chain, no retry. Each token is pushed independently,
tokens never block tokens, and scene order only rewrites `prev`. Edits never push (5.10) and height
never enters (5.9). (3) **Delegated and picked** [FIXED (owner-delegated)]: within the body's axial
span the target is the face offset by `r`; past an end it is the offset from the nearest end corner
**keeping the along-axis coordinate**, i.e. today's `foot + n·sqrt(r^2 - e^2)` generalised to the
end face — a radial displacement from the corner was rejected because it also moves the token along
the axis and would break the zero-thickness gate. A centre "inside the body" for the side test means
inside the body or past an end but within the body's normal span, which reduces to today's
centre-on-the-line test at zero thickness. The target and the validity check use the same
rectangle-distance primitive as the collider (other thick bodies included), and `PushEps` = 1e-6 px
is reused. **Zero thickness must return byte-identical values to today's `pushFrom` on the same
inputs**, and the existing push tests are the regression gate, unchanged (10.3). (4) **Settled
consequences** [FIXED (owner decision)]: a locked door and an opening window push exactly like a
plain closed door; a fixed window (`door:false`) never closes, so it never pushes; a secret door
pushes exactly as a solid wall, so #46's equivalence holds for thick doors too; the
independent-per-token, no-token-collision, `prev`-rewriting order rule above is final and not a
later "fix". (5) **Downstream**: #49 needs **no new wire field for doors** — the leaf is the
existing `thickness`/`position` body and the existing switch set, and an open door changes no
geometry, only `open`. See 5.4, 5.5, 5.8, 5.10, 10.3.
Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, #49]: the wall record's wire
format, storage and migration. (1) **Wall height is a typed wall field** [FIXED (owner decision)]:
metres, optional, `> 0` and `<= 100`, absent/`null` = full height; GM-only, carried on the GM
`wall`/`walls` frames and never on a player frame (`WALLDATA`). This resolves the old contradiction
— 5.7's "no dedicated column and no wire field" (narrowed there with a dated tag to tokens and
characters, which have `props` buckets; a wall has none), 6.1's wall frames (which already carried
the other fields) and 5.8's "no behaviour in `flags`". The property registry is unchanged: still
`height` and `eye_height` for tokens and characters. (2) **Migration** [FIXED (owner decision)]:
every existing token and character gets `height: 1.8 m` in `props_gm` (the 93 % eye rule is
unchanged and `eye_height` is not written); every existing wall migrates to today's behaviour
exactly — `thickness 0`, `position center`, `blocks_sight`/`blocks_movement` 1, `sight_dir both`,
`player_marker` 0, `label` NULL, `height` NULL, `secret`/`locked` 0, `kind='door'` -> `door=1` with
the same `open`, `kind='wall'` -> `door=0`. No real user data exists (pre-M4), so correctness is
fixture/history hygiene plus byte-identical behaviour gates (5.8 player frames, #50 zero-thickness
push). (3) **Storage: typed columns with CHECK constraints** [FIXED (owner-delegated)]: one column
per field, CHECKs for the switch invariants, `flags` kept for uninterpreted GM data; chosen by
precedent (interpreted data is always a column, `flags`/`props_*` are for unread data), because
CHECKs can reject an impossible switch set, and because `loadScene` then has no second
parse/validate path. 5.8's "one object" is the domain/wire object; the columns are its storage. (4)
**Migration step 8, forward-only** [FIXED (owner-delegated)]: the `Migration` entry gains a `data`
hook for the height backfill; the `wall` table is rebuilt and the legacy `kind` column is
**dropped** (`kind` is output-only derived); the rebuild is preferred to `ALTER TABLE ... DROP
COLUMN` because it must drop `kind` and add six NOT NULL CHECKed columns atomically and SQLite
refuses to drop a column named in a CHECK. (5) **Wire** [FIXED (owner-delegated)]:
`wall.add`/`wall.update` carry `thickness`, `position`, `height`, `label` and the switches; a preset
XOR raw switches, raw switches patch only what is present, a preset replaces the whole switch set,
and a preset never implies geometry; `wall.update` stays absolute and `door.set` unchanged; add,
update and the M6 UVTT importer share one expand-and-validate path; `walls`/`wall` gain `height` and
keep the derived `kind`. (6) **`proto` 2** [FIXED (owner decision)]: the input `kind` disappears and
an old client's `{"kind":"door"}` would silently create a solid wall, so the version goes up with a
6.2 changelog line; `marker` is the one new server message. (7) **The `marker` message** [FIXED
(owner-delegated)]: `{full:bool, set:[{id,pos}], del:[id]}`, mirroring `encountered`; `pos` is the
drawn midpoint in integer px; `id` is an opaque per-player 12-character string, never the wall id;
emission needs `player_marker` on **and** the wall deriving `window`; the full set goes after
`explored` in the 6.3 player order; the GM never receives marker frames (a player's markers are
their own memory, like explored); storage is `marker_seen` with cascades on player and wall (and
through the scene via the wall). (8) **Label NULL** [FIXED (owner-delegated)]: `label` and `height`
are written as SQL literals (`NULL` when absent) by one helper, because db_connector cannot bind
NULL and neither `''` nor `0` is a legal value, unlike `encountered.actual_name`'s `''`. (9) **UVTT
importer** [FIXED (owner-delegated)]: `thickness 0`, `center`, both blocks on, `sight_dir both`,
`player_marker` false, no label/height; a portal is `door:true, open = not closed`; recorded in
6.1/8, no ticket. (10) **Oracles and tests**: `BannedAlways` gains every wall field name and
`marker` joins the allowed types; the marker oracle's shape is fixed; the migration gets a schema-7
fixture, the mapping assertions and a byte-identical behaviour gate against a freshly built scene
(10.3). See 3.1, 4.4, 5.7, 5.8, 5.9, 5.10, 6.1, 6.2, 6.3, 8, 10.3.
Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, after review of
`docs/ANALYSIS.md`; review in `docs/ANALYSIS-review.md`]: four decisions and one process note. (1)
**Build order**: thick walls (5.10, #45/#50) and wall/token heights with see-over (5.7, 5.9,
#41/#44) stay FIXED design but are **built after the first playable M4 client and a phone
playtest**; the v1-first build is thin walls with the 5.8 switches, doors, secret/locked, windows,
one-way and player markers; the #49 schema lands complete now with `thickness 0`, `position center`,
`height NULL` defaults, so the later build needs no migration. (2) **Split DESIGN.md before
`/to-spec`**: a short current spec, ADRs in `docs/adr/`, and history out to their own file; tracking
issue "Design doc split: current spec + ADRs + history". (3) **Minimum zoom 0.5** for players in v1,
which bounds tile requests (about 1.3k at 0.5, about 5k at 0.25); a per-player explored-masked
overview image is possible later, not v1. (4) **Walls-sourced statuses accepted**: a player seeing
`stuck`/`squeezed` source `walls` is an accepted, documented effect, not a leak to fix; leak note 6
is closed because a refused move already reveals the same fact. Technical, owner-delegated: "close a
slow client when lag exceeds a bound" is superseded by **stop feeding on Pong lag and full resync on
recovery**; only nginx proxy timeouts close a dead peer (4.3). See 1, 4.3, 5.5, 5.10, 6.1, 6.5, 7.4,
13.
<!-- END old section 14 -->
## E. Owner decisions after the split
Owner also decided 2026-11-20 [FIXED (owner-delegated, 2026-11-20, #32)]: a readable intent that
fails in handling is answered `ack {ok:false, code:"internal"}`, with no detail, and the transaction
helpers roll back on every unwind path (`Defect` included) so the shared connection stays usable. If
the handler's own ack was already enqueued, it stands and no second ack is appended. `internal` is
additive in proto 2. A `Defect` is bounded damage, not a restart policy. See current 4.2, 6.2, 6.5.
Owner also decided 2026-11-20 [FIXED (owner-delegated, 2026-11-20, #35)]: wall `flags` and scene
`extra` are opaque but capped uniformly, on the same measure as a prop value: serialized JSON at
most 8 KB, at most 64 keys per object (per object, not summed) and nesting depth at most 8 (a
top-level object is depth 1). At a cap is accepted; over is `invalid` and applies nothing. The caps
live next to the property caps and are read from one shared validator; token `flags`, props and
stored values above a cap are out of scope. See current 6.1.
Owner also decided 2026-11-21 [FIXED (owner-delegated, 2026-11-21, #78)]: a new token's `flags`
stays the §8 default `'{}'`, so the GM token panel's Vision checkbox starts unchecked and its vision
radius starts blank (scene default), on create and on edit. No wire default changed; the panel
follows the existing `'{}'` reading rather than choosing "vision on for a player-controlled token".
See current 8.
Owner also decided 2026-11-21 [FIXED (owner-delegated, 2026-11-21, #79; recorded here in the
decision log that continues the old §C)]: **the map import CLI moves from M6 to M4.** It is the
designed CLI of 11.1, not a throwaway seeder: `fff-vtt import --image=<png|webp> [--scene=1]
[--tile-size=<px>] [--state-dir=<path>]` writes `<state>/tiles/<scene>/v<art_version>/<x>_<y>.png`
(origin at the world origin) and updates the one scene row's `w`, `h`, `tile_size` and `art_version`.
A re-import for art that already exists grows `art_version`; old versions stay until M6 cleanup. It
takes the state-dir lock (a live server refuses it, exit 3) because the server reads the scene at
startup, so the operator stops the server, imports and restarts. `--tile-size` defaults to the
scene's tile size and must be a positive multiple of the explored cell (64 px fallback). Decoding
uses ImageMagick from the root devbox with disk-backed pixel-cache limits, so a 16384 px source is
memory-sane; no Nim/npm image dependency is added and the FIXED stack (2) is unchanged. This note
supersedes #63's "map import CLI (M6)" Out-of-Scope line for the CLI only; NixOS deployment, the
production vhost and tile-version cleanup stay M6. See current 3.3, 6.1, 11.1, 13 and TESTING 3.3 /
10.3.
Owner also decided 2026-11-21 [FIXED (owner decision), #85]: **map images are capped at Full HD.**
The long side is at most 1920 px and the short side at most 1080 px, either orientation; the import
shrinks a larger source before tiling (Lanczos, alpha kept, proportions preserved, no upscaling) and
records the shrunk `w,h`; `scene.set` still cannot set them, so the importer is the only writer. An
existing DB scene above the cap is not rewritten: the server logs `map_above_cap` at startup and
`serve` prints the re-import advice. Rationale: a 16384 px map meant ~30k tiles at 32 px, minutes per
import and ~1 GB VRAM for a zoomed-out GM; an LOD pyramid was rejected as the more complex cure. The
16384 px / 262144-cell bench and test rows become labelled server stress references, not the product
target; the phone gate re-runs on the Full HD scene. See current 3.3, 5.3, 8, 11.1, 13 and ADR-0023.
## D. Superseded statements removed from the current spec
Each entry quotes the superseded statement (excerpt) and names the surviving rule.
1. **Wall presets and derived kind (v0.22 #42).** Old: "v1 presets ... are `wall`
(default), `door`, `secret door`, `locked door`, `terrain` (blocks movement, not
sight: railing, bushes) and `one-way wall`"; and "`kind` survives on the wire as a
derived read-only label (exact preset match, else `custom`)". Superseded by #48:
four presets, `secret`/`locked` as door checkboxes, `kind` derived by shape
(`wall`, `door`, `window`, `one_way`, `custom`). Surviving rule: current §5.8.
2. **Fixed window as `terrain` (v0.26 #47).** Old: "the fixed form's switches are
`terrain`'s and derive `terrain` (the rules are identical), with no second preset
and no new kind". Superseded by #48: the fixed form derives `window`, `terrain` is
dropped everywhere. Surviving rule: current §5.8.
3. **Closing a slow client on lag (pre-v0.30).** Old: "close a slow client when lag
exceeds a bound". Superseded 2026-11-17 (`docs/ANALYSIS-review.md` §6.4): stop
feeding a lagging client, full resync on recovery; lag never closes a connection.
Surviving rule: current §4.3.
4. **Status name `blocked` (Q14, 2026-11-08).** Old: "a GM edit that lands on a token
gives it status `blocked`"; door-close failure "stuck only if neither side is
valid". Superseded by #4 (2026-11-10): `stuck`/`squeezed`; a door close pushes.
Surviving rules: current §5.4, §5.5.
5. **Retired wire names (#11).** Old: "`invite.*`, `gmClearBlocked` and `blocked` are
retired"; server `door` folded into `wall`, `presence` into `roster`, `pong` into
the ping `ack`. The retirement stands; the decommissioned names must not reappear.
Surviving rule: current §6, §6.1.
6. **Prototype gaps (v0.20 and earlier).** Old: "`Tok.gmOnly` is loaded from
`scene.json` but never consulted in `sync()`"; "every message carries the global
`gseq`". Both were prototype facts and are fixed in the built server: `gm_only` is
enforced in the view builder (`GMONLY_TOKEN`, 10.3) and players get a
per-connection counter (`n`, 6.4). Surviving rules: current §3.1, §6.4.
7. **"The server never interprets props in v1".** Narrowed by #41: the server reads
only the registered keys the core sight rules use (`height`, `eye_height`).
Surviving rule: current §8, §9.
8. **Wall height as "no dedicated column and no wire field" (v0.21 #41).** Old: the
sentence applied to all heights. Narrowed 2026-11-17 (#49) to tokens and
characters, which have `props` buckets; a wall has no buckets, so its height is a
typed wall field. Surviving rules: current §5.7, §8.
9. **The Q14-undefined pin test (pre-M2).** Old §5.4: "Current pin: ... 'door closed
on a token: Q14 undecided, DESIGN 5.4 vs 12 H2 conflict'". Replaced in M2 by the
move-rule tests of §5.5. Surviving rule: current §5.4, §5.5.
10. **Door-open-clears-stuck, former §5.5 item (b).** Closed by the Keep rule
(2026-11-08): opening a door does not free a token that another blocking wall
overlaps. Surviving rule: current §5.5.
11. **Q6's `wall`|`door` only.** Superseded by #42 (switches + presets), then #48
(four presets). Surviving rule: current §1, §5.8.
12. **Connection cap 8.** Superseded by #15: 4 connections per player, 16 total.
Surviving rule: current §4.3.
13. **M3 catalogue count "14 server messages, 15 with `closing`".** Later counts in
the same change log ("29 intents, 15 server messages") are superseded by #49's
`proto` 2 count: 29 intents, 16 server messages. Surviving rule: current §6.
14. **Slice-build narratives.** The old §10.3/§13/§14 recorded which M3 slice built
which intent, test or schema step ("Built by slice 9 (#24) ...", the M3 acceptance
checklist table, mutation letters a-b4). Those are build provenance, not rules;
the tests themselves and their accept groups remain binding (current §10, §13).
15. **`ANALYSIS` D1-D4 as "not built yet".** The v0.30 note said the split was "not
built yet". Done 2026-11-17 under #51; D2 (the split) is unchanged. D1, D3 and D4 are
ADR-0012/0013/0014 and current §1, §7.4 and §5.5.
16. **The 5.7 conflict note (v0.30).** Old: "section 1's non-goals (windows/transparent
walls, one-way walls) and Q6's `wall`|`door` only were contradicted by the wall-model work.
That is 5.8 [#42], which superseded both; this block fixed heights and units only, and what a
low wall hides (#44) and thickness (#45) were settled afterwards in 5.9 and 5.10." Historical
provenance only; the surviving rules are current §1, §5.7, §5.8, §5.9, §5.10.
17. **All marker deletes in the derived transaction (2026-11-19, #60).** Old §8: "marker
inserts/deletes are derived player memory and ride the mutation's `NORMAL` transaction (the
same one as the explored chunks)". Narrowed after the #60 crash review: a cause-change delete
rides the wall row's `FULL` transaction (inserts stay `NORMAL`), because a crash between the
two would restore the marker with the new geometry and reveal a position the player never saw.
Surviving rules: current §5.8, §8.
18. **"A 16384 px map is the target" (v0.30 and earlier).** Old: the M4 gate and the bench/tests
named a 16384 px map (512x512 cells, 262144 files at 32 px) as the product target. Superseded
2026-11-21 (#85): map images are capped at Full HD, the import shrinks larger sources, and the
product maximum is 2040 explored cells. The 16384 px rows survive only as labelled server stress
references. Surviving rules: current §3.3, §5.3, §8, §11.1, §13 and ADR-0023.
+2076 -581
View File
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
# Frozen
**Status: frozen 2026-11-22 at `fda8362`** (the M4 code tree, #64-#89). No further work is planned
in this repository; it is an archive. The freeze commit that adds this file is tagged
`frozen-2026-11-22`. A new project starts elsewhere with a fresh plan built around playability and
may borrow from this tree.
## Why
The owner ran a real playtest and found the project not usable as a play tool. The build put
fog/leak safety first and playability second: gated tiles, 403s, leakcheck, mutation testing and
evidence over the experience of running a table. Examples of the gap:
- tokens are placed by typing X/Y coordinates, not by pointing at the map;
- new tokens are blind by default, so a GM must remember to switch vision on;
- GM UI gaps tracked in #81: token↔character link, prop editor, scene settings, player rename;
- the test flow is heavy for what the change was (mutation runs, evidence maps, e2e stacks).
## State at freeze
- M4 built; #64-#89 closed. Server: `proto` 2, 29 intents, one scene, thin walls with the 5.8
switches, doors/secret/locked, windows, one-way, per-player vision + explored, lock-free tile
gate. Client: Vite + TS + PixiJS v8.
- **#77** (real-phone playtest) open and **not passed**; its acceptance never happened.
- **#63**, **#62** open.
- **#81** (GM UI gaps) `needs-triage`.
- M5 (robustness) and M6 (NixOS deployment) were not built.
## Worth borrowing
Paths are relative to the repo root; the modules below are self-contained and were read at freeze.
| What | Path | What it does |
| --- | --- | --- |
| Wall/sight geometry + vision | `server/geometry.nim` | Visibility polygon cast from a point against wall segments, one-way `sightDir`, radial-wall handling; pure Nim, stdlib only. |
| Vision and explored state | `server/vision.nim` | Per-player union of token visibility polygons, radius from token or scene, open doors don't block; monotonic explored cells. |
| Explored persistence | `server/explored.nim` | Chunked 64x64-cell bitmaps, one row per (player, scene, chunk), writes only dirty chunks. |
| Move rules + status | `server/moverules.nim` | Swept-circle move check, token-on-wall escape rule, step cap, `stuck/squeezed` status from the `walls` source. |
| Record↔geometry adapters | `server/worldmap.nim` | One place that turns stored wall/token records into the pure inputs of the two modules above. |
| Full HD import | `server/importer.nim` | Offline slice of a source image into tiles, shrink to 1920x1080 cap, `art_version` bump. ADR-0023 (`docs/adr/0023-full-hd-map-cap.md`). |
| LAN TLS/h2 serve | `tools/serve.sh`, `tools/serve.mjs`, `tools/lanserve.mjs` | One command: build client + server, mint a long-lived TLS cert for the LAN SAN, nginx on the LAN address in front of the loopback server, persistent state, print URL/GM key/trust steps. |
| Test nginx vhost | `tools/nginx.mjs`, `tools/tlsdev.mjs` | Generated vhost for `/`, `/join`, `/tiles/`, internal `/_tiles/`, `/ws`, TLS + HTTP/2, healthz. |
| Parallel test harness | `tools/test.sh`, `tools/jobs.sh` | Half-cores-capped job count, one process per test file, wall-clock-sensitive tests serialised; `client/e2e/run.sh` reuses the same jobs helper. |
| Group/evidence map | `tools/groups.mjs`, `tools/evidence.mjs` | Named acceptance groups → the exact test body, checked statically and against the reporter output (no skips). |
| Mutation check | `tools/mutation.sh` | One mutation at a time on a temp copy, every mutation must fail a named test. |
| Leak checker | `tools/leakcheck.nim`, `tools/leak.mjs` | Replays a player transcript and recomputes the view from GM truth (independent oracles for polygons and explored). |
| Single egress | `server/views.nim` | Typed `GmView`/`PlayerView` built before frames; raw records have no serializer. |
| Protocol shell | `server/protocol.nim` | Frame catalogue, envelope rules, intent rate limiter, malformed-frame window. |
| Tile client loading | `client/src/tiles.ts` | Concurrency cap, centre-out wanted list, no duplicate fetch, 403 = permanent denied, 404/5xx = bounded backoff, drop off-screen queued tiles. |
| Camera / tile window | `client/src/viewport.ts` | Pure camera, pan, anchored zoom, tile-window maths; no Pixi or DOM. |
| Wall editor rules | `client/src/wallEditor.ts` | Presets and derived kinds, validation, snapping, one-way arrow, undo; pure. |
| State slices + reducer | `client/src/slices/`, `client/src/reducer.ts` | Per-feature reducers fed by wire frames, unit-tested without a browser. |
## Lessons for the next project
1. Start from one real evening of play. Build the smallest thing that runs a table, play it, then
grow it. Play early, and repeatedly.
2. Fog safety is a constraint, not the centre. Keep it provable, but budget most of the effort on
what the GM and players do at the table.
3. Keep tests light and sized to the change: one focused suite that fails for the right reason
beats a gate stack nobody wants to run.
4. Full HD maps are enough. The cap (ADR-0023) cost nothing and removed a whole class of problems.
5. The phone UI must be simple: direct manipulation over forms and typed coordinates.
+5 -2
View File
@@ -1,6 +1,8 @@
# Handoff: start of M3 session
Written 2026-11-08 at main 809f219. Paste the "Prompt" section into a new agent session.
**Historical.** Written 2026-11-08 at main 809f219; M3 is complete. Kept as a record.
Section numbers still resolve (the 2026-11-17 split kept them); the old §14 decision log is now
`docs/DESIGN-history.md` §C.
## Prompt
@@ -14,7 +16,8 @@ State:
- M1 (geometry port) and M2 (move rules, blocked/stuck policy, door push,
scanline cells, bench, mutation a–o) DONE. See git log, results/.
- All DESIGN.md §14 questions answered or deferred (owner decisions 2026-11-08,
tagged FIXED). docs/DESIGN.md = source of truth; §5.5 = move rules.
tagged FIXED; the log is now docs/DESIGN-history.md §C). docs/DESIGN.md = source of truth; §5.5 =
move rules.
- Research notes: docs/research/. Prototypes (prototype-*/) read-only.
### Your job
+56
View File
@@ -0,0 +1,56 @@
# Handoff: end of M4
**FROZEN 2026-11-22, see [FROZEN.md](FROZEN.md).** This handoff is historical: the project was
frozen after the owner's playtest; #77 never passed and no successor milestone started here.
**Current at 2026-11-21**, M4 built (#76); its automatable gates are green and acceptance pends the
real-phone playtest #77. M1-M4 are built; M5 is next. This is the close-out note for the M4 run:
what exists, what is proven, what is deliberately still open.
## State
- **Server:** `proto` 2, 29 intents / 16 server messages, one scene, thin walls with the 5.8
switches, doors/secret/locked, windows, one-way, player markers, characters/names, per-player
explored + vision, lock-free tile gate and session cache (#64, #65). `devbox run test` is the
server gate.
- **Client:** `/client` (Vite + TS + PixiJS v8, plain DOM overlay). Sign-in, name prompt, badge,
reconnect + full resync, tiles/grid/pan/zoom, three-state fog + markers, tokens/labels/statuses,
both lists, drag with prediction/rollback, GM wall editor, roster/keys/tokens panel, characters/
reveals/who-sees-it. Gates: `devbox run client-test`, `devbox run e2e`.
- **M4 automatable accept gates:** `devbox run e2e` proves join, fog pixels, drag/rollback, reconnect
and the independent player-traffic audit; `results/m4-fog-bench.md` records 50 tokens on a Full HD
map (1920x1080, the capped max scene; server move path recorded, headless SwiftShader cadence
recorded as a floor, not a phone number). Map images are capped at Full HD and the import shrinks
larger ones (#85, ADR-0023). Thickness/height controls are **not** in M4 (ADR-0012); walls round 2
is #37/#45/#50/#41/#44.
- **Archived:** the three `prototype-*` trees now live under `docs/archive/prototypes/` (frozen,
not built). One maintained client (`/client`), one server (`/server`).
## Still open
- **#77** - the human real-phone playtest: Note 10 + laptop, Full HD (1920x1080, max scene) map,
50 tokens, fog active, LAN TLS/h2. Its comment is the checklist with commands, numbers to record
and pass thresholds; any image works because the import shrinks it to the cap (#85). M4 is
accepted only when it passes; `#63` and `#62` close only after #77.
- **Playtest tooling (#82, closed with this note):** `?perf=1` in-app fps/frame/JS/token/zoom
overlay (off by default), `fff-vtt import` on a fresh/empty state dir, `devbox run serve --
--image=<file>`, `devbox run seed -- --url=...` for the 50 tokens, and the GM token form's X/Y
default to the viewport centre. #84 fixed the seam that made those `--` arguments invisible:
devbox 0.17.2 scripts must end with `"$@"` in `devbox.json`, `serve` now fails on an unknown or
unusable flag, and `devbox run serve -- --dry-run` prints the parsed options. On NixOS the serve
output prints `security.pki.certificateFiles`, not the Debian `update-ca-certificates` steps.
- **M5** - concurrency, bounded outbox/coalescing, lag tracking, SIGTERM, metrics, nginx dead-peer
timeout, stats outside the lock. `#34` heartbeat is M5.
- **Deferred:** `db_connector` -> thin sqlite3 binding (build item 13); per-token polygon cache and
incremental wall-edit refresh (items 3/4) are **not** needed by the M4 measurement.
## Notes for the next session
- `AGENTS.md` points at the issue tracker and the domain docs. Use the Gitea issues, not the docs,
for work state.
- Gates are sequential and real: `devbox run test`, `devbox run client-test`, `devbox run e2e`,
`devbox run mutation`, `devbox run bench`, and (for fog numbers) `devbox run fogbench`.
- `results/*.log` are evidence and committed; `results/node-test.log`, `results/e2e.log`,
`results/client-test.log` are gitignored scratch and regenerated.
- Browser e2e: `client/e2e/` owns `playwright-core`; `tools/` stays built-ins-only (TESTING §10.4).
The e2e stack is the real server through the TLS/HTTP2 test nginx, never a fixture.
+747
View File
@@ -0,0 +1,747 @@
# FFF_vtt testing
Status: how [`docs/DESIGN.md`](DESIGN.md) is proven, 2026-11-17. This file holds the test, acceptance,
oracle, fault-class, gate and bench detail; DESIGN holds the rules. Both are current: a rule is stated
once in DESIGN, its proof once here.
Organised by DESIGN section number: every block names the rule it proves. Section numbers mirror the
spec's, so `DESIGN §x.y` and `TESTING §x.y` are the same subject, and the old `DESIGN 10.x` citations in
code and test comments still resolve (DESIGN §10 is now a pointer to §10 here; the mapping is
10.1 → §10.1, 10.2 → §10.2, 10.3 → §10.3, 10.4 → §10.4).
Tags are the spec's: **[MEASURED]** a number or behaviour from a prototype run (cited by path),
**[INFERRED]** a reading or reasoning, **[PROPOSED]** a choice the owner may overturn, **[FIXED]** an
owner decision. A moved block keeps its tag, its tickets and its evidence path.
Two principles carried from the prototype, and they apply to everything below: the checker must be
independent of the code under test where possible, and every check needs a negative control that proves
it can fail.
Evidence roots (relative to repo root):
- `docs/archive/prototypes/pixi-perf/` (client perf; README holds all tables)
- `docs/archive/prototypes/server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
`results/spike/investigation.md`)
- `docs/archive/prototypes/tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run)
How to run: `devbox run test` = Nim in-process tests first, then the Node black-box harnesses;
`devbox run mutation` = the mutation suite. Run everything from the repo root through `devbox run`.
Both gates run concurrently at `FFF_TEST_JOBS` (default: half the cores, capped at 8; `FFF_TEST_JOBS=1`
serialises). Concurrency does not change a test or an assertion; it is safe because the harnesses
were already isolated (each Node test file is its own process with its own state dir, free ports,
nginx and server). What makes it fast: the real server (clean, `leakfault`, `dispfault`) and the leak
checker are built once per source+flags and shared across the parallel files (`lib.mjs`
`cachedNimBuild`, locked and published by rename), each Nim test file compiles into a worktree-local
`run/nimcache/test-*`, and `fault.test.mjs`'s 22 independent cases are sharded across processes
(`FFF_TEST_SHARDS`/`FFF_TEST_SHARD`). Two Node files whose assertions are wall-clock gates
(`persistence.test.mjs`'s move-ack budget, `tiles.test.mjs`'s lock-free burst) run alone before the
fan-out, so those numbers are never measured under the suite's own load. `devbox run e2e` uses
`FFF_E2E_JOBS` (default: the same, capped at 4) and keeps its timing-gate files (`map`, `fog`,
`fogbench`, `perf`) in a serial first phase for the same reason. The host froze under uncapped load
before, hence the half-cores default.
Harness state dirs are created under `TMPDIR`; the gates point it at `/dev/shm` when it exists
(`FFF_TEST_NO_TMPFS=1` opts out). On a disk-backed `/tmp`, the fan-out's SQLite commits
(`synchronous=FULL`) plus transcripts and tile fixtures could stall a first commit long enough for a
harness ack to look lost; tmpfs keeps the same SQLite and SIGKILL-restart semantics without the
fsync storm. The harness ack/handshake patience is 15 s (`lib.mjs` `HARNESS_TIMEOUT_MS`) so a busy
host is not mistaken for a missing answer; the wall-clock gate files keep their own asserted budgets.
**Do not export devbox's `LD_LIBRARY_PATH` into host tools or stale binaries.** The devbox store is
built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built `libsqlite3` loaded by a
2.42 loader fails at load time (or loads a mismatched libc). Rebuild after a `devbox.lock` change
(`devbox run test`/`bench` do it on first use); never reuse a binary built before the change.
---
## 3. Security model
### 3.1 What each role receives
**Rule:** DESIGN §3.1.
- `gm_only` is enforced in the view builder, before any frame is built; fault class `GMONLY_TOKEN`
(§10.3).
### 3.3 Tiles
**Rule:** DESIGN §3.3.
- Direct hits on `/_tiles/` give 404 [MEASURED: `docs/archive/prototypes/server-vision/results/smoke.log`, README
"Phase 2a"].
- A tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak
test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`].
- The residual 32 px edge leak's sizing evidence: `docs/archive/prototypes/tile-leak/README.md` (desktop numbers;
phone run 2026-11-08). M4's tile-size gates are in §13 below.
- `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect
unchanged; nginx adds nothing of its own there (the test vhost records this, §11.1).
- Slice 9 (#24) pins the full status split of DESIGN §3.3: `404` also for another scene or a stale art
version, `403` also for a missing or unknown session (one response with "unexplored"), and
`Cache-Control: private`. The proving group is §10.3 Tiles (`tools/tiles.test.mjs`).
- Map import (#79) writes the tree this gate parses: `tools/import.test.mjs` runs the real binary's
`fff-vtt import`, checks the exact `<x>_<y>.png` set and per-tile geometry, then starts the real
server and test nginx and proves a player with an explored overlapping cell gets `200` (and an
unexplored tile `403`, another art version `404`). A re-import grows `art_version` and the
restarted server serves the `v<new>` tree. The CLI also creates and migrates a fresh/empty state
dir through the server's startup path (#82), so an import works before the first serve. Every
refused import (bad/absent image, unsupported or multi-frame format, scene ≠ 1, `tile_size % cell
≠ 0`, malformed DB, or a running server holding the lock) exits non-zero and leaves no tile tree;
`serve --image` runs the import before starting the stack. This is §10.3 Tiles evidence.
### 3.4 Threat list
**Rule:** DESIGN §3.4 (threat, mitigation and the accepted residuals). The `Test` column moved here.
| # | Proving test |
|---|---|
| T1 | leak test + fault classes |
| T2 | fault `walls` [MEASURED caught]; door-equivalence test (T17, §10.3) [MEASURED caught: fault `secretgap`]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3) [MEASURED caught: `tools/fault.test.mjs`, Walls r1 #60]; scenario coverage of the rewritten leak world (Walls r1 #61) [MEASURED: `tools/leak.test.mjs`] |
| T3 | faults `other-*` [MEASURED caught] |
| T4 | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) |
| T5 | documented, not testable as a leak; M4 timing gates (§13) |
| T6 | config test (grep logs for secret) [new] |
| T7 | new test |
| T8 | M2 in-process probing test (§5.5, §13); WS version in M3 (§10.3): count wall/door facts recoverable from nacks beyond LOS |
| T9 | leak test (e) |
| T10 | new tests (§10.3 slow client, protocol) |
| T11 | not tested |
| T12 | smoke |
| T13 | new test |
| T14 | leak test |
| T15 | deploy check |
| T16 | fault classes `ACTUAL_NAME`, `CHAR_LIST` (§10.3) |
| T17 | differential door-equivalence test `tools/doors.test.mjs` (§10.3, #46), positive control on an open door [MEASURED], fault `secretgap` [MEASURED caught: `SECRETGAP`], door-key scan in `tools/leakcheck.nim` -> `WALLDATA` (Walls r1 #56) |
---
## 4. Server
### 4.1 State model
**Rule:** DESIGN §4.1.
- Monsters/NPCs have no vision [MEASURED design: `vision_ms move-monster` 0.000 ms; the bench row is in
§5.3].
### 4.2 Mutation pipeline
**Rule:** DESIGN §4.2.
- The pipeline order under one global lock is proven correct by 3 x 60 s concurrency runs (§4.3).
### 4.3 Locking and threading
**Rule:** DESIGN §4.3 (one global lock, the p99 trigger, slow-client handling, connection limits).
- [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223 intents/s): no crash, no
reorder, no loss, consistent final views (`results/concurrency-final{1,2,3}.log`); intent->ack avg
1.40 ms, p99 4.58 ms, worst 20.31 ms.
- A table of <= ~10 clients is 2 orders of magnitude below the single-core limit (server total per
mutation avg 0.70 ms [MEASURED]). This is why the global lock is kept; the revisit trigger is a
measured p99 > 50 ms in production (§11.3).
- Proposed: add a test that fails if mummy's `WebSocket` fields change (the pin makes this stable, the
test makes it explicit) [PROPOSED].
- SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and
every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted for
v1; moving persist out of the lock would break ack-after-commit and order.
- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (host stall or node harness pause;
not proven either way, `results/spike/investigation.md`). Production logging (DESIGN §11.3) must make
a recurrence diagnosable (SLOW lines with breakdown).
### 4.4 Persistence
**Rule:** DESIGN §4.4.
- Commit cost [MEASURED] avg 0.60 -> 0.17 ms, server total avg 1.16 -> 0.74 ms; tail unchanged (~20 ms
worst) (`results/spike/investigation.md`).
- Process kill (SIGKILL) loses nothing [MEASURED: `results/final-restart.log`, SIGTERM and SIGKILL, same
DB, identical state].
- Chunked explored, measured cost of one mutation-scale write (BEGIN; 512 B upsert; COMMIT): avg
0.015 ms, p99 0.035 ms (DESIGN §4.3's accepted commit tail is ~20 ms), and a real move's ack stays at
avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, `tools/persistence.test.mjs`).
Sizes: the seeded 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); the largest Full HD
scene (60x34 cells) is one 512 B chunk (#85).
- The chunk layout is pinned by `tests/texplored.nim` (exact byte/bit positions) and re-read
independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes or bit order.
- Seeding the scene in migration step 3 keeps it identical on every start and lets the migration test
assert it (§10.3).
---
## 5. Vision and explored
### 5.1 Algorithm
**Rule:** DESIGN §5.1.
- The vertex-in-cell case was added after a bug (polygon wholly inside one cell) [MEASURED bug log,
prototype `NOTES.md`; covered by `tests/tgeometry.nim`, suite "cells", test "tiny polygon inside one
cell"].
### 5.2 Edge cases handled
**Rule:** DESIGN §5.2 (the list of handled cases is the rule).
- Port baseline [MEASURED, `tests/tgeometry.nim`]: M1 port baseline (history) 33 test blocks / 98
checks, none dropped; current count 92 `[OK]` test cases in `results/nimble-test.log` (M2,
2026-11-08).
- Angle-sort bug [MEASURED bug, prototype `NOTES.md` "Post-phase-3"]: circle angles must use the same
(-pi, pi] range as wall angles (`atan2(sin,cos)`), otherwise the polygon is a bow-tie (position
dependent). Regression test: `tests/tgeometry.nim`, suite "visibility", test "wall endpoints behind
the viewer: fan stays angularly ordered".
- Vision circle is an inscribed 64-gon: error <= ~0.12% of R [MEASURED, prototype `NOTES.md`].
### 5.3 Performance
**Rule:** DESIGN §5.3 (targets and accepted decisions). Measurements and the bench methodology
[MEASURED; single laptop, release build, loopback, power-save CPU]: `results/bench.log`,
`results/concurrency-final1-server.log`.
| item | avg | worst |
|---|---|---|
| 1 visibility polygon (prototype scene, 60 walls) | 0.038 ms | 0.18 ms |
| 1 polygon + `cellsTouched` | 0.451 ms | 0.98 ms |
| 6 polygons + `cellsTouched` | 2.95 ms | 3.73 ms |
| server vision recompute per player move (incl. cells + diff) | 1.18 ms | 4.55 ms |
| door toggle (2 players) | 0.20 ms | 0.30 ms |
| monster move | ~0 | 0.024 ms |
- `cellsTouched` is ~12x the polygon itself and dominates [MEASURED]. M2 replaced per-cell polygon
tests with scanline rasterization over the explored grid, differential-tested against the ported
implementation [PROPOSED; built in M2].
- The prototype scene the table measures has 60 walls and 8 tokens, so its numbers say nothing about
big maps; the 5k bench scenes below are the answer.
- **Product maximum [FIXED (owner decision), 2026-11-21, #85]:** map images are capped at Full HD,
so the largest scene is 1920x1080 (60x34 cells at cell 32). The fog measurement and the M4 phone
gate use that maximum; numbers below at 16384 px / 262144 cells are labelled **server stress**,
not the product target.
- Bench scenes (`tools/scenegen.nim`): the sparse **stress** layout `genScene(16384, 5000, 1)`:
0.058 ms avg [MEASURED, `results/bench.log`]. The dense layout `genScene(4096, 5000, 1)` is also a
stress reference (1.409 ms avg, ~207 walls in the vision bbox) [MEASURED]; the uniform spatial
grid is revisited if real maps approach that density.
- **Thickness cost** [#43, DESIGN §5.10]: a thick body is a quad, and the fan costs about 10x on a dense
scene (13.2 ms vs 1.25 ms baseline on the 5k dense layout; 0.26 ms per polygon, 3.15x, on the 5k
sparse one). The owner accepted that and re-baselined the per-move budget [FIXED (owner decision),
#43]; polygon optimisation is deferred.
- Timings are single machine loopback power-save CPU; no real network, no client render [MEASURED
caveat]. A real-network run (laptop over the intended HTTPS path, phone on LAN) is an M7 item.
- Load/perf regression gate: `bench` + concurrency numbers (this section and §4.3) compared with
the committed baselines; the 2x threshold and its [PROPOSED] status are in DESIGN §5.3.
- **In-process egress gate** (#28, `tests/tviews.nim`): wall-clock gates are load-sensitive, so every
asserted number is the *fastest* of 20 timed passes after a warm-up (min-of-N), never a mean: a pass
the OS descheduled is not the minimum, while a regression raises every pass. Stated budgets are
10 us for one `Context` build and 2 ms for one egress pass (M5's 7.5 ms is a whole-mutation p99, not
a per-pass mean; the #28 shape measured 0.79 ms GM / 0.32 ms player on the reference build, 0.5-1.7 ms
in the debug suite depending on CPU clocks). The gate allows a documented 2x around each budget
(20 us, 4 ms) for a saturated box. The load-insensitive explored-size invariant
`smallMs <= gmMs*3 + 0.5` (synthetic 16384 vs 262144 cells; the Full HD product maximum is 2040
cells, #85) is kept on minima. Absolute averages are
*recorded*, not asserted, by `devbox run bench` (`results/bench.log`: GM egress pass 0.24 ms,
player 0.08 ms, release build).
### 5.4 Known limitations
**Rule:** DESIGN §5.4.
- Token exactly on a wall cannot move off it [MEASURED limit, `tests/tgeometry.nim` test "KNOWN
LIMITATION: token exactly on a wall cannot move off it"; also in the `server/geometry.nim` header].
- Explored and tile checks in the leak test recompute with the server's own `cellsTouched`:
self-consistency only (caveat in §10.2). The independent oracle exists now (§10.2, §10.3).
### 5.5 Move rules and statuses
**Rule:** DESIGN §5.5.
- Implemented as a pure in-process module with unit tests; the WebSocket layer only maps its result to
`ack` (DESIGN §6.1). The WebSocket probing test is M3.
- The push rule's arithmetic: a zero-thickness door must return identical values on the same inputs;
the unchanged existing tests are the regression gate (§10.3 Door push with thickness).
- Oracle comparisons use 0.5 px, as the leak checker (DESIGN §3.4 T14).
- **Regression baseline** [FIXED, accepted default]: "results equal old implementation" =
`visibilityPolygon` and `cellsTouched` on the prototype leak transcripts plus
`tests/fixtures/scene.json`. `moveBlocked` is excluded: its results change on purpose.
### 5.7 Heights
**Rule:** DESIGN §5.7.
- A wall's `height` is in leakcheck's `BannedAlways` (`WALLDATA`, §10.3) because no player frame ever
carries it.
### 5.8 Wall switches, presets, doors, windows and one-way
**Rule:** DESIGN §5.8.
- The oracle that pins the secret/locked door obligation is the differential door-equivalence test
(§10.3, DESIGN §3.4 T17, #46).
- A wall `label` is in the leak checker's `BannedAlways` key scan (§10.3), so a player frame carrying
`label` is `WALLDATA`.
- One-way sight (built, #58): the two sides, the direction flip, monotone explored/tiles and the
restart are proven by `tools/oneway.test.mjs`; the checker's own side test and the `ONEWAY` fault
are in §10.3.
### 5.9 Low walls: see-over
**Rule:** DESIGN §5.9 (the predicate, the strict polygon and the GM-only fraction).
- Oracles [FIXED (owner-delegated), #44]. `tools/leakcheck.nim`'s `clearLine` gets its own height test
(walls carry their height; a target's top is compared independently of the server's code, never by
calling vision.nim). Cells in a low wall's hidden band are **maybe** for the independent
explored/tile oracle: a tile there may be allowed or refused, both correct, but a band cell may never
be **sure** (a `200` on a band cell is legitimate, a withheld proof cell never). A token hidden only
by the band gives no `token` frame, no name and no encountered entry, and no churn: no alternating
frames as a position crosses the line. The assertions land with the build tickets (/to-spec), not
here (DESIGN §13 build order: heights are built after the M4 playtest).
### 5.10 Thick walls: the body, sight and movement
**Rule:** DESIGN §5.10.
- Sight input cost [FIXED (owner-delegated), #45; #43 measured]: 4-face quad 0.263 ms hoisted vs 0.943
ms per query on 5k sparse, 12.721 vs 13.229 ms dense; the 3-face near+caps silhouette is
observer-dependent, cannot be hoisted, and costs 0.699 ms per query sparse (8.4x thin), so the
hoisted quad is the cheaper exact model.
- Joints [FIXED (owner-delegated), #45]: #43 measured that joints need no thickness: zero-width corners
show no crack either.
- Oracles build the body rectangle from `a`, `b`, `thickness` and `position` with their own code, never
by calling `vision.nim` or the move rules, and use it for both the sight footprint and the distance
test (§10.2, §10.3).
---
## 6. Protocol
### 6.3 Reconnect and resync
**Rule:** DESIGN §6.3.
- The client reducer resets everything on `hello` (reconnect-reset bug fixed in the prototype; test in
`client/src/state.test.ts`, 4/4 pass) [MEASURED].
- Assets (tiles) are kept across reconnect because explored only grows [MEASURED prototype behaviour].
- The turn-over point for a snapshot size is measured, not guessed: revisit if a measured full resync
exceeds ~100 KB (DESIGN §6.3).
### 6.4 Deltas and size
**Rule:** DESIGN §6.4.
- The per-connection `known` table gives correct enter/leave [MEASURED, leak test (c)].
- The stored diff base is the frame **before** the per-connection `n` is stamped: `protocol.withN`
deep-copies, so stamping cannot make the next comparison see a different frame and re-send unchanged
state (this was a live bug until slice 8; the leak checker now sees a genuinely sparse stream).
- Bytes [MEASURED, `results/concurrency-final1-server.log`]: monster move 145 B to a seeing player,
244 B to GM; player move: mover 3359-3653 B (worst 4.9 KB, dominated by the full `vision` polygon +
`explored` diff), GM 145 B; door toggle 45 B (prototype `door` message; the M3 `wall` upsert is a
little larger).
### 6.5 Refusals, errors and connection outcomes
**Rule:** DESIGN §6.5.
- Consequence for tests: every close assertion is "the last message is `closing` with this reason and
code, then the close event reports 1005". The proving group is §10.3 Protocol.
### 6.6 HTTP surface in M3
**Rule:** DESIGN §6.6.
- `GET /tiles/...`: the full status split (DESIGN §3.3) is pinned by the tiles group (§3.3, §10.3
Tiles).
---
## 7. Client
### 7.3 Fog rendering
**Rule:** DESIGN §7.3.
- Browser rendering of fog/drag/reconnect is unverified in the prototype (no browser in the build env).
M4 adds a headless-browser pixel check (§10.3 Browser e2e), which is the acceptance criterion for the
explored/vision layers.
---
## 10. Testing strategy
**Rule:** DESIGN §10 (the pointer section that keeps 10.1-10.4 as references to this section).
Every rule in DESIGN maps to a block above; this section is the test plan itself: what carries over
from the prototype, what was missing, what the M3 build added, and the tools it uses.
### 10.1 Carry over (port, keep as acceptance gates)
| Test | From | Notes |
|---|---|---|
| Geometry unit tests (M1 port baseline: 33 test blocks / 98 checks, none dropped; current count in `results/nimble-test.log`) | `tests/tgeometry.nim`, `results/nimble-test.log` | Port with `geometry.nim`. |
| Geometry mutation check | `tools/mutation.sh` (a: no +-RayEps rays, b/c: upper/lower segment end exclusive) | Control passes, each mutation fails >= 1 test [MEASURED 1, 2, 2]. Port. |
| Leak test | `tools/leak.mjs`, `leakcheck.nim`, `leaktest.sh` | Subject A and B, fresh DB, ~240 steps; asserts (a)-(e) in README. Independent LOS oracle for token visibility (added after the bow-tie bug). Walls r1 #61 rewrote the scenario into one world (a marked window, a one-way wall, a secret and a locked door, marked walls on both sides of the sight test) and `tools/leak.test.mjs` asserts that coverage. |
| Negative control / fault injection | `tools/faulttest.sh`, `-d:leakfault` build | 8 faults, exact failure-class set each, clean build passes, `LEAK_FAULT` string asserted absent from clean binary [MEASURED 8/8]. Port and extend. |
| Restart | `tools/restart.mjs` | SIGTERM + SIGKILL, identical player keys/positions/doors/vision/explored/hello+state. |
| Concurrency | `tools/concurrency.mjs` | 60 s, 3 clients, gseq monotonic, every intent acked, quiesced views == fresh connection. **M5 port [FIXED, #15]:** 6 walkers on one GM socket (~200/s) exceeds the 30/s per-connection rate (DESIGN §6.4); spread walkers across connections (4 per player, 16 total; DESIGN §4.3). |
| Client reducer tests | `client/test/*.test.ts` (Vitest) | Pure frame/ack -> state; `hello` resets every slice. No Pixi or DOM import at the seam. |
| Smoke | `tools/smoke.mjs` | auth/cookie/tile/steal/garbage. |
| Isolation harness | `tools/withserver.sh` | own DB/ports (`run/test/`), never touch a live session. |
### 10.2 Known test gaps to fix while porting
- Shared-endpoint test passes with the horizontal arm removed [MEASURED, `HANDOFF.md`]: port a test
that fails if either arm is missing, verified by a new mutation (d) in the mutation script.
- Explored/tile checks use the server's own `cellsTouched` (self-consistency). New **independent
explored oracle**: brute-force per-cell sampling with the clear-LOS segment test over cell
centres/corners; compare as superset/subset with a stated tolerance [PROPOSED]. Differential test
old `cellsTouched` vs scanline version (M2).
- Leak checker oracle initially only checked "nothing extra", not "everything visible shows"; the
completeness check is kept (assert (b)).
### 10.3 New
- **Fault classes.** Each class has an injected fault (`-d:leakfault`, `LEAK_FAULT=<name>`) and an
exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`,
`GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`,
`OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`,
`CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`, `ONEWAY` (#58), `MARKER_EARLY`,
`MARKER_EXTRA`, `MARKER_OFF` (#60). Walls r1 built: `secretgap`
(#56), asserted as exactly `SECRETGAP` by `tools/doors.test.mjs` (the differential group, not the
transcript checker); `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (#60), each asserted as exactly
its own class by `tools/fault.test.mjs` (the leak transcript checker, with the scenario's unseen
marked window and marked solid wall as the negative controls).
**The scenario itself (Walls r1 #61)** is one coherent world, not appended fragments: a room with
an opening door, a far wall holding a solid stretch, a secret door and a locked door with a token
behind each, a one-way screen, a marked window the subject sees, the same window's switch cleared
and restored (retraction and re-earn), a marked solid wall and a marked window the subject never
sees. `tools/leak.test.mjs` asserts that coverage from the GM's wall frames and the subject's
marker frames, so a rewrite that drops an element fails on its own, not only inside a fault. The
world also holds a wall lying along one of the subject's vision rays with a token beyond it on the
same line: a zero-width wall hides exactly that line, and `HIDDEN_TOKEN` is the token-level
assertion for it (#26) — the class checks a token's own centre and the viewer -> token segment
against the walls, not sampled polygon points, because the `GEOMETRY` class only tests *missing*
vision and cannot see an over-approximation. All
pre-existing classes still fire under the rewrite, each as exactly its own class (all 21 entries
of the `FAULTS` table of `tools/fault.test.mjs`, 22 tests with the clean-build gate).
`tools/leakcheck.nim`
refuses the `gm` bucket, the `owner` bucket on a
non-controller and any `source` on a player status entry. Two consequences: the `hidden` and
`gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the client
holding it with no correcting message, indistinguishable from a withheld `token_gone`; both
invariants are broken), and the tile gate is HTTP-plane, so `tools/tiles.test.mjs` proves it (10.3
Tiles), not the WS transcript checker. `GLOBAL_COUNTER` is structurally impossible (per-connection
`n`).
- **Characters and names (#14)**: tests for reveal per player and reveal to all; owner sees own actual
name; a character owner change leaves token controllers unchanged; encountered entries survive token
removal and a `gm_only` flip (greyed) and are removed only by the GM; `gm_only` tokens never enter an
encountered list. Group: `tools/characters.test.mjs`, including "a status source is not shown to a
non-GM" (the controller included). Fault classes: `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`,
`CHAR_OWNER_PROP`.
- **Tiles (#24)**: `tools/tiles.test.mjs` is the group's leak check (d) and the smoke tile-steal
checks, through the real binary and a test nginx (`tools/nginx.mjs`, nginx from devbox; config
generated per run in the state dir). An **independent explored oracle** (born in 10.2) recomputes
visibility per cell from the GM's walls and the token's vision radius with its own clear-segment
maths (inscribed 64-gon radius - 0.5 px for "sure", radius + 0.5 px and proper crossings for
"maybe"): a `200` must be oracle-maybe (no invented disclosure) and oracle-sure must be `200` (no
withheld tile). The 32x32-tile sweep is 1024 requests; slice 9's scene allows 283, all 283
oracle-sure, 0 maybe-refused. Also checked: a player with no sight state gets `403`; another player
gets `403` on a tile its neighbour sees; direct `/_tiles/` is `404` (the file exists) for every
identity; malformed/canonical/out-of-range/stale-version/scene paths are `404` (with and without a
session, including the GM); traversal and encoded shapes never reach a file; the direct-from-Nim
answer carries `X-Accel-Redirect: /_tiles/1/v1/<x>_<y>.png`, `Cache-Control: private` and an empty
body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under the state dir at test
time; the test asserts the repo tracks no `.png` at all.
- **Map import CLI (#79)**: `tools/import.test.mjs` is the black-box harness for the offline
`fff-vtt import` subcommand (DESIGN 11.1, 3.3). It writes a real fixture PNG at test time, runs
the binary, and asserts the exact gate tree (`tiles/1/v1/<x>_<y>.png`, row-major, 4x3 at 64 px),
each tile's 64x64 geometry, the scene row via `hello.scene` (w, h, tile_size, art_version), and a
player with an explored overlapping cell getting `200` through the real nginx+server stack while
an unexplored tile gets `403` and a stale version `404`. A second import must grow `art_version`
and a restarted server must serve the `v<new>` tree (the persisted explored grid still allows it).
Negative cases each exit non-zero and leave no tile tree: missing/unsupported/multi-frame image,
`--scene` other than 1, `tile_size % cell != 0`, absent state dir, state dir without `state.db`,
and a running server holding the state-dir lock (exit 3). `tools/groups.mjs` registers the first
title as Tiles evidence.
- **Probing test (T8)**: M2, in-process against the move-rules module (DESIGN §5.5): arbitrary far
moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount
(step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2).
- **Door equivalence (#46, T17)** — built: Walls r1 #56, `tools/doors.test.mjs`. It is the accept
group for the "a player cannot tell a secret or locked door from a wall" obligation DESIGN §5.8
states. Node harness, built-ins only (10.4): two servers, fresh state, two scenes identical except
one segment, one identical scripted sequence. Pairs: (i) solid `wall` vs a closed `door` with
`secret`; (ii) solid wall vs a closed door with `secret` and `locked`; (iii) closed `door` vs a
closed `door` with `locked` (since #48 there are no `secret_door`/`locked_door` presets: the switches
are the same, only the name changed). Script, run against both servers in lockstep: player tokens
with vision near and around the segment; player moves along, into and across it (accepted, collision
nacks, over-cap nacks); the GM adds the segment over a player token (`stuck`); the GM edits and
toggles unrelated walls and doors elsewhere and moves tokens; a resync/reconnect; a GM `door.set
open` on the secret/locked segment, refused `invalid` and GM-side only. **Assertion:** each player's
complete received frame sequence — `hello`, `roster`, `vision`, `explored` (full and delta), `token`
(statuses included), `encountered`, and every `ack`/nack with its `code` and `pos` — is identical
between the two runs after JSON canonicalisation (keys sorted, no numeric reformatting).
**Normalisation allowed:** the one run-local value a fresh two-server world forces is an opaque
token id (the server CSPRNG, DESIGN 8); the harness maps each run's ids to `TOK<n>` in creation order
and sorts an encountered list by that id before comparison. Nothing else is normalised: `n`, player
ids, positions, statuses, polygons, explored cells and tile statuses compare byte for byte.
**Tiles:** the same per-player tile sweep in both runs, through the test nginx
(`tools/nginx.mjs`, §11.1), must give the same status and body per tile. **Closing push:** the
script closes an ordinary door over a token and pins the resulting position (320,350), the
zero-thickness push gate unchanged. **Positive control:** the same script against a scene whose
segment is an open door must produce *different* transcripts, otherwise the harness cannot fail
(this file's first principles). **Negative control:** a `-d:leakfault` build with
`LEAK_FAULT=secretgap` makes a secret door not block sight in the player-facing computation; the
pair then fails as exactly `SECRETGAP`, the clean build passes, and the shipped binary carries no
fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:**
`door.set` on a secret or locked door is `invalid` for the GM; a player `door.set` is `not-allowed`
for every door (DESIGN §6.5), so the player side has one code and no oracle. **Not covered:** timing
and size side channels (T11), accepted and unchanged.
- **Door push with thickness (#50).** In-process pins in `tests/tmoverules.nim` (DESIGN §5.5).
**Zero-thickness regression gate:** the existing push tests run unchanged and keep their exact
positions (including "past the end", where the along-axis coordinate does not move). **Thick cases:**
face push by `r` with the along-axis coordinate kept; past an end, push to `r` around the nearest end
corner; inside the body, out of the `prev` side (left with no history); first side invalid (another
blocking body or out of bounds) falls back to the other; both invalid leaves the token and `squeezed`
while the door closes; `position` `left`/`right` moves the body and the target by the thickness.
**Equivalence:** the #46 two-server test gains thick pairs (thick secret door vs thick solid wall;
thick locked door vs thick plain door), byte-identical. Also pinned: a fixed window and an open door
never push, and no wall edit pushes. **Mutations:** push from the drawn line; push ignoring the normal
span; ambiguous side ignoring `prev`; validity check on the door only — each fails at least one test.
- **One-way direction (#47; built: Walls r1 #58)**: `tools/leakcheck.nim` and the independent
explored/tile oracle apply
**their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of
`a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall stays in
the oracle's wall list only for a viewer on its blind side (the side `sight_dir` names), and a
wall that is `blocks_sight:false` is dropped for everyone. Assertions: a token on the blind side
gets no polygon point, explored cell or tile beyond the wall, and a token across it gives no
`token` frame, no name and no encountered entry; a viewer on the seeing side does see across (the
positive control, so the oracle can fail). `tools/oneway.test.mjs` runs the two sides, the
`sight_dir` flip with fixed endpoints, the monotone explored/tile set across flips and a restart,
and the per-tile sweep with the same own side test.
Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-*maybe* (a `200`
there is legitimate, but never *sure*), and anything clearly behind the blind wall is
oracle-refused (a withheld proof cell still fails). Fault class `ONEWAY` (built) — the
player-facing computation drops `sight_dir`, so the one-way wall becomes two-way — with its
injected fault (`LEAK_FAULT=oneWay`) and exact-class assertion, shaped like the existing classes.
- **Player marker (#48; shape fixed by #49; emission/storage/oracle built #59; retraction and the
exact fault classes #60).** `leakcheck.nim` allows the `marker` type and, with its own code (never
calling `vision.nim`), checks that a marker exists for a player exactly when some point of the
wall's visible extent has entered that player's polygon **and** the wall is `player_marker:true`
and derives `window`, and that the frame carries only the opaque marker id and the anchor: anything
else is `WALLDATA`/`PROTOCOL`. Positive control: a marked window the subject sees yields exactly
one marker at its drawn midpoint; a wall behind a sight blocker, `player_marker:false`, or a solid
wall with the switch on yields none. The oracle's expected set accumulates like explored memory,
so walking away, a door or lost sight never makes a sent marker wrong; a wall removal, a cleared
switch, a lost `window` or a geometry move retract it (the oracle drops the entry when the GM's
wall frame shows the cause changed, mirroring the server). An extra marker at a candidate's anchor
before its extent was seen is `MARKER_EARLY`; an extra marker with no candidate wall is
`MARKER_EXTRA`; an expected marker never sent is `MARKER_OFF`. The oracle keys a sent marker id by
the GM-truth wall it belongs to (resolved by anchor), never by the anchor alone, so two candidate
walls that share a midpoint remain two obligations. Marker ids are stable across refreshes: a
`set` that re-mints a wall's marker while its old id is still live is `PROTOCOL` — the four marker
classes describe the emission gate, while id stability is a frame invariant (5.8: minted once,
fresh only after a retraction). Faults `MARKER_EARLY`,
`MARKER_EXTRA`, `MARKER_OFF` (`markerEarly`/`markerExtra`/`markerOff`) are built and asserted as
exactly their own class by `tools/fault.test.mjs`, with the scenario's far unseen marked window
and marked solid wall as the negative controls. The WS group `tools/markers.test.mjs` proves the
four retraction causes (del only), a fresh id on re-earn, no re-send of an untouched marker, no
`set` and `del` for one id in a frame, no explored write from a pure retraction, and durability
of the deletes across a restart. A `LEAK_FAULT=markerCrash` hook quits in a `-d:leakfault` build
between the wall commit and the derived write; after a restart the changed wall's marker is gone
for all four causes while the untouched window's marker is restored (the positive control). The
leak scenario (#61) also drives one retraction and one re-earn end to end, so the transcript
checker's own memory drop is exercised inside the world.
- **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every
wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`,
`player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of them in a player
frame is `WALLDATA`; `marker` is an allowed server type with its own oracle (built #59);
positive control: a wall
`height` injected into a player `token` frame fails with exactly `WALLDATA`. **Migration:** a
schema-7 fixture (both wall kinds, an open door, non-empty `flags`, tokens and a character with props)
migrates under the real binary, every decoded row equals the DESIGN §4.4 mapping, `props_gm.height`
is `1.8` on every token and character and `eye_height` untouched; a second run is a no-op and a
failing step rolls back. **Behaviour:** one scene built through `wall.add` with today's switch set and
one migrated schema-7 scene holding the same walls produce byte-identical player frames, refusals and
per-tile statuses for the same script; the #50 zero-thickness push tests pass unchanged against
migrated rows. Fixture churn: `tests/tdb.nim` `LatestVersion` 8, `tools/persistence.test.mjs`
schema-8 assertions and the schema-7 fixture, and every hand-built `wall` row gains the columns.
- **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove
player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10
FIXED), Origin mismatch rejected, cookie flags present.
- **Protocol tests** (#18, `tools/protocol.test.mjs`): proto missing/non-integer (HTTP 400) and mismatch
(`closing` 4003, no `hello`); unknown intent type (`unknown-type`) with unknown fields ignored;
exactly one `ack` per `reqId` (reqId 0 and 2^31-1 included); `hello` first with `n = 1` and a
per-connection `n` thereafter; `error malformed` for unreadable frames; the malformed flood (nine
tolerated, the tenth closes 1008); the intent bucket (burst then `rate-limited`, connection stays
open, a refused intent applies nothing, `error rate-limited` for an unreadable frame on an empty
bucket); the 64 KB inbound boundary (exactly 64 KB is a message, 64 KB + 1 drops the TCP connection
with no close frame); unmasked and bad-opcode frames; the server Ping and the Pong answer to a client
Ping; the connection cap (503 + `Retry-After: 5`); and every server-initiated close as `closing` then
1005.
- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart extended to
wall CRUD and entity props. `tests/texplored.nim` pins the chunk layout, whole-chunk encoding, upsert
replacement, per-player keying, restore and write cost; `tools/persistence.test.mjs` covers the
fresh-resync round trip, per-player isolation, SIGTERM/SIGKILL equality, a wall removal's revealed
cells after the wall returns, independently decoded chunk rows, move-ack timing, and a fixture DB
migrated by the real binary.
- **Restart (#25)**: `tools/restart.test.mjs` is the "restart" accept group. It builds one world that
exercises every CRUD path (walls and an open door, plain/monster/player/linked tokens, a resize and a
GM status, props in three buckets with a `prop.unset`, a character with props, a per-player reveal
and a token `reveal_all`, a sighting in the encountered list, players and a name) and compares the
complete DESIGN §6.3 resync of a fresh GM connection and a fresh player connection before and after
the restart: hello scene block, roster, walls, characters, tokens, encountered, vision and the full
explored RLE, all normalized (only the per-connection `n` is dropped) and deep-equal. Both SIGTERM
and SIGKILL are checked, because every ack follows its COMMIT (DESIGN §4.2).
- **Logs (#25)**: `tools/logs.test.mjs` is the "logs" accept group. It records every GM key (the CLI
key, a `--new` rotation, an old key after rotation), every player key (`key.create`, `key.show`,
`key.replace`), every session cookie from `/join` (several devices) and its SHA-256 hash, plus a
wrong key, a refused tile, a proto mismatch and a malformed frame, across two server runs on the same
state dir, then greps the whole `server.log` for every value: none may appear. The second test is the
negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a raw key to stdout past
`eventlog`, and the same grep must find it (so a log that was never captured cannot pass).
- **Slow client** (Q13, DESIGN §4.3): a client that stops reading; outbox stays under cap, no further
state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the
dead `/ws` socket within its configured timeout.
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype
already drives devbox chromium, `docs/archive/prototypes/pixi-perf/bench.mjs`; SwiftShader is fine for correctness,
not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area
map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect
restores view; drag moves token and rollback works. The harness is `client/e2e/` (the client package
owns `playwright-core`, outside `tools/`; TESTING 10.4 keeps the black-box harnesses npm-free) and the
gate is `devbox run e2e`, which builds the real client and is separate from `devbox run test` (§11.1).
T4's slice of it (`client/e2e/shell.test.mjs`, `mismatch.test.mjs`): no session shows only the
sign-in door and no canvas; a wrong and an unknown key give the same `401` and the same
"Key not recognised." text; GM and player join, get the canvas and the `hello`/`roster` HUD; a
server `closing{proto-mismatch}` shows reload and stops; a revoked key returns the page to sign-in
with no reconnection.
- **TLS/HTTP2 vhost (#66)**: `tools/vhost.test.mjs` (built-ins, `node:http2`) is the independent
client for the vhost itself: the generated certificate is self-signed and names loopback, ALPN
selects `h2`, `/` serves the client `dist` with index `no-cache`, `/assets/` with a year-immutable
cache and no SPA fallback for a missing hash, a client route falls back to `index.html`, and direct
`/_tiles/` is still 404. `client/e2e/h2.test.mjs` proves the same from real Chromium against the
real Vite build (`client/e2e/run.sh` runs `npm run build` first):
`performance.getEntriesByType('navigation')[0].nextHopProtocol` is `h2` over TLS. The vhost group
keeps a local stub dist because `devbox run test` must not depend on the client's npm install.
- **Independent traffic audit in e2e**: `client/e2e/audit.test.mjs` records every WS frame and every
HTTP response the *player browser* receives and judges them with its own catalogue and banned-key
list (never importing `tools/leakcheck.nim`): only the 13 player frame types; no wall geometry or
GM-only column at any depth; vision polygons only for the player's own tokens; no other player's
id or out-of-sight token id; explored cells only inside a historical own-vision bbox and never near
the other player; tiles only on `/tiles/`, only 200/403, every 200 covering an explored cell, and
`/_tiles/` unreachable (direct fetch 404). It runs in `devbox run e2e` beside the fog, drag and
reconnect files. A negative control runs the same rules against a `-d:leakfault` build with
`LEAK_FAULT=otherVision`, so the rule that rejects a foreign vision polygon is proven able to fail.
### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from
`docs/archive/prototypes/server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`,
`lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required
for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the
server cannot share its protocol bugs; zero deps; already measured. The harness lives in
`tools/withserver.mjs`; the test nginx is `tools/nginx.mjs`.
- Harness tooling: built-ins only, no npm deps. Global `WebSocket` with `{headers}` for Cookie/Origin;
`node:net` for raw and malformed frames (oversize, bad opcode/rsv, unmasked, flood); `node:test` as
runner. Node 26 header behaviour [MEASURED, 2026-11-14, #16, node v26.11.1]: `{headers}` still puts
`Cookie` and `Origin` on the wire, and without `{headers}` no `Origin` is sent; pinned by
`tools/wsheaders.test.mjs` so a Node upgrade that drops the option fails loudly.
- Root `devbox.json` pins `nodejs` 26 and the `nginx` used only by the test harness (DESIGN §11.1); no
global tooling. M4 (#66) adds `chromium` (the browser e2e) and `openssl` (generating the test
certificate); the e2e's only npm dependency, `playwright-core`, is pinned by
`client/package-lock.json` and lives with the client, outside `tools/`, so this built-ins-only rule
keeps holding.
- `devbox run test` = Nim tests first, then Node harnesses. `devbox run client-test` = the client's
Vitest seam (pure reducer, protocol client, envelope); `devbox run e2e` = the built client through
the real server and vhost; `devbox run fogbench` = the 50-token Full HD (1920x1080, the max scene)
server measurement (`results/m4-fog-bench.log`). The finish gate (#76) runs all of them plus
`mutation` and `bench`.
Both suites fan out files at `FFF_TEST_JOBS` (see "How to run"); no file is serialised for
correctness, only the wall-clock gate files are run alone so their budgets stay meaningful.
- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`;
`tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the
acceptance checklist cannot silently go stale. Harnesses that are not an accept group (`smoke`,
`walls`, `tokens`, `details`, `scene`, `wsheaders`) run in the same pass.
- In-process tests stay Nim (every `tests/*.nim` file, compiled and run like `nimble test`; the
runner only bounds how many files compile at once).
- Browser e2e details and the client-side extension rules (append-only reducer slices and render
modules): `client/README.md`.
---
## 11. Ops
### 11.1 Deployment on NixOS
**Rule:** DESIGN §11.1 (module, config keys, vhost shape).
- Test nginx [FIXED (owner-delegated), #24]: `tools/nginx.mjs` starts the devbox `nginx` package on a
free loopback port in front of the harness server, with a config generated per run under the
server's state dir (ports and state paths never committed). It mirrors the vhost shape DESIGN §11.1
describes: `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and
`location /_tiles/ { internal; alias <state>/tiles/; }`. Tile bytes are 32 px fixture PNGs from
`tools/tilefixture.mjs`, written under `<state>/tiles/`; none is committed.
- TLS + HTTP/2 + client dist (#66, spec #63 decision 6): the listener is TLS-only with `http2 on`,
because browsers negotiate h2 only over TLS and the session cookie is `Secure`. `tools/tlsdev.mjs`
generates the self-signed certificate per run (SAN `localhost`/`127.0.0.1`, never committed) and
appends it to the process's default CA list, so fetch/WebSocket/`node:http2` verify it with
verification on. `distDir` (default `<state>/dist`) is served at `/` with the production cache
split; the tile/doors/oneway harnesses keep their `publicOrigin` at the vhost, so they now run
through the same TLS origin the browser uses.
### 11.2 Backups
**Rule:** DESIGN §11.2.
- Restore drill documented and tested once (M6): restore into a temp dir, start server, run the
restart-equivalence assertions (§10.3 Restart).
### 11.3 Logging and metrics
**Rule:** DESIGN §11.3.
- The `SLOW` line (total > `SLOW_MS`, default 50) with breakdown `lock_wait / vision / sqlite / send /
other` and intent type is what diagnosed the SQLite COMMIT tail [MEASURED,
`results/spike/investigation.md`].
- The prototype's instrumentation appends every sample to unbounded arrays and sorts them inside
`finish()` under the global lock; **do not port** [MEASURED/HANDOFF].
---
## 13. Build status and milestones
**Rule:** DESIGN §13 (milestones and their accept criteria).
- **M3 accept result.** Measured 2026-11-20: `devbox run test` exit 0 (Nim suite all pass; 149 Node
harness tests) and `devbox run mutation` exit 0 (control passes, all 78 mutations fail at least one
expected test). The nine groups map to their proving tests in `tools/groups.mjs`. Evidence is
executable, not a title substring (#36): `tools/groups.test.mjs` pins each test's exact title, a
minimum assertion count and the calls its body must keep, and the last step of `devbox run test`
(`tools/evidence.mjs`) parses the reporter output in `results/node-test.log` and fails unless every
registered test ran and passed. The restart group takes its baseline from the as-built state on the
first server instance, before any restart, not from a state that has already been through one
(#36).
- **M4 automatable gates result.** Measured 2026-11-21 at the build commit (#76): `devbox run test`
exit 0 (Nim suite all pass, 419 OK checks; 159 Node harness tests with the group evidence step),
`devbox run client-test` 164, `devbox run e2e` 27/27 (join, fog pixel probes, drag + rollback,
reconnect, the independent traffic audit and the 50-token measurement), `devbox run mutation`
control + 80 mutations each failing at least its expected test, `devbox run bench` PASS and
`devbox run fogbench` PASS. Evidence: `results/nimble-test.log`, `results/mutation.log`,
`results/bench.log`, `results/m4-fog-bench.md` (+ `.log`); the e2e/client logs are regenerated
per run and not committed. The phone gate's scene is the Full HD maximum (1920x1080) [FIXED
(owner decision), 2026-11-21, #85]; the fog-update test's 4096 px / 128x128-cell scene is a
synthetic correctness/stress fixture above the cap, not the product target. The manual Note 10 +
laptop 60 fps run is **#77** and is the only open M4 accept item: M4 is accepted after it passes,
not before. Mutation housekeeping found
here: `c1`/`c2` still patched the pre-#65 tile-gate expression and had silently become `sed`
no-ops; both now patch `cy * sc.cols + cx in explored` and fail the tile gate group again.
- **M4 gate harness.** (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU
and network throttle) against the real server path (nginx HTTP/2 + caching); (b) one manual run on
the owner's 5-year-old Android phone. Gate (a)'s fill is the fastest of 4 fresh page loads after a
warm-up (min-of-N, §5.3), asserted against 2x the 1 s DESIGN budget (the documented saturated-host
tolerance); every sample is printed on every run. Measured 2026-11-21: 439 ms fastest on the dev
host (628, 778, 444, 439), 1.3-1.9 s fastest under a saturated 16-core host, same binary, and a
planted 50 ms/tile decode delay raised the minimum to 4264 ms so the gate fails. The
`data-tiles=ready` wait is a completed-pass signal: a stored transient tile `error` is terminal
until the next window or reconnect, so one host hiccup cannot hold every e2e wait at `loading`
(proven by aborting one tile: the wait timed out before the fix, passed after). The 2026-11-08 prototype phone run is evidence, not the gate
(HTTP/1.1, no-store, zoom 0.5 only, first cold load up to 3.3 s).
- **M4/M5 proving harnesses.** Headless e2e (§10.3 Browser e2e), the independent traffic audit
(§10.3) and the slow-client test (§10.3) are the gates' harnesses; the pass criteria stay in DESIGN
§13.
- **M6 proof.** `/_tiles/` 404 and the log grep (§10.3 Logs), the WS upgrade (§10.3 Protocol), and the
restore drill (§11.2).
@@ -0,0 +1,30 @@
# The server alone decides what each player sees
Every client is untrusted, including the GM's browser. The server computes per-player vision and
explored area, builds a typed per-recipient view, and sends only the diff; client-side fog is
cosmetic. All bytes to a player leave through one egress module that accepts a recipient and that
recipient's view, and raw world state has no code path into it. We chose this over trusting the
client to hide fog or over sending world state and filtering in the browser, because a modified
client must learn nothing it is not entitled to.
## Status
accepted
## Alternatives
- Trust the client with the full world and draw fog client-side: rejected, one devtools tab defeats
it.
- Send a filtered frame from each handler: rejected, filtering spreads across the codebase and a new
frame is a new leak surface.
- Enforce the boundary by discipline in a `sync()` function (the prototype): kept as the fallback,
replaced by distinct `PlayerView`/`GmView` types.
## Consequences
The server recomputes vision on every relevant mutation and holds per-player explored state, so it
needs the vision budget of current §5.3. A new message type must be built inside the egress or it
cannot reach a player. Leak testing is possible because there is one place to audit.
## Tickets
#11 (wire catalogue), #20 (typed views and single egress).
## Spec
Current §2 (trust boundary, single egress rule), §3.1 (what each role receives), §3.4 T1/T2.
@@ -0,0 +1,31 @@
# Per-recipient typed views and state-based diffs
Each connection keeps a `known` table of the last view it was sent; the egress builds the current
view for that recipient, diffs it against `known`, and sends only what changed. Messages are built
from typed structures (`PlayerView`, `GmView`, per-token views), not from a shared JSON tree, and
every server frame carries a per-connection counter `n` rather than a global sequence number. We
chose this over broadcasting mutations and over a global counter because players must not learn that
a hidden mutation happened from a gap in a sequence, and because a full-state push per mutation is
too large (a player move's full polygon is ~3 KB).
## Status
accepted
## Alternatives
- Broadcast every mutation and let each client filter: rejected, leaks hidden entities and needs the
client to hold world state.
- Global `gseq` with per-recipient filtering: rejected, gaps reveal that something hidden changed
(the prototype did this).
- Full snapshot per mutation: rejected, the vision polygon alone is ~3 KB per move.
## Consequences
The diff base is the frame before `n` is stamped, so stamping must deep-copy; otherwise every frame
looks changed (a real bug fixed in slice 8). State messages can be coalesced per key at flush time
without desynchronising the client, which is what makes the bounded outbox (ADR-0017) safe. Ordering
between an ack and the state messages it caused is not guaranteed.
## Tickets
#11, #20; #28 (borrowed egress context), #31 (one scene read per request).
## Spec
Current §2, §3.1, §4.2, §6.4.
+28
View File
@@ -0,0 +1,28 @@
# A refused move carries only the old position
A refused player move — locked, over the step cap, wall collision — returns `ack {ok:false, pos:<old
position>}` with no `code` and no reason, and a GM move out of bounds uses the same shape. Every
other refusal carries a static code and no position. We chose one opaque shape because a
wall-probing client can otherwise binary-search walls and doors beyond its line of sight from the
differences between refusals.
## Status
accepted
## Alternatives
- Per-cause codes (`blocked`, `out-of-range`, `locked`): rejected, each distinction is an oracle.
- Echoing the collision point or the blocking wall: rejected, leaks geometry.
- Explicitly refusing the whole intent class with a reason for the GM: the GM already sees all
walls, but one shape keeps the code path single.
## Consequences
The client cannot explain a refusal; it snaps back (or waits for release while dragging). The step
cap (the token's effective vision radius, or the scene default) bounds what one probe can learn, and
the rate limit bounds the number of probes. Tests assert the shape and that two scenes differing
only beyond the cap produce identical replies.
## Tickets
#11, #15, Q18; T8/T9 in current §3.4.
## Spec
Current §5.5 (player move, GM move), §6 (uniform move refusal), §6.5 (ack codes).
+27
View File
@@ -0,0 +1,27 @@
# Tokens get random opaque ids; walls get per-scene counters
A token id is 12 characters from `[A-Za-z0-9_-]` drawn from the OS CSPRNG (72 bits),
collision-checked at create and unique game-wide. A wall id is a per-scene counter (`next_wall_id`)
that is monotonic and never reused. We chose different schemes because token ids reach players (as
`mine`, `encountered`, `vision`), so a counter would leak how many hidden tokens exist through gaps,
while wall ids never reach a player and a counter keeps scene copy/export stable.
## Status
accepted
## Alternatives
- Dense counters for tokens: rejected, gaps leak hidden tokens.
- Random ids for walls: rejected, ids must stay readable/stable across a scene export and import,
and nothing player-facing depends on them.
- A game-wide wall counter: rejected, per-scene ids keep a scene self-contained.
## Consequences
Token creation checks collision against the loaded set; no counter column is needed. A token may
later change scene and keep its id. Removing a wall never renumbers and never reuses its id, and a
restart reloads `next_wall_id` from the scene row.
## Tickets
#3 (ids), #20 (token ids).
## Spec
Current §8 (ids, wall and token paragraphs), §4.4 step 3 (`next_wall_id`).

Some files were not shown because too many files have changed in this diff Show More