tests: characters, names, the encountered list and migration step 7 (#23)

This commit is contained in:
2026-11-15 12:01:30 +01:00
parent 20dcb87afb
commit f134534c6c
5 changed files with 1064 additions and 18 deletions
+318
View File
@@ -0,0 +1,318 @@
## Characters, the name rule, reveals and the encountered snapshot (#23, DESIGN 3.1, 4.4, 6.1, 8).
## Pure/unit level: the records, the name rule, the reveal set and the write-through persistence
## (including the reload a restart performs). The wire behaviour lives in tools/characters.test.mjs
## and the egress filtering in tests/tviews.nim.
import std/[json, options, os, sequtils, sets, strutils, tables, unittest]
import db_connector/db_sqlite
import auth, characters, db, props, tokens, world
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "fffchars-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc freshDb(): tuple[db: DbConn, dir: string] =
let d = tmpDir()
let conn = openDatabase(d / "state.db")
discard migrate(conn)
(conn, d)
proc ownedBy(conn: DbConn): int =
## A real owner id: the persisted characters have an FK to `player`, so a unit test needs one.
if gmPlayer(conn).isNone: discard ensureGm(conn)
parseInt(conn.getValue(sql"SELECT id FROM player ORDER BY id LIMIT 1"))
proc aChar(owner = 1, id = ""): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: "a grumpy man", actualName: "Lord Vex",
props: newProps())
proc plainToken(id = "tok1", owner = 0): TokenRec =
TokenRec(id: id, scene: 1, kind: "npc", descriptiveName: "a wolf", actualName: "Fang",
owner: owner, flags: %*{"vision": true}, props: newProps())
suite "the name rule (DESIGN 8: one copy, used by every frame)":
test "an owner, a reveal_all and a per-player reveal each expose the actual name":
check knowsActual(isOwner = true, revealAll = false, revealed = false)
check knowsActual(isOwner = false, revealAll = true, revealed = false)
check knowsActual(isOwner = false, revealAll = false, revealed = true)
check not knowsActual(isOwner = false, revealAll = false, revealed = false)
test "visibleName picks the name the recipient knows":
check visibleName("a grumpy man", "Lord Vex", false) == "a grumpy man"
check visibleName("a grumpy man", "Lord Vex", true) == "Lord Vex"
test "a character owner sees the actual name without any reveal row":
var reveals: Reveals
let c = aChar(owner = 2)
check subjectNamesOf(c).nameFor(2, reveals) == "Lord Vex"
check subjectNamesOf(c).nameFor(3, reveals) == "a grumpy man"
reveals.withReveal(3, c.id)
check subjectNamesOf(c).nameFor(3, reveals) == "Lord Vex"
test "a linked token borrows the character's names, so one reveal covers all of them":
var reveals: Reveals
let c = aChar(owner = 2, id = "char1")
var t = plainToken()
t.characterId = some("char1")
t.descriptiveName = ""
t.actualName = ""
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "a grumpy man"
check subjectNamesOf(t, @[c]).id == "char1" # the reveal key is the character, not the token
reveals.withReveal(3, "char1")
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "Lord Vex"
test "a plain token is nobody's character: only a reveal or reveal_all shows the actual name":
var reveals: Reveals
var t = plainToken(owner = 2) # its controller gets no free actual name
check subjectNamesOf(t, @[]).nameFor(2, reveals) == "a wolf"
t.revealAll = true
check subjectNamesOf(t, @[]).nameFor(3, reveals) == "Fang"
test "revealedPlayers lists the reveal rows of one subject, sorted":
var reveals: Reveals
for p in [4, 2, 3]: reveals.withReveal(p, "char1")
reveals.withReveal(2, "other")
check revealedPlayers(reveals, "char1") == @[2, 3, 4]
check revealedPlayers(reveals, "nothing") == newSeq[int]()
check reveals.isRevealed(3, "char1")
check not reveals.isRevealed(5, "char1")
test "player.remove takes that player's reveal rows with it":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(3, "b")
reveals.withoutRevealsOf(2)
check not reveals.isRevealed(2, "a")
check reveals.isRevealed(3, "b")
test "one reveal row per (player, subject): a repeated reveal changes nothing":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(2, "a")
check reveals.pairs.len == 1
suite "encountered snapshot (DESIGN 8: the name the player knows, frozen)":
test "a first sighting records what the player knows right now":
let c = aChar(owner = 2, id = "char1")
let names = subjectNamesOf(c)
let unknown = newEntry("t1", names, knowsActual = false)
check unknown.entryName == "a grumpy man"
check unknown.actualName.isNone
check unknown.characterId.get == "char1"
let known = newEntry("t1", names, knowsActual = true)
check known.entryName == "Lord Vex"
test "a rename follows the subject, and a player who was never told keeps not knowing":
let c = aChar(id = "char1")
var e = newEntry("t1", subjectNamesOf(c), knowsActual = false)
e = e.renamed("a tall stranger", "Lady Vex")
check e.entryName == "a tall stranger"
check e.actualName.isNone
var known = newEntry("t2", subjectNamesOf(c), knowsActual = true)
known = known.renamed("a tall stranger", "Lady Vex")
check known.entryName == "Lady Vex"
test "a reveal fills in the actual name and leaves the rest alone":
var e = newEntry("t1", subjectNamesOf(aChar(id = "char1")), knowsActual = false)
e = e.revealed("Lord Vex")
check e.entryName == "Lord Vex"
check e.descriptiveName == "a grumpy man"
suite "names and validation (6.5: 1..64 code points, trimmed, no control characters)":
test "a character needs two valid names and an owner":
let c = aChar()
check validCharacter(c)
check validCharacterName("Lord Vex")
check not validCharacterName("")
check not validCharacterName(" padded")
var bad = c
bad.actualName = ""
check not validCharacter(bad)
bad = c
bad.owner = 0
check not validCharacter(bad)
bad = c
bad.descriptiveName = repeat("x", 65)
check not validCharacter(bad)
test "a linked token carries no names of its own (they belong to the character)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plainToken()
t.characterId = some("char1")
check not validToken(sc, t) # still has plain-token names
t.descriptiveName = ""
t.actualName = ""
check validToken(sc, t)
test "parseSubject accepts exactly the two wire words":
check parseSubject("character").get == nsCharacter
check parseSubject("token").get == nsToken
check parseSubject("Character").isNone
check parseSubject("").isNone
suite "persistence (write-through, restart-identical)":
test "create assigns an id from the shared namespace, stores every column, reloads identically":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gm = ensureGm(conn)
let gmId = parseInt(conn.getValue(sql"SELECT id FROM player WHERE role = 'gm'"))
var c = aChar(owner = gmId)
c.props[pbPublic] = %*{"class": "fighter"}
c.props[pbOwner] = %*{"hp": 12}
c.props[pbGm] = %*{"secret": true}
let (outcome, stored) = addCharacter(conn, c, @[])
check outcome == coOk
check gm.key.len > 0
check stored.id.len == TokenIdLength
let reloaded = loadCharacters(conn)
check reloaded.len == 1
check reloaded[0].id == stored.id
check reloaded[0].owner == gmId
check reloaded[0].descriptiveName == "a grumpy man"
check reloaded[0].actualName == "Lord Vex"
check not reloaded[0].revealAll
check reloaded[0].props[pbOwner]["hp"].getInt == 12
check reloaded[0].props[pbGm]["secret"].getBool
test "the id namespace is shared with tokens: taken ids are never handed out again":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
# an exhaustive "taken" list is impossible; check the call site contract instead: the ids of
# every token AND every character are passed to freshId, so the two can never collide.
let (firstOutcome, first) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
let (secondOutcome, second) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[first.id])
check firstOutcome == coOk
check secondOutcome == coOk
check second.id != first.id
test "reveal_all and the props round-trip through a full replacement":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var changed = stored
changed.revealAll = true
changed.actualName = "Lady Vex"
changed.props[pbPublic] = %*{"aura": "cold"}
check storeCharacter(conn, changed) == coOk
let r = loadCharacters(conn)[0]
check r.revealAll
check r.actualName == "Lady Vex"
check r.props[pbPublic]["aura"].getStr == "cold"
var invalid = changed
invalid.descriptiveName = ""
check storeCharacter(conn, invalid) == coInvalid
check loadCharacters(conn)[0].descriptiveName == "a grumpy man"
test "remove deletes the row; a second remove reports nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
check removeCharacter(conn, stored.id)
check loadCharacters(conn).len == 0
check not removeCharacter(conn, stored.id)
test "a reveal row survives a reload and a repeated reveal":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
addReveal(conn, created.id, "char1")
addReveal(conn, created.id, "char1")
let r = loadReveals(conn)
check r.pairs.len == 1
check r.isRevealed(created.id, "char1")
deleteRevealsOf(conn, created.id)
check loadReveals(conn).pairs.len == 0
test "encountered rows survive a reload, keep their NULL actual name, and replace per entry":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man", actualName: none(string)))
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t2", characterId: none(string),
descriptiveName: "a wolf", actualName: some("Fang")))
var loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].actualName.isNone
check loaded[created.id]["t1"].characterId.get == "char1"
check loaded[created.id]["t2"].entryName == "Fang"
# an upsert replaces the snapshot of that (player, token)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a tall stranger", actualName: some("Lord Vex")))
loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].entryName == "Lord Vex"
check deleteEncountered(conn, created.id, "t1")
check not deleteEncountered(conn, created.id, "t1")
check loadEncountered(conn)[created.id].len == 1
test "a character rename follows the snapshots of everyone who met it":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
let p2 = createPlayerWithKey(conn)
writeEncountered(conn, p1.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: none(string)))
writeEncountered(conn, p2.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: some("Lord Vex")))
renameEncountered(conn, "char1", "a tall stranger", "Lady Vex")
let loaded = loadEncountered(conn)
check loaded[p1.id]["t1"].entryName == "a tall stranger" # still not told the actual name
check loaded[p1.id]["t1"].actualName.isNone
check loaded[p2.id]["t1"].entryName == "Lady Vex"
revealEncountered(conn, "char1", "Lady Vex")
check loadEncountered(conn)[p1.id]["t1"].entryName == "Lady Vex"
test "player.remove hands the player's characters to the GM (DESIGN 3.2)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gmId = int(insertID(conn, sql"INSERT INTO player (name, role, colour, created_at) VALUES ('GM','gm','#000','x')"))
let created = createPlayerWithKey(conn)
let (_, stored) = addCharacter(conn, aChar(owner = created.id), @[])
transferToGm(conn, created.id, gmId)
check loadCharacters(conn)[0].owner == gmId
check loadCharacters(conn)[0].id == stored.id
test "a character still figured by a token is in use (6.5)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var t = plainToken()
t.characterId = some(stored.id)
t.descriptiveName = ""
t.actualName = ""
let (outcome, added) = addToken(conn, sc, t, @[])
check outcome == toOk
check tokensLinkedTo(loadTokens(conn), stored.id) == 1
check tokensLinkedTo(loadTokens(conn), "other") == 0
check added.id.len == TokenIdLength
+18 -9
View File
@@ -38,9 +38,9 @@ suite "migrate":
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 6
check LatestVersion == 7
let rows = appliedMigrations(db)
check rows.len == 6
check rows.len == 7
check rows[0][0] == 1
check rows[0][1] == "meta"
check rows[1][0] == 2
@@ -53,6 +53,8 @@ suite "migrate":
check rows[4][1] == "explored"
check rows[5][0] == 6
check rows[5][1] == "token details"
check rows[6][0] == 7
check rows[6][1] == "characters"
# the steps' own DDL ran: meta and the auth tables exist and are empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0"
@@ -69,12 +71,18 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM entity_status") == "0"
for col in ["props_public", "props_owner", "props_gm"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('entity') WHERE name = '" & col & "'")) == "1"
# step 7 creates the character world and adds the link columns to the token table
check db.getValue(sql"SELECT count(*) FROM character") == "0"
check db.getValue(sql"SELECT count(*) FROM name_reveal") == "0"
check db.getValue(sql"SELECT count(*) FROM encountered") == "0"
for col in ["character_id", "reveal_all"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('entity') WHERE name = '" & col & "'")) == "1"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
block:
let db = openFresh(d)
check migrate(db) == 6
check migrate(db) == LatestVersion
close(db)
let db = openFresh(d)
defer:
@@ -83,7 +91,7 @@ suite "migrate":
let before = appliedMigrations(db)
check migrate(db) == 0
check migrate(db) == 0
check schemaVersion(db) == 6
check schemaVersion(db) == LatestVersion
check appliedMigrations(db) == before
test "history and user_version must agree":
@@ -157,8 +165,8 @@ suite "migrate":
check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == 4 # steps 3, 4, 5 and 6 run
check schemaVersion(db) == 6
check migrate(db) == LatestVersion - 2 # steps 3 to 7 run
check schemaVersion(db) == LatestVersion
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
@@ -190,11 +198,12 @@ suite "migrate":
check schemaVersion(db) == 4
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0"
check migrate(db) == 2 # steps 5 and 6 run
check schemaVersion(db) == 6
check appliedMigrations(db).len == 6
check migrate(db) == 3 # steps 5, 6 and 7 run
check schemaVersion(db) == LatestVersion
check appliedMigrations(db).len == 7
check appliedMigrations(db)[4] == (version: 5, name: "explored")
check appliedMigrations(db)[5] == (version: 6, name: "token details")
check appliedMigrations(db)[6] == (version: 7, name: "characters")
# step 6: the status table exists, and the old token's buckets default to empty objects
check db.getValue(sql"SELECT count(*) FROM entity_status") == "0"
check db.getValue(sql"SELECT props_public || props_owner || props_gm FROM entity") == "{}{}{}"
+7 -6
View File
@@ -40,7 +40,7 @@ suite "envelope (6.5 step 2)":
test "the catalogue is the 29 intents of 6.1 and the built set is a subset":
check IntentCatalogue.len == 29
check ImplementedIntents.len == 13 # slice 3's five + slice 4's four walls + slice 5's four token intents
check ImplementedIntents.len == 28 # 29 - `scene.set`, which is slice 10
for t in ImplementedIntents:
check t in IntentCatalogue
check isCatalogueIntent(t)
@@ -63,11 +63,12 @@ suite "envelope (6.5 step 2)":
check isGmOnlyIntent(t) # walls are GM-only (3.1, T2)
for t in ["token.create", "token.update", "token.move", "token.remove"]:
check isImplementedIntent(t)
check not isImplementedIntent("player.setname")
check not isImplementedIntent("scene.set")
check not isImplementedIntent("token.resize")
check not isImplementedIntent("status.set")
check not isImplementedIntent("character.create")
for t in ["player.setname", "player.rename", "key.show", "token.resize", "status.set",
"status.clear", "prop.set", "prop.unset", "character.create", "character.update",
"character.remove", "character.reassign", "name.reveal", "name.reveal_all",
"encountered.remove"]:
check isImplementedIntent(t)
check not isImplementedIntent("scene.set") # the only catalogue intent left for slice 10
suite "intent rate limit (6.4: 30/s, burst 100)":
test "a fresh bucket allows exactly the burst, then refuses":
+178 -3
View File
@@ -3,7 +3,7 @@
## that keep GM-only data out of a player's frames. The black-box proof over a real socket is
## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import geometry, props, tokens, views, vision, world
import characters, geometry, props, tokens, views, vision, world
const Pid = 2 # the subject player
const Other = 3 # another player
@@ -128,8 +128,10 @@ suite "diff (6.4: only what changed)":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first) == @["vision", "explored", "token"]
check first[1]["full"].getBool
check typesOf(first) == @["encountered", "vision", "explored", "token"]
check first[0]["full"].getBool # 6.3: the whole list on connect/resync
check first[0]["set"].len == 0
check first[2]["full"].getBool
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token that moved sends one `token` frame with the new position":
@@ -295,3 +297,176 @@ suite "props and statuses (#22, 6.1: the bucket and the source are per-recipient
check typesOf(frames) == @["token"]
check frames[0]["radius"].getFloat == 35.0
check not frames[0].hasKey("radius_own") # the GM-only own-radius field stays out
# ---------------------------------------------------------------------------------------------------
# Slice 8 (#23): characters, names and the encountered list in the typed view.
proc charOf(id: string, owner: int, dname = "a grumpy man", actual = "Lord Vex"): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: dname, actualName: actual, props: newProps())
proc withChar(ctx: var Context, c: CharacterRec): int =
ctx.characters.add c
ctx.characters.len - 1
proc linked(id: string, x, y: float, owner: int, characterId: string): TokenRec =
TokenRec(id: id, scene: 1, kind: "pc", characterId: some(characterId), pos: (x, y),
owner: owner, flags: %*{"vision": true}, props: newProps())
suite "characters in the egress (3.1, 6.1, 8)":
test "the GM gets every character with owner, reveal_all, revealed and all three buckets":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
var c = charOf("c1", 2)
c.revealAll = true
c.props[pbGm] = %*{"trap": true}
discard ctx.withChar(c)
ctx.reveals.withReveal(Other, "c1")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
check frames.len == 1
let f = frames[0]
check f["t"].getStr == "character"
check f["owner"].getInt == 2
check f["descriptive_name"].getStr == "a grumpy man"
check f["actual_name"].getStr == "Lord Vex"
check f["reveal_all"].getBool
check f["revealed"] == %*[Other]
check f["props"].keys.toSeq.sorted == @["gm", "owner", "public"]
test "a player gets only its own characters, without owner, reveal_all or revealed":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("mine", Pid))
discard ctx.withChar(charOf("theirs", Other))
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
let chars = frames.filterIt(it["t"].getStr == "character")
check chars.len == 1
check chars[0]["id"].getStr == "mine"
check chars[0]["actual_name"].getStr == "Lord Vex" # the owner always knows it (8)
check chars[0]["props"].keys.toSeq.sorted == @["owner", "public"]
for key in ["owner", "reveal_all", "revealed", "nhidden"]:
check not chars[0].hasKey(key)
test "a reassignment withdraws the record from the old owner and sends it to the new one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
var known: Known
check typesOf(egressFrames(Recipient(isGm: false, playerId: Other), ctx, known, resync = true))
.contains("character")
var otherKnown: Known
check not typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
ctx.characters[idx].owner = Pid
let otherFrames = egressFrames(Recipient(isGm: false, playerId: Other), ctx, known)
check typesOf(otherFrames) == @["character_gone"]
check otherFrames[0]["id"].getStr == "c1"
check typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
test "a linked token's name follows the character, and the owner sees the actual one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
# the subject controls the token but does not own the character
var known: Known
var frame = playerView(ctx, Pid).tokens[0]
check frame.name == "a grumpy man"
check frame.characterId.isNone # 6.1 leak note 2
check frame.cpropsPublic.len == 0
# the character's owner sees the actual name and the link
let owner = playerView(ctx, Other)
check owner.tokens.len == 0 # no LOS of its own: the token is not in its view
discard known
test "cprops carries the character's public bucket to a non-owner, and never the owner bucket":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
ctx.characters[idx].props[pbPublic] = %*{"rank": "noble"}
ctx.characters[idx].props[pbOwner] = %*{"hp": 3}
ctx.characters[idx].props[pbGm] = %*{"trap": true}
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
let frame = playerTokenFrame(playerView(ctx, Pid).tokens[0])
check frame["cprops"].keys.toSeq == @["public"]
check frame["cprops"]["public"]["rank"].getStr == "noble"
check "owner" notin keysDeep(frame["cprops"])
check "gm" notin keysDeep(frame)
check frame["props"].keys.toSeq.sorted == @["owner", "public"] # its own buckets
test "a player sees the actual name only when the GM revealed it to them (8)":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
var known: Known
check playerView(ctx, Pid).tokens[0].name == "a grumpy man"
ctx.reveals.withReveal(Pid, "c1")
check playerView(ctx, Pid).tokens[0].name == "Lord Vex"
discard known
suite "the encountered list (8)":
proc entryFor(id: string, name: string, grey = false): EncounteredView =
EncounteredView(id: id, name: name, grey: grey)
test "a resync sends the whole list, then only what changed, then what was removed":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
ctx.encountered[Pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine",
descriptiveName: "a mine")
var known: Known
let full = pass(ctx, known, resync = true)
let enc = full.filterIt(it["t"].getStr == "encountered")
check enc.len == 1
check enc[0]["full"].getBool
check enc[0]["set"] == %*[{"id": "mine", "name": "a mine", "grey": false}]
# nothing changed: no frame
check pass(ctx, known).len == 0
# greyed: the entry is re-sent, nothing is deleted
ctx.encountered[Pid]["mine"].actualName = some("Mine")
let changed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check changed.len == 1
check changed[0]["full"].getBool == false
check changed[0]["set"] == %*[{"id": "mine", "name": "Mine", "grey": false}]
check changed[0]["del"] == newJArray()
# removed: only a `del`
ctx.encountered[Pid].del "mine"
let removed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check removed.len == 1
check removed[0]["set"] == newJArray()
check removed[0]["del"] == %*["mine"]
test "an entry for a token that is gone (or out of view) is grey":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
check not ctx.greyFor(Pid, "near") # in LOS
check ctx.greyFor(Pid, "unknown") # removed from the world
ctx.tokens[1].pos = (3000.0, 3000.0)
check ctx.greyFor(Pid, "near") # moved away
ctx.tokens[1].gmOnly = true
ctx.tokens[1].pos = (500.0, 400.0)
check ctx.greyFor(Pid, "near") # a gm_only flip greys it, it is not deleted
test "the GM gets one list per player, tagged with the player id":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("theirs", 400, 400, Other)],
@[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine", descriptiveName: "a mine")
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
let lists = frames.filterIt(it["t"].getStr == "encountered")
check lists.len == 2
check lists[0]["player"].getInt == Pid
check lists[0]["set"][0]["id"].getStr == "mine"
check lists[1]["player"].getInt == Other
check lists[1]["set"][0]["id"].getStr == "theirs"
test "a player never receives another player's list":
var ctx = ctxOf(sceneWith(@[]), @[tok("theirs", 400, 400, Other)], @[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
for f in frames.filterIt(it["t"].getStr == "encountered"):
check f["set"].len == 0
check not f.hasKey("player")
+543
View File
@@ -0,0 +1,543 @@
// M3 slice 8 (#23): characters and names over the real wire - `character.create`/`update`/
// `remove`/`reassign`, the per-player reveal of an actual name (`name.reveal`, `name.reveal_all`),
// the per-player encountered list (`encountered.remove`), character props through `prop.*`, the
// token link (`character_id`), and the players/keys half that gives a player a name
// (`player.setname`, `player.rename`, `key.show`, `roster`).
//
// The leak/fault proof lives in tools/leak.test.mjs + tools/leakcheck.nim; this file is the
// "characters and names" acceptance group of DESIGN 13: reveal per player and to all, the owner
// sees its own actual name, an owner change leaves token controllers alone, encountered survives
// token removal and a `gm_only` flip, and a status source is never shown to a non-GM.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, openWs, sleep } from './lib.mjs'
import { signIn, withGmServer } from './withserver.mjs'
async function gmConnect(origin, gmKey) {
const { cookie } = await signIn(origin, gmKey)
const ws = await openWs(origin, cookie)
const hello = await ws.waitText('hello')
await ws.waitText('walls')
return { ...{ ws }, sceneId: hello.scene.id, scene: hello.scene }
}
// A player connection that names itself the way a browser does: sign in, connect, `player.setname`,
// then the second `hello` (6.1) and the resync (6.3).
async function connectNamed(origin, key, name) {
const { cookie } = await signIn(origin, key)
const ws = await openWs(origin, cookie)
await ws.waitText('hello')
const from = ws.messages.length
const ack = await ws.request({ t: 'player.setname', name })
assert.equal(ack.ok, true, `player.setname refused: ${JSON.stringify(ack)}`)
const hello = await ws.waitFor((m, i) => i >= from && m.t === 'hello')
return { ws, hello, ack }
}
// One intent plus a cursor, so a wait can never be satisfied by an older frame.
async function mutate(client, payload) {
const from = client.messages.length
const ack = await client.request(payload)
return {
ack,
wait: (pred, ms = 5000) => client.waitFor((m, i) => i >= from && pred(m), ms),
eventually: async (pred, ms = 5000) => {
const deadline = Date.now() + ms
for (;;) {
const hit = client.messages.find((m, i) => i >= from && pred(m))
if (hit) return hit
if (Date.now() > deadline) throw new Error(`no matching frame in ${ms} ms`)
await sleep(10)
}
},
}
}
const characterFrames = ws => ws.messages.filter(m => m.t === 'character')
const encounteredFrames = ws => ws.messages.filter(m => m.t === 'encountered')
test('player.setname: the first name, the second hello, a roster to everyone, and the codes of 6.1',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const bob = await createPlayer(gm.ws)
const a = await openAs_(s.origin, alice.key)
const hello = await a.ws.waitText('hello')
assert.equal(hello.me.name, null, 'a fresh key has no name yet')
assert.equal(hello.scene, undefined, 'an unnamed player gets no scene block (6.1)')
const from = a.ws.messages.length
const ack = await a.ws.request({ t: 'player.setname', name: ' Alice ' })
assert.equal(ack.ok, true)
const named = await a.ws.waitFor((m, i) => i >= from && m.t === 'hello')
assert.equal(named.me.name, 'Alice', 'the name is trimmed before it is stored (6.5)')
assert.equal(named.scene.id, 1, 'a named player gets the scene block')
const roster = await a.ws.waitFor((m, i) => i >= from && m.t === 'roster')
assert.deepEqual(roster.players.map(p => p.name).sort(), ['Alice', 'GM'],
'a player sees the named players only (6.1 leak note 4)')
assert.equal(roster.players.find(p => p.name === 'Alice').connected, true)
assert.equal(roster.players.find(p => p.name === 'GM').connected, true)
// the GM hears about it too
const gmRoster = await gm.ws.waitFor(m => m.t === 'roster' && m.players.some(p => p.name === 'Alice'))
assert.equal(gmRoster.players.filter(p => p.name === null).length, 1, 'the unused key, name: null')
// a second setname is refused (6.1: only while own name is null)
assert.equal((await a.ws.request({ t: 'player.setname', name: 'Alicia' })).code, 'not-allowed')
// a taken name, in another case, is refused
const b = await openAs_(s.origin, bob.key)
await b.ws.waitText('hello')
const taken = await b.ws.request({ t: 'player.setname', name: 'alice' })
assert.equal(taken.code, 'name-taken')
assert.equal((await b.ws.request({ t: 'player.setname', name: 'GM' })).code, 'name-taken',
'the GM name is a name like any other (6.5)')
for (const bad of ['', ' ', 'two\nlines', 'x'.repeat(33)]) {
assert.equal((await b.ws.request({ t: 'player.setname', name: bad })).code, 'invalid',
JSON.stringify(bad))
}
// the GM does not name itself on the wire (its name comes from the CLI)
assert.equal((await gm.ws.request({ t: 'player.setname', name: 'Boss' })).code, 'not-allowed')
b.ws.close(); a.ws.close(); gm.ws.close()
})
})
test('player.rename and key.show: the GM renames, re-shows a key, and never touches its own',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const rename = await mutate(gm.ws, { t: 'player.rename', id: alice.id, name: 'Alicia' })
assert.equal(rename.ack.ok, true)
const roster = await rename.wait(m => m.t === 'roster' && m.players.some(p => p.name === 'Alicia'))
assert.ok(roster)
await a.ws.waitFor(m => m.t === 'roster' && m.players.some(p => p.name === 'Alicia'))
assert.equal((await gm.ws.request({ t: 'player.rename', id: alice.id, name: 'GM' })).code,
'name-taken')
assert.equal((await gm.ws.request({ t: 'player.rename', id: 999, name: 'Nobody' })).code,
'not-found')
assert.equal((await gm.ws.request({ t: 'player.rename', id: alice.id, name: '' })).code,
'invalid')
// renaming to the same name (the player's own) is not "taken"
assert.equal((await gm.ws.request({ t: 'player.rename', id: alice.id, name: 'alicia' })).ok,
true)
const shown = await gm.ws.request({ t: 'key.show', id: alice.id })
assert.equal(shown.ok, true)
assert.equal(shown.key, alice.key, 'Q11: the GM can re-show a player key')
const gmSelf = await gm.ws.request({ t: 'key.show', id: 1 })
assert.equal(gmSelf.code, 'not-allowed', 'the GM key is CLI-only (3.2)')
assert.equal((await gm.ws.request({ t: 'key.show', id: 999 })).code, 'not-found')
// a player may not see another player's key (G-only, 6.5 step 6)
assert.equal((await a.ws.request({ t: 'key.show', id: alice.id })).code, 'not-allowed')
a.ws.close(); gm.ws.close()
})
})
test('character.create: the record reaches the GM and the owner only, and the codes of 6.1',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const bob = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const b = await connectNamed(s.origin, bob.key, 'Bob')
const create = await mutate(gm.ws, { t: 'character.create', descriptive_name: 'a grumpy man',
actual_name: 'Lord Vex', owner: alice.id,
props: { public: { klass: 'fighter' },
owner: { hp: 12 }, gm: { secret: true } } })
assert.equal(create.ack.ok, true)
assert.equal(typeof create.ack.id, 'string')
assert.equal(create.ack.id.length, 12, 'the same id alphabet as a token (8)')
const gmFrame = await gm.ws.waitFor(m => m.t === 'character' && m.id === create.ack.id)
assert.equal(gmFrame.owner, alice.id)
assert.deepEqual(gmFrame.revealed, [])
assert.equal(gmFrame.reveal_all, false)
assert.deepEqual(Object.keys(gmFrame.props).sort(), ['gm', 'owner', 'public'])
const ownerFrame = await a.ws.waitFor(m => m.t === 'character' && m.id === create.ack.id)
assert.equal(ownerFrame.owner, undefined, 'an owner is never told `owner`')
assert.equal(ownerFrame.reveal_all, undefined, 'nor `reveal_all`')
assert.equal(ownerFrame.revealed, undefined, 'nor who else was told the name')
assert.equal(ownerFrame.actual_name, 'Lord Vex', 'the owner always sees the actual name (8)')
assert.deepEqual(Object.keys(ownerFrame.props).sort(), ['owner', 'public'])
await sleep(120)
assert.equal(characterFrames(b.ws).length, 0, 'no other player gets a character record (T16)')
// codes
assert.equal((await gm.ws.request({ t: 'character.create', descriptive_name: '',
actual_name: 'X' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'character.create', descriptive_name: 'a',
actual_name: 'X', owner: 999 })).code, 'not-found')
assert.equal((await gm.ws.request({ t: 'character.create', descriptive_name: 'a',
actual_name: 'X', props: { nope: {} } })).code, 'invalid')
// G-only
assert.equal((await a.ws.request({ t: 'character.create', descriptive_name: 'a',
actual_name: 'X' })).code, 'not-allowed')
b.ws.close(); a.ws.close(); gm.ws.close()
})
})
test('names: the owner sees the actual name, a reveal covers one player, reveal_all covers everyone',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const bob = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const b = await connectNamed(s.origin, bob.key, 'Bob')
// Owned by the GM: neither viewer owns it, so both see the descriptive name (8)
const char = await gm.ws.request({ t: 'character.create', descriptive_name: 'a cloaked figure',
actual_name: 'Lady Vex' })
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], character_id: char.id })
assert.equal(tok.ok, true, 'a linked token needs no names of its own (6.1)')
// Both players control a token next to the linked one, so both see it while it is unrevealed
await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [350, 400],
descriptive_name: 'Alice', actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [350, 450],
descriptive_name: 'Bob', actual_name: 'Bob', controller: bob.id,
flags: { vision: true } })
const seen = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
assert.equal(seen.name, 'a cloaked figure', 'the descriptive name until a reveal (8)')
assert.equal(seen.character_id, undefined, 'character_id only for the owner and the GM')
assert.deepEqual(seen.cprops, { public: {} })
// the character's public bucket reaches someone who sees one of its tokens
const prop = await mutate(gm.ws, { t: 'prop.set', target: 'character', id: char.id,
bucket: 'public', key: 'rank', value: 'noble' })
assert.equal(prop.ack.ok, true, 'prop.set now honours target:"character" (6.1)')
const withProp = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.cprops.public.rank === 'noble')
assert.equal(withProp.cprops.owner, undefined, 'the owner bucket of a character stays private')
await gm.ws.request({ t: 'prop.set', target: 'character', id: char.id, bucket: 'gm',
key: 'trap', value: true })
await gm.ws.request({ t: 'prop.set', target: 'character', id: char.id, bucket: 'owner',
key: 'hp', value: 3 })
await sleep(120)
const bobCprops = b.ws.messages.filter(m => m.t === 'token' && m.id === tok.id).pop()
assert.deepEqual(Object.keys(bobCprops.cprops), ['public'],
'cprops carries the public bucket and nothing else')
// reveal to Alice only
const reveal = await mutate(gm.ws, { t: 'name.reveal', subject: 'character', id: char.id,
player: alice.id })
assert.equal(reveal.ack.ok, true)
const revealed = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.name === 'Lady Vex')
assert.ok(revealed)
const gmReveal = await gm.ws.waitFor(m => m.t === 'character' && m.id === char.id &&
m.revealed.includes(alice.id))
assert.ok(gmReveal)
await b.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
await sleep(100)
const bobToken = b.ws.messages.filter(m => m.t === 'token' && m.id === tok.id).pop()
assert.equal(bobToken.name, 'a cloaked figure', 'the reveal was for Alice only')
// reveal_all covers everyone, idempotently
assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'character',
id: char.id })).ok, true)
await b.ws.waitFor(m => m.t === 'token' && m.id === tok.id && m.name === 'Lady Vex')
assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'character',
id: char.id })).ok, true)
// codes: a token that has a character is revealed through the character (6.1)
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token', id: tok.id,
player: alice.id })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'nope', id: char.id,
player: alice.id })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'character', id: 'nope',
player: alice.id })).code, 'not-found')
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'character', id: char.id,
player: 999 })).code, 'not-found')
b.ws.close(); a.ws.close(); gm.ws.close()
})
})
test('a plain token has its own names: reveal, reveal_all and the cprops of a plain token',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'item',
pos: [400, 400], descriptive_name: 'a rune',
actual_name: 'The Rune' })
const mine = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [350, 400], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
assert.ok(mine.ok)
const seen = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
assert.equal(seen.name, 'a rune')
assert.deepEqual(seen.cprops, { public: {} }, 'a plain token still carries cprops (leak note 3)')
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token', id: tok.id,
player: alice.id })).ok, true)
await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id && m.name === 'The Rune')
// the GM frame keeps the reveal bookkeeping for a plain token
const gmFrame = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.revealed.includes(alice.id))
assert.equal(gmFrame.reveal_all, false)
assert.equal(gmFrame.actual_name, 'The Rune')
a.ws.close(); gm.ws.close()
})
})
test('character.reassign: the character changes hands and the token controllers do not (3.1, 8)',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const bob = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const b = await connectNamed(s.origin, bob.key, 'Bob')
const char = await gm.ws.request({ t: 'character.create', descriptive_name: 'a grumpy man',
actual_name: 'Lord Vex', owner: bob.id })
// Alice controls a token next to the linked one, so she sees it while not owning the character
await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [350, 400],
descriptive_name: 'Alice', actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
// the token starts controlled by the character's owner (6.1 default)
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], character_id: char.id })
const gmTok = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
assert.equal(gmTok.controller, bob.id, "a new linked token is controlled by the character's owner")
const before = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
assert.equal(before.character_id, undefined, 'not her character yet (6.1 note 2)')
assert.equal(before.name, 'a grumpy man')
const aFrom = a.ws.messages.length
const reassign = await mutate(gm.ws, { t: 'character.reassign', id: char.id, owner: alice.id })
assert.equal(reassign.ack.ok, true)
await a.ws.waitFor(m => m.t === 'character' && m.id === char.id)
await b.ws.waitFor(m => m.t === 'character_gone' && m.id === char.id)
const after = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.controller === bob.id)
assert.equal(after.controller, bob.id, 'a character owner change never moves a controller (3.1)')
const mine = await a.ws.waitFor((m, i) => i >= aFrom && m.t === 'token' &&
m.id === tok.id && m.character_id === char.id)
assert.equal(mine.mine, false, 'the token is still Bob\'s')
assert.equal(mine.name, 'Lord Vex', 'the owner of the character sees the actual name')
// codes
assert.equal((await gm.ws.request({ t: 'character.reassign', id: char.id, owner: 999 })).code,
'not-found')
assert.equal((await gm.ws.request({ t: 'character.reassign', id: 'nope', owner: alice.id })).code,
'not-found')
b.ws.close(); a.ws.close(); gm.ws.close()
})
})
test('character.update and character.remove: rename, in-use, and a token link that must be cut first',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const char = await gm.ws.request({ t: 'character.create', descriptive_name: 'a grumpy man',
actual_name: 'Lord Vex', owner: alice.id })
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], character_id: char.id })
const rename = await mutate(gm.ws, { t: 'character.update', id: char.id,
descriptive_name: 'a tall stranger' })
assert.equal(rename.ack.ok, true)
const frame = await a.ws.waitFor(m => m.t === 'character' && m.id === char.id &&
m.descriptive_name === 'a tall stranger')
assert.equal(frame.actual_name, 'Lord Vex')
const gmTok = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.name === 'a tall stranger')
assert.equal(gmTok.character_id, char.id)
assert.equal((await gm.ws.request({ t: 'character.update', id: char.id })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'character.update', id: 'nope',
actual_name: 'X' })).code, 'not-found')
// `props` is not a `character.update` field (6.1): it is an unknown field, so it is ignored
// (6.2) and the intent then names no field at all, which is `invalid`.
const withProps = await gm.ws.request({ t: 'character.update', id: char.id,
props: { public: {} } })
assert.equal(withProps.code, 'invalid')
// in-use while a token links it (6.5)
assert.equal((await gm.ws.request({ t: 'character.remove', id: char.id })).code, 'in-use')
// unlinking needs both names (6.1)
assert.equal((await gm.ws.request({ t: 'token.update', id: tok.id,
character_id: null })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'token.update', id: tok.id, character_id: null,
descriptive_name: 'a wolf',
actual_name: 'Fang' })).ok, true)
const unlinked = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.character_id === null &&
m.descriptive_name === 'a wolf')
assert.equal(unlinked.actual_name, 'Fang')
assert.equal((await gm.ws.request({ t: 'character.remove', id: char.id })).ok, true)
await a.ws.waitFor(m => m.t === 'character_gone' && m.id === char.id)
assert.equal((await gm.ws.request({ t: 'character.remove', id: char.id })).code, 'not-found')
// a token cannot be linked with names of its own (6.1)
assert.equal((await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [100, 100], character_id: char.id,
descriptive_name: 'x', actual_name: 'X' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [100, 100], character_id: 'nope' })).code, 'not-found')
a.ws.close(); gm.ws.close()
})
})
test('encountered: a sighting is kept under the name the player knows, and survives everything',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const mine = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
const other = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
pos: [500, 400], descriptive_name: 'a wolf',
actual_name: 'Fang' })
assert.ok(mine.ok && other.ok)
const entry = await a.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(e => e.id === other.id))
assert.equal(entry.full, false)
const e = entry.set.find(x => x.id === other.id)
assert.equal(e.name, 'a wolf', 'the name the player knows (8)')
assert.equal(e.grey, false)
assert.equal(e.character_id, undefined, 'no character link for a player (6.1)')
assert.equal(e.pos, undefined, 'no position either')
// a reveal updates the snapshot
await gm.ws.request({ t: 'name.reveal', subject: 'token', id: other.id, player: alice.id })
const told = await a.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(x => x.id === other.id && x.name === 'Fang'))
assert.ok(told)
// `gm_only` hides the token but the entry stays, greyed (8)
const hidden = await mutate(gm.ws, { t: 'token.update', id: other.id, gm_only: true })
assert.equal(hidden.ack.ok, true)
const greyed = await a.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(x => x.id === other.id && x.grey === true))
assert.deepEqual(greyed.del, [], 'nothing is deleted by a gm_only flip')
await gm.ws.request({ t: 'token.update', id: other.id, gm_only: false })
// removing the token keeps the entry (still greyed)
assert.equal((await gm.ws.request({ t: 'token.remove', id: other.id })).ok, true)
await a.ws.waitFor(m => m.t === 'token_gone' && m.id === other.id)
const still = await a.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(x => x.id === other.id && x.grey === true))
assert.ok(still)
// only the GM removes an entry, and `del` tells the player
const gone = await mutate(gm.ws, { t: 'encountered.remove', player: alice.id, id: other.id })
assert.equal(gone.ack.ok, true)
const del = await a.ws.waitFor(m => m.t === 'encountered' && (m.del ?? []).includes(other.id))
assert.deepEqual(del.set, [])
assert.equal((await gm.ws.request({ t: 'encountered.remove', player: alice.id,
id: other.id })).code, 'not-found')
assert.equal((await gm.ws.request({ t: 'encountered.remove', player: 999,
id: other.id })).code, 'not-found')
// the GM sees one list per player, tagged with the player id
const gmList = await gm.ws.waitFor(m => m.t === 'encountered' && m.player === alice.id)
assert.ok(gmList)
// a connection that starts later gets the whole list (`full:true`, 6.1)
const a2 = await openAs_(s.origin, alice.key)
const full = await a2.ws.waitFor(m => m.t === 'encountered' && m.full === true)
assert.ok(full.set.some(x => x.id === mine.id), 'the list is the list the player had')
a2.ws.close()
a.ws.close(); gm.ws.close()
})
})
test('a status source is never shown to a non-GM, the controller included (5.5, 6.1 note 6)',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
assert.equal((await gm.ws.request({ t: 'status.set', id: tok.id, status: 'stuck' })).ok, true)
assert.equal((await gm.ws.request({ t: 'status.set', id: tok.id, status: 'squeezed' })).ok,
true)
const gmView = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.statuses.length === 2)
assert.deepEqual(gmView.statuses, [{ status: 'squeezed', source: 'GM' },
{ status: 'stuck', source: 'GM' }].sort(
(x, y) => x.status.localeCompare(y.status)).reverse(),
'the GM sees the cause')
const playerView = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.statuses.length === 2)
assert.deepEqual(playerView.statuses.map(x => x.status).sort(), ['squeezed', 'stuck'])
for (const st of playerView.statuses) {
assert.deepEqual(Object.keys(st), ['status'], 'no `source` on a player entry')
}
a.ws.close(); gm.ws.close()
})
})
test('restart: characters, reveals and encountered lists come back', async () => {
const { makeStateDir, gmKeyOf, startServer, stopServer } = await import('./withserver.mjs')
const fs = await import('node:fs')
const stateDir = makeStateDir()
try {
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let saved
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await createPlayer(gm.ws)
const a = await connectNamed(s.origin, alice.key, 'Alice')
const char = await gm.ws.request({ t: 'character.create', descriptive_name: 'a cloaked figure',
actual_name: 'Lady Vex', owner: alice.id,
props: { public: { rank: 'noble' },
owner: { hp: 5 } } })
const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], character_id: char.id })
await gm.ws.request({ t: 'name.reveal_all', subject: 'character', id: char.id })
await a.ws.waitFor(m => m.t === 'encountered' && m.set.some(e => e.id === tok.id))
saved = { char, tok, alice }
a.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const gmChar = await gm.ws.waitFor(m => m.t === 'character' && m.id === saved.char.id)
assert.equal(gmChar.reveal_all, true)
assert.equal(gmChar.actual_name, 'Lady Vex')
assert.deepEqual(gmChar.props.public, { rank: 'noble' })
const gmTok = await gm.ws.waitFor(m => m.t === 'token' && m.id === saved.tok.id)
assert.equal(gmTok.character_id, saved.char.id)
assert.equal(gmTok.name, 'a cloaked figure')
// The name survived, so this is a plain signed-in connection (no `player.setname`).
const a = await openAs_(s.origin, saved.alice.key)
const hello = await a.ws.waitText('hello')
assert.equal(hello.me.name, 'Alice', 'the display name survived the restart')
const enc = await a.ws.waitFor(m => m.t === 'encountered' && m.full === true)
assert.ok(enc.set.some(e => e.id === saved.tok.id), 'the sighting survived the restart')
assert.equal(enc.set.find(e => e.id === saved.tok.id).name, 'Lady Vex',
'the reveal_all survived too')
const tokFrame = await a.ws.waitFor(m => m.t === 'token' && m.id === saved.tok.id)
assert.equal(tokFrame.character_id, saved.char.id)
a.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
// Local alias so the imports stay at the top of the file.
async function openAs_(origin, key) {
const { cookie } = await signIn(origin, key)
const ws = await openWs(origin, cookie)
return { ws, cookie }
}