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()
}
})
})