// T6 / #69: map tiles, grid and pan/zoom, against the real server behind the TLS/HTTP2 test nginx // (TESTING 10.3, spec #63 decisions 7/8/12). The mobile context is the phone-class emulation of the // tile-size gate (a): 412x869 CSS px, DPR 2.625, touch, no network throttle. The gate measures the // first viewport filling at zoom 1; the 4x CPU throttle is applied right after that measurement for // the grid/pinch/reconnect checks (the fill is page-load work, and CDP throttling multiplies each of // the ~480 image callbacks; see client/README.md, gate (a)). import test from 'node:test' import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' import path from 'node:path' import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs' import { openAs, startServer, stopServer } from '../../tools/withserver.mjs' import { writeTileGrid, writeTiles } from '../../tools/tilefixture.mjs' import { launchBrowser, signIn, waitForVisible, withStack } from './stack.mjs' import { probe } from './pixels.mjs' const MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true } const SMALL = { viewport: { width: 160, height: 160 }, deviceScaleFactor: 1 } async function gmWorld(origin, gmKey) { const gm = await openAs(origin, gmKey) const hello = await gm.ws.waitText('hello') const walls = await gm.ws.waitText('walls') return { ...gm, hello, scene: hello.scene ?? walls.scene } } /** Player with one sighted token at `pos`; the server then explores around it. */ async function playerWithToken(origin, gmKey, { pos, radius }) { const gm = await gmWorld(origin, gmKey) const player = await createPlayer(gm.ws) await namePlayer(origin, player.key, 'Alice') const ack = await gm.ws.request({ t: 'token.create', scene: gm.scene.id, kind: 'pc', pos, flags: { vision: true }, vision_radius: radius, controller: player.id, descriptive_name: 'Alice', actual_name: 'Alice', }) assert.equal(ack.ok, true, JSON.stringify(ack)) gm.ws.close() await gm.ws.closed return { player, scene: gm.scene } } async function tileMap(stateDir, scene) { const tile = scene.tile_size const last = Math.ceil(scene.w / tile) - 1 writeTileGrid(stateDir, { scene: scene.id, artVersion: scene.art_version, size: tile, x0: 40, x1: last - 40, y0: 40, y1: last - 40 }) } /** The importer owns w/h/tile_size (DESIGN 6.1); a harness writes the row before the server boots. */ function setScene(stateDir, { w, h, tile }) { const db = path.join(stateDir, 'state.db') const sql = `UPDATE scene SET w=${w}, h=${h}, tile_size=${tile}, cell=${tile} WHERE id=1` const r = spawnSync('sqlite3', [db, sql], { encoding: 'utf8' }) assert.equal(r.status, 0, `set scene: ${r.stderr}`) } /** The fixture tile colour (tools/tilefixture.mjs `colourOf`), for a pixel probe. */ function tileColour(x, y) { return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff } } function nearColour(a, b, tolerance = 40) { return Math.abs(a.r - b.r) <= tolerance && Math.abs(a.g - b.g) <= tolerance && Math.abs(a.b - b.b) <= tolerance } async function mobileContext(browser) { const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE }) const page = await context.newPage() const cdp = await context.newCDPSession(page) return { context, page, cdp } } const canvas = '#stage canvas' const zoomOf = page => page.evaluate(() => document.querySelector('#stage canvas')?.dataset.zoom ?? null) const gridOf = page => page.evaluate(() => document.querySelector('#stage canvas')?.dataset.grid ?? null) const requestsOf = page => page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.tileRequests ?? -1)) const distinctOf = page => page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.tileDistinct ?? -1)) const waitTilesReady = (page, timeout = 30000) => page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready', null, { timeout }) const fillDebugOf = page => page.evaluate(() => { const c = document.querySelector('#stage canvas') return c ? { ...c.dataset, cw: c.clientWidth, ch: c.clientHeight } : null }) // Gate (a) budget, DESIGN 13: the viewport fills in < 1 s at zoom 1. A single wall-clock sample is // host-load-sensitive (a renderer the OS descheduled is not the app's speed), so the gate is the // fastest fresh first fill after a warm-up, the min-of-N shape of TESTING 5.3. A real regression // raises every sample, so the minimum fails with it. TESTING 5.3's documented 2x tolerance for a // saturated box applies to the budget: the gate is 2x the 1 s budget and the absolute minimum is // always reported. A reload is a fresh page load (new JS context, empty module-level tile cache), so // every sample is a real "first viewport" fill rather than a cache hit. const FILL_BUDGET_MS = 1000 const FILL_GATE_MS = FILL_BUDGET_MS * 2 const FILL_WARMUP = 1 const FILL_SAMPLES = 4 /** * One first-viewport fill: a reload is a fresh page load (new JS context, empty module-level tile * cache), so every sample is a real "first viewport" rather than a cache hit. The session cookie * carries the sign-in across the reload, so the page goes live without the key again. */ async function firstFill(page, origin) { await page.goto(`${origin}/`) await waitForVisible(page, canvas) const shownAt = Date.now() await waitTilesReady(page) return { fillMs: Date.now() - shownAt, debug: await fillDebugOf(page) } } test('mobile player: first viewport fills in under a second at zoom 1, grid toggles, pinch works, cache survives reconnect', { timeout: 180000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const world = await gmWorld(origin, gmKey) await tileMap(stateDir, world.scene) const { player } = await playerWithToken(origin, gmKey, { pos: [2048, 2048], radius: 1200 }) world.ws.close() const browser = await launchBrowser() try { const { context, page } = await mobileContext(browser) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, player.key) await waitForVisible(page, canvas) const cdp = await context.newCDPSession(page) const errors = [] // No per-response listener while measuring: Playwright serialising ~480 tile responses // through Node would double the measurement; the status split is the 403 test. page.on('pageerror', error => errors.push(error.message)) page.on('console', message => { // A transient tile-image failure is tolerated by the tile contract (the hole fills on the // next window or reconnect; the no-retry proof is the 403 test below, per URL), so the // browser's network-level resource line is not a client error, same as in the fog suites. const text = message.text() if (message.type() === 'error' && !text.includes('WebSocket connection') && !text.includes('403') && !text.includes('net::ERR_')) { errors.push(text) } }) // Tile-size gate (a): the viewport fills at zoom 1 on the phone-class viewport/DPR/touch. // Warm-up first (module cache, JIT, TLS), then the fastest of FILL_SAMPLES fresh fills. for (let i = 0; i < FILL_WARMUP; i++) await firstFill(page, origin) const fills = [] for (let i = 0; i < FILL_SAMPLES; i++) fills.push(await firstFill(page, origin)) const best = fills.reduce((a, b) => (b.fillMs < a.fillMs ? b : a)) // Recorded on every run, pass or fail: the absolute gate measurement for this host. console.log( `tile-size gate (a): fastest first viewport fill ${best.fillMs} ms ` + `(samples ${fills.map(f => f.fillMs).join(', ')} ms, budget ${FILL_BUDGET_MS} ms, gate ${FILL_GATE_MS} ms)`, ) assert.ok( best.fillMs < FILL_GATE_MS, `fastest of ${FILL_SAMPLES} first viewport fills after ${FILL_WARMUP} warm-up: ${best.fillMs} ms, ` + `budget ${FILL_BUDGET_MS} ms, gate ${FILL_GATE_MS} ms (2x saturated-host tolerance; ` + `samples ${fills.map(f => f.fillMs).join(', ')} ms; ${JSON.stringify(best.debug)})`, ) assert.equal(await zoomOf(page), '1') // Phone-class CPU for everything after the fill measurement (the gate itself is page-load // work and is measured at real CPU; the interactions below must still hold on a slow phone). await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 }) // Viewport + exactly one tile of margin, each distinct tile fetched once: the distinct-URL // count is the wanted count, and it is the 480-tile window the maths predicts for 412x869 at // zoom 1. `tileRequests` can be one larger when the #70 rule re-asks a tile whose 403 became // allowed (the explored frame landing after the first window), so it is not the duplicate // check; a tile fetched twice would show up in the distinct count. const visible = await page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.visibleTiles ?? 0)) assert.ok(visible > 300, `a phone viewport wants its tiles: ${visible}`) assert.equal(await distinctOf(page), visible, 'one fetch per wanted tile, none twice') assert.ok(await requestsOf(page) >= visible, 'the attempt counter covers every distinct tile') // Story 18: the grid toggle changes both the button state and the rendered canvas. await waitForVisible(page, '#grid-toggle') assert.equal(await page.getAttribute('#grid-toggle', 'aria-pressed'), 'true') const gridOn = await page.screenshot() await page.click('#grid-toggle') await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.grid === 'off') assert.equal(await page.getAttribute('#grid-toggle', 'aria-pressed'), 'false') await sleep(120) const gridOff = await page.screenshot() assert.ok(!gridOn.equals(gridOff), 'turning the grid off changes what is drawn') await page.click('#grid-toggle') assert.equal(await gridOf(page), 'on') // Story 15: a synthetic two-finger pinch zooms (touch pointers, the same path a finger takes). const beforePinch = Number(await zoomOf(page)) await page.evaluate(() => { const target = document.querySelector('#stage canvas') const fire = (type, id, x) => target.dispatchEvent(new PointerEvent(type, { pointerId: id, pointerType: 'touch', isPrimary: id === 1, clientX: x, clientY: 400, bubbles: true, cancelable: true, })) fire('pointerdown', 1, 150) fire('pointerdown', 2, 250) fire('pointermove', 1, 50) fire('pointermove', 2, 350) fire('pointerup', 1, 50) fire('pointerup', 2, 350) }) const afterPinch = Number(await zoomOf(page)) assert.ok(afterPinch > beforePinch, `pinch apart zoomed in: ${beforePinch} -> ${afterPinch}`) assert.ok(afterPinch <= 4, 'at most 4') // Story 14: a reconnect keeps the decoded tiles; the page makes no new tile fetch. const fetchesBefore = await requestsOf(page) await context.setOffline(true) await page.locator('#badge[data-state="offline"]').waitFor({ state: 'visible', timeout: 20000 }) await context.setOffline(false) await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 }) await waitTilesReady(page) const fetchesAfter = await requestsOf(page) assert.equal(fetchesAfter, fetchesBefore, 'the tile cache survives the reconnect: no refetch') assert.deepEqual(errors, []) await context.close() } finally { await browser.close() } }) }) test('clamps: player stops at 0.5 and 4, the GM goes below 0.5 and stops at 4', { timeout: 120000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const world = await gmWorld(origin, gmKey) await tileMap(stateDir, world.scene) const { player } = await playerWithToken(origin, gmKey, { pos: [2048, 2048], radius: 1200 }) world.ws.close() const browser = await launchBrowser() try { const playerContext = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL }) const page = await playerContext.newPage() await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, player.key) await waitForVisible(page, canvas) await waitTilesReady(page) await page.mouse.move(80, 80) await page.mouse.wheel(0, 2000) await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '0.5') assert.equal(await zoomOf(page), '0.5') await page.mouse.wheel(0, -2000) await page.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '4') assert.equal(await zoomOf(page), '4') await playerContext.close() const gmContext = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL }) const gmPage = await gmContext.newPage() await gmPage.goto(`${origin}/`) await waitForVisible(gmPage, '#signin') await signIn(gmPage, gmKey) await waitForVisible(gmPage, canvas) await waitTilesReady(gmPage) // 0.25 is below the player's 0.5 floor: the GM's survey zoom is not clamped there. await gmPage.mouse.move(80, 80) await gmPage.mouse.wheel(0, 924) await gmPage.waitForFunction(() => { const zoom = Number(document.querySelector('#stage canvas')?.dataset.zoom) return zoom < 0.3 && zoom > 0.2 }) const gmZoom = Number(await zoomOf(gmPage)) assert.ok(gmZoom < 0.5, `the GM zoomed to ${gmZoom}, below the player floor`) await gmPage.mouse.wheel(0, -2000) await gmPage.waitForFunction(() => document.querySelector('#stage canvas')?.dataset.zoom === '4') assert.equal(await zoomOf(gmPage), '4') await gmContext.close() } finally { await browser.close() } }) }) test('a 403 is remembered: no retry loop, even when the viewport re-syncs', { timeout: 120000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const world = await gmWorld(origin, gmKey) await tileMap(stateDir, world.scene) // A sighted token far from the map centre: the camera looks at unexplored floor, so the gate // answers 403 for every tile in view. const { player } = await playerWithToken(origin, gmKey, { pos: [300, 300], radius: 200 }) world.ws.close() const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, ...SMALL }) const page = await context.newPage() const perUrl = new Map() const statuses = [] page.on('request', request => { const path = new URL(request.url()).pathname if (!path.startsWith('/tiles/')) return perUrl.set(path, (perUrl.get(path) ?? 0) + 1) }) page.on('response', response => { if (new URL(response.url()).pathname.startsWith('/tiles/')) statuses.push(response.status()) }) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, player.key) await waitForVisible(page, canvas) await waitTilesReady(page) const first = await requestsOf(page) assert.ok(first > 20, `the viewport asked for tiles: ${first}`) assert.ok(statuses.length > 0 && statuses.every(status => status === 403), `unexplored floor is refused: ${JSON.stringify([...new Set(statuses)])}`) // Re-sync (toggle the grid twice) and wait: not one denied tile may be asked for twice. await page.click('#grid-toggle') await page.click('#grid-toggle') await sleep(2000) assert.equal(await requestsOf(page), first, 'no retry after a viewport re-sync') // A denied tile costs exactly one request: the status comes from the fetch itself (#86). assert.ok([...perUrl.values()].every(count => count === 1), `a denied tile was requested more than once: ${JSON.stringify([...perUrl].filter(([, count]) => count !== 1))}`) await context.close() } finally { await browser.close() } }) }) // #86: a GM survey zoom asks for the whole map. The fill must be one request per tile (no // duplicate classification fetches), centre-out, and it must reach `ready`. Headless SwiftShader, // so the time is a host floor, not the phone budget; recorded, never gated tightly. test('GM survey zoom on a Full HD map fills one request per tile', { timeout: 120000 }, async () => { const W = 1920 const H = 1080 const TILE = 32 await withStack( async ({ origin, gmKey }) => { const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } }) const page = await context.newPage() const perUrl = new Map() const transient = new Set() page.on('request', request => { const p = new URL(request.url()).pathname if (p.startsWith('/tiles/')) perUrl.set(p, (perUrl.get(p) ?? 0) + 1) }) page.on('response', response => { const p = new URL(response.url()).pathname if (p.startsWith('/tiles/') && response.status() !== 200 && response.status() !== 403) transient.add(p) }) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, gmKey) await waitForVisible(page, canvas) await waitTilesReady(page) const before = await requestsOf(page) // Fit: zoom = min(1000/1920, 700/1080); one wheel is enough (delta -> exp factor). const fit = Math.min(1000 / W, 700 / H) await page.mouse.move(500, 350) const startedAt = Date.now() await page.mouse.wheel(0, Math.log(1 / fit) / 0.0015) await page.waitForFunction( () => { const data = document.querySelector('#stage canvas')?.dataset ?? {} return Number(data.zoom ?? 1) < 0.53 && Number(data.visibleTiles ?? 0) > 1900 && data.tiles === 'ready' }, null, { timeout: 60000, polling: 50 }, ) const fillMs = Date.now() - startedAt const visible = await page.evaluate(() => Number(document.querySelector('#stage canvas')?.dataset.visibleTiles ?? 0)) const requests = await requestsOf(page) console.log(`#86 GM survey fill: ${fillMs} ms, ${visible} tiles, ${requests} requests (before ${before})`) assert.equal(visible, (W / TILE) * Math.ceil(H / TILE), 'the whole Full HD map at this zoom') assert.ok(perUrl.size >= visible, `every wanted tile was asked for: ${perUrl.size} of ${visible}`) // No tile that answered 200 cost a second request (the old path re-asked on every image // error to learn its status). A genuinely failed tile may retry. const duplicated = [...perUrl].filter(([url, count]) => count > 1 && !transient.has(url)) assert.deepEqual(duplicated, [], 'one request per tile that succeeded') assert.ok(fillMs < 30000, `the survey fill reached ready in ${fillMs} ms`) await context.close() } finally { await browser.close() } }, { prepare: stateDir => { setScene(stateDir, { w: W, h: H, tile: TILE }) writeTileGrid(stateDir, { scene: 1, artVersion: 1, size: TILE, x0: 0, x1: W / TILE - 1, y0: 0, y1: Math.ceil(H / TILE) - 1, }) }, }, ) }) // #86: a tile that 404s (art imported after the page loaded) is retried a bounded number of times, // and a reconnect retries it after the file appears. Before, the void was permanent until reload. test('a 404 tile is retried with a budget and recovers on reconnect', { timeout: 120000 }, async () => { const W = 1920 const H = 1080 const TILE = 32 const MISSING = [Math.floor(W / 2 / TILE), Math.floor(H / 2 / TILE)] const missingUrl = `/tiles/1/v1/${MISSING[0]}_${MISSING[1]}.png` await withStack( async ({ origin, gmKey, stateDir, server }) => { const browser = await launchBrowser() let restarted = null try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } }) const page = await context.newPage() let missingRequests = 0 page.on('request', request => { if (new URL(request.url()).pathname === missingUrl) missingRequests += 1 }) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, gmKey) await waitForVisible(page, canvas) await waitTilesReady(page) // The first pass spends its whole budget (3 loads), not 2 requests per load. for (let i = 0; i < 100 && missingRequests < 3; i++) await sleep(100) assert.equal(missingRequests, 3, 'three bounded loads, one request each') const camera = await page.evaluate(() => (document.querySelector('#stage canvas')?.dataset.camera ?? '0,0').split(',').map(Number)) const zoom = Number(await zoomOf(page)) const at = [(MISSING[0] + 0.5) * TILE * zoom + camera[0], (MISSING[1] + 0.5) * TILE * zoom + camera[1]] const blank = await probe(page, at[0], at[1]) assert.ok(!nearColour(blank, tileColour(MISSING[0], MISSING[1])), `the missing tile is not painted yet: ${JSON.stringify(blank)}`) // The art arrives, then a reconnect (a real socket close and a fresh `hello`) gives the // stored failure another chance. A server restart on the same port is the honest trigger: // CDP "offline" does not necessarily close an established WebSocket. writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles: [MISSING] }) await stopServer(server) restarted = await startServer({ stateDir, port: server.port, publicOrigin: origin }) // The badge may flip through `reconnecting` faster than a poll sees it; `connected` after a // real socket close is the hello that matters. await page.locator('#badge[data-state="reconnecting"]').waitFor({ state: 'visible', timeout: 20000 }) .catch(() => {}) await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 }) let painted = null for (let i = 0; i < 100; i++) { painted = await probe(page, at[0], at[1]) if (nearColour(painted, tileColour(MISSING[0], MISSING[1]))) break await sleep(100) } assert.ok(missingRequests >= 4, `the reconnect re-asked for the failed tile: ${missingRequests}`) assert.ok(nearColour(painted, tileColour(MISSING[0], MISSING[1])), `the recovered tile is painted: ${JSON.stringify(painted)}`) await context.close() } finally { if (restarted) await stopServer(restarted) await browser.close() } }, { prepare: stateDir => { setScene(stateDir, { w: W, h: H, tile: TILE }) const tiles = [] for (let y = 0; y <= Math.ceil(H / TILE) - 1; y++) for (let x = 10; x <= 50; x++) { if (x === MISSING[0] && y === MISSING[1]) continue tiles.push([x, y]) } writeTiles(stateDir, { scene: 1, artVersion: 1, size: TILE, tiles }) }, }, ) })