// 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)}`) } /** The world is 4096 px; the camera starts centred, so this is the middle of the screen at zoom 1. */ const CENTRE = [2048, 2048] /** Canvas rect plus the world container's transform (#69): `screen = world * zoom + camera.xy`. */ async function viewOf(page) { return page.evaluate(() => { const canvas = document.querySelector('#stage canvas') if (!canvas) throw new Error('no canvas') const rect = canvas.getBoundingClientRect() const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number) return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') } }) } /** Page coordinates of a world point, through the camera at any zoom (no 1:1 assumption). */ async function screenOf(page, world) { const view = await viewOf(page) return { x: view.left + world[0] * view.zoom + view.x, y: view.top + world[1] * view.zoom + view.y, } } /** Wheel-zoom around `anchorWorld`, keeping that point under the pointer; read the clamped zoom. */ async function zoomTo(page, zoom, anchorWorld) { for (let attempt = 0; attempt < 30; attempt += 1) { const view = await viewOf(page) if (Math.abs(view.zoom - zoom) < 1e-9) return view.zoom const point = await screenOf(page, anchorWorld) await page.mouse.move(point.x, point.y) await page.mouse.wheel(0, view.zoom < zoom ? -250 : 250) await sleep(40) } const view = await viewOf(page) throw new Error(`zoom never reached ${zoom}, stuck at ${view.zoom}`) } /** 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 start = await screenOf(page, from) await page.mouse.move(start.x, start.y) 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 const point = await screenOf(page, [x, y]) await page.mouse.move(point.x, point.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 = CENTRE) { 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, CENTRE, [2148, 2108]) // 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] - 2148) <= 2 && Math.abs(message.pos[1] - 2108) <= 2, 10000, ) assert.deepEqual(frame.pos, [2148, 2108]) const settled = await waitForRender( page, view => Math.abs(view.positions[token]?.[0] - 2148) <= 2 && Math.abs(view.positions[token]?.[1] - 2108) <= 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] - 2148) <= 2 && Math.abs(view.positions[token]?.[1] - 2108) <= 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, [2148, 2108]) } 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: [2248, 1948], b: [2248, 2148], }) 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, CENTRE, [2328, 2048], 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 <= 2230, `rolled back to the clear side of the wall, got ${finalX}`) assert.ok(finalX >= 2048, '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 start = await screenOf(page, CENTRE) const held = await screenOf(page, [2128, 2048]) await page.mouse.move(start.x, start.y) await page.mouse.down() await page.mouse.move(held.x, held.y) await sleep(80) let view = await waitForRender(page, state => state.dragId === token) assert.deepEqual(view.dragPos, '2128,2048') // 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: [2098, 2048] }) assert.equal(gmMove.ok, true) await gm.ws.waitFor( message => message.t === 'token' && message.id === token && message.pos[0] === 2098, 5000, ) await sleep(150) view = await renderState(page) assert.equal(view.dragId, token) assert.deepEqual(view.positions[token], [2128, 2048], 'the sprite stayed under the pointer') await page.mouse.up() // The release send starts from the GM's position (2098) to 2128: inside the step cap, accepted. await gm.ws.waitFor( message => message.t === 'token' && message.id === token && Math.abs(message.pos[0] - 2128) <= 2 && Math.abs(message.pos[1] - 2048) <= 2, 10000, ) const settled = await waitForRender(page, state => state.dragId === '' && state.pending === 0) assert.deepEqual(settled.positions[token], [2128, 2048]) 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 start = await screenOf(page, CENTRE) const held = await screenOf(page, [2118, 2048]) await page.mouse.move(start.x, start.y) await page.mouse.down() await page.mouse.move(held.x, held.y) 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] - 2118) <= 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] - 2118) <= 2 && state.dragPhase === '', ) assert.deepEqual(resumed.positions[token], [2118, 2048], '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], [2118, 2048]) } finally { if (restarted) await stopServer(restarted) gm.ws.close() await browser.close() } }) }) test('drag follows the camera transform at zoom 0.5 and 4, and a token drag never pans', { 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)) // Player maximum (4.0): 80 screen px is 20 world px. assert.equal(await zoomTo(page, 4, CENTRE), 4) const cameraAt4 = await viewOf(page) await drag(page, CENTRE, [2068, 2048], 6) await gm.ws.waitFor( message => message.t === 'token' && message.id === token && Math.abs(message.pos[0] - 2068) <= 2 && Math.abs(message.pos[1] - 2048) <= 2, 10000, ) await waitForRender( page, view => Math.abs(view.positions[token]?.[0] - 2068) <= 2 && Math.abs(view.positions[token]?.[1] - 2048) <= 2 && view.dragId === '', ) // The press landed on a controlled token, so the camera's pan never saw the gesture. const afterTokenDrag = await viewOf(page) assert.equal(afterTokenDrag.zoom, 4) assert.equal(afterTokenDrag.x, cameraAt4.x, 'a token drag must not pan the map') assert.equal(afterTokenDrag.y, cameraAt4.y, 'a token drag must not pan the map') // Player minimum (0.5): 80 world px is only 40 screen px, still a real pointer path. const moved = [2068, 2048] assert.equal(await zoomTo(page, 0.5, moved), 0.5) await drag(page, moved, [2148, 2048], 6) await gm.ws.waitFor( message => message.t === 'token' && message.id === token && Math.abs(message.pos[0] - 2148) <= 2 && Math.abs(message.pos[1] - 2048) <= 2, 10000, ) await waitForRender( page, view => Math.abs(view.positions[token]?.[0] - 2148) <= 2 && Math.abs(view.positions[token]?.[1] - 2048) <= 2 && view.dragId === '', ) // Elsewhere the same gesture is a pan (#69): the empty canvas still moves the camera. const empty = await screenOf(page, [2280, 2048]) const cameraBeforePan = await viewOf(page) await page.mouse.move(empty.x, empty.y) await page.mouse.down() await page.mouse.move(empty.x + 40, empty.y + 20) await page.mouse.up() await sleep(80) const afterPan = await viewOf(page) assert.equal(afterPan.zoom, 0.5) assert.ok(afterPan.x > cameraBeforePan.x + 20, `the empty canvas panned: ${cameraBeforePan.x} -> ${afterPan.x}`) const panned = await renderState(page) assert.deepEqual(panned.positions[token], [2148, 2048], 'panning never moves the token') } finally { gm.ws.close() await browser.close() } }) })