Files
FFF_vtt_frozen/README.md
T

434 lines
25 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.