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
This commit is contained in:
2026-11-21 00:18:17 +01:00
parent 2727617db9
commit 465259c853
9 changed files with 1040 additions and 38 deletions
+124 -3
View File
@@ -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()
})
})
+209 -5
View File
@@ -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<number, { fn: () => void; ms: number }>()
setTimeout(fn: () => void, ms: number): number {
const id = this.#next++
this.pending.set(id, { fn, ms })
return id
}
clearTimeout(handle: number): void {
this.pending.delete(handle)
}
get size(): number {
return this.pending.size
}
nextDelay(): number | null {
const first = this.pending.values().next()
return first.done ? null : first.value.ms
}
runNext(): void {
const first = this.pending.entries().next()
if (first.done) throw new Error('no scheduled timer')
this.pending.delete(first.value[0])
first.value[1].fn()
}
}
function reconnectingClient(options: { autoReconnect?: boolean; random?: () => number } = {}): {
client: ProtocolClient
sockets: FakeSocket[]
events: ClientEvent[]
timers: ManualTimers
} {
const sockets: FakeSocket[] = []
const events: ClientEvent[] = []
const timers = new ManualTimers()
const client = new ProtocolClient({
url: 'wss://test/ws?proto=2',
createSocket: () => {
const socket = new FakeSocket()
sockets.push(socket)
return socket
},
onEvent: event => events.push(event),
timers,
random: options.random ?? (() => 0.5),
...(options.autoReconnect === undefined ? {} : { autoReconnect: options.autoReconnect }),
})
return { client, sockets, events, timers }
}
const helloFrame = { t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } }
describe('reconnect backoff (6.3, story 8)', () => {
it('uses the 1/2/4/8/10 s base schedule with bounded jitter', () => {
expect(RECONNECT_BASE_DELAYS_MS).toEqual([1000, 2000, 4000, 8000, 10000])
expect([1, 2, 3, 4, 5, 6, 99].map(reconnectBaseMs)).toEqual([
1000, 2000, 4000, 8000, 10000, 10000, 10000,
])
for (let attempt = 1; attempt <= 6; attempt += 1) {
const base = reconnectBaseMs(attempt)
expect(backoffDelay(attempt, () => 0.5)).toBe(base)
expect(backoffDelay(attempt, () => 0)).toBe(base - base * RECONNECT_JITTER)
expect(backoffDelay(attempt, () => 0.999999)).toBeLessThanOrEqual(
Math.round(base * (1 + RECONNECT_JITTER)),
)
}
// Jitter is real, not cosmetic: two random draws give different delays, and the cap still holds.
expect(backoffDelay(1, () => 0)).not.toBe(backoffDelay(1, () => 0.9))
expect(backoffDelay(99, () => 0.999999)).toBeLessThanOrEqual(
Math.round(10000 * (1 + RECONNECT_JITTER)),
)
})
it('reconnects after a transport close and drops the pending reqIds with it', async () => {
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
const pending = client.send('conn.ping', { ts: 1 })
expect(client.pendingCount).toBe(1)
sockets[0]!.serverClose(1006)
expect(client.pendingCount).toBe(0)
await expect(pending).rejects.toThrow(/closed/)
expect(events.filter(event => event.type === 'close')).toEqual([
{ type: 'close', reason: null, code: 1006 },
])
const reconnecting = events.filter(event => event.type === 'reconnecting')
expect(reconnecting).toEqual([{ type: 'reconnecting', attempt: 1, delay: 1000 }])
expect(timers.size).toBe(1)
timers.runNext()
expect(sockets).toHaveLength(2)
sockets[1]!.open()
sockets[1]!.receive(helloFrame)
expect(events.filter(event => event.type === 'open')).toHaveLength(2)
// The backoff resets after a successful reconnect: the next drop starts again at 1 s.
sockets[1]!.serverClose(1006)
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toEqual({
type: 'reconnecting',
attempt: 1,
delay: 1000,
})
})
it('grows the delay while attempts keep failing', () => {
const { client, sockets, events, timers } = reconnectingClient({ random: () => 0.5 })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
for (const attempt of [1, 2, 3, 4, 5]) {
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
attempt,
delay: reconnectBaseMs(attempt),
})
timers.runNext()
sockets.at(-1)!.serverClose(1006) // the retry never got a hello
}
expect(events.filter(event => event.type === 'reconnecting').at(-1)).toMatchObject({
attempt: 6,
delay: 10000,
})
})
it('does not reconnect after a terminal server outcome', () => {
for (const reason of ['revoked', 'proto-mismatch', 'evicted', 'malformed-flood'] as const) {
const { client, sockets, events, timers } = reconnectingClient()
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.receive({ t: 'closing', n: 2, reason, code: 4000 })
sockets[0]!.serverClose(1005)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
expect(client.state).toBe('closed')
}
})
it('does not reconnect before the first open (a refused upgrade)', () => {
const { client, sockets, events, timers } = reconnectingClient()
client.connect()
sockets[0]!.serverClose(1006)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
})
it('does not reconnect when autoReconnect is off', () => {
const { client, sockets, events, timers } = reconnectingClient({ autoReconnect: false })
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
expect(events.some(event => event.type === 'reconnecting')).toBe(false)
expect(timers.size).toBe(0)
})
it('retryNow skips the wait and a manual close cancels the retry', () => {
const { client, sockets, timers } = reconnectingClient()
client.connect()
sockets[0]!.open()
sockets[0]!.receive(helloFrame)
sockets[0]!.serverClose(1006)
expect(timers.size).toBe(1)
client.retryNow()
expect(timers.size).toBe(0)
expect(sockets).toHaveLength(2)
sockets[1]!.serverClose(1006)
expect(timers.size).toBe(1)
client.close()
expect(timers.size).toBe(0)
expect(client.state).toBe('closed')
})
})