feat(client): drag with prediction and rollback (#72)

Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release;
the sprite follows the pointer while authoritative frames are ignored for drawing.
Uniform move nacks roll back with a short tween (on release if still dragging),
rate-limited acks drop quietly, and pending reqIds die with the connection.

- slices/move.ts: pure drag/pending/ack state machine at the reducer seam
- render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins
  over pan/pinch (#69); sends via the new intents bridge
- tokens renderer draws the optimistic/confirmed position and tweens the rollback
- intents.ts + ws.send onReqId: one reqId-keyed sender for render modules
- e2e: drag persists after reload, wall refusal tween, GM move mid-drag,
  reconnect mid-drag dropping the pending map
This commit is contained in:
2026-11-21 09:41:03 +01:00
parent 4534ed6426
commit c7d5e2cc69
10 changed files with 1284 additions and 13 deletions
+322
View File
@@ -0,0 +1,322 @@
// T9 (#72, TESTING 10.3): drag with prediction and rollback against the real server through the
// TLS/HTTP2 nginx. The browser's real mouse drives the canvas; the assertions read the sprite
// positions the renderer publishes on the canvas dataset, and the real per-recipient `token`
// frames a GM connection receives. No fixture, no mocked protocol.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import {
launchBrowser,
newPage,
signIn,
waitForVisible,
withStack,
} from './stack.mjs'
async function waitForBadge(page, state, timeout = 30000) {
await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout })
}
/** The renderer's instrumentation: what the browser actually draws, plus the move counters. */
async function renderState(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) return null
const data = canvas.dataset
const positions = {}
for (const entry of (data.tokenPositions ?? '').split(' ').filter(Boolean)) {
const [id, point] = entry.split(':')
const [x, y] = point.split(',').map(Number)
positions[id] = [x, y]
}
return {
ids: (data.tokenIds ?? '').split(' ').filter(Boolean),
positions,
dragId: data.dragId ?? '',
dragPos: data.dragPos ?? '',
dragPhase: data.dragPhase ?? '',
pending: Number(data.dragPending ?? '0'),
refused: Number(data.dragRefused ?? '0'),
rateLimited: Number(data.dragRateLimited ?? '0'),
rollbacks: Number(data.dragRollbacks ?? '0'),
}
})
}
async function waitForRender(page, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await renderState(page)
if (last !== null && predicate(last)) return last
await sleep(25)
}
throw new Error(`drag renderer never reached the expected state: ${JSON.stringify(last)}`)
}
async function canvasOrigin(page) {
return page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
if (!canvas) throw new Error('no canvas')
const rect = canvas.getBoundingClientRect()
return { x: rect.left, y: rect.top }
})
}
/** Press on a world point, move in real steps (so the 20 Hz sender emits several), release. */
async function drag(page, from, to, steps = 8) {
const origin = await canvasOrigin(page)
await page.mouse.move(origin.x + from[0], origin.y + from[1])
await page.mouse.down()
for (let step = 1; step <= steps; step += 1) {
const x = from[0] + ((to[0] - from[0]) * step) / steps
const y = from[1] + ((to[1] - from[1]) * step) / steps
await page.mouse.move(origin.x + x, origin.y + y)
await sleep(60)
}
await page.mouse.up()
}
/** One GM-owned scene with a player and one controlled token. */
async function sceneWithPlayer(origin, gmKey, pos = [400, 400]) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const scene = (await gm.ws.waitText('walls')).scene
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
const token = await gm.ws.request({
t: 'token.create',
scene,
kind: 'pc',
pos,
descriptive_name: 'Ann',
actual_name: 'Ann',
controller: player.id,
flags: { vision: true },
radius: 20,
})
assert.equal(token.ok, true)
return { gm, scene, player, token: token.id }
}
test('drag persists after reload (stories 38, 39)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
await drag(page, [400, 400], [500, 460])
// The server remains the only judge: its frame carries the final position (story 39).
const frame = await gm.ws.waitFor(
message =>
message.t === 'token' &&
message.id === token &&
Math.abs(message.pos[0] - 500) <= 2 &&
Math.abs(message.pos[1] - 460) <= 2,
10000,
)
assert.deepEqual(frame.pos, [500, 460])
const settled = await waitForRender(
page,
view =>
Math.abs(view.positions[token]?.[0] - 500) <= 2 &&
Math.abs(view.positions[token]?.[1] - 460) <= 2 &&
view.dragId === '' &&
view.pending === 0,
)
assert.equal(settled.pending, 0, 'the final ack settled the pending intent')
// The move is durable: a reload rebuilds the view from the server, not from the drag.
await page.reload()
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const reloaded = await waitForRender(
page,
view => Math.abs(view.positions[token]?.[0] - 500) <= 2 && Math.abs(view.positions[token]?.[1] - 460) <= 2,
)
assert.equal(reloaded.dragPhase, '')
// The player's own frame after the resync is the server's position, not a replay.
assert.deepEqual(gm.ws.messages.filter(m => m.t === 'token' && m.id === token).at(-1).pos, [500, 460])
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('a wall refuses the move and the sprite slides back (story 40)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, scene, player, token } = await sceneWithPlayer(origin, gmKey)
// A blocking wall between the token and the drop point. A player cannot see it: prediction is
// optimistic and the server judges (DESIGN 7.5).
const wall = await gm.ws.request({
t: 'wall.add', scene, a: [600, 300], b: [600, 500],
})
assert.equal(wall.ok, true)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
await drag(page, [400, 400], [680, 400], 10)
// The refusal increments the counter and starts the cosmetic tween (436/440: a slide back).
await page.waitForFunction(
() => {
const canvas = document.querySelector('#stage canvas')
return canvas && Number(canvas.dataset.dragRollbacks ?? '0') >= 1
},
null,
{ timeout: 10000, polling: 16 },
)
// Catch the tween mid-flight: the sprite is strictly between the drop point and the rollback
// target while the reducer's rollback is live.
const mid = await page.evaluate(() => {
const canvas = document.querySelector('#stage canvas')
return { phase: canvas.dataset.dragPhase ?? '', positions: canvas.dataset.tokenPositions ?? '' }
})
assert.equal(mid.phase, 'rollback')
const entry = mid.positions.split(' ').find(item => item.startsWith(`${token}:`))
const midX = Number(entry?.split(':')[1]?.split(',')[0])
assert.ok(Number.isFinite(midX), `the sprite is being drawn mid-tween: ${mid.positions}`)
const settled = await waitForRender(
page,
view => view.dragPhase === '' && view.refused >= 1 && view.rollbacks >= 1 && view.pending === 0,
)
assert.equal(settled.refused >= 1, true)
const finalX = settled.positions[token]?.[0] ?? 0
assert.ok(finalX <= 582, `rolled back to the clear side of the wall, got ${finalX}`)
assert.ok(finalX >= 400, 'the rollback is left of the wall but not past the start')
assert.ok(midX > finalX, `the tween is between the drop and the target: mid=${midX} final=${finalX}`)
// The authoritative frame says the same thing the sprite shows.
await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && message.pos[0] === finalX,
5000,
)
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('authoritative frames are ignored under the finger; the GM can move the token meanwhile', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const base = await canvasOrigin(page)
await page.mouse.move(base.x + 400, base.y + 400)
await page.mouse.down()
await page.mouse.move(base.x + 480, base.y + 400)
await sleep(80)
let view = await waitForRender(page, state => state.dragId === token)
assert.deepEqual(view.dragPos, '480,400')
// Story 41/43: the GM moves the same token while the player still holds it. The player's
// sprite must not jump (the authoritative frame is ignored for drawing while dragging).
const gmMove = await gm.ws.request({ t: 'token.move', id: token, pos: [450, 400] })
assert.equal(gmMove.ok, true)
await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && message.pos[0] === 450,
5000,
)
await sleep(150)
view = await renderState(page)
assert.equal(view.dragId, token)
assert.deepEqual(view.positions[token], [480, 400], 'the sprite stayed under the pointer')
await page.mouse.up()
// The release send starts from the GM's position (450) to 480: inside the step cap, accepted.
await gm.ws.waitFor(
message =>
message.t === 'token' && message.id === token &&
Math.abs(message.pos[0] - 480) <= 2 && Math.abs(message.pos[1] - 400) <= 2,
10000,
)
const settled = await waitForRender(page, state => state.dragId === '' && state.pending === 0)
assert.deepEqual(settled.positions[token], [480, 400])
assert.equal(settled.rollbacks, 0, 'an accepted release needs no rollback')
} finally {
gm.ws.close()
await browser.close()
}
})
})
test('a reconnect mid-drag drops the pending intent and resumes from the server', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, server }) => {
const { gm, player, token } = await sceneWithPlayer(origin, gmKey)
const browser = await launchBrowser()
let restarted = null
try {
const { page } = await newPage(browser)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForBadge(page, 'connected')
await waitForRender(page, view => view.ids.includes(token))
const base = await canvasOrigin(page)
await page.mouse.move(base.x + 400, base.y + 400)
await page.mouse.down()
await page.mouse.move(base.x + 470, base.y + 400)
await sleep(80)
await waitForRender(page, state => state.dragId === token)
const before = await gm.ws.waitFor(
message => message.t === 'token' && message.id === token && Math.abs(message.pos[0] - 470) <= 2,
5000,
)
assert.ok(before)
// Kill the server with the finger still down: the close ends the drag and every pending
// `reqId` dies with the socket (DESIGN 6.3), so no orphan awaits an ack that cannot come.
await stopServer(server)
await waitForBadge(page, 'reconnecting')
const dropped = await waitForRender(page, state => state.dragId === '' && state.pending === 0)
assert.equal(dropped.dragPhase, '')
restarted = await startServer({
stateDir: server.stateDir,
port: server.port,
publicOrigin: server.publicOrigin,
})
await waitForBadge(page, 'connected', 60000)
await waitForRender(page, state => state.ids.includes(token))
const resumed = await waitForRender(
page,
state => Math.abs(state.positions[token]?.[0] - 470) <= 2 && state.dragPhase === '',
)
assert.deepEqual(resumed.positions[token], [470, 400], 'the resync is the server position')
assert.equal(resumed.pending, 0)
await page.mouse.up() // the stale release must not send a move onto the new connection
await sleep(150)
const after = await renderState(page)
assert.deepEqual(after.positions[token], [470, 400])
} finally {
if (restarted) await stopServer(restarted)
gm.ws.close()
await browser.close()
}
})
})
+35
View File
@@ -0,0 +1,35 @@
// The one way a render module sends an intent (#72). Render modules are mounted by the stage with
// no socket of their own; this module is the tiny, replaceable bridge to the session's protocol
// client. `main.ts` installs the live client on connect and clears it on teardown.
//
// The callback exists because a `token.move` ack is matched by `reqId`, not by token id (6.1):
// the move slice records the `reqId` the socket assigned, then the ack frame finds it. Keeping the
// callback here means the drag module never knows the counter and the protocol client stays pure.
import type { AckFrame } from './protocol.ts'
export type IntentSender = (
t: string,
fields?: Record<string, unknown>,
onReqId?: (reqId: number) => void,
) => Promise<AckFrame>
let sender: IntentSender | null = null
export function setIntentSender(next: IntentSender | null): void {
sender = next
}
/**
* Send one intent, or reject when there is no live session (a drag that raced a disconnect). The
* optional `onReqId` runs only after the frame actually left the socket, so a failed send never
* leaves a pending entry that no ack can settle.
*/
export function sendIntent(
t: string,
fields: Record<string, unknown> = {},
onReqId?: (reqId: number) => void,
): Promise<AckFrame> {
if (!sender) return Promise.reject(new Error('not connected'))
return sender(t, fields, onReqId)
}
+6
View File
@@ -10,6 +10,7 @@ import { mountCastPanel } from './panels/gmcast.ts'
import type { Stage } from './render/stage.ts'
import { createStage } from './render/stage.ts'
import type { RootState } from './reducer.ts'
import { setIntentSender } from './intents.ts'
const KEY_REFUSED = 'Key not recognised.'
@@ -114,6 +115,11 @@ function connect(): void {
store.dispatch(event)
},
})
// Render modules (the drag, #72) send through this bridge; it is the same client every other
// intent uses, so `reqId` ordering and the pending map stay in one place.
setIntentSender((t, fields, onReqId) =>
client ? client.send(t, fields, onReqId) : Promise.reject(new Error('not connected')),
)
client.connect()
}
+14
View File
@@ -13,6 +13,7 @@ import type {
RosterEntry,
SceneInfo,
ServerFrame,
Vec2,
} from './protocol.ts'
import { closeOutcome, isClosing, isHello } from './protocol.ts'
@@ -68,6 +69,19 @@ export type ReducerEvent =
| { type: 'signed-out' }
/** GM token panel selection (#74); slices own the state, the core just carries the event. */
| { type: 'admin-select'; token: string | null }
/**
* Drag prediction (#72). The drag render module turns pointer input into these events; the move
* slice owns the optimistic position, the pending `reqId` map and the rollback tween. Keeping
* them in the reducer means the token renderer only reads state, and the state machine is tested
* without a DOM or a socket (DESIGN 7.5).
*/
| { type: 'drag-start'; id: string; pos: Vec2 }
| { type: 'drag-move'; id: string; pos: Vec2 }
| { type: 'drag-end'; id: string; pos: Vec2 }
/** One `token.move` intent left the socket; its ack is matched by `reqId` (6.3). */
| { type: 'move-sent'; reqId: number; id: string; pos: Vec2 }
/** The renderer finished the cosmetic rollback tween for this token. */
| { type: 'rollback-done'; id: string; seq: number }
/**
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
+148
View File
@@ -0,0 +1,148 @@
// Drag own tokens with prediction and rollback (T9, #72; DESIGN 7.4 input, 7.5, 5.5, 6.4).
//
// Hand-rolled DOM pointer events on the canvas (DESIGN 7.2: Pixi federated events are off). The
// listener sits on `window` in the capture phase and only starts a drag when the press lands on
// the canvas *and* on a token this session may move. When it does, propagation is stopped, so the
// camera's pan/pinch (#69), which listens at the canvas, never sees the gesture: a token drag takes
// precedence over pan exactly when the pointer starts on a token the user controls.
//
// The module owns input only. Prediction lives in `slices/move.ts` (a `reqId`-keyed pending map and
// the rollback state machine); the token renderer draws the optimistic position. Sends are capped
// at 20 Hz (DESIGN 6.4) plus one final position on release, each through the session's protocol
// client (`intents.ts`) so the ack can be matched by `reqId`.
import type { RenderContext, RenderModule } from '../stage.ts'
import type { Vec2 } from '../../protocol.ts'
import { sendIntent } from '../../intents.ts'
import { dragOf, draggableAt } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
/** 20 Hz while dragging (DESIGN 6.4, FIXED #15); the release always sends. */
export const MOVE_SEND_INTERVAL_MS = 50
interface ActiveDrag {
id: string
pointerId: number
/** `performance.now()` of the last intent; 0 so the first move is sent at once. */
lastSent: number
}
export const renderModule: RenderModule = {
name: 'drag',
mount({ app, layers, store }: RenderContext): () => void {
const canvas = app.canvas
let active: ActiveDrag | null = null
/** Canvas CSS pixels -> the tokens layer's world coordinates (the camera's inverse, #69). */
function worldPointOf(event: PointerEvent): Vec2 {
const rect = canvas.getBoundingClientRect()
const local = layers.tokens.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
return [local.x, local.y]
}
function send(id: string, pos: Vec2): void {
try {
const pending = sendIntent('token.move', { id, pos: [pos[0], pos[1]] }, reqId => {
// The slice records the intent first; the ack frame that follows finds it by `reqId`.
store.dispatch({ type: 'move-sent', reqId, id, pos })
})
// A refused/unreachable send has no pending entry (onReqId never ran) and nothing to undo.
pending.catch(() => undefined)
} catch {
// `sendIntent` rejects rather than throws, but a drag must never break the render loop.
}
}
function detach(): void {
window.removeEventListener('pointermove', onMove, true)
window.removeEventListener('pointerup', onUp, true)
window.removeEventListener('pointercancel', onCancel, true)
window.removeEventListener('blur', onCancel)
}
function stop(): void {
active = null
detach()
}
function onDown(event: PointerEvent): void {
if (active !== null) return
// Only the primary pointer over the canvas itself; DOM panels keep their clicks.
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
const state = store.state
if (state.connection.phase !== 'live') return
const point = worldPointOf(event)
const token = draggableAt(tokensOf(state), state.session.role, point)
if (!token) return
// A token drag wins over pan/pinch (#69): the camera's listener never sees this gesture.
event.preventDefault()
event.stopImmediatePropagation()
active = { id: token.id, pointerId: event.pointerId, lastSent: 0 }
store.dispatch({ type: 'drag-start', id: token.id, pos: token.pos })
window.addEventListener('pointermove', onMove, true)
window.addEventListener('pointerup', onUp, true)
window.addEventListener('pointercancel', onCancel, true)
window.addEventListener('blur', onCancel)
}
function onMove(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
// A reconnect (`hello`/`close`) reset the slice under us: stop sending stale intents.
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
event.preventDefault()
event.stopImmediatePropagation()
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-move', id: drag.id, pos })
const now = performance.now()
if (now - drag.lastSent >= MOVE_SEND_INTERVAL_MS) {
drag.lastSent = now
send(drag.id, pos)
}
}
function onUp(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
event.preventDefault()
event.stopImmediatePropagation()
// A reconnect (or the server dropping the token) already ended this drag: do not send a
// final intent that belongs to the dead connection (6.3).
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-end', id: drag.id, pos })
stop()
// The final position always goes out (6.4); a dud has its own ack and may rate-limit.
send(drag.id, pos)
}
function onCancel(event: Event): void {
const drag = active
if (drag === null) return
if (event.type === 'pointercancel') {
const pointer = event as PointerEvent
if (pointer.pointerId !== drag.pointerId) return
}
const current = dragOf(store.state)
if (current?.id === drag.id) {
store.dispatch({ type: 'drag-end', id: drag.id, pos: current.pos })
}
stop()
}
// Capture on `window` beats every listener attached to the canvas (#69's pan included).
window.addEventListener('pointerdown', onDown, true)
return () => {
window.removeEventListener('pointerdown', onDown, true)
stop()
}
},
}
+116 -12
View File
@@ -12,8 +12,12 @@
import { BitmapFont, BitmapText, Container, Graphics, GraphicsContext } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import type { RootState } from '../../reducer.ts'
import type { Vec2 } from '../../protocol.ts'
import { TokenBoard } from '../tokenBoard.ts'
import type { TokenPatch } from '../tokenBoard.ts'
import { drawPositionOf, moveOf, rollbacksOf } from '../../slices/move.ts'
import type { RollbackTween } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
import type { TokenView } from '../../slices/tokens.ts'
@@ -170,7 +174,14 @@ function applyView(
}
/** Publish the renderer's own counts, so the e2e can observe "only changed entities touched". */
function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch, labels: number): void {
function publish(
canvas: HTMLCanvasElement,
board: TokenBoard,
patch: TokenPatch,
labels: number,
state: RootState,
nodes: ReadonlyMap<string, TokenNode>,
): void {
const datasets = canvas.dataset
datasets['tokens'] = String(board.size)
datasets['tokenEntered'] = String(patch.entered.length)
@@ -181,8 +192,34 @@ function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch
datasets['tokenStatuses'] = [...board.views.values()]
.flatMap(view => view.statuses.map(status => `${view.id}:${status}`))
.join(' ')
// The drag renderer's instrumentation (#72): the drawn position (so the e2e reads what the
// browser shows, not what the reducer predicts) plus the move state machine's counters.
datasets['tokenPositions'] = [...nodes.entries()]
.map(([id, node]) => `${id}:${Math.round(node.container.x)},${Math.round(node.container.y)}`)
.join(' ')
const move = moveOf(state)
datasets['dragId'] = move.drag?.id ?? ''
datasets['dragPos'] = move.drag
? `${Math.round(move.drag.pos[0])},${Math.round(move.drag.pos[1])}`
: ''
datasets['dragPhase'] = move.drag !== null ? 'drag' : Object.keys(move.rollbacks).length > 0 ? 'rollback' : ''
datasets['dragPending'] = String(move.pending.length)
datasets['dragRefused'] = String(move.refused)
datasets['dragRateLimited'] = String(move.rateLimited)
datasets['dragRollbacks'] = String(move.rollbackCount)
datasets['dragDropped'] = String(move.dropped)
}
/** Cosmetic rollback tween (DESIGN 7.5: a short slide back, never a teleport). */
const ROLLBACK_MS = 280
interface ActiveTween {
rb: RollbackTween
from: Vec2
started: number
}
export const renderModule: RenderModule = {
name: 'tokens',
mount(context: RenderContext): (() => void) | void {
@@ -193,32 +230,99 @@ export const renderModule: RenderModule = {
const pool: TokenNode[] = []
const nodes = new Map<string, TokenNode>()
const stats = { labels: 0 }
/** At most one cosmetic rollback per token; keyed by token id, replaced on a newer sequence. */
const tweens = new Map<string, ActiveTween>()
function removeNode(id: string): void {
const node = nodes.get(id)
if (!node) return
tweens.delete(id)
layers.tokens.removeChild(node.container)
node.container.visible = false
nodes.delete(id)
pool.push(node)
}
function enterNode(view: TokenView): void {
function atFor(state: RootState, view: TokenView, node: TokenNode): Vec2 {
// A rollback tween owns the sprite position while it runs; a drag/pending prediction owns it
// otherwise (7.5); with neither, the authoritative `token` frame is the truth.
if (tweens.has(view.id)) return [node.container.x, node.container.y]
return drawPositionOf(state, view.id) ?? view.pos
}
function enterNode(view: TokenView, state: RootState): void {
const node = pool.pop() ?? createNode(view.radius)
node.container.visible = true
applyView(node, view, stats)
applyView(node, view, stats, atFor(state, view, node))
layers.tokens.addChild(node.container)
nodes.set(view.id, node)
}
/**
* Apply the reducer's drag/rollback state to the sprites. Touches only a dragged token and the
* tokens with a pending tween, so a pointer move never walks the whole scene (DESIGN 7.2).
*/
function applyMovement(state: RootState, now: number): void {
const move = moveOf(state)
if (move.drag) {
const node = nodes.get(move.drag.id)
if (node) {
tweens.delete(move.drag.id)
node.container.position.set(move.drag.pos[0], move.drag.pos[1])
}
}
const active = rollbacksOf(state)
const current = new Set<string>()
for (const rb of active) {
current.add(rb.id)
const node = nodes.get(rb.id)
if (!node) continue
const existing = tweens.get(rb.id)
if (existing?.rb.seq === rb.seq) continue
tweens.set(rb.id, {
rb,
from: [node.container.x, node.container.y],
started: now,
})
}
// A tween the reducer no longer knows about (a new drag, a reset) is done.
for (const id of [...tweens.keys()]) {
if (!current.has(id) || !nodes.has(id)) tweens.delete(id)
}
}
function tick(): void {
if (tweens.size === 0) return
const now = performance.now()
for (const [id, tween] of tweens) {
const node = nodes.get(id)
if (!node) {
tweens.delete(id)
continue
}
const t = Math.min(1, (now - tween.started) / ROLLBACK_MS)
const eased = 1 - (1 - t) * (1 - t) * (1 - t) // ease-out cubic
node.container.position.set(
tween.from[0] + (tween.rb.to[0] - tween.from[0]) * eased,
tween.from[1] + (tween.rb.to[1] - tween.from[1]) * eased,
)
if (t >= 1) {
tweens.delete(id)
store.dispatch({ type: 'rollback-done', id, seq: tween.rb.seq })
}
}
publish(canvas, board, { reset: false, entered: [], updated: [], left: [] }, stats.labels, store.state, nodes)
}
// The stage is created only once the session is live, but `app.init` is async and the resync
// can beat it: start from whatever the reducer already holds, then follow the event stream.
board.seed(tokensOf(store.state))
let patch = board.drain()
for (const view of patch.entered) enterNode(view)
publish(canvas, board, patch, stats.labels)
for (const view of patch.entered) enterNode(view, store.state)
publish(canvas, board, patch, stats.labels, store.state, nodes)
app.ticker.add(tick)
const unsubscribe = store.subscribe((_state, event) => {
const unsubscribe = store.subscribe((state, event) => {
board.apply(event)
patch = board.drain()
if (patch.reset) {
@@ -227,17 +331,17 @@ export const renderModule: RenderModule = {
for (const id of patch.left) removeNode(id)
for (const view of patch.updated) {
const node = nodes.get(view.id)
if (node) applyView(node, view, stats)
else enterNode(view)
}
for (const view of patch.entered) enterNode(view)
if (patch.reset || patch.entered.length > 0 || patch.updated.length > 0 || patch.left.length > 0) {
publish(canvas, board, patch, stats.labels)
if (node) applyView(node, view, stats, atFor(state, view, node))
else enterNode(view, state)
}
for (const view of patch.entered) enterNode(view, state)
applyMovement(state, performance.now())
publish(canvas, board, patch, stats.labels, state, nodes)
})
return () => {
unsubscribe()
app.ticker.remove(tick)
}
},
}
+331
View File
@@ -0,0 +1,331 @@
// Move prediction and rollback (T9, #72; DESIGN 7.5, 5.5, 6.4). The pure half of the drag: pointer
// input becomes `drag-*` events, each `token.move` intent is remembered by `reqId`, and the acks
// decide whether the optimistic position stands or slides back. No Pixi, no DOM, no socket.
//
// The contract is DESIGN 7.5:
// - while dragging, the sprite follows the pointer and authoritative positions for that token are
// ignored for drawing (they keep arriving in the tokens slice, unmodified);
// - `ack{ok:true}` confirms the requested position, which the server's `token` frame repeats;
// - the uniform move nack (`ok:false` with `pos`, no `code`) rolls back: at once when idle, on
// release when the finger is still down;
// - `ack{ok:false, code:"rate-limited"}` is dropped quietly: the optimistic position is discarded
// and the next authoritative frame reconciles the view (6.4);
// - pending requests die with the connection (6.3).
//
// Append-only registration: adding this file was enough; the reducer's glob picked it up and
// `hello` resets it with every other slice.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { isAck } from '../protocol.ts'
import type { TokenView } from './tokens.ts'
import { tokensOf } from './tokens.ts'
export interface DragState {
id: string
/** Where the token was when the drag began (the server's last position). */
origin: Vec2
/** The optimistic position under the pointer; the renderer draws here. */
pos: Vec2
}
export interface MovePending {
reqId: number
id: string
pos: Vec2
}
/** A refused move while the finger is still down: snap there on release, never under the finger. */
export interface MoveSnap {
id: string
pos: Vec2
}
export interface RollbackTween {
/** Monotonic id so the renderer can report the exact tween it finished. */
seq: number
id: string
from: Vec2
to: Vec2
}
export interface MoveState {
drag: DragState | null
/** `token.move` intents awaiting their ack, in send order (the server acks in order). */
pending: MovePending[]
snap: MoveSnap | null
/** Cosmetic rollbacks the renderer is sliding; keyed by token id, newest per token wins. */
rollbacks: Record<string, RollbackTween>
/** Confirmed positions kept until the matching `token` frame lands (ack precedes the frame). */
confirmed: Record<string, Vec2>
seq: number
/** Counters for the browser e2e's instrumentation and for the unit tests. */
accepted: number
refused: number
rateLimited: number
/** Pending intents thrown away because the connection closed (6.3). */
dropped: number
rollbackCount: number
}
const EMPTY: MoveState = {
drag: null,
pending: [],
snap: null,
rollbacks: {},
confirmed: {},
seq: 0,
accepted: 0,
refused: 0,
rateLimited: 0,
dropped: 0,
rollbackCount: 0,
}
export function initMove(): MoveState {
return { ...EMPTY, pending: [], rollbacks: {}, confirmed: {} }
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function copy(pos: Vec2): Vec2 {
return [pos[0], pos[1]]
}
/** The newest pending intent for one token, or null. */
function latestPending(state: MoveState, id: string): MovePending | null {
let found: MovePending | null = null
for (const entry of state.pending) {
if (entry.id === id && (found === null || entry.reqId > found.reqId)) found = entry
}
return found
}
function hasNewerPending(state: MoveState, id: string, reqId: number): boolean {
return state.pending.some(entry => entry.id === id && entry.reqId > reqId)
}
function startRollback(state: MoveState, id: string, from: Vec2, to: Vec2): void {
state.seq += 1
state.rollbackCount += 1
state.rollbacks = {
...state.rollbacks,
[id]: { seq: state.seq, id, from: copy(from), to: copy(to) },
}
}
export const slice: Slice<MoveState> = {
name: 'move',
init: initMove,
reduce(state: MoveState, event: ReducerEvent, root: RootState): void {
switch (event.type) {
case 'drag-start': {
// A new drag is a new prediction: any pending snap or tween for this token is obsolete.
state.drag = { id: event.id, origin: copy(event.pos), pos: copy(event.pos) }
state.snap = null
if (state.rollbacks[event.id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
}
delete state.confirmed[event.id]
return
}
case 'drag-move': {
if (state.drag?.id !== event.id) return
state.drag = { ...state.drag, pos: copy(event.pos) }
return
}
case 'drag-end': {
if (state.drag?.id !== event.id) return
state.drag = null
// A refusal seen during the drag is settled on release (7.5): its ack handler starts the
// tween from the released position. Nothing to do here but keep the snap for that ack.
return
}
case 'move-sent': {
state.pending = [
...state.pending.filter(entry => entry.reqId !== event.reqId),
{ reqId: event.reqId, id: event.id, pos: copy(event.pos) },
]
return
}
case 'rollback-done': {
const tween = state.rollbacks[event.id]
if (tween?.seq !== event.seq) return
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
return
}
case 'close': {
// 6.3: pending reqIds are dropped with the connection; no ack will ever arrive.
state.dropped += state.pending.length
state.pending = []
state.drag = null
state.snap = null
state.rollbacks = {}
state.confirmed = {}
return
}
case 'frame': {
const frame = event.frame
if (frame.t === 'token') {
// The server remains the judge (story 39): its frame wins for drawing once no drag or
// pending intent covers the token. Any frame settles a confirmed position.
const id = frame['id']
if (typeof id !== 'string') return
// A frame during a cosmetic rollback does not cancel the tween: the ack that produced it
// already gave the authoritative position, and the renderer only animates the sprite.
delete state.confirmed[id]
return
}
if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string') return
if (state.drag?.id === id) state.drag = null
if (state.snap?.id === id) state.snap = null
state.pending = state.pending.filter(entry => entry.id !== id)
delete state.confirmed[id]
if (state.rollbacks[id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[id]
state.rollbacks = rollbacks
}
return
}
if (isAck(frame)) {
applyAck(root, state, frame)
}
return
}
}
},
}
function applyAck(root: RootState, state: MoveState, frame: AckFrame): void {
const index = state.pending.findIndex(entry => entry.reqId === frame.reqId)
if (index < 0) return // an intent this slice does not own (admin, name, ...)
const entry = state.pending[index]!
// What the sprite shows right now, before the pending entry is removed (7.5 rollback tween).
const shown = drawPositionOf(root, entry.id) ?? entry.pos
const snap = state.snap?.id === entry.id ? state.snap : null
state.pending = state.pending.filter(item => item.reqId !== frame.reqId)
if (frame.ok) {
state.accepted += 1
if (state.snap?.id === entry.id) state.snap = null
// Ack then the token frame (settleLocked); hold the confirmed position for the frame so the
// sprite never blinks back to the pre-move position for one dispatch.
state.confirmed = {
...state.confirmed,
[entry.id]: isVec2(frame.pos) ? copy(frame.pos) : copy(entry.pos),
}
return
}
if (frame.code === 'rate-limited') {
// 6.4: refused by the bucket, never applied, no position to roll back to. Drop quietly and let
// the next frame (or the next drag sample) reconcile; dragging keeps its optimistic position.
state.rateLimited += 1
if (state.snap?.id === entry.id) state.snap = null
if (state.drag?.id !== entry.id) {
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
return
}
if (!isVec2(frame.pos)) return // a malformed nack cannot move the sprite
// A newer intent is already in flight; its ack decides. Acks arrive in order, so ignore this one.
if (hasNewerPending(state, entry.id, entry.reqId)) return
state.refused += 1
if (state.drag?.id === entry.id) {
// 7.5: do not teleport under the finger; snap on release.
state.snap = { id: entry.id, pos: copy(frame.pos) }
return
}
// Idle: slide back from the predicted position to the server's old position (story 40).
startRollback(state, entry.id, snap ? entry.pos : shown, frame.pos)
if (state.snap?.id === entry.id) state.snap = null
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
/** The move slice, or an empty one before the registry has run (unit helpers stay total). */
export function moveOf(state: RootState): MoveState {
return (state.slices['move'] as MoveState | undefined) ?? EMPTY
}
/**
* The position the token renderer must draw at, or null when the authoritative `token` frame is
* the truth. Precedence: under the finger, then the newest pending request, then a confirmed ack
* whose `token` frame has not arrived yet (DESIGN 7.2's `at` parameter, 7.5).
*/
export function drawPositionOf(state: RootState, id: string): Vec2 | null {
const move = moveOf(state)
if (move.drag?.id === id) return move.drag.pos
const pending = latestPending(move, id)
if (pending) return pending.pos
const confirmed = move.confirmed[id]
if (confirmed) return confirmed
return null
}
/** True while the pointer owns this token: its authoritative frames must not move the sprite. */
export function isDragging(state: RootState, id: string): boolean {
return moveOf(state).drag?.id === id
}
/** The rollbacks the renderer should be tweening, newest sequence first. */
export function rollbacksOf(state: RootState): RollbackTween[] {
return Object.values(moveOf(state).rollbacks)
}
/** The active drag (the module's own state machine), if any. */
export function dragOf(state: RootState): DragState | null {
return moveOf(state).drag
}
/**
* O(N) hit test on press only (DESIGN 7.2): the topmost token this recipient may move whose circle
* contains the world point. Players move only their own tokens; the GM moves any token (story 43).
* GM frames say `mine:false`, so the role check is what makes a GM drag work.
*/
export function draggableAt(
tokens: readonly TokenView[],
role: 'gm' | 'player' | null,
point: Vec2,
): TokenView | null {
if (role === null) return null
for (let index = tokens.length - 1; index >= 0; index -= 1) {
const token = tokens[index]
if (!token) continue
if (role !== 'gm' && !token.mine) continue
const dx = point[0] - token.pos[0]
const dy = point[1] - token.pos[1]
if (dx * dx + dy * dy <= token.radius * token.radius) return token
}
return null
}
/** The tokens a drag may start on, for the shell/e2e; not a secrecy filter (the server already is). */
export function draggableTokens(state: RootState): TokenView[] {
const role = state.session.role
if (role === null) return []
return tokensOf(state).filter(token => role === 'gm' || token.mine)
}
+9 -1
View File
@@ -187,8 +187,15 @@ export class ProtocolClient {
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
* `hello` on a live connection does not drop them.
*
* `onReqId` is told the request id once the frame has left the socket, so a caller that must
* match the ack itself (the drag's `token.move`, #72) can record it before the reply can arrive.
*/
send(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame> {
send(
t: string,
fields: Record<string, unknown> = {},
onReqId?: (reqId: number) => void,
): Promise<AckFrame> {
const socket = this.#socket
if (this.#state !== 'open' || !socket) {
return Promise.reject(new Error('not connected'))
@@ -199,6 +206,7 @@ export class ProtocolClient {
this.#pending.set(reqId, { resolve, reject })
try {
socket.send(frame)
onReqId?.(reqId)
} catch (error) {
this.#pending.delete(reqId)
reject(error instanceof Error ? error : new Error(String(error)))
+284
View File
@@ -0,0 +1,284 @@
// T9 (#72): the drag state machine at the reducer seam (DESIGN 7.5, 5.5, 6.4). Every test drives
// the same events the drag render module and the socket produce, then reads what the token renderer
// would draw. No DOM, no GPU, no socket.
import { describe, expect, it } from 'vitest'
import { initialState, reduce } from '../src/reducer.ts'
import type { ReducerEvent, RootState } from '../src/reducer.ts'
import { parseServerFrame } from '../src/protocol.ts'
import { tokenOf, tokensOf } from '../src/slices/tokens.ts'
import type { TokenView } from '../src/slices/tokens.ts'
import {
draggableAt,
draggableTokens,
dragOf,
drawPositionOf,
moveOf,
} from '../src/slices/move.ts'
const frame = (body: Record<string, unknown>): ReducerEvent => {
const parsed = parseServerFrame(JSON.stringify(body))
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
return { type: 'frame', frame: parsed }
}
const hello = (n = 1): ReducerEvent =>
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } })
const token = (n: number, id: string, overrides: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n,
id,
scene: 1,
name: 'Ann',
pos: [400, 400],
radius: 20,
mine: true,
statuses: [],
props: {},
...overrides,
})
const ack = (n: number, reqId: number, ok: boolean, extra: Record<string, unknown> = {}): ReducerEvent =>
frame({ t: 'ack', n, reqId, ok, ...extra })
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
/** The initial live view: one controlled token at 400,400 and one another player controls. */
const live = (): ReducerEvent[] => [
{ type: 'connecting' },
hello(),
token(2, 'own'),
token(3, 'other', { mine: false, pos: [800, 400] }),
]
describe('optimistic drag (stories 38, 39, 41)', () => {
it('draws the token under the pointer and ignores authoritative frames while dragging', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [450, 430] })
expect(drawPositionOf(state, 'own')).toEqual([450, 430])
expect(dragOf(state)?.id).toBe('own')
// Story 41: a slow ack/authoritative frame must not move the sprite under the finger.
state = reduce(state, token(4, 'own', { pos: [400, 400] }))
expect(drawPositionOf(state, 'own')).toEqual([450, 430])
// The reducer still keeps what the server said; only drawing is overridden.
expect(tokenOf(state, 'own')?.pos).toEqual([400, 400])
})
it('tracks the last pointer position; the input module decides which tokens may start a drag', () => {
let state = run(...live())
// The slice is a mechanical state machine: `draggableAt` (tested below) is the permission gate,
// and the server still refuses a move of someone else's token (story 39) with a nack.
expect(draggableAt(tokensOf(state), 'player', [800, 400])).toBeNull()
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [410, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [420, 410] })
expect(drawPositionOf(state, 'own')).toEqual([420, 410])
// A drag-move for another id is ignored while this drag is active.
state = reduce(state, { type: 'drag-move', id: 'other', pos: [820, 400] })
expect(dragOf(state)?.id).toBe('own')
expect(drawPositionOf(state, 'other')).toBeNull()
})
})
describe('ack reconciliation and rollback (stories 39, 40, 42)', () => {
it('holds the predicted position until the authoritative frame after an ok ack', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [460, 400] })
state = reduce(state, { type: 'move-sent', reqId: 7, id: 'own', pos: [460, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [460, 400] })
expect(dragOf(state)).toBeNull()
expect(drawPositionOf(state, 'own')).toEqual([460, 400])
// The ack precedes the token frame (settleLocked): keep drawing the confirmed position.
state = reduce(state, ack(5, 7, true, { pos: [460, 400] }))
expect(moveOf(state).pending).toEqual([])
expect(drawPositionOf(state, 'own')).toEqual([460, 400])
expect(moveOf(state).accepted).toBe(1)
expect(moveOf(state).rollbacks).toEqual({})
// The frame lands: the prediction is no longer needed.
state = reduce(state, token(6, 'own', { pos: [460, 400] }))
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('rolls back a uniform nack while idle, and clears the tween when the renderer is done', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [640, 400] })
state = reduce(state, { type: 'move-sent', reqId: 8, id: 'own', pos: [640, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [640, 400] })
// The uniform nack (5.5): ok:false, the old position, no code.
state = reduce(state, ack(5, 8, false, { pos: [400, 400] }))
const move = moveOf(state)
expect(move.pending).toEqual([])
expect(move.refused).toBe(1)
expect(move.rollbackCount).toBe(1)
const rollback = move.rollbacks['own']
expect(rollback).toBeDefined()
expect(rollback).toMatchObject({ id: 'own', from: [640, 400], to: [400, 400] })
// No pending intent remains, so the draw falls through to the authoritative frame.
expect(drawPositionOf(state, 'own')).toBeNull()
state = reduce(state, { type: 'rollback-done', id: 'own', seq: rollback!.seq })
expect(moveOf(state).rollbacks).toEqual({})
// A stale completion cannot clear a newer tween.
state = reduce(state, ack(6, 8, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks).toEqual({})
})
it('does not snap under the finger: a nack while dragging rolls back on release', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [600, 400] })
state = reduce(state, { type: 'move-sent', reqId: 9, id: 'own', pos: [600, 400] })
state = reduce(state, ack(5, 9, false, { pos: [400, 400] }))
// Still under the pointer, still at the pointer; the snap is remembered for release.
expect(drawPositionOf(state, 'own')).toEqual([600, 400])
expect(moveOf(state).snap).toEqual({ id: 'own', pos: [400, 400] })
expect(moveOf(state).rollbacks).toEqual({})
state = reduce(state, { type: 'drag-move', id: 'own', pos: [610, 410] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [610, 410] })
// The release sends the final position; its nack starts the tween from where the finger was.
state = reduce(state, { type: 'move-sent', reqId: 10, id: 'own', pos: [610, 410] })
state = reduce(state, ack(6, 10, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks['own']).toMatchObject({
from: [610, 410],
to: [400, 400],
})
expect(moveOf(state).snap).toBeNull()
})
it('lets a later accepted intent win over an earlier refusal', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [800, 400] })
state = reduce(state, { type: 'move-sent', reqId: 11, id: 'own', pos: [800, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [500, 400] })
state = reduce(state, { type: 'move-sent', reqId: 12, id: 'own', pos: [500, 400] })
// The first (over-cap) intent is refused while the second is in flight: no tween yet.
state = reduce(state, ack(5, 11, false, { pos: [400, 400] }))
expect(moveOf(state).rollbacks).toEqual({})
expect(moveOf(state).snap).toBeNull()
expect(drawPositionOf(state, 'own')).toEqual([500, 400])
state = reduce(state, ack(6, 12, true, { pos: [500, 400] }))
expect(moveOf(state).accepted).toBe(1)
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).rollbacks).toEqual({})
})
it('drops a rate-limited intent quietly and reconciles with the next frame (story 42)', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'move-sent', reqId: 13, id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [430, 400] })
// 6.4: refused by the bucket, no position, no rollback, connection stays open.
state = reduce(state, ack(5, 13, false, { code: 'rate-limited' }))
expect(moveOf(state).rateLimited).toBe(1)
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).rollbacks).toEqual({})
expect(drawPositionOf(state, 'own')).toBeNull()
// The next authoritative frame is the reconciliation; a drag continues from it, not from a
// corrupted map.
state = reduce(state, token(6, 'own', { pos: [420, 400] }))
expect(tokenOf(state, 'own')?.pos).toEqual([420, 400])
state = reduce(state, { type: 'drag-start', id: 'own', pos: [420, 400] })
state = reduce(state, { type: 'drag-move', id: 'own', pos: [440, 400] })
expect(drawPositionOf(state, 'own')).toEqual([440, 400])
})
it('ignores acks for intents this slice does not own', () => {
let state = run(...live())
state = reduce(state, ack(5, 99, false, { pos: [1, 1] }))
expect(moveOf(state).refused).toBe(0)
expect(moveOf(state).pending).toEqual([])
})
})
describe('pending map lifecycle (6.3)', () => {
it('drops every pending reqId, drag and tween when the connection closes', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'move-sent', reqId: 20, id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'drag-end', id: 'own', pos: [430, 400] })
state = reduce(state, { type: 'move-sent', reqId: 21, id: 'own', pos: [440, 400] })
expect(moveOf(state).pending).toHaveLength(2)
state = reduce(state, { type: 'close', reason: null, code: 1006 })
const move = moveOf(state)
expect(move.pending).toEqual([])
expect(move.dropped).toBe(2)
expect(move.drag).toBeNull()
expect(move.rollbacks).toEqual({})
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('drops pending intents on hello (the full resync resets every slice)', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, { type: 'move-sent', reqId: 30, id: 'own', pos: [430, 400] })
state = reduce(state, hello(10))
expect(moveOf(state).pending).toEqual([])
expect(moveOf(state).drag).toBeNull()
expect(drawPositionOf(state, 'own')).toBeNull()
})
it('stops a drag when its token leaves the view', () => {
let state = run(...live())
state = reduce(state, { type: 'drag-start', id: 'own', pos: [400, 400] })
state = reduce(state, frame({ t: 'token_gone', n: 4, id: 'own' }))
expect(moveOf(state).drag).toBeNull()
expect(drawPositionOf(state, 'own')).toBeNull()
})
})
describe('hit test and permission (stories 38, 43)', () => {
const view = (id: string, mine: boolean, pos: [number, number]): TokenView => ({
id,
scene: 1,
name: id,
pos,
radius: 20,
mine,
statuses: [],
props: {},
gmOnly: false,
kind: null,
controller: null,
characterId: null,
})
const views = [view('a', true, [100, 100]), view('b', false, [200, 100])]
it('picks the topmost token under the pointer that the role may move', () => {
expect(draggableAt(views, 'player', [100, 100])?.id).toBe('a')
expect(draggableAt(views, 'player', [200, 100])).toBeNull()
expect(draggableAt(views, 'gm', [200, 100])?.id).toBe('b')
expect(draggableAt(views, 'player', [150, 150])).toBeNull()
expect(draggableAt(views, null, [100, 100])).toBeNull()
})
it('lists what the session may drag: its own tokens, or every token for the GM', () => {
let state = run(...live())
expect(draggableTokens(state).map(item => item.id)).toEqual(['own'])
state = run(
{ type: 'connecting' },
frame({ t: 'hello', n: 1, proto: 2, role: 'gm', me: { id: 1, name: 'GM' } }),
token(2, 'own', { mine: false }),
token(3, 'other', { mine: false }),
)
expect(tokensOf(state)).toHaveLength(2)
expect(draggableTokens(state).map(item => item.id)).toEqual(['own', 'other'])
})
})
+19
View File
@@ -85,6 +85,25 @@ describe('protocol client', () => {
expect(client.pendingCount).toBe(0)
})
it('tells the caller the reqId after the frame left the socket (#72)', async () => {
const { client, socket } = connect()
const seen: number[] = []
const pending = client.send('token.move', { id: 'aaa', pos: [10, 20] }, reqId => {
// The callback runs only once the frame is on the wire, so recording it cannot outrun send.
expect(socket.sent).toHaveLength(1)
seen.push(reqId)
})
expect(seen).toEqual([1])
expect(JSON.parse(socket.sent[0] ?? '{}')).toMatchObject({
t: 'token.move',
reqId: 1,
id: 'aaa',
pos: [10, 20],
})
socket.receive({ t: 'ack', n: 1, reqId: 1, ok: true, pos: [10, 20] })
await expect(pending).resolves.toMatchObject({ ok: true })
})
it('keeps pending requests across a hello on a live connection (6.3)', async () => {
const { client, socket } = connect()
const pending = client.send('player.setname', { name: 'Ann' })