From 465259c8535e6a9826d3d5b46d6b8b34873247d3 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sat, 21 Nov 2026 00:18:14 +0100 Subject: [PATCH] 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 --- client/README.md | 29 +++- client/e2e/session.test.mjs | 284 ++++++++++++++++++++++++++++++++++++ client/src/main.ts | 58 +++++++- client/src/reducer.ts | 77 +++++++++- client/src/shell.ts | 123 ++++++++++++++-- client/src/style.css | 45 +++++- client/src/ws.ts | 121 ++++++++++++++- client/test/reducer.test.ts | 127 +++++++++++++++- client/test/ws.test.ts | 214 ++++++++++++++++++++++++++- 9 files changed, 1040 insertions(+), 38 deletions(-) create mode 100644 client/e2e/session.test.mjs diff --git a/client/README.md b/client/README.md index 3352508..84e99f7 100644 --- a/client/README.md +++ b/client/README.md @@ -28,7 +28,7 @@ is wiring: | `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. No DOM. | +| `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. | @@ -72,3 +72,30 @@ change them only if a slice needs a new *core* event, and say so in the PR. 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. + +## 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. diff --git a/client/e2e/session.test.mjs b/client/e2e/session.test.mjs new file mode 100644 index 0000000..d50a392 --- /dev/null +++ b/client/e2e/session.test.mjs @@ -0,0 +1,284 @@ +// 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$/) + await waitForText(page, '#roster', /Bob/) + 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'), /Ann/) + 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, '#roster', /Dee Two/) + await waitForBadge(view.page, 'connected') + } + } finally { + await browser.close() + } + }) +}) diff --git a/client/src/main.ts b/client/src/main.ts index d353f81..df1fedf 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -11,6 +11,13 @@ import type { RootState } from './reducer.ts' const KEY_REFUSED = 'Key not recognised.' +/** Story 6: a refused name is shown with a reason, next to the prompt. */ +const NAME_REFUSALS: Record = { + '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('#app') if (!host) throw new Error('#app is missing') @@ -23,6 +30,9 @@ const shell = mountShell(host, { onSubmitKey: key => { void signIn(key) }, + onSubmitName: name => { + void submitName(name) + }, onReload: () => location.reload(), }) @@ -58,6 +68,31 @@ async function signIn(key: string): Promise { 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 { + 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 => { @@ -67,17 +102,21 @@ function connect(): void { 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 live = state.connection.phase === 'live' - if (!live) { + 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 (stage || startingStage) return + if (!live || stage || startingStage) return startingStage = createStage(stageRoot, store) .then(created => { - if (store.state.connection.phase !== 'live') { + const phase = store.state.connection.phase + if (phase !== 'live' && phase !== 'reconnecting') { created.destroy() return } @@ -96,8 +135,19 @@ store.subscribe(state => { syncStage(state) }) +// 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: show the neutral connecting screen and probe for a session. A visitor without a session // gets a refused `/ws` upgrade and lands on the sign-in page; no map data is ever created. +store.dispatch({ type: 'network', online: navigator.onLine }) store.dispatch({ type: 'connecting' }) shell.render(store.state) connect() diff --git a/client/src/reducer.ts b/client/src/reducer.ts index 428d30d..98658dc 100644 --- a/client/src/reducer.ts +++ b/client/src/reducer.ts @@ -16,7 +16,9 @@ import type { } from './protocol.ts' import { closeOutcome, isClosing, isHello } from './protocol.ts' -export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reload' | 'offline' +export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reconnecting' | 'reload' | 'offline' + +export type ConnectionBadge = 'connected' | 'reconnecting' | 'offline' export interface ConnectionState { phase: Phase @@ -27,6 +29,14 @@ export interface ConnectionState { 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 { @@ -51,7 +61,10 @@ export type ReducerEvent = | { 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' } /** @@ -87,7 +100,32 @@ export function sliceOf(state: RootState, name: string): S { } function initialConnection(): ConnectionState { - return { phase: 'boot', frames: 0, lastN: 0, notice: null, error: null } + 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 { @@ -123,6 +161,9 @@ function onFrame(state: RootState, frame: ServerFrame): void { 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 (isClosing(frame)) { // DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code. const outcome = closeOutcome(frame.reason) @@ -160,17 +201,34 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState { 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') { + if (state.connection.phase === 'live' || state.connection.phase === 'reconnecting') { const outcome = closeOutcome(event.reason) if (outcome === 'signin') { resetDomain(state) @@ -179,6 +237,10 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState { } 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.' @@ -193,12 +255,21 @@ export function reduce(previous: RootState, event: ReducerEvent): RootState { 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 } diff --git a/client/src/shell.ts b/client/src/shell.ts index 441efc3..1b4cc2b 100644 --- a/client/src/shell.ts +++ b/client/src/shell.ts @@ -4,19 +4,25 @@ // 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 { rosterOf } 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 } function element( @@ -34,6 +40,12 @@ 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 @@ -65,13 +77,40 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { 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 roster = element('ul', 'roster') - hud.append(role, scene, me, roster) + hud.append(role, scene, me, badge, roster) const fatal = element('section', 'fatal') fatal.hidden = true @@ -82,7 +121,7 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { fatal.append(fatalText, reload) const panels = element('div', 'panels') - root.replaceChildren(stage, hud, signin, boot, fatal, panels) + root.replaceChildren(stage, hud, signin, boot, namePanel, fatal, panels) form.addEventListener('submit', event => { event.preventDefault() @@ -91,7 +130,16 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { 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 @@ -101,8 +149,15 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { 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, fatal]) node.hidden = node !== active + for (const node of [boot, signin, hud, namePanel, fatal]) node.hidden = node !== active } function renderRoster(players: RosterEntry[]): void { @@ -118,23 +173,47 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { ) } + 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 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' + stage.hidden = phase !== 'live' && phase !== 'reconnecting' + renderBadge(state) - // Leaving the live phase clears every server-derived DOM text, so a revoked session cannot - // leave a roster (or names) behind the sign-in page. - if (phase !== 'live') { - role.textContent = '' - scene.textContent = '' - me.textContent = '' - roster.replaceChildren() + // 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) { @@ -152,6 +231,24 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { 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) + role.textContent = state.session.role === 'gm' ? 'GM' : 'Player' + scene.textContent = state.session.scene?.name ?? '' + me.textContent = state.session.me?.name ?? '' + renderRoster(rosterOf(state)) + break + case 'reconnecting': + // Keep the HUD (and the stale map) visible; only the badge changes. showOnly(hud) role.textContent = state.session.role === 'gm' ? 'GM' : 'Player' scene.textContent = state.session.scene?.name ?? '' @@ -169,5 +266,5 @@ export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell { } } - return { render, setBusy } + return { render, setBusy, setNameBusy } } diff --git a/client/src/style.css b/client/src/style.css index 6515adb..0ed1176 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -28,6 +28,7 @@ body { #boot, #signin, +#name, #fatal { position: absolute; inset: 0; @@ -40,14 +41,16 @@ body { text-align: center; } -#signin form { +#signin form, +#name form { display: flex; flex-direction: column; gap: 8px; width: min(360px, 90vw); } -#key { +#key, +#name-input { font: inherit; padding: 10px 12px; border-radius: 6px; @@ -58,7 +61,13 @@ body { text-transform: uppercase; } +#name-input { + letter-spacing: normal; + text-transform: none; +} + #signin button, +#name button, #fatal button { font: inherit; padding: 10px 12px; @@ -68,7 +77,8 @@ body { color: inherit; } -#signin-error { +#signin-error, +#name-error { color: #ff8a8a; } @@ -102,3 +112,32 @@ body { #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; +} diff --git a/client/src/ws.ts b/client/src/ws.ts index 8826e4c..4628d80 100644 --- a/client/src/ws.ts +++ b/client/src/ws.ts @@ -1,11 +1,15 @@ // The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId` -// counter and the pending-request map; it emits reducer events and never touches the DOM. The -// socket factory and clock-free design make it unit-testable without a browser. +// 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: this client does not reconnect to them. Reconnect -// with backoff is T5 (#68); T4 only proves the outcome mapping. +// `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' @@ -23,11 +27,53 @@ 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 = { @@ -43,16 +89,26 @@ 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() #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' { @@ -63,15 +119,33 @@ export class ProtocolClient { 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' - const socket = this.#createSocket(this.#url) + 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 => { @@ -93,10 +167,18 @@ export class ProtocolClient { } socket.onclose = event => { if (this.#state === 'closed') return - this.#state = 'closed' 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 }) } } @@ -124,7 +206,16 @@ export class ProtocolClient { }) } + /** 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 { @@ -135,6 +226,24 @@ export class ProtocolClient { 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() diff --git a/client/test/reducer.test.ts b/client/test/reducer.test.ts index 574c23d..e9f9458 100644 --- a/client/test/reducer.test.ts +++ b/client/test/reducer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { SLICES, initialState, reduce, rosterOf } from '../src/reducer.ts' +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' @@ -140,9 +140,10 @@ describe('connection outcomes (6.5)', () => { expect(state.connection.phase).toBe('offline') }) - it('a transport close while live is offline, not a silent sign-out', () => { + 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('offline') + expect(state.connection.phase).toBe('reconnecting') + expect(connectionBadge(state)).toBe('reconnecting') }) }) @@ -182,3 +183,123 @@ describe('registry', () => { }) }) + +// --------------------------------------------------------------------------------------------- +// 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() + }) +}) diff --git a/client/test/ws.test.ts b/client/test/ws.test.ts index d29a0a6..76fd4f9 100644 --- a/client/test/ws.test.ts +++ b/client/test/ws.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from 'vitest' -import { ProtocolClient } from '../src/ws.ts' -import type { ClientEvent, SocketLike } from '../src/ws.ts' +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 @@ -104,9 +110,20 @@ describe('protocol client', () => { }) it('treats a close without a closing frame as a transport failure', () => { - const { socket, events } = connect() - socket.serverClose(1006) - expect(events.at(-1)).toEqual({ type: 'close', reason: null, code: 1006 }) + 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)', () => { @@ -145,3 +162,190 @@ describe('protocol client', () => { 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 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') + }) +})