diff --git a/client/e2e/characters.test.mjs b/client/e2e/characters.test.mjs new file mode 100644 index 0000000..e20d635 --- /dev/null +++ b/client/e2e/characters.test.mjs @@ -0,0 +1,209 @@ +// T12 (#75, TESTING 10.3): GM characters, reveals, encountered remove and who-sees-it against the +// real server through the TLS/HTTP2 test nginx. The GM drives the panels; a player page records its +// own WS frames, so the reveal and the encountered removal are proven on the player wire and the +// GM-only `seen_by` field is proven absent from it. + +import test from 'node:test' +import assert from 'node:assert/strict' +import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs' +import { openAs } from '../../tools/withserver.mjs' +import { + launchBrowser, + newPage, + signIn, + waitForText, + waitForVisible, + withStack, +} from './stack.mjs' + +async function recordSockets(page) { + await page.addInitScript(() => { + window.__wsLog = { frames: [] } + const Native = window.WebSocket + class RecordingSocket extends Native { + constructor(url, protocols) { + super(url, protocols) + this.addEventListener('message', event => { + try { + window.__wsLog.frames.push(JSON.parse(event.data)) + } catch { + // non-JSON frames are not state + } + }) + } + } + window.WebSocket = RecordingSocket + }) +} + +const frames = page => page.evaluate(() => window.__wsLog.frames ?? []) + +async function waitTokenFrame(page, id, predicate, timeout = 20000) { + const deadline = Date.now() + timeout + let last = null + while (Date.now() < deadline) { + last = await page.evaluate( + tokenId => + (window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1), + id, + ) + if (last && predicate(last)) return last + await sleep(50) + } + throw new Error(`token ${id} never matched; last was ${JSON.stringify(last)}`) +} + +test('GM characters, reveals, encountered remove and who-sees-it', { timeout: 240000 }, async () => { + await withStack(async ({ origin, gmKey }) => { + const browser = await launchBrowser() + const raw = await openAs(origin, gmKey) + const rawHello = await raw.ws.waitText('hello') + const scene = rawHello.scene?.id ?? (await raw.ws.waitText('walls')).scene + try { + // Two named players and one scout each; Alice's scout stands beside the linked token. + const alice = await createPlayer(raw.ws) + await namePlayer(origin, alice.key, 'Alice') + const bob = await createPlayer(raw.ws) + await namePlayer(origin, bob.key, 'Bob') + + const playerView = await newPage(browser) + const player = playerView.page + await recordSockets(player) + await player.goto(`${origin}/`) + await waitForVisible(player, '#signin') + await signIn(player, alice.key) + await waitForVisible(player, '#hud') + await waitForText(player, '#me', /^Alice$/) + + const gmView = await newPage(browser) + const gm = gmView.page + await gm.goto(`${origin}/`) + await waitForVisible(gm, '#signin') + await signIn(gm, gmKey) + await waitForVisible(gm, '#gm-panels') + await waitForVisible(gm, '#gm-cast') + + // ---- character.create through the panel (owner defaults to the GM) -------------------- + await gm.fill('#character-name', 'a cloaked figure') + await gm.fill('#character-actual', 'Lord Vex') + await gm.click('#character-create-submit') + await waitForText(gm, '#gm-character-status', /created/i) + const row = gm.locator('#gm-character-list li[data-character]').first() + await row.waitFor({ state: 'visible', timeout: 20000 }) + const characterId = await row.getAttribute('data-character') + assert.ok(characterId, 'created character has no id in the panel') + await waitForText(gm, `#gm-character-title-${characterId}`, /a cloaked figure/) + + // ---- fixture tokens: Alice's scout, Bob's far scout and one token linked to the character + const aScout = await raw.ws.request({ + t: 'token.create', scene, kind: 'pc', pos: [400, 400], descriptive_name: 'Alice', + actual_name: 'Alice', controller: alice.id, flags: { vision: true }, + }) + assert.equal(aScout.ok, true, JSON.stringify(aScout)) + const bScout = await raw.ws.request({ + t: 'token.create', scene, kind: 'pc', pos: [3900, 3900], descriptive_name: 'Bob', + actual_name: 'Bob', controller: bob.id, flags: { vision: true }, + }) + assert.equal(bScout.ok, true, JSON.stringify(bScout)) + const linked = await raw.ws.request({ + t: 'token.create', scene, kind: 'npc', pos: [500, 500], character_id: characterId, + controller: alice.id, + }) + assert.equal(linked.ok, true, 'a linked token needs no names of its own (6.1)') + // Alice sees it by sight, Bob by control; a far, uncontrolled token has nobody. + const shared = await raw.ws.request({ + t: 'token.create', scene, kind: 'npc', pos: [300, 300], descriptive_name: 'a shared thing', + actual_name: 'Shared Thing', controller: bob.id, + }) + assert.equal(shared.ok, true, JSON.stringify(shared)) + const unseen = await raw.ws.request({ + t: 'token.create', scene, kind: 'npc', pos: [2000, 2000], descriptive_name: 'a far thing', + actual_name: 'Far Thing', + }) + assert.equal(unseen.ok, true, JSON.stringify(unseen)) + + // The owner sees the descriptive name until the GM reveals the actual one. + await waitTokenFrame(player, linked.id, frame => frame.name === 'a cloaked figure') + await waitTokenFrame(player, linked.id, frame => frame.seen_by === undefined) + + // ---- who-sees-it: Alice's sight reaches the token, Bob's does not --------------------- + const seenText = await waitForText(gm, `#gm-seen-${linked.id}`, /Alice.*100 %/) + assert.equal(seenText.includes('Bob'), false, `Bob must not be a viewer: ${seenText}`) + await waitForText(gm, `#gm-seen-${shared.id}`, /Alice, Bob.*100 %/) + await waitForText(gm, `#gm-seen-${unseen.id}`, /nobody \(0 %\)/) + assert.equal(await gm.locator('#gm-cast').isVisible(), true) + + // ---- reveal to one player through the panel ------------------------------------------ + await gm.selectOption(`#gm-character-reveal-player-${characterId}`, String(alice.id)) + await gm.click(`#gm-character-reveal-${characterId}`) + await waitForText(gm, '#gm-character-status', /revealed/i) + await waitTokenFrame(player, linked.id, frame => frame.name === 'Lord Vex') + await waitForText(gm, `#gm-character-meta-${characterId}`, /told: Alice/) + + // ---- a character owner change never moves a token controller ------------------------- + const before = await new Promise(resolve => { + const deadline = Date.now() + 20000 + const poll = () => { + const frame = raw.ws.messages.filter(m => m.t === 'token' && m.id === linked.id).at(-1) + if (frame) resolve(frame) + else if (Date.now() > deadline) resolve(null) + else setTimeout(poll, 25) + } + poll() + }) + assert.equal(before?.controller, alice.id) + await gm.selectOption(`#gm-character-owner-${characterId}`, String(bob.id)) + await gm.click(`#gm-character-reassign-${characterId}`) + await waitForText(gm, '#gm-character-status', /reassigned/i) + await waitForText(gm, `#gm-character-meta-${characterId}`, /owner Bob/) + await sleep(250) + const after = raw.ws.messages.filter(m => m.t === 'token' && m.id === linked.id).at(-1) + assert.equal(after.controller, alice.id, 'character.reassign must not touch token controllers') + await waitForText( + gm, + `#gm-token-list li[data-token="${linked.id}"]`, + /controller Alice/, + ) + + // ---- encountered remove through the panel -------------------------------------------- + // The entry exists while the token is in sight; forgetting becomes meaningful once the + // player can no longer see it (DESIGN 8: a sighting is re-recorded while it stays in view). + await waitForText(gm, `#gm-encountered-${alice.id}`, /Lord Vex/) + assert.equal(await gm.locator(`#gm-encountered-remove-${alice.id}-${linked.id}`).count(), 0, + 'an in-sight entry has no Forget button') + assert.equal((await raw.ws.request({ t: 'token.remove', id: linked.id })).ok, true) + await player.waitForFunction( + tokenId => + (window.__wsLog?.frames ?? []).some( + frame => frame.t === 'token_gone' && frame.id === tokenId, + ), + linked.id, + { timeout: 20000 }, + ) + await waitForText(gm, `#gm-encountered-${alice.id}`, /met, not in sight/) + await waitForVisible(gm, `#gm-encountered-remove-${alice.id}-${linked.id}`) + await gm.click(`#gm-encountered-remove-${alice.id}-${linked.id}`) + await waitForText(gm, '#gm-encountered-status', /forgotten/i) + await player.waitForFunction( + tokenId => + (window.__wsLog?.frames ?? []).some( + frame => + frame.t === 'encountered' && + (frame.del ?? []).includes(tokenId), + ), + linked.id, + { timeout: 20000 }, + ) + + // ---- the GM-only field never reaches a player ---------------------------------------- + const playerFrames = await frames(player) + assert.equal(JSON.stringify(playerFrames).includes('seen_by'), false, + 'seen_by reached the player wire') + assert.equal(await player.locator('#gm-cast').isVisible(), false, + 'a player page must not show the GM cast panel') + } finally { + raw.ws.close() + await browser.close() + } + }) +}) diff --git a/client/src/main.ts b/client/src/main.ts index 5ebefb7..3df3624 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -6,6 +6,7 @@ import { ProtocolClient } from './ws.ts' import { Store } from './store.ts' import { mountShell } from './shell.ts' import { mountAdminPanel } from './panels/admin.ts' +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' @@ -45,11 +46,14 @@ const stageRoot: HTMLElement = stageHost // the live session is the GM. Its send callback is the same protocol client as every other intent. const panelsHost = document.querySelector('#panels') if (!panelsHost) throw new Error('#panels is missing') +const sendIntent = (t: string, fields?: Record) => + client ? client.send(t, fields) : Promise.reject(new Error('not connected')) const adminPanel = mountAdminPanel(panelsHost, { - send: (t, fields) => - client ? client.send(t, fields) : Promise.reject(new Error('not connected')), + send: sendIntent, select: token => store.dispatch({ type: 'admin-select', token }), }) +// T12 (#75): characters, reveals, encountered remove and who-sees-it, beside the #74 panel. +const castPanel = mountCastPanel(panelsHost, { send: sendIntent }) async function signIn(key: string): Promise { shell.setBusy(true) @@ -145,6 +149,7 @@ store.subscribe(state => { shell.render(state) syncStage(state) adminPanel.render(state) + castPanel.render(state) }) // Story 7: the badge distinguishes "no network at all" from "socket is reconnecting". The socket diff --git a/client/src/panels/gmcast.ts b/client/src/panels/gmcast.ts new file mode 100644 index 0000000..c126b4d --- /dev/null +++ b/client/src/panels/gmcast.ts @@ -0,0 +1,486 @@ +// GM cast panels (T12, #75): characters and assignment, name reveals to one player or all, the +// per-player encountered list with its remove action, and the who-sees-it panel. Plain DOM and +// `textContent` only (DESIGN 7.1 layer 6, spec #63 decisions 10/15). Mounted under the shell's +// existing `#panels` host beside the #74 admin panel; the sign-in flow and HUD are untouched. +// +// WHO-SEES-IT: the server computes `seen_by` from each player's existing sight (DESIGN 7.4, #75) +// and sends it on GM `token` frames only. M4 is binary: a token is seen by a player (100 %) or not +// (0 %); the graded fraction waits for wall heights. A player never receives the field. + +import type { RootState } from '../reducer.ts' +import type { AckFrame, RosterEntry } from '../protocol.ts' +import { rosterOf } from '../reducer.ts' +import type { AdminToken } from '../slices/admin.ts' +import { adminTokens } from '../slices/admin.ts' +import type { CastCharacter } from '../slices/cast.ts' +import { castCharacters, encounteredOf, seenByOf } from '../slices/cast.ts' + +export interface CastPanelHandlers { + send(t: string, fields?: Record): Promise +} + +export interface CastPanel { + render(state: RootState): void + destroy(): void +} + +const CODE_TEXT: Record = { + 'cap-reached': 'The table is full (6 players). Remove a player first.', + 'not-found': 'That player, character or entry no longer exists.', + 'not-allowed': 'The server refused that action.', + invalid: 'That value is not valid.', + 'in-use': 'A token still figures that character: unlink or remove the token first.', +} + +function describeCode(code: string | undefined): string { + if (code === undefined) return 'The server refused that action.' + return CODE_TEXT[code] ?? `The server refused that action (${code}).` +} + +function element( + tag: K, + id?: string, + text?: string, +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag) + if (id !== undefined) node.id = id + if (text !== undefined) node.textContent = text + return node +} + +function field(tag: K, id: string, text?: string) { + const node = element(tag, id, text) + const label = element('label', undefined, text ?? '') + label.htmlFor = id + return { node, label } +} + +function playerLabel(entry: RosterEntry): string { + return entry.name ?? `(unnamed ${entry.id})` +} + +function nameOf(players: RosterEntry[], id: number): string { + const entry = players.find(player => player.id === id) + return entry ? playerLabel(entry) : `#${id}` +} + +export function mountCastPanel(host: HTMLElement, handlers: CastPanelHandlers): CastPanel { + const root = element('section', 'gm-cast') + root.hidden = true + + // ---- characters ---------------------------------------------------------------------------- + const characterSection = element('section', 'gm-characters') + characterSection.append(element('h3', undefined, 'Characters')) + + const createForm = element('form', 'gm-character-create') + const createName = field('input', 'character-name', 'Descriptive name') + createName.node.type = 'text' + const createActual = field('input', 'character-actual', 'Actual name') + createActual.node.type = 'text' + const createOwner = field('select', 'character-owner', 'Owner') + const createSubmit = element('button', 'character-create-submit', 'Create character') + createSubmit.type = 'submit' + createForm.append( + createName.label, + createName.node, + createActual.label, + createActual.node, + createOwner.label, + createOwner.node, + createSubmit, + ) + + const characterList = element('ul', 'gm-character-list') + const characterStatus = element('p', 'gm-character-status') + characterStatus.hidden = true + characterStatus.setAttribute('role', 'status') + characterSection.append(createForm, characterList, characterStatus) + + // ---- encountered --------------------------------------------------------------------------- + const encounteredSection = element('section', 'gm-encountered-section') + encounteredSection.append(element('h3', undefined, 'Encountered')) + const encounteredBox = element('div', 'gm-encountered') + const encounteredStatus = element('p', 'gm-encountered-status') + encounteredStatus.hidden = true + encounteredStatus.setAttribute('role', 'status') + encounteredSection.append(encounteredBox, encounteredStatus) + + // ---- who sees it --------------------------------------------------------------------------- + const seenSection = element('section', 'gm-seen') + seenSection.append(element('h3', undefined, 'Who sees it')) + const seenHint = element('p', 'gm-seen-hint', 'M4 is binary per player: 100 % in sight, 0 % not.') + const seenList = element('ul', 'gm-seen-list') + seenSection.append(seenHint, seenList) + + root.append(characterSection, encounteredSection, seenSection) + host.append(root) + + let active = false + let characterSig = '' + let encounteredSig = '' + let seenSig = '' + let current: RootState | null = null + + function setCharacterStatus(text: string | null): void { + if (text === null) { + characterStatus.textContent = '' + characterStatus.hidden = true + } else { + characterStatus.textContent = text + characterStatus.hidden = false + } + } + + function setEncounteredStatus(text: string | null): void { + if (text === null) { + encounteredStatus.textContent = '' + encounteredStatus.hidden = true + } else { + encounteredStatus.textContent = text + encounteredStatus.hidden = false + } + } + + function renderPlayerOptions( + select: HTMLSelectElement, + players: RosterEntry[], + includeGm: boolean, + value: string, + ): void { + const wanted = players.filter(entry => includeGm || entry.role !== 'gm') + const signature = wanted.map(entry => `${entry.id}:${entry.role}`).join(',') + if (select.dataset['options'] !== signature) { + select.replaceChildren() + for (const entry of wanted) { + const option = element('option', undefined, playerLabel(entry)) + option.value = String(entry.id) + select.append(option) + } + select.dataset['options'] = signature + } + if (value !== '') select.value = value + } + + function renderCharacters(characters: CastCharacter[], players: RosterEntry[]): void { + if (characters.length === 0) { + characterList.replaceChildren(element('li', 'gm-character-empty', 'No characters yet.')) + return + } + characterList.replaceChildren( + ...characters.map(character => { + const item = element('li') + item.dataset['character'] = character.id + const title = element( + 'span', + `gm-character-title-${character.id}`, + `${character.descriptiveName} — ${character.actualName}`, + ) + const meta = element( + 'span', + `gm-character-meta-${character.id}`, + [ + `owner ${nameOf(players, character.owner)}`, + character.revealAll ? 'reveal all' : 'not revealed to all', + character.revealed.length === 0 + ? 'nobody told' + : `told: ${character.revealed.map(id => nameOf(players, id)).join(', ')}`, + ].join(' · '), + ) + + const dname = field('input', `gm-character-dname-${character.id}`, 'Descriptive') + dname.node.type = 'text' + dname.node.value = character.descriptiveName + const aname = field('input', `gm-character-aname-${character.id}`, 'Actual') + aname.node.type = 'text' + aname.node.value = character.actualName + const rename = element('button', `gm-character-rename-${character.id}`, 'Rename') + rename.type = 'button' + rename.addEventListener('click', () => { + void renameCharacter(character.id, dname.node.value, aname.node.value) + }) + + const owner = field('select', `gm-character-owner-${character.id}`, 'Owner') + renderPlayerOptions(owner.node, players, true, String(character.owner)) + const move = element('button', `gm-character-reassign-${character.id}`, 'Move to owner') + move.type = 'button' + move.addEventListener('click', () => { + void reassignCharacter(character.id, Number(owner.node.value)) + }) + + const revealPlayer = field( + 'select', + `gm-character-reveal-player-${character.id}`, + 'Reveal actual name to', + ) + renderPlayerOptions(revealPlayer.node, players, false, '') + const reveal = element('button', `gm-character-reveal-${character.id}`, 'Reveal') + reveal.type = 'button' + reveal.addEventListener('click', () => { + void revealCharacter(character.id, Number(revealPlayer.node.value)) + }) + const revealAll = element( + 'button', + `gm-character-reveal-all-${character.id}`, + 'Reveal to all', + ) + revealAll.type = 'button' + revealAll.addEventListener('click', () => { + void revealCharacterAll(character.id) + }) + const remove = element('button', `gm-character-remove-${character.id}`, 'Remove') + remove.type = 'button' + remove.addEventListener('click', () => { + void removeCharacter(character.id) + }) + + item.append( + title, + meta, + dname.label, + dname.node, + aname.label, + aname.node, + rename, + owner.label, + owner.node, + move, + revealPlayer.label, + revealPlayer.node, + reveal, + revealAll, + remove, + ) + return item + }), + ) + } + + function renderEncountered(state: RootState, players: RosterEntry[]): void { + const lists: HTMLElement[] = [] + for (const entry of players) { + const list = encounteredOf(state, entry.id) + if (list.length === 0) continue + const playerLabelNode = element('h4', `gm-encountered-title-${entry.id}`, playerLabel(entry)) + const ul = element('ul', `gm-encountered-${entry.id}`) + ul.replaceChildren( + ...list.map(row => { + const item = element('li') + item.dataset['token'] = row.id + const name = element('span', undefined, row.name) + const memory = element('span', undefined, row.grey ? 'met, not in sight' : 'in sight') + item.append(name, memory) + // A sighting is recorded again on the next refresh while the token is in view, so + // forgetting is only meaningful once the player can no longer see it (DESIGN 8). + if (row.grey) { + const remove = element( + 'button', + `gm-encountered-remove-${entry.id}-${row.id}`, + 'Forget', + ) + remove.type = 'button' + remove.addEventListener('click', () => { + void forgetEncountered(entry.id, row.id) + }) + item.append(remove) + } + return item + }), + ) + lists.push(playerLabelNode, ul) + } + if (lists.length === 0) { + encounteredBox.replaceChildren(element('p', 'gm-encountered-empty', 'No entry yet.')) + } else { + encounteredBox.replaceChildren(...lists) + } + } + + function renderSeen(tokens: AdminToken[], players: RosterEntry[], state: RootState): void { + if (tokens.length === 0) { + seenList.replaceChildren(element('li', 'gm-seen-empty', 'No token yet.')) + return + } + seenList.replaceChildren( + ...tokens.map(token => { + const seen = seenByOf(state, token.id) + const watchers = (seen ?? []).map(id => nameOf(players, id)) + const percent = watchers.length === 0 ? 0 : 100 + const item = element('li') + item.dataset['token'] = token.id + const label = element( + 'span', + `gm-seen-${token.id}`, + watchers.length === 0 + ? `${token.name} — nobody (0 %)` + : `${token.name} — ${watchers.join(', ')} (${percent} %)`, + ) + item.append(label) + return item + }), + ) + } + + function refresh(): void { + const state = current + if (!state || !active) return + const players = rosterOf(state) + const characters = castCharacters(state) + const tokens = adminTokens(state) + const orderedPlayers = [...players].sort((a, b) => a.id - b.id) + const nextCharacterSig = JSON.stringify(characters) + JSON.stringify(players) + if (nextCharacterSig !== characterSig) { + characterSig = nextCharacterSig + renderCharacters(characters, orderedPlayers) + renderPlayerOptions( + createOwner.node, + orderedPlayers, + true, + createOwner.node.value || String(state.session.me?.id ?? ''), + ) + } + const encounteredLists = orderedPlayers.map(entry => [entry.id, encounteredOf(state, entry.id)]) + const nextEncounteredSig = JSON.stringify(encounteredLists) + JSON.stringify(players) + if (nextEncounteredSig !== encounteredSig) { + encounteredSig = nextEncounteredSig + renderEncountered(state, orderedPlayers) + } + const seenMap = tokens.map(token => [token.id, seenByOf(state, token.id)]) + const nextSeenSig = + JSON.stringify(seenMap) + JSON.stringify(tokens.map(t => [t.id, t.name])) + JSON.stringify(players) + if (nextSeenSig !== seenSig) { + seenSig = nextSeenSig + renderSeen(tokens, orderedPlayers, state) + } + } + + async function request( + t: string, + fields: Record = {}, + ): Promise { + try { + const ack = await handlers.send(t, fields) + if (!ack.ok) setCharacterStatus(describeCode(ack.code)) + return ack + } catch { + setCharacterStatus('Could not reach the server.') + return null + } + } + + async function createCharacter(): Promise { + setCharacterStatus(null) + const descriptive = createName.node.value.trim() + const actual = createActual.node.value.trim() + if (descriptive === '' || actual === '') { + setCharacterStatus('Both names are required.') + return + } + const owner = createOwner.node.value === '' ? undefined : Number(createOwner.node.value) + const ack = await request('character.create', { + descriptive_name: descriptive, + actual_name: actual, + ...(owner === undefined ? {} : { owner }), + }) + if (ack?.ok) { + createName.node.value = '' + createActual.node.value = '' + setCharacterStatus('Character created.') + } + } + + async function renameCharacter(id: string, descriptive: string, actual: string): Promise { + setCharacterStatus(null) + if (descriptive.trim() === '' || actual.trim() === '') { + setCharacterStatus('Both names are required.') + return + } + const ack = await request('character.update', { + id, + descriptive_name: descriptive.trim(), + actual_name: actual.trim(), + }) + if (ack?.ok) setCharacterStatus('Character renamed.') + } + + async function reassignCharacter(id: string, owner: number): Promise { + setCharacterStatus(null) + if (!Number.isInteger(owner) || owner <= 0) { + setCharacterStatus('Choose an owner first.') + return + } + const ack = await request('character.reassign', { id, owner }) + if (ack?.ok) setCharacterStatus('Character reassigned. Token controllers did not move.') + } + + async function revealCharacter(id: string, player: number): Promise { + setCharacterStatus(null) + if (!Number.isInteger(player) || player <= 0) { + setCharacterStatus('Choose a player first.') + return + } + const ack = await request('name.reveal', { subject: 'character', id, player }) + if (ack?.ok) setCharacterStatus('Actual name revealed to that player.') + } + + async function revealCharacterAll(id: string): Promise { + setCharacterStatus(null) + const ack = await request('name.reveal_all', { subject: 'character', id }) + if (ack?.ok) setCharacterStatus('Actual name revealed to everyone.') + } + + async function removeCharacter(id: string): Promise { + setCharacterStatus(null) + const ack = await request('character.remove', { id }) + if (ack?.ok) setCharacterStatus('Character removed.') + } + + async function forgetEncountered(player: number, token: string): Promise { + setEncounteredStatus(null) + try { + const ack = await handlers.send('encountered.remove', { player, id: token }) + setEncounteredStatus(ack.ok ? 'Entry forgotten.' : describeCode(ack.code)) + } catch { + setEncounteredStatus('Could not reach the server.') + } + } + + createForm.addEventListener('submit', event => { + event.preventDefault() + void createCharacter() + }) + + function render(state: RootState): void { + current = state + const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting' + const gm = state.session.role === 'gm' && state.session.me?.name != null + const nextActive = live && gm + if (!nextActive) { + active = false + characterSig = '' + encounteredSig = '' + seenSig = '' + root.hidden = true + characterList.replaceChildren() + encounteredBox.replaceChildren() + seenList.replaceChildren() + setCharacterStatus(null) + setEncounteredStatus(null) + return + } + if (!active) { + active = true + characterSig = '' + encounteredSig = '' + seenSig = '' + } + root.hidden = false + refresh() + } + + return { + render, + destroy() { + root.remove() + }, + } +} diff --git a/client/src/slices/cast.ts b/client/src/slices/cast.ts new file mode 100644 index 0000000..6283f9b --- /dev/null +++ b/client/src/slices/cast.ts @@ -0,0 +1,171 @@ +// GM cast slice (T12, #75): the character records, the per-player encountered lists and the GM-only +// who-sees-it field of `token` frames. Append-only registration: this file is enough; the reducer's +// glob picks it up and `hello` resets it with every other slice. +// +// This slice is deliberately separate from `slices/admin.ts` (#74, the token editor) so the two +// tickets stay file-disjoint. It only reads frames; the panel in `src/panels/gmcast.ts` sends the +// intents. `seen_by` is a GM-only additive field (DESIGN 6.1/7.4): a player frame never carries it, +// so a player session simply leaves the map empty. + +import type { ReducerEvent, RootState, Slice } from '../reducer.ts' +import type { ServerFrame } from '../protocol.ts' + +export interface CastCharacter { + id: string + /** The player who owns the character (the GM owns through its own player id). */ + owner: number + descriptiveName: string + actualName: string + revealAll: boolean + /** Players the actual name was revealed to (8); never revoked. */ + revealed: number[] + props?: Record +} + +export interface CastEncountered { + id: string + name: string + grey: boolean +} + +export interface CastState { + characters: CastCharacter[] + /** playerId -> that player's encountered list, in the order the server sent it. */ + encountered: Record + /** tokenId -> the players who see it (GM-only `seen_by`, 0/100 in M4). */ + seenBy: Record +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function playerIds(value: unknown): number[] { + if (!Array.isArray(value)) return [] + return value.filter( + (entry): entry is number => typeof entry === 'number' && Number.isInteger(entry), + ) +} + +/** Read one GM `character` frame; `null` for a shape the panel cannot show. */ +export function characterFromFrame(frame: ServerFrame): CastCharacter | null { + const id = frame['id'] + const owner = frame['owner'] + const descriptiveName = frame['descriptive_name'] + const actualName = frame['actual_name'] + if ( + typeof id !== 'string' || + id.length === 0 || + typeof owner !== 'number' || + !Number.isInteger(owner) || + typeof descriptiveName !== 'string' || + typeof actualName !== 'string' + ) { + return null + } + return { + id, + owner, + descriptiveName, + actualName, + revealAll: frame['reveal_all'] === true, + revealed: playerIds(frame['revealed']), + props: isRecord(frame['props']) ? frame['props'] : undefined, + } +} + +function entries(value: unknown): CastEncountered[] | null { + if (!Array.isArray(value)) return null + const out: CastEncountered[] = [] + for (const entry of value) { + if (!isRecord(entry) || typeof entry['id'] !== 'string' || typeof entry['name'] !== 'string') { + continue + } + out.push({ id: entry['id'], name: entry['name'], grey: entry['grey'] === true }) + } + return out +} + +function upsertCharacter(state: CastState, character: CastCharacter): void { + const index = state.characters.findIndex(entry => entry.id === character.id) + if (index >= 0) state.characters[index] = character + else state.characters.push(character) +} + +function reduceEncountered(state: CastState, frame: ServerFrame): void { + const player = frame['player'] + if (typeof player !== 'number' || !Number.isInteger(player)) return + const set = entries(frame['set']) + if (set === null) return + if (frame['full'] === true) { + state.encountered[player] = set + return + } + const current = state.encountered[player] ?? [] + for (const entry of set) { + const index = current.findIndex(row => row.id === entry.id) + if (index >= 0) current[index] = entry + else current.push(entry) + } + const del = frame['del'] + if (Array.isArray(del)) { + const gone = new Set(del.filter((id): id is string => typeof id === 'string')) + state.encountered[player] = current.filter(entry => !gone.has(entry.id)) + } else { + state.encountered[player] = current + } +} + +export const slice: Slice = { + name: 'cast', + init: () => ({ characters: [], encountered: {}, seenBy: {} }), + reduce(state: CastState, event: ReducerEvent, _root: RootState): void { + if (event.type !== 'frame') return + const frame = event.frame + switch (frame.t) { + case 'character': { + const character = characterFromFrame(frame) + if (character) upsertCharacter(state, character) + return + } + case 'character_gone': { + const id = frame['id'] + if (typeof id !== 'string') return + state.characters = state.characters.filter(entry => entry.id !== id) + return + } + case 'encountered': + reduceEncountered(state, frame) + return + case 'token': { + const id = frame['id'] + if (typeof id !== 'string') return + const seen = frame['seen_by'] + if (!Array.isArray(seen)) return + state.seenBy[id] = playerIds(seen) + return + } + case 'token_gone': { + const id = frame['id'] + if (typeof id !== 'string') return + delete state.seenBy[id] + return + } + } + }, +} + +export function castCharacters(state: RootState): CastCharacter[] { + return (state.slices['cast'] as CastState | undefined)?.characters ?? [] +} + +export function encounteredOf(state: RootState, player: number): CastEncountered[] { + return (state.slices['cast'] as CastState | undefined)?.encountered[player] ?? [] +} + +/** The players who see a token, or `null` when no GM frame has carried it yet. */ +export function seenByOf(state: RootState, token: string): number[] | null { + const map = (state.slices['cast'] as CastState | undefined)?.seenBy + const seen = map ? map[token] : undefined + return seen ?? null +} diff --git a/client/src/style.css b/client/src/style.css index 2b85142..fc95406 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -334,3 +334,93 @@ body { #lists li.grey .entry-name { color: #8f8f8f; } + +/* GM cast panels (T12, #75): characters, reveals, encountered and who-sees-it, below the #74 + panel in the same right-hand column. Same secret rules: hidden and cleared unless GM + live. */ +#gm-cast { + display: flex; + flex-direction: column; + gap: 10px; + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgb(10 10 12 / 88%); + border: 1px solid #333; + pointer-events: auto; + font: 12px/1.4 ui-monospace, monospace; +} + +#gm-cast h3, +#gm-cast h4 { + margin: 0; + font-weight: 600; +} + +#gm-cast h3 { + font-size: 12px; + opacity: 0.8; +} + +#gm-cast ul { + display: flex; + flex-direction: column; + gap: 4px; + margin: 6px 0; + padding: 0; + list-style: none; +} + +#gm-cast li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + padding: 4px; + border-radius: 4px; + background: rgb(255 255 255 / 4%); +} + +#gm-cast button { + font: inherit; + padding: 2px 6px; + border-radius: 4px; + border: 1px solid #666; + background: #222; + color: inherit; +} + +#gm-cast input, +#gm-cast select { + font: inherit; + padding: 3px 5px; + border-radius: 4px; + border: 1px solid #555; + background: #111; + color: inherit; + width: 100%; + box-sizing: border-box; +} + +#gm-character-create, +#gm-cast form { + display: flex; + flex-direction: column; + gap: 4px; + margin: 6px 0; +} + +#gm-cast label { + opacity: 0.7; +} + +#gm-character-status, +#gm-encountered-status, +#gm-seen-hint { + margin: 4px 0 0; + word-break: break-word; + color: #e3b341; +} + +#gm-seen-hint { + opacity: 0.7; +} diff --git a/client/test/cast.test.ts b/client/test/cast.test.ts new file mode 100644 index 0000000..e1b0349 --- /dev/null +++ b/client/test/cast.test.ts @@ -0,0 +1,148 @@ +// T12 (#75) reducer seam: the GM cast slice consumes `character`, `encountered` and the GM-only +// `seen_by` field of `token` frames. Pure, no DOM and 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 { castCharacters, encounteredOf, seenByOf } from '../src/slices/cast.ts' + +const frame = (body: Record): 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: number): ReducerEvent => + frame({ + t: 'hello', + n, + proto: 2, + role: 'gm', + me: { id: 1, name: 'GM' }, + }) + +const character = (id: string, patch: Record = {}): ReducerEvent => + frame({ + t: 'character', + n: 2, + id, + owner: 2, + descriptive_name: 'a cloaked figure', + actual_name: 'Lord Vex', + reveal_all: false, + revealed: [], + props: { public: {}, owner: {}, gm: {} }, + ...patch, + }) + +const encountered = (player: number, patch: Record = {}): ReducerEvent => + frame({ t: 'encountered', n: 3, player, full: false, set: [], del: [], ...patch }) + +const token = (id: string, seenBy: number[]): ReducerEvent => + frame({ + t: 'token', + n: 4, + id, + scene: 1, + name: 'a cloaked figure', + pos: [400, 400], + radius: 20, + mine: false, + statuses: [], + props: {}, + seen_by: seenBy, + }) + +const run = (...events: ReducerEvent[]): RootState => + events.reduce((state, event) => reduce(state, event), initialState()) + +describe('GM cast slice', () => { + it('upserts character frames, keeps the reveal list and replaces on a later frame', () => { + const first = run({ type: 'connecting' }, hello(1), character('c1')) + expect(castCharacters(first)).toEqual([ + expect.objectContaining({ + id: 'c1', + owner: 2, + descriptiveName: 'a cloaked figure', + actualName: 'Lord Vex', + revealAll: false, + revealed: [], + }), + ]) + const changed = reduce( + first, + character('c1', { owner: 3, actual_name: 'The Duke', reveal_all: true, revealed: [2, 3] }), + ) + expect(castCharacters(changed)).toEqual([ + expect.objectContaining({ + id: 'c1', + owner: 3, + actualName: 'The Duke', + revealAll: true, + revealed: [2, 3], + }), + ]) + }) + + it('removes a character on character_gone and ignores a malformed record', () => { + const state = run( + { type: 'connecting' }, + hello(1), + character('c1'), + frame({ t: 'character', n: 3, id: 7 }), + frame({ t: 'character_gone', n: 4, id: 'c1' }), + ) + expect(castCharacters(state)).toEqual([]) + }) + + it('keeps one encountered list per player: full replaces, a diff upserts, del removes', () => { + const full = run( + { type: 'connecting' }, + hello(1), + encountered(2, { + full: true, + set: [ + { id: 't1', name: 'Rat', grey: false }, + { id: 't2', name: 'Bat', grey: true }, + ], + }), + ) + expect(encounteredOf(full, 2)).toEqual([ + { id: 't1', name: 'Rat', grey: false }, + { id: 't2', name: 'Bat', grey: true }, + ]) + const diff = reduce( + full, + encountered(2, { set: [{ id: 't2', name: 'Giant Bat', grey: false }], del: ['t1'] }), + ) + expect(encounteredOf(diff, 2)).toEqual([{ id: 't2', name: 'Giant Bat', grey: false }]) + expect(encounteredOf(diff, 3)).toEqual([]) + }) + + it('records seen_by from GM token frames and drops it on token_gone', () => { + const state = run( + { type: 'connecting' }, + hello(1), + token('t1', [2, 3]), + token('t2', []), + ) + expect(seenByOf(state, 't1')).toEqual([2, 3]) + expect(seenByOf(state, 't2')).toEqual([]) + expect(seenByOf(reduce(state, frame({ t: 'token_gone', n: 5, id: 't1' })), 't1')).toBeNull() + }) + + it('hello resets every list and the seen_by map with every other slice', () => { + const live = run( + { type: 'connecting' }, + hello(1), + character('c1'), + encountered(2, { full: true, set: [{ id: 't1', name: 'Rat', grey: false }] }), + token('t1', [2]), + ) + const reset = reduce(live, hello(9)) + expect(castCharacters(reset)).toEqual([]) + expect(encounteredOf(reset, 2)).toEqual([]) + expect(seenByOf(reset, 't1')).toBeNull() + }) +}) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 72877d3..84849e3 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1196,10 +1196,10 @@ settled by #49 (6.1, 8). Answers #41's open question: the *target's* height matt cover rules (a rules-engine judgement, non-goal 1). - **GM-only who-sees-it view [FIXED (owner decision), in v1, #44].** The GM can see, per token, which player(s)/characters see it and its **visible fraction**: the share of the token's height - above the highest blocking sight line, 100 % when nothing is crossed (definition below). GM-only, - derived from data the GM already receives (all walls, all tokens, the `gm` props), so no - player-visible field is added; never on a player wire in any form. The panel's shape is M4 - editor/fog work (7.4). + above the highest blocking sight line, 100 % when nothing is crossed (definition below). GM-only + and never on a player wire in any form. M4 ships the round-1 binary answer (0/100 %, no heights + yet) as `seen_by` on GM `token` frames, computed from each player's existing sight; the graded + fraction and the client's own derivation arrive with the heights round (7.4, #75). - **Delegated knobs [FIXED (owner-delegated), #44].** - Comparison strict, equality hidden, evaluated at every face of the wall the line crosses — 5.10 fixes the thick case (with zero thickness the faces coincide with the wall line, so this is @@ -1684,7 +1684,7 @@ only. | `wall_gone` | `scene, id` | GM only | | `vision` | `polys:[{id:, pts:[[x,y],...]}]` integer px, the full set for this player's controlled tokens with `vision` | player only; never GM | | `explored` | `full:true, rle:[[cy, x0, len, x0, len, ...], ...]` on connect and resync; `full:false, cells:[[cx,cy],...]` afterwards (fresh cells) [format PROPOSED, 6.4] | player only; never GM | -| `token` | `id, scene, name, pos, radius, mine, statuses:[{status}], props`; `name` = the one name this recipient may see (8), no reveal state; `radius` = effective px; `props` = only the buckets this recipient may read (public; plus owner for the controller; all three for GM). More for specific recipients: `statuses[].source` (GM only); `character_id` (GM, and a player who owns that character); `cprops:{public:{}}` the character's public props (player who does not own the character; `{}` for a plain token); `kind, controller (id or null), gm_only, flags, vision_radius, radius_own (number or null)` (GM); `vision_radius` also for the controller (the step cap, 5.5); plain tokens, GM: `descriptive_name, actual_name, reveal_all, revealed:[player ids]` | GM: all tokens; player: tokens they control, plus tokens inside own LOS and not `gm_only` (3.1). Whole view of one token per message | +| `token` | `id, scene, name, pos, radius, mine, statuses:[{status}], props`; `name` = the one name this recipient may see (8), no reveal state; `radius` = effective px; `props` = only the buckets this recipient may read (public; plus owner for the controller; all three for GM). More for specific recipients: `statuses[].source` (GM only); `character_id` (GM, and a player who owns that character); `cprops:{public:{}}` the character's public props (player who does not own the character; `{}` for a plain token); `kind, controller (id or null), gm_only, flags, vision_radius, radius_own (number or null)` (GM); `vision_radius` also for the controller (the step cap, 5.5); plain tokens, GM: `descriptive_name, actual_name, reveal_all, revealed:[player ids]`; `seen_by:[player ids]` (GM only, ascending; M4 who-sees-it, 7.4) | GM: all tokens; player: tokens they control, plus tokens inside own LOS and not `gm_only` (3.1). Whole view of one token per message | | `token_gone` | `id` | a recipient who had it in their `known` table and no longer may see it (left LOS, removed, `gm_only` set, controller lost it). Never sent for a token the recipient never saw | | `character` | GM: `id, owner, descriptive_name, actual_name, reveal_all, revealed:[player ids], props:{public,owner,gm}`. Owner (P): `id, descriptive_name, actual_name, props:{public,owner}`; the owner is never sent `reveal_all` or `revealed` | GM: every character; player: only the characters they own. No other player ever gets a character record (no browsable list, T16) | | `character_gone` | `id` | GM; and the previous owner on reassign | @@ -1708,7 +1708,10 @@ action caused it. A `walls`-sourced status still tells a viewer that some blocki token; **CLOSED as accepted [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D4]**: a refused move already reveals the same fact, so this is a documented, accepted effect, not a leak to fix. (7) `encountered.grey` flipping and `token`/`token_gone` carry the same fact (the token left -view), so deletion and moving away look identical to the player. +view), so deletion and moving away look identical to the player. (8) `seen_by` is GM-only: it names +the players whose sight sees the token, which is exactly the who-sees-it view (7.4). It never +reaches a player frame in any form; the leak checker bans the key outright, with a positive-control +fault build (#75). ### 6.2 Versioning [PROPOSED] - `proto` is an integer compiled into both client and server. `proto = 1` is M3 as shipped. **`proto @@ -1734,7 +1737,9 @@ view), so deletion and moving away look identical to the player. + `open` + `flags`. `2` (#49, 2026-11-17): the wall record's typed fields (`thickness`, `position`, `height`, `label`, `player_marker`, the eight switches), `kind` output-only, and the player `marker` message; the same build ships migration step 8, so a `proto` 1 client and a - migrated DB cannot be paired by accident. + migrated DB cannot be paired by accident. **No version after 2:** `seen_by` (#75, 2026-11-21) is + an additive optional field on GM `token` frames only, so the "additive only" rule above applies + and `proto` stays `2` [FIXED (owner-delegated), 2026-11-21, spec #63 decision 10]. ### 6.3 Reconnect and resync - Reconnect = full resync. After `hello` the server sends, in this order: `roster`; GM: `walls`, @@ -1981,9 +1986,14 @@ Prototype `client/src/main.ts`: explored rects appended to a `Graphics` mask for - Grid snap on drop: client option, off by default [FIXED, Q18]. Server accepts any in-bounds position within the step cap and clear of walls (5.5; step cap = effective vision radius, Q18 FIXED). -- Who-sees-it view (GM only) [FIXED (owner decision), 2026-11-15, #44]: for each token, which - player(s)/characters see it and its visible fraction (5.9, 100 % when unobstructed). GM-only and - never on a player wire; the panel's shape belongs to the M4 editor/fog work. +- Who-sees-it view (GM only) [FIXED (owner decision), 2026-11-15, #44; M4 shape FIXED + (owner-delegated), 2026-11-21, #75]: for each token, which player(s) see it and its visible + fraction (5.9, 100 % when unobstructed). **M4 ships the round-1 binary form:** a panel row per + token lists the seeing players, 0 % when nobody sees it and 100 % otherwise; the graded fraction + waits for wall heights (ADR-0012). The server computes the list from each player's existing sight + (`PlayerVision.visibleTo`, no extra polygon pass) and sends it as `seen_by:[player ids]` on GM + `token` frames only (6.1, 6.2). It is never on a player wire in any form; the leak checker bans + the key. ### 7.5 Prediction and rollback for own moves - Players do **not** know the walls, so the client cannot predict collisions [INFERRED, consequence diff --git a/server/views.nim b/server/views.nim index 60e7e2b..fd78985 100644 --- a/server/views.nim +++ b/server/views.nim @@ -60,6 +60,7 @@ type revealed*: seq[int] ## plain tokens only: who was told the actual name statuses*: seq[StatusEntry] ## every entry, source included (GM only, 6.1) props*: Props ## all three buckets, never nil + seenBy*: seq[int] ## who-sees-it, ascending; GM only, additive in proto 2 (6.1, 7.4) PlayerTokenView* = object id*: string @@ -224,15 +225,27 @@ proc greyFor*(ctx: Context, playerId: int, entityId: string): bool = proc gmView*(ctx: Context): GmView = result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len) + # Who-sees-it (7.4, #75): the players whose *existing* sight already sees each token. The + # visibility rule is `PlayerVision.visibleTo`, the same one the player egress uses, so no polygon + # is recomputed and no fan is added; the per-player polygons are the ones `refresh` left in place. + var viewerIds: seq[int] + for pid in ctx.visions.keys: + if pid == GmControlled: continue + viewerIds.add pid + viewerIds.sort() for t in ctx.tokens: let ch = ctx.characterOf(t) + var seenBy: seq[int] + var fallback: PlayerVision + for pid in viewerIds: + if visionAt(ctx, pid, fallback)[].visibleTo(t, pid): seenBy.add pid var view = GmTokenView(id: t.id, scene: t.scene, name: (if ch.isSome: ch.get.descriptiveName else: t.descriptiveName), pos: t.pos, radius: effectiveRadius(ctx.scene, t), kind: t.kind, controller: t.owner, gmOnly: t.gmOnly, flags: t.flags, visionRadius: t.visionRadius, radiusOwn: t.radius, characterId: t.characterId, - statuses: t.statuses, props: t.props) + statuses: t.statuses, props: t.props, seenBy: seenBy) if ch.isNone: # The names and the reveal state of a plain token; a linked token's live on its character. view.descriptiveName = t.descriptiveName @@ -406,7 +419,10 @@ proc gmTokenFrame*(v: GmTokenView): JsonNode = "gm_only": v.gmOnly, "flags": v.flags, "vision_radius": (if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()), "radius_own": (if v.radiusOwn.isSome: %v.radiusOwn.get else: newJNull()), - "character_id": (if v.characterId.isSome: %v.characterId.get else: newJNull()) + "character_id": (if v.characterId.isSome: %v.characterId.get else: newJNull()), + # 7.4 who-sees-it: the players whose existing sight sees this token (0/100 in M4). GM-only; + # additive within proto 2 (6.2), and banned for players by the leak checker. + "seen_by": %*v.seenBy } if v.characterId.isNone: # A linked token's names and reveal state live on the character record (6.1). @@ -444,6 +460,9 @@ proc playerTokenFrame*(v: PlayerTokenView): JsonNode = if faultActive("wallHeight"): # WALLDATA positive control (#54): a wall field name (`height`) in a player token frame. result["height"] = %1.8 + if faultActive("seenBy"): + # WALLDATA positive control (#75): the GM-only who-sees-it field in a player token frame. + result["seen_by"] = %*[v.id.len] proc tokenGoneFrame*(id: string): JsonNode = %*{"t": "token_gone", "id": id} diff --git a/tests/tviews.nim b/tests/tviews.nim index a6b9440..e5b60bd 100644 --- a/tests/tviews.nim +++ b/tests/tviews.nim @@ -59,7 +59,7 @@ proc keysDeep(node: JsonNode): HashSet[string] = const ForbiddenToPlayers = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", "flags", "descriptive_name", "actual_name", "reveal_all", - "revealed", "source", "radius_own", "extra"] + "revealed", "source", "radius_own", "extra", "seen_by"] suite "GM view (3.1: everything, with the GM-only extras)": test "every token, in token order, with controller and both names": @@ -83,6 +83,23 @@ suite "GM view (3.1: everything, with the GM-only extras)": let view = gmView(ctxOf(sc, @[tok("a", 100, 100, 0)], @[Pid])) check gmTokenFrame(view.tokens[0])["controller"].kind == JNull + test "seen_by lists the players whose existing sight sees each token, ascending": + let sc = sceneWith(@[]) + let tokens = @[tok("mine", 400, 400, Pid), + tok("near", 600, 400, Other), + tok("secret", 500, 500, 0, gmOnly = true), + tok("secret-mine", 500, 600, Pid, gmOnly = true), + tok("far", 3000, 3000, Other)] + let view = gmView(ctxOf(sc, tokens, @[Pid, Other])) + let seen = view.tokens.mapIt(it.seenBy) + check seen == @[@[Pid, Other], # Pid controls it; Other's sight reaches it + @[Pid, Other], # Other controls it; Pid's sight reaches it + newSeq[int](), # gm_only and GM-controlled: nobody sees it + @[Pid], # gm_only, but its controller always sees it + @[Other]] # out of Pid's sight; its controller sees it + let frame = gmTokenFrame(view.tokens[0]) + check frame["seen_by"] == %*[Pid, Other] + test "the GM never gets vision polygons or explored cells": let sc = sceneWith(@[]) var known: Known diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs index 43bc2d3..ff88e0f 100644 --- a/tools/fault.test.mjs +++ b/tools/fault.test.mjs @@ -32,6 +32,7 @@ const FAULTS = { gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'], walls: ['WALLDATA'], wallHeight: ['WALLDATA'], + seenBy: ['WALLDATA'], // #75: the GM-only who-sees-it field in a player token frame oneWay: ['ONEWAY'], markerEarly: ['MARKER_EARLY'], markerExtra: ['MARKER_EXTRA'], diff --git a/tools/leakcheck.nim b/tools/leakcheck.nim index a63a70e..a67369d 100644 --- a/tools/leakcheck.nim +++ b/tools/leakcheck.nim @@ -54,7 +54,7 @@ const MarkerIdLength = 12 MarkerIdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-" BannedAlways = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", - "flags", "radius_own", "extra", + "flags", "radius_own", "extra", "seen_by", # every wall field name (#54): geometry, switches, door settings, label "thickness", "position", "height", "blocks_sight", "blocks_movement", "sight_dir", "player_marker", "door", "secret", "locked", "label"] diff --git a/tools/tokens.test.mjs b/tools/tokens.test.mjs index 908d0e9..49986e5 100644 --- a/tools/tokens.test.mjs +++ b/tools/tokens.test.mjs @@ -383,6 +383,68 @@ test('restart: tokens, positions and controllers come back with the same view', } }) +test('seen_by: the GM sees which players see each token (0/100); players never receive it', async () => { + await withGmServer(async (s, gmKey) => { + const gm = await gmConnect(s.origin, gmKey) + const alice = await namedPlayer(s.origin, gm, 'Alice') + const bob = await namedPlayer(s.origin, gm, 'Bob') + const pa = await playerConnect(s.origin, alice) + const pb = await playerConnect(s.origin, bob) + const create = fields => gm.ws.request({ t: 'token.create', scene: gm.scene, ...fields }) + // One scout each: Alice at (400,400), Bob far away at (3900,3900). Both have sight, so the + // `seen_by` lists below are the server's own per-player vision, not a second rule. + const aScout = await create({ kind: 'pc', pos: [400, 400], descriptive_name: 'A', + actual_name: 'A', controller: alice.id, flags: { vision: true } }) + const bScout = await create({ kind: 'pc', pos: [3900, 3900], descriptive_name: 'B', + actual_name: 'B', controller: bob.id, flags: { vision: true } }) + // In Alice's sight, controlled by nobody. + const near = await create({ kind: 'npc', pos: [500, 500], descriptive_name: 'near', + actual_name: 'Near' }) + // In Alice's sight, controlled by Bob: both see it (sight plus control, 3.1). + const bobs = await create({ kind: 'npc', pos: [300, 300], descriptive_name: 'bobs', + actual_name: 'Bobs', controller: bob.id }) + // gm_only inside Alice's sight: nobody sees it. + const hidden = await create({ kind: 'npc', pos: [450, 450], descriptive_name: 'hidden', + actual_name: 'Hidden', gm_only: true }) + // gm_only, controlled by Alice: its controller always sees it. + const hiddenMine = await create({ kind: 'npc', pos: [450, 550], descriptive_name: 'hidden mine', + actual_name: 'Hidden Mine', gm_only: true, + controller: alice.id }) + // Out of Alice's sight, controlled by Bob: its controller sees it. + const far = await create({ kind: 'npc', pos: [3000, 3000], descriptive_name: 'far', + actual_name: 'Far', controller: bob.id }) + + const seen = async id => { + const frame = await gm.ws.waitFor(m => m.t === 'token' && m.id === id && Array.isArray(m.seen_by)) + return frame.seen_by + } + assert.deepEqual(await seen(aScout.id), [alice.id]) + assert.deepEqual(await seen(bScout.id), [bob.id]) + assert.deepEqual(await seen(near.id), [alice.id]) + assert.deepEqual(await seen(bobs.id), [alice.id, bob.id].sort((a, b) => a - b)) + assert.deepEqual(await seen(hidden.id), [], 'gm_only and uncontrolled: nobody sees it') + assert.deepEqual(await seen(hiddenMine.id), [alice.id], 'a controller always sees its token') + assert.deepEqual(await seen(far.id), [bob.id]) + + // A `gm_only` flip updates the list: control survives it, sight does not. + assert.equal((await gm.ws.request({ t: 'token.update', id: bobs.id, gm_only: true })).ok, true) + let flipped = null + await gm.ws.waitFor(m => { + if (m.t === 'token' && m.id === bobs.id && m.gm_only === true) flipped = m + return flipped !== null + }) + assert.deepEqual(flipped.seen_by, [bob.id]) + + // The only M4 wire change is GM-only: neither player socket ever receives the field. + await sleep(150) + for (const conn of [pa, pb]) { + assert.equal(JSON.stringify(conn.ws.messages).includes('seen_by'), false, + 'seen_by reached a player wire') + } + pa.ws.close(); pb.ws.close(); gm.ws.close() + }) +}) + test('player.remove hands the player\'s tokens to the GM (3.2)', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey)