Skip to content

Web app

Homefelt’s Canasta in the browser: Vite, React and TypeScript (strict) over the Rust rules engine compiled to WebAssembly (rust/canasta-wasm). Play solo against computer players (Easy or Normal), or play every human seat from one screen. With a game server in the build, play online with friends too (“Online play”).

Build and run

The engine is not committed: build it first, then the app.

bin/build-wasm # writes rust/canasta-wasm/pkg/ (needs wasm32-unknown-unknown and wasm-bindgen-cli)
cd web
npm ci
npm run dev # http://localhost:5173
npm run typecheck # tsc --noEmit
npm test # Vitest: the node-state and online glue, the save store, the lobby screens, and the glue against the real engine
npm run build # dist/, served by `npm run preview`
npm run e2e # Playwright in a real browser (below)

vite.config.ts aliases canasta-wasm to rust/canasta-wasm/pkg/canasta_wasm.js; the build copies canasta_wasm_bg.wasm into dist/assets/ and fetches it at start. Rebuild the engine after changing rust/ or spec/rulesets/.

Routes

The app answers several paths (docs/architecture.md “Web routes”); a host serving the build must answer each with index.html (vercel.json):

  • /: the Homefelt home (src/Home.tsx). A card per game from the registry (src/games.ts): Play (Continue while a game is saved here) and How it plays on the site (VITE_SITE_URL, default https://homefelt.io); your tables across games once the refresh cookie signs you in (GET /me/tables), or a link to sign in at /online; and the display settings. It loads no engine.
  • /canasta (and its subpaths): the local game, below. ?seed=…&stream=… pins its deal; /canasta/learn (the home card’s Learn to play) starts the tutorial, then reads as /canasta.
  • /online, /join/*, /table/*: online play (“Online play”), each table sent to its game by gameForTable (Canasta for now). A build without VITE_SERVER_URL says online play is not here.
  • Anything else: a not-found page linking home.

src/main.tsx picks the page with pageFor (src/routes.ts) and sets the tab’s title (“Homefelt”, or “Canasta · Homefelt” on Canasta’s pages). A game’s UI and canasta-wasm load with a dynamic import() (src/canasta.tsx) only on its own pages, so the home page’s JS holds no engine.

How it works

The app is a screen over the CLI protocol (spec/protocol/cli.md), the way the native apps’ NodeState drives their cores:

  • src/engine.ts loads the module and opens Session.withShippedRuleSets().
  • Computer seats: the root screen picks who plays each other seat (Human, Easy or Normal; seat 1 is you), sent as newGame’s controllers. Like the native apps, NodeState turns the session’s setRunsComputers(false) on and plays the computer seats itself, one stepComputer() every 700 ms, so a person can follow them; the engine chooses every move. While one plays, the action bar says so and the hand shown is the first human seat’s. Computer seats carry a robot mark; the table calls every seat “Player N” and never shows a computer’s level.
  • src/nodeState.ts (mirror of swift/App/Sources/NodeState.swift) sends only ls and do <action> <json>, keeps the focused node, the selection and the last refusal, and turns the selection into a move: a selection of one natural rank the side has melded is added to that meld (meldTarget, “Add to 9s”); anything else is a lay or a take built by the session’s groupMelds and takeSelection (the core’s Selections, so a take can carry extra melds). It knows no rule: whether a move is legal is the engine’s answer.
  • What the screens show comes from the state, as on the apps: the player counts and “may I go out?” from the root state’s ruleSets[] (players, askPartner); games are dealt with view hotSeat, so only the viewer’s hand is shown, in the game’s handOrder (the “Sort hand” menu, a native <select>, sends sortHand), with each card’s handPoints (“Meld 60 points”). The hand draws the meldable marks, with a legend, only with Beginner aids on in Settings (spec/README.md “Beginner aids”, #193).
  • The tutorial (spec/README.md “The coach”, #196): Learn to play on the new-game screen (and, the first time, TutorialOffer) sends newTutorial. While the game node has a tutorial, src/CoachBubble.tsx sits between the felt and the hand with the step’s words, the nudge after a notTutorialStep refusal and Skip tutorial; the table outlines the step’s highlight targets and the coach focuses the first. NodeState never saves a tutorial, plays its computer seats every 1.5 s, and leaves it by opening a fresh session (openSession).
  • src/protocol.ts types the response lines; src/refusal.ts words every rule error with the iPhone app’s title and sentence, with the numbers of the error’s context.
  • Views mirror the apps: RootView, TableView (with the hand), ActionBar, RefusalCard, HandScoreView, CardViews. Cards are drawn in CSS and SVG; there are no image files.
  • The saved game. Like the apps’ SaveStore, NodeState keeps the solo game in play as a saved game after every move, computer moves included: the session’s save(), written to localStorage under one versioned key per game, homefelt.canasta.savedGame.v1 (src/saveStore.ts; the keys are in src/storageKeys.ts, and a save or homefelt.settings still under its pre-rename canasta. key moves on first read). A game that ends deletes it. On launch the root screen offers Continue game while one is stored, which sends do resumeGame {"save":…}; a save that does not load (badJson, unsupportedVersion: 2, inconsistent: …) is deleted and the root screen says, in words, “The saved game could not be resumed (…)” until the next move, as the iPhone app’s saveProblem does. Every storage access is guarded: when storage is missing, blocked or full the game plays the same, and only continuing it after a reload is lost. Online tables are the server’s and never saved here.
  • src/tableModel.ts is what the table screens drive, whichever transport answers: NodeState over the Wasm session, or OnlineState over the server (below). It holds the focused node, the selection and the refusal, and builds every move’s input with the engine’s Selections (groupMelds, takeSelection), which online play loads from canasta-wasm too.

Online play

Set VITE_SERVER_URL at build time and the app plays online as well, through the game server (rust/canasta-server, spec/protocol/server.md). Without it the online pages are not offered. Online play lives at /online (your tables), /join/t/TOKEN (an invite link), /join/CODE (a code), /join/request/ID (waiting for the host) and /table/ID (all routes: “Routes” above).

Build variable Meaning
VITE_SERVER_URL The game server, https://… (http:// only for localhost). The WebSocket base is the same host, wss://
VITE_GOOGLE_CLIENT_ID Google Identity Services’ web client id: shows “Sign in with Google”
VITE_APPLE_SERVICES_ID, VITE_APPLE_REDIRECT_URI Sign in with Apple JS’s Services ID and its registered return URL (default: the site’s /): shows “Sign in with Apple”. The server needs the same two as HOMEFELT_APPLE_WEB_SERVICES_ID and HOMEFELT_APPLE_WEB_REDIRECT_URI
VITE_SITE_URL The marketing site, for each game’s “How it plays” link (default https://homefelt.io)
VITE_DEV_AUTH 1: the dev sign-in (a name, no password) for a local server built with dev-auth. Offered only when VITE_SERVER_URL is localhost, and vite build fails if it is set with any other server, so it never ships
  • Sign-in (src/online/auth.ts, providers.ts). AuthClient carries out the Session machine’s effects (src/online/session.ts, spec/online/README.md “Session”). Each sign-in makes a raw nonce, gives the provider its SHA-256, and posts the identity token and raw nonce to /auth/apple|google, with Apple’s one-time authorization code (the server trades it as the Services ID, so deleting the account can revoke the Apple sign-in; docs/server.md “The web client”). Every auth request is a web request (X-Canasta-Client: web, credentials included): the server keeps the refresh token in an HttpOnly cookie, and the access token stays in memory only, never in storage. A reload refreshes through the cookie; refreshes run one at a time, across tabs too (Web Locks), since the server treats a refresh token used twice as stolen. The server must list the site in HOMEFELT_WEB_ORIGINS and be on the same site (docs/server.md “The web client”).
  • Your name (src/online/profile.ts, NameForm.tsx). After a sign-in the app reads GET /me; while nameChosen is false (a new account is “Player”; a dev player starts from its sign-in name) it asks “What should the table call you?” before anything else. “Save name” sends PATCH /me; “Not now” skips it for the rest of the tab’s session (sessionStorage), and the next sign-in asks again. Your tables page says “Playing as ” with “Change name”. The form checks the server’s rules first and says what is wrong in words (NFC, trimmed, 1 to 40 characters, no hidden characters such as zero-width spaces, at least one letter, number or symbol, at most 2 accents stacked on a letter); the server’s invalidName and tooManyRenames (one rename every 5 seconds) have their own words. Tables in play show the new name at once.
  • Tables and invites (src/online/OnlineApp.tsx, MyTables.tsx, tables.ts, joinRequest.ts). Your tables: the list from GET /me/tables links to each table you sit at, saying in words whose turn it is (or the lobby, paused, between hands) and who else sits there, and to each join request still waiting; it reads the list again when the page shows again. Create one (rules, players, a person or a computer per seat; you are seat 1 and host), or type a code. An invite (from the lobby or the Table sheet) is a /join/t/TOKEN link, which seats one person at once (copy or share; “Make another invite” for the next friend), and a 6-character code to type instead, shown with its 30-minute countdown. Opening a link signs in if needed, asks “Take a seat”, and redeems {"token":…}; a typed code redeems {"code":…}. A code from someone the host does not know answers 202 pending: the waiting screen (/join/request/ID, so a reload keeps waiting) polls GET /invites/requests/{id} from 2 s, half as long again each time up to 15 s, and a Retry-After longer than that, until the host approves (to the table), denies or the request lapses. “Cancel request” withdraws it (DELETE /invites/requests/{id}); if the host approved it first, the next poll takes the seat. rateLimited (with how long to wait), tooManyRequests and tooManyAccounts each have their own words (wordings.ts).
  • Guests (OnlineApp.tsx GuestJoin and GuestTable; spec/protocol/server.md “Join as a guest”). A link opened without a session also offers “Join as a guest”: a name, then POST /auth/guest with the link’s token. A guest session (the Session machine’s guest, kept through a reload’s refresh) shows only its table: every other path goes there, the lobby and the Table sheet show no invite, Leave ends the seat for good, and the ended screen (guestEnded, close 4410) leads to signing in. The host sees “guest” beside the name, with Remove (the host’s remove).
  • The lobby (src/online/Lobby.tsx, TableParts.tsx). A new table waits until its host starts it: no node, only the table message with each seat’s state. Everyone sees the seats (a person, connected or away; a computer; open) and can invite; everyone but the host reads “Waiting for to start the game”. The host also sees join requests (name, account age, time left) with Approve and Deny, and pending seats (to everyone else they are open, like the server’s copy); gives an open seat to an Easy or Normal computer (handOver) or opens a computer’s seat again (openSeat); and starts: “Start the game”, or with seats open “Start with Normal computers” / “Start with Easy computers” (start with computers). When the role passes on (the host left, or stayed away), a banner says “ is now the host” and the new host gets the controls. “Leave table” (with a confirmation) sends leave: in the lobby the seat opens again, in a game a Normal computer takes it for good; the server closes with 1000 and the page goes back to your tables. If it answers tableUnavailable instead, the player stays seated with a card saying so.
  • The table (src/online/onlineState.ts, OnlineTable.tsx). What every frame and close means is the TableClient machine’s (src/online/tableClient.ts, spec/online/README.md): OnlineState runs its effects and words its codes. One WebSocket per table: a hello with the access token, the lobby until the start, then the server’s seat view is the focused node and TableView draws it, with players’ names, who is connected or away, and “You”. Moves go out without a seat (the server fills it in); refusals come back as cards, rule errors with their context. The seat view carries only the viewer’s own hand, handPoints and meldable (spec/protocol/server.md “The seat view”), in this connection’s own order: the “Sort hand” menu sends sortHand, and the hand draws the meldable marks with Beginner aids on, as in a game on this device. The host may turn aids off for the table before the start (aidsAllowed, #194): the “Allow beginner aids” switch in the New table form and the lobby sends aids; everyone else, and everyone in the Table sheet once the game started (it is locked then), reads what it is set to; and while it is off the view has no meldable and a player with aids on reads a note in the legend’s place. The host’s Table sheet pauses and continues the game, decides join requests (the Table button shows how many wait) and hands a dropped or empty seat to an Easy or Normal computer; the server decides whether it may. Closes are handled by code: 4401 refreshes the token once (then sign in again), 4403 goes back to your tables with the reason (notSeated, noSuchTable; tableUnavailable retries), 4409 stops until you choose “Play here”, 4428 and 4429 back off from 10 s to 2 min, and anything else (1001, 1006, 4400, 4408) reconnects from 1 s, doubling to 30 s. The banner says what is happening and offers “Try now”.

Network and app-status messages

One network layer, one client per service (decision 0015):

  • src/net/: HttpClient (fetch behind an injectable Transport, timeouts, the unreachable and timeout errors, readCapped), errors.ts (ServerError, read from the server’s {"error":{…}}) and socket.ts (the WebSocket factory). No test touches the network.
  • src/online/auth.ts AuthClient (sign-in, refresh through the cookie, one at a time, never retried), src/online/serverClient.ts ServerClient (the API with the bearer token, one refresh on a 401) and src/online/gameSocket.ts GameSocket (the table’s socket, the hello, close codes and the backoff curves; what each close means stays in OnlineState).
  • Timeouts, and why some calls have none. A budget covers the whole answer, body included (HttpClient.read). ServerClient’s GETs (/me, /me/tables, a join request’s status) get 15 s: giving up and asking again is safe. AuthClient has none: the server rotates the refresh token when it answers /auth/refresh, so a refresh the page gave up on could still have rotated it, and the next refresh would then look like a stolen token and sign the whole family out. Writes that are not idempotent (createTable, redeem, invites, profile changes) have none either: a retry after a timeout could do them twice. The feed and version.json get 5 s.
  • Sign-in races. Every sign-in and sign-out bumps a session generation; a refresh that started before one throws its answer away, so it can never bring the old session back.
  • src/status/statusClient.ts StatusClient: the app-status feed (spec/app-status), a bare GET with no credentials or custom headers, 5 s, 64 KiB, no retries, failing open to the last good copy in localStorage. It fetches at launch and when the tab comes back, at most every 15 minutes.
  • src/status/StatusLayer.tsx draws in #status-root, above the page: a banner (warning) and a sheet (<dialog>, info) at safe points only (the home page, the deal screen, a hand’s score, game over, the online home: useSafePoint()), never mid-hand; a blocking message takes the page’s place (blocks: app everywhere, blocks: online on the online pages; elsewhere a banner, and the home page’s online tables and the deal screen’s “Play online” link are hidden, useOnlineBlocked()). Dismissals live in homefelt.status.dismissed.v1.
  • The reload check: the build writes dist/version.json with its commit (__HOMEFELT_BUILD__); the tab reads it when it becomes visible and every 30 minutes, and a newer one brings “Homefelt has been updated” at the next safe point. A lazy chunk that fails to load (vite:preloadError) reloads once a minute at most; when sessionStorage cannot hold that guard it does not reload on its own and shows the reload banner instead.
  • Builds read https://homefelt.io/app-status/v1.json (VITE_SITE_URL); VITE_STATUS_FEED_URL names another feed (the end-to-end tests point it at the preview and answer it with page.route), and a dev build takes ?statusFeed=<url>.

Theme and settings

src/theme.generated.css comes from design/tokens.json through bin/gen-theme (do not edit it; bin/gen-theme --check runs in CI). Every word comes from design/strings/en.json through bin/gen-strings (src/strings.generated.ts, looked up with t in src/i18n.ts), and the language from the locale setting or the browser (docs/i18n.md). Light and dark follow prefers-color-scheme. The Settings (red-and-black deck by default or four colours, standard or large text, Beginner aids off by default, language) set data-deck and data-text on <html> and are kept in localStorage when it is available. Large text also changes the table’s layout (mockup e in design/mockups.html): the seats fold into each side’s team line, your side sits just above the hand, the stock and pile come right after the first side with their words trimmed, and the hand wraps at 5 cards, so the pile never scrolls below the hand.

The table follows the iPhone app: the seat strip (whose turn, in words, each seat’s card count and a robot for a computer), the melds, then the stock and the pile with the Frozen chip and the status line under them. The hand’s rows line up on the left and each covers the one above it card for card, showing only its corners. On a phone at standard text only the melds scroll (a focusable “Melds” region), so the seats, the stock, the pile, the Frozen chip and the status stay in view above the hand. On a short screen (up to 820px tall, shortQuery in TableView.tsx: every iPhone in Safari, with its bars) the table takes the large-text layout at either text size (the seats in the team lines, the pile after the first side, your side above the hand), the score bar fits one line (“Hand N”, the scores, a gear named Settings and New game; at large text the scores take a second line), the moves bar is tighter, and fades at the felt’s top and bottom edges show only while it can scroll that way (a scroll-driven animation; a browser without one shows none). The hand’s header row holds a short heading (“Your hand · 11”) and the order menu as a chip: a native <select> drawn about 32px tall with a 48px touch target. From 60rem wide (useWide in TableView.tsx, the same width in styles.css) the table widens: the melds sit beside a column with the stock, the pile, a refusal and the status, which stays in view while the melds scroll, and the hand takes one row of up to 15 cards (11 at large text) beside its heading and order menu, so a 1280 × 800 window shows the pile and the hand without scrolling. Scores and card ranks use the system font’s figures: Atkinson Hyperlegible Next slashes its zero, which reads as a garbled glyph at those heavy weights.

Accessibility

Every move is a button in the action bar. The table also takes taps on the destination, through the same NodeState methods: the stock draws, the pile takes (draw stage) or discards one selected card (play stage), and your side’s meld area melds the selection. Each is a button with a label and a description (“Draws a card”) only while its move is offered to a person, with a brass ring while the tap would act. The game plays from the keyboard: Tab between areas, arrow keys move between cards in the hand, Space or Enter selects one. The felt (seats, melds, pile) takes focus too, so the arrow keys scroll it on a small screen. Cards are named like “Ace of spades, selected”; a joker’s corner shows “JKR” (the star is decoration) and its name starts with it, “JKR, Joker” (label in name), while sentences that mention it say “Joker”; a polite live region announces each turn and each refused move. Selected cards, the frozen pile, wild cards, teams and meldable melds each carry a shape, word or icon as well as colour, and targets are at least 44 px.

Pinned deals

?seed=15&stream=54 deals every game of the page with that seed and stream (the CLI’s newGame inputs, spec/protocol/cli.md), so a test or a bug report replays the same cards. Both must be whole numbers up to 2^53 − 1, or the deal is random. It works in every build, production included: a seed is no secret on a table where one screen plays every human seat (src/pinnedDeal.ts).

End-to-end tests

e2e/ holds Playwright tests that play the production build (npm run build, then vite preview on port 4173, started by playwright.config.ts) by role and accessible name, as a person would:

  • play.spec.ts: the AGENTS.md example (Official, seed 15: draw, lay AS AD AD, discard KS), the same turn by tapping the stock, the meld area and the pile, and a refused take (pileFrozen) that shows the refusal card and changes nothing.
  • hand.spec.ts: the scripted Family hand of the behaviour suite (spec/scenarios/scoring/seeded-full-hand-family.json) played to the score panel, row by row.
  • home.spec.ts: the Homefelt home lists Canasta, whose Play opens /canasta and whose How it plays points at the site; axe in light and dark at both text sizes; no .wasm request on /; a display setting that holds in the game; a solo deal at /canasta that the home card continues; a not-found page; and /join/CODE still reaching the join flow (or, without a server, saying online play is not here).
  • a11y.spec.ts: axe-core on the root screen and the table, no serious or critical violations: with a refusal, with a joker in hand (seed 5) and selected, and at large text on a phone.
  • keyboard.spec.ts: one turn without the mouse.
  • save.spec.ts: a solo game with computers, a reload and Continue game back at the same table, hand and turn (axe on the root screen with the button); a save that does not load, deleted with its message shown once; and a game that plays on with storage blocked.
  • table-layout.spec.ts: the table’s layout (#86): the scores’ 0 drawn without Atkinson’s slashed zero, the hand’s rows lined up card for card on a phone with no horizontal scroll, the seat strip, the Frozen chip and the status line in a solo game three turns in, and at 1280 × 800 (both text sizes) and at 390 × 844 (standard) the stock, the pile, the status and the hand in view without scrolling, with axe clean. On a short phone (390 × 664 and 375 × 548, both text sizes, light and dark, after the deal and mid-game with melds) the hand, the stock, the pile and Draw / Take pile show together, none cut by the felt, the score bar takes one line at standard text, and each fade shows exactly when the felt can scroll that way. A selected card in the hand’s first row rises clear of the order menu.
  • screens.spec.ts: not a test. With E2E_SCREENS=<name> it writes design/screens/web-table-{desktop,phone}-{standard,large}-<name>.png of that solo game at 1280 × 800 and 390 × 844 (E2E_SCREENS=after npm run e2e -- screens); otherwise it is skipped.
  • solo.spec.ts: a solo hand, Player 1 against three Normal computers (Official, seed 15), played to the score panel; page.clock skips the 700 ms between computer moves.
  • online.spec.ts (with E2E_ONLINE=1): dev players in separate browser contexts on the local server. The host creates a table (its lobby) and an invite; one player opens the link and is seated, another types the code and waits until the host approves; the host starts with an Easy computer in the open seat; they play and see each other’s moves; a reload is back at the seat through the refresh cookie; the host pauses and continues, then leaves: a computer takes the seat and the next player hosts. In a second lobby the host opens and refills a computer’s seat, then leaves, and the seat opens while the role passes on. A new player names themselves at the prompt (refused names in words, a zero-width space among them), the lobby shows the name, and “Change name” on the tables page renames them at the open table (once the 5-second rename limit, shown in words, has passed); another skips the prompt, which stays away after a reload. Also a refused code, and axe on the online pages (the lobby, the waiting screen and the name forms too). Also the Homefelt home’s “Your tables”, whose link opens the table, and /join/CODE reaching the join flow. devSignIn keeps the dev sign-in’s name at the prompt. playwright.config.ts then starts ../bin/dev (Postgres, the dev sign-in; docs/development.md) unless a server already answers on port 8080, and builds the app with VITE_SERVER_URL and VITE_DEV_AUTH. Each run signs in new dev players, since a host makes at most 10 tables an hour.

The scripted tests pick Human for every other seat (deal() in e2e/table.ts), since the root screen starts them as computers.

npx playwright install chromium # once: Playwright's Chromium
npm run e2e # Chromium only
PLAYWRIGHT_CHANNEL=chrome npm run e2e # or the installed Google Chrome, without the download
E2E_WEBKIT=1 npm run e2e # WebKit too (npx playwright install webkit)
E2E_ONLINE=1 PLAYWRIGHT_CHANNEL=chrome npm run e2e # online play too, against bin/dev

E2E_PORT (4173) moves the preview and E2E_SERVER_PORT (8080) the game server the build calls, so two checkouts can run the tests at once. Another server port needs that server running already (bin/dev takes its PORT from .env.development.local), with the preview’s origin in its HOMEFELT_WEB_ORIGINS. CI runs them in the web job with --trace off and uploads the HTML report when they fail.

Deploy

The Vercel project homefelt-play builds this folder (docs/deploy.md): vercel.json runs bin/vercel-install-web (Rust, wasm-bindgen-cli, bin/build-wasm, npm ci), then npm run build. The build is static: index.html and assets/, including canasta_wasm_bg.wasm, served as application/wasm. vercel.json also answers /canasta, /canasta/*, /online, /join/* and /table/* with index.html. For online play the app must sit on the same site as the server (the refresh cookie is SameSite=Strict) and be built with VITE_SERVER_URL: in production https://api.homefelt.io, set on the Vercel project’s Production environment only (docs/deploy.md, “Game server”, step 8).

vercel.json also sends the security headers on every path (#251): HSTS, nosniff, a referrer policy, a permissions policy, X-Frame-Options: DENY and a Content Security Policy, for now as Content-Security-Policy-Report-Only. The policy allows the Wasm engine ('wasm-unsafe-eval'), the game server (https://api.homefelt.io, wss://api.homefelt.io), the status feed at https://homefelt.io, Google’s sign-in script, style and frame, and Apple’s sign-in script; no 'unsafe-inline'. Apple needs no frame-src or form-action: the client signs in with usePopup: true (online/providers.ts), so Apple’s page opens in its own window, which this page’s policy does not govern, and answers by message. A new origin the app talks to goes into that policy. Enforcing it waits for sign-in against the deployed server (#270). e2e/security.spec.ts plays the app with the policy enforced and fails on any violation; vite preview does not apply vercel.json, so the tests add it.

Follow-ups

  • Your tables: the server lists none yet, so a table you closed without leaving is reached again only by its /table/ID address.