Commands and what each page sees
A game in a room talks to it in three ways beyond the input every page sends each tick.
Send the room a command
Section titled “Send the room a command”Moves, walks, shots and item verbs need no code of the game’s own. For anything else a player asks for, such as “I am ready”, “I take this card” or “buy two potions”, a game declares a command on a plugin with defineCommand, by the fields of its payload, and a system on the room answers it. The page awaits one result for each command it sends: accepted, with a value the command declares, or refused, with a reason. The game lists the plugin in its plugins, so the room’s world and every page’s know the same command:
import { addTrait, defineCommand, definePlugin, defineTrait, findWalletHolder, integer, readCommands, setTrait, spendCoins, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";
// A potion stall, built as a creator's plugin is, from the engine's public// entry alone: a page asks to buy, and the reader on the room checks the// buyer's wallet before it sells, then answers with the potions the// buyer now holds.
/** Coins one potion costs. */export const potionPrice = 5;
/** The most potions the player * entity may hold. */export const mostPotions = 10_000;
/** The potions the * player entity holds. */export const PotionsTrait = defineTrait("potions", { count: 0 });
/** Sells each buyer their potions where the buyer has room for them and * the buyer's wallet holds their price, and refuses `bag-full` or * `too-poor` before anything changes where the buyer has not. */function sell(step: AuthoritativeStep) { const world = step.world; for (const command of readCommands(step, market.commands.buy)) { const { player, payload } = command; const count = (player.get(PotionsTrait)?.count ?? 0) + payload.count; if (count > mostPotions) { command.refuse("bag-full"); continue; } const wallet = findWalletHolder(world, player); if (!spendCoins(step, wallet, payload.count * potionPrice)) { command.refuse("too-poor"); continue; } setTrait(step, player, PotionsTrait, { count }); command.accept({ potions: count }); }}
export const market = definePlugin(() => ({ name: "market", commands: { // The payload names what the buyer wants, never its price: the // reader reads the price and the buyer's wallet from the world. buy: defineCommand( { count: integer(1, 10) }, { refusals: ["bag-full", "too-poor"], returns: { potions: integer(0, mostPotions) }, }, ), }, // A command's reader runs on the room alone, which decides the sale. systems: [ defineSystem({ name: "sell", phase: Phase.Rules, answers: ["buy"], run: sell, }), ], onPlayerJoin: ({ step, player }) => { addTrait(step, player, PotionsTrait); },}));The stall adds the player’s potions in onPlayerJoin. What the player owns beyond the player entity, such as a flag the player planted, comes down in onPlayerLeave(step, player, { reason }). It runs on the room as the player leaves, before the core destroys the player entity, so the hook still reads the player entity and destroy(step, flag) takes the player’s flag down. What a plugin adds to a player lists the player hooks.
defineCommand(fields, options) takes no name, unlike defineTrait and defineEvent. The plugin names the command by its key under commands: market registers market.buy, and hands back its handle as market.commands.buy. Every call reaches the command through that handle. A plugin that takes options reads them in the function definePlugin takes, as Plugins shows, and the factory carries the handles, such as matches.commands.start for the engine’s matches().
A page sends market.buy with sendCommand(world, market.commands.buy, { count: 2 }). Import sendCommand and useWorld from @spawnite/engine. A command with no fields can take a key and a touch button instead, so the game writes no key listener, as its options say.
The handle types the payload, reasons and result, so a missing or wrong field fails to typecheck. sendCommand returns a promise that never rejects:
CommandStatus.Accepted, withvalueset to what the reader passed toaccept, here{ potions: 2 }.CommandStatus.Refused, withreason, one of the command’srefusalsor the engine’s ownCommandRefusal.CommandStatus.Unknown, in a room alone: the sender’s page lost the room before the result came. The command may have run, so a game reads the world again rather than tell the sender it failed.
A HUD shows the outcome where it awaits the call, or reads useCommandResults(handle) for the sender’s last 16 results of one handle, each Pending from the moment the sender sends it, or useLatestCommandResult(handle) for the newest alone.
A command asks, and the room decides. The payload names what the player wants; the reader checks it against the world before it changes anything. A “buy” command carries the count, never the price, and the reader reads the price and the player’s wallet from the world. A command never states a fact the room would have to take the player’s word for, such as the player’s score or balance, or the character’s position. An amount the player asks for or offers is a request, such as five coins for a trade, and the reader checks the player holds it.
Read and settle each command
Section titled “Read and settle each command”The system that answers a command sits under the phase it runs in, here rules, which judges what the step did. Its entry names the command’s key in answers, as answers: ["buy"], and the system reads the commands with readCommands(step, handle), from @spawnite/engine/core, in the order the room took them. Leave answers out and the read fails: a command no system answers throws as the world is made, and in development a system that reads a command its entry does not list throws at the read. Each error names the key to add.
Each command holds player, the sender’s player entity, and payload, checked, with each entity field resolved to the room’s own copy. A command declared entity: true also holds entity, the entity it acts through; on any other command, command.entity fails to typecheck. A system finds every player with readPlayers(world), and a page finds its own with usePlayer() or readLocalPlayer(world). Both read undefined until the local player’s page has joined, so a HUD checks for the player entity before it reads the player entity’s traits or sends. The reader settles each command it reads in one of three ways:
accept(value)runs it, with the value the command’sreturnsdeclares, or with nothing where it declares none.refuse(reason, detail)answers it with one of the command’srefusals, and an optional short line of detail. Any other reason fails to typecheck, an engine reason such asfaultedamong them: a reason the reader may give is one the command declares, orworld-fullfor its own check of the world’s size. The detail reaches the sender’s page, so it never names what the sender may not know. A refusal undoes nothing the reader already wrote, so a reader checks before it writes, asspendCoinschecks and spends in one call.addCoins(step, player, coins)adds to the player’s wallet, as a reward or a refund does; both live in@spawnite/engine/core.defer()leaves it queued for the system’s next run, such as a purchase that waits for a shop to open.
One system answers each command. The composer refuses a world where two systems answer one command, where none does, or where a system reads a command another one answers: a system that wants to know what happened reads an event the answering system emits instead. A reader of a command the sender’s page does not predict runs on the room alone, so its system takes no predicted or runsOn; a predicted command’s reader is a predicted system, as Build a predicted mechanic shows. A command its system leaves unsettled is refused faulted, and in development the step throws, naming the system. readCommands(step, [shop.commands.buy, shop.commands.sell]) reads two handles of one plugin in one pass, in the order the room took them, and the reader branches on command.key; its system lists both in answers.
In a game played alone, sendCommand takes the same path: the world’s own next step admits the command with the same checks and runs the same reader, and the promise settles the same way, so single player needs no second code path. A scene’s bot sends a command with writeCommand(step, bot, { command, payload }), from @spawnite/engine/core.
Fields, options and refusals
Section titled “Fields, options and refusals”A field is one of the following, each from @spawnite/engine/core, and a payload holds every field it declares and no other. A command with no payload declares {}.
integer(min, max)andnumber(min, max): a whole number, or any finite number, in range.boolean(): true or false.oneOf(["red", "teal"]): one value of a closed set, given as a list of strings, a string enum such asoneOf(DoorState), or a registry the world holds. The room refuses a value outside the set, so no command carries free text.entity()andentities(maxLength): an entity on the room, or a list of at mostmaxLength.entity({ optional: true })holds null where the sender names none.controlled(maxLength): a selection of entities the sender controls, such as the units the sender ordered. The command’s result names inskippedthose the sender no longer controlled.vector3()andlist(field, maxLength): a point, or a list of one single-value kind.worldId(): a world’s id, such as one the player’s directory lists, read as aWorldId. The room checks its shape alone, so the reader checks what the sender may do with that world, such as fetching its keyed save.
The wire carries an entity as the key the room files it under, and the room refuses entity-gone a command whose entity is gone.
defineCommand(fields, options) takes these options beside the fields:
refusals: the reasons its reader may refuse it with, kebab-case codes such as["too-poor", "occupied"].returns: the fields of the value an accepted command carries back, such as{ building: entity() }. A returned entity the sender’s page does not hold reads as null there.entity: true: the command acts through one entity the sender controls, whichsendCommandnames in itsentityoption and the reader reads ascommand.entity. The room runs it only while the sender still controls that entity.lifetime: what ends it before it runs, aCommandLifetime.Session, the default with no entity, ends only when the sender leaves.Levelalso ends with the level the sender sent it in.Entityalso ends when the entity it acts through is destroyed.Control, the default withentity: true, also ends when the sender’s control of that entity changes.Matchalso ends with the contest the sender was in as the sender sent it, refusedmatch-changedonce the sender’s match changed or reset, so a serve sent before a reset never lands in the next match.perSecondandburst: how many the sender may send each second, 4 by default, any number above 0 and up to 60, such as 0.5 for one every two seconds, and how many at once past that, at most 16 and 2 by default. They guard against a flood, not a game rule.timeoutSeconds: how long it may wait in its queue for its reader, 10 seconds by default.rewind: how far back the room may judge it, asRewindBounds. The room holds the step the sender’s screen drew as the sender sent it within those bounds of the sender’s latency, and a query or a read withrewind: commandmeets the world there, as Rewind a game’s own weapon shows. By default, 200 ms either side of the sender’s latency and at most a second back.predicted: true: the sender’s page runs it on its tick as a guess, and the room runs it on the same tick and decides. It needsentity: true, and its reader is a predicted system.lateSecondssays how late it may reach the room and still run, 0.28 seconds by default, counted in the room’s ticks.keysandtouch: the keys that send a command with no fields, byKeyboardEvent.code, and a button for it on a phone. Each press sends it assendCommanddoes, such asplant: defineCommand({}, { entity: true, keys: ["KeyG"], touch: { label: "Plant" } }). The engine draws the button on a phone, as Touch controls says. Withentity: true, a key sends it through the entity the player’s keys steer.
The engine refuses with its own reasons, the same in a room and alone, so a HUD can show a line for each. They are malformed for a field out of its kind or a payload past 16,384 bytes, too-fast past the rate, too-many past 64 of the sender’s commands with no result, and not-active where the command’s plugin does not run. The rest are entity-gone, not-controlled, level-changed, player-left, room-closing, timed-out, late for a predicted command that reached the room past its lateSeconds, faulted, and world-full. The last is a spawn a full world refused, as A world’s size says. commandRefusalLines, from @spawnite/engine, holds a plain line for each, which a game spreads into its own: { ...commandRefusalLines, "too-poor": "Not enough coins" }. The sender’s page refuses at once what it can check as the room would, so a command the room would refuse for its shape, its rate or the sender’s control never leaves the page.
A resend runs once. Each page numbers its commands, and after a broken socket the sender’s page resends what it never heard answered: the room answers a resend of a command it already settled with the first result, and never runs it again. A game writes no duplicate check of its own.
Roblox’s RemoteFunction is the closest shape: a call the client awaits. A command differs from it in four places. Its result is typed and always arrives, refusals included, so no game writes its own reply. A resend runs once. A lifetime gives a race with a death or a level change one stated outcome. The engine’s refusals for rate, shape and lost control come with a reason the page can show, where Unreal disconnects the client and Godot logs.
An action the page should show at once, such as a dash, is a predicted command. It is the same defineCommand with predicted: true, sent with sendCommand or a key, and read with readCommands(step, handle) in a predicted system. It is shown in useLatestCommandResult first as the sender’s page’s guess, then as the room’s result. Build a predicted mechanic builds one.
When a command does nothing
Section titled “When a command does nothing”A button that seems to do nothing either sent no command, sent one the room refused, sent one that has no result yet, or sent one the room accepted whose effect the sender’s page does not show. Every command has exactly one result, so its reason says what happened. In a game played alone and in a room, read it in this order:
spawnite play stateprints aCommands:line for the local player’s page’s own player. It says how many the page sent, accepted, refused by each reason, unknown and with no result yet, and the last refusal with who refused it and on which tick, such asthe last refused: market.buy, too-poor, by market.sell at tick 1204. NoCommands:line means the button never calledsendCommand:spawnite play command market.buy '{"count":2}'sends the command with no button and prints its result, which tells the button’s wiring from the command.- Read the reason. One the command declares, such as
too-poor, came from its reader, the system named afterby. An engine reason names its cause:too-fastfor the rate,not-controlledfor an entity the sender does not control, andnot-activefor a command whose plugin does not run or whose answering system was omitted.timed-outis for a reader that kept deferring it or a schedule that ran past itstimeoutSeconds, and the rest are as the list above says. A plugin the game does not list at all never gets this far:sendCommandthrows, naming the plugin to add. spawnite play dump --commandsprints the last 64 commands one by one. Each has its result, its reason and detail, the tick the sender’s page sent it on, the tick its result was settled on, and who settled it, aCommandSettler. That ispagewhere the sender’s page refused it before it left,roomfor the engine’s own refusal, orsystemwith the system’s name insystem. Underpendingit lists the sender’s commands with no result: one withisSent: falsehas not left the sender’s page, because the page is not joined or the sender’s socket is down, and goes once the sender rejoins. In a game played alone, where one world decides, the dump also holds the tick each was admitted on andqueues, each command still waiting for its reader with its age and the ticks left beforetimed-out. In a room those live on the room, which a page’s dump does not reach.- A command
acceptedwhose effect does not show ran on the room: read what its reader wrote withspawnite play dump --where, and check that the trait reaches the sender’s page, as Choose who a trait reaches says. - A predicted command whose entry reads
isUndone: trueran on the sender’s page as a guess and the room refused it, so its effect was taken back. Its reason says why the two ends decided apart.
The devtools’ Commands section, at the foot of the rail, lists the same timeline while you play. In a test, readCommandTimeline(world) from @spawnite/engine returns those entries, and dumpState(world).commands the whole section. A development world keeps the timeline; a built game keeps only the counts. A room’s own log counts its commands by reason in each heartbeat, as the development room says.
Tell every page what happened
Section titled “Tell every page what happened”A page that joins a room already playing gets the room’s world whole in its welcome, and so does a page that rejoins or a replay that opens mid-fight. Every entity a welcome brings carries the engine’s CaughtUpTrait trait on that page, and an entity that spawns after it does not, so a view plays a spawn effect only for what spawns while the player watches. An entity that enters the player’s view under interest culling carries it too. A monster the welcome brought stands up at once rather than climbing out of the ground. The mark is the page’s own, and no dump or hash carries it. Unreal marks a level’s own actors the same way, with bNetStartup; Roblox, Unity’s Netcode and Godot leave it to the game.
The same holds for an entity that goes. A welcome takes the whole stream down before it brings the world back, so an entity the new world leaves out, such as a monster that died before the moment a replay seeks to, is gone from the page as if the room had taken it away. The world’s WelcomesTrait trait counts the welcomes the page has taken. A view reads the count as its entity mounts and again as the entity goes: a count that moved means a welcome replaced the stream, so the view plays no death or despawn effect and the page shows only what the world holds. Unreal’s replays skip cosmetic effects the same way while they scrub, with IsFastForwarding. Under interest culling an entity also goes as it leaves the player’s view, with no welcome, so a view plays a death from the event that means it, never from its unmount.
A command goes from a page to the room; an event goes from the room to every page. A hit, a trigger crossed, a coin taken or a game’s own moment, such as a chain of lightning between two monsters, is an event the room emits. The room sends every event emitted since its last send beside the next delta, one entry per emit, and each page’s useEvent hears each once, to play a sound or draw a flash. A game makes its own with defineEvent and emits it with emitEvent, on an entity or about the world, and needs no code of its own to send it.
Choose who a trait reaches
Section titled “Choose who a trait reaches”The room streams a trait a game defines under its name. Two traits, two events or two behaviours may not share a name: a second definition under a name another of its kind holds throws and names both. A trait and its behaviour may share one, since the stream knows a trait by the trait’s name. A module that hot reload runs again, or a watched room imports again after an edit, defines its own anew, and each new definition takes its name.
A page holds only what it may see, receives a trait only within its reach, and reads as null anything that names an entity it does not hold. Three settings decide what a page receives:
| Setting | Set with | Default | What it decides |
|---|---|---|---|
| A trait’s reach | defineTrait’s reach |
Reach.Everyone; Reach.Owner for a predicted trait |
Which pages that hold an entity receive this trait of it |
| An entity’s visibility | setVisibility, or visibility on a spawn or a prefab |
Audience.Everyone; an audience entity’s own members |
Which pages hold the entity at all |
| An entity’s audience | setAudience, or audience on a spawn or a prefab |
Audience.Nobody |
Which pages receive its Reach.Audience traits |
An audience is Audience.Everyone, Audience.Owner, Audience.Nobody, one player, or an audience entity, which spawnAudience makes and whose members the room keeps with addAudienceMember and removeAudienceMember. Members stay on the room: a game that wants a team’s members to know each other streams a roster or their roles, as the sample’s impostors do.
Every one of these verbs runs on the room and takes an authority first: a system’s step, a join hook’s, or requireAuthority(world) in a test. setTrait(step, entity, Trait, value) writes a trait later, whatever its reach. The following sample keeps a hand, a team’s plan and marker, the roles of a hidden-role round, a deck, and a field that names a player:
import { addTrait, defineTrait, Reach, setAudience, spawn, spawnAudience, setTrait, type Authority, type AudienceEntity, type Entity, type PlayerEntity,} from "@spawnite/engine/core";
// Who sees what on two teams and in a hidden-role round, built from the// engine's public entry alone. Each player's hand reaches that player// alone, a team's plan reaches the team, a role reaches the impostors or// its own player, the deck stays on the room, and a marker a team drops is// held by that team's pages alone. Each function runs on the room, from a// system's step or a hook's, which is the authority it takes.
/** The player's cards: one page reads * them, the owner's. */export const HandTrait = defineTrait( "secretsHand", { cards: "" }, { reach: Reach.Owner },);
/** A team's plan, on the team's own entity: its audience's pages read * it, and no page reads it until the audience is set. */export const PlanTrait = defineTrait( "secretsPlan", { route: "" }, { reach: Reach.Audience },);
/** A player's role, on the player entity: the impostors read each * impostor's, and a crewmate alone reads the crewmate's own. One trait * for both roles, so no page learns a role from which trait * a player carries. */export const RoleTrait = defineTrait( "secretsRole", { role: "crew" }, { reach: Reach.Audience },);
/** Whom every page last accused: a field that names an entity, which a * page reads as null while it does not hold that entity. */export const AccusedTrait = defineTrait( "secretsAccused", { player: null as Entity | null }, { entities: ["player"] },);
/** The order of the deck: the room's rules read it, and no page does. */export const DeckTrait = defineTrait( "secretsDeck", { order: "" }, { reach: Reach.Authority },);
/** What a marker says: every page that holds the marker reads it. */export const MarkerTrait = defineTrait("secretsMarker", { label: "" });
/** Makes a team of `members` with its plan, which reaches the team: the * team is an audience entity, visible to its members alone, and its own * audience. */export function spawnTeam( authority: Authority, members: readonly PlayerEntity[], route: string,): AudienceEntity { const team = spawnAudience(authority, { members }); setAudience(authority, team, team); spawn(authority, { traits: [PlanTrait({ route })], audience: team, owner: team, }); return team;}
/** Drops a marker only `team`'s pages hold: every other page is never sent * it, nor any reference to it. */export function dropMarker( authority: Authority, team: AudienceEntity, label: string,) { return spawn(authority, { traits: [MarkerTrait({ label })], visibility: team, });}
/** Deals `player` their cards, which the player's * page alone receives. */export function dealHand( authority: Authority, player: PlayerEntity, cards: string,) { return spawn(authority, { traits: [HandTrait({ cards })], owner: player, });}
/** Deals the roles of a hidden-role round: `impostors` share an audience, * so each impostor's role reaches both of them, and each crewmate's role * reaches that crewmate alone. An audience's members stay on the room, * so a game that wants the impostors to know each other streams their * roles, as this does. */export function dealRoles( authority: Authority, players: readonly PlayerEntity[], impostors: readonly PlayerEntity[],): AudienceEntity { const pact = spawnAudience(authority, { members: impostors }); for (const player of players) { const isImpostor = impostors.includes(player); addTrait(authority, player, RoleTrait); setTrait(authority, player, RoleTrait, { role: isImpostor ? "impostor" : "crew", }); setAudience(authority, player, isImpostor ? pact : player); } return pact;}
/** Names `player` as the last accused on `board`, which every page * reads: `setTrait` writes a trait the room streams. */export function accuse( authority: Authority, board: Entity, player: PlayerEntity,) { setTrait(authority, board, AccusedTrait, { player });}reach takes one of five values:
reach |
Pages that hold the entity |
|---|---|
Reach.Everyone |
Every one |
Reach.Owner |
Its owner’s alone |
Reach.Audience |
Those of the players its audience names |
Reach.Authority |
None: the room alone holds it |
Reach.Local |
None: the room and each page keep their own |
The dump shows every trait, whatever its reach.
An entity’s owner is a player: the player for the player entity, the first player up its setOwner chain, else the player who controls it. So a pet the player owns, or a chest the player’s pet owns, sends the player its Reach.Owner traits, and findOwningPlayer reads who that is. When the owner changes, the new owner’s page receives those traits whole, and the old owner’s page loses them.
Use Reach.Owner for what one player alone may see, such as a hand of cards: another player’s page never receives it, so no changed page can read it. Use Reach.Audience for what a group sees, such as a team’s plan or a role the impostors share: the trait reaches no page until its entity’s audience is set. A player entity takes an audience too, so one role trait on each player reaches the impostors for an impostor and the player alone for a crewmate. Use Reach.Authority for what a rule reads and no page draws or predicts.
Use setVisibility for an entity some players must not know exists, such as a team’s marker or a hidden unit: a page outside its visibility is never sent the entity, its traits, its events or its key. Privacy wins over interest culling, over Relevance.Always and over an attachment. A player entity takes no visibility, by type: hide what the player controls with a control’s visibility instead.
A trait names each field that holds an entity in entities. An entity’s number means nothing on another world, so a streamed trait carries each such field as the key the room files the entity under, and a page reads the key back as its own copy. A field whose entity is gone, hidden from the page or outside its interest reaches the page as null, and nothing tells the three apart. When the entity enters the player’s view, the field goes again with its key. An event carries an entity to a page, as Tell every page what happened describes.
A trait names each field whose default cannot show the vector it holds in vectors, with the class it holds: { vectors: { target: Vector3 } }. The stream carries a Vector2, a Vector3 or a Quaternion as a list of numbers, and a page reads it back by the value it replaces. A field that defaults to null, an optional one, and a list that starts empty have no such value, so each fails to typecheck until vectors names it. A field inside a record or a list of records, down to five records, takes a dotted path, as "teams.points". A list of numbers that no value and no vectors names stays numbers, such as an optional [x, y, z] tuple. Unity’s GhostField and Unreal’s UPROPERTY know each field’s type from its declaration, and Godot’s Variant carries it on the wire.
Use Reach.Local for what the room and a page each work out for themselves and nothing rolls back, such as where a cast waiting on a walk sends the character. State of the player’s character that the player’s page predicts step by step, such as a dash’s timer, is predicted instead, which rolls it back with the character’s movement. A predicted trait reaches its owner unless its reach names more, Reach.Everyone for every page. A predicted control of an entity whose predicted trait leaves the controller out is refused with ControlRefusal.OutOfReach.
A page never holds a Reach.Authority trait, so a system that reads one there acts on its absence. A system that reads one runs on the room alone, which is the default. In development, a system that runs on a page throws on its first read of one, as A page’s read of a room-only trait describes.
Define each trait once, at module scope, in a module the room and the page both import. The name is a dump key: letters and digits, starting with a lower case letter. A predicted trait with Reach.Authority or Reach.Local fails to typecheck, and so does anyEntity without predicted. Every trait whose record holds an entity names each such field in entities, typed with | null, or it fails to typecheck, and so does every event. A predicted trait is a PredictedTrait, which koota’s own functions refuse, unless anyEntity: true keeps it koota’s own, as Build a predicted mechanic says.
A game can still give a secret away. Each of these is the game’s choice:
- A prefab names its kind. Spawning an impostor’s prefab rather than a crewmate’s tells every page the role: use one prefab, and keep the role in a
Reach.Audiencetrait. - A refusal names a cause.
"occupied"for a tile a hidden unit stands on tells the sender something stands there. - A scene file shows its entities. A secret entity is spawned by a system, not placed in a scene.
- A hidden collider shows through corrections. A page whose predicted mover walks into a hidden blocker is corrected without seeing why.
- Voice does not follow privacy. A hidden player who speaks gives away who they are: turn voice off for the game or the phase.
Unreal marks a property Replicated with a condition such as COND_OwnerOnly, and an unmarked property is each machine’s own, as Reach.Local is here. Unity’s Netcode gives a NetworkVariable a read permission of Everyone or Owner, and hides an object from a client with NetworkHide. Neither has a group between one owner and everyone, which Reach.Audience is. Godot filters a synchronizer’s visibility for each peer, and Roblox decides by where an instance is stored.
Prove no page receives a secret
Section titled “Prove no page receives a secret”A hidden-information game is fair only if no page is ever sent what its player may not see, since a modified page keeps whatever reached it. Three checks prove that, from the fastest to the one a test keeps:
- The development room’s guard. A development room reads every frame a second time before it leaves, decoded as the page decodes it, against the room’s own rules. Where the two disagree, the room closes and names the trait, the entity, the page and the send. The guard finds what the engine knows is private; The development room describes it.
spawnite play framesandspawnite play why. In a playtest,framesprints what one player’s page received andwhysays which rule let an entity or a trait reach it, as The director shows.capturePageTrafficandexpectNeverReceived, on@spawnite/engine/testing. A test joins pages to a real room, keeps every frame each receives, and fails on the first value a rule forbids. This check finds what only the game knows is private, such as a public field computed from a hand.
capturePageTraffic(room, { players: 4 }) takes a running room and joins that many pages, 2 when left out, named Page 1, Page 2 and so on. Each joins as a browser’s page does and sends no input. The room is the one startRoom of @spawnite/room answers. Started with director: true, it is stepped a tick at a time, so the test takes no time on the wall; closing the room ends the capture. The call answers the following:
pages, andpage(number)from 1: each with itsnumber, itsname, itsplayer, the room’s player entity, and itsframes, each frame asspawnite play framesprints one.play(seconds), which runs the room that long and waits until every page has received what it sent. It fails where the room closed a page’s socket, as a room that failed does.- On a page,
leave()leaves for good, as a player who quits does: the room takes the player entity out. - On a page,
rejoin()drops its socket and joins again with its rejoin key. The player entity stays the same, and the new welcome is among the page’s frames. - On a page,
isTraitEverReceived(entity, trait)says whether any frame carried a value of that trait on that entity. - On a page,
isTextEverReceived(text)searches what the page received for a string, in each frame’s bytes and in every string a frame decodes to. It finds a secret by the string the game writes; a secret kept as a number is read by a rule.
capturePageTraffic(room, { players: 4, seconds: 30, rejoin: true }) plays the room for that long and drops and rejoins page 1 halfway, for a game whose own systems deal and play.
expectNeverReceived(traffic, isForbidden) calls isForbidden with each value of a trait any page received, and fails where it answers true, naming the page, the frame and the value. A value a later message of the same frame replaced is still read. Each value carries the following:
page, the page that received it, andframe, which of the page’sframescarried it.traitandname, the trait and the name a dump writes it under, andvalue, the value as the frame carried it.entity, the room’s entity, or null where the room had destroyed it by the time the frame landed, andkey, the key the frame named it by.owner, the player aReach.Ownertrait of that entity reaches, read as the frame landed. A rule runs after the capture, when the entity may be gone, so it readsownerandvaluerather than the world.
For a Reach.Audience trait, a rule reads value and the test’s own record of who is in the audience, such as trait === RoleTrait && value.role === "impostor" && !impostors.includes(page.player).
The following test deals four pages a hand each at the card table of packages/room/test/outside/cards.ts, whose hand is Reach.Owner and whose deck is Reach.Authority. It plays a card face up, draws one, has one player leave and another rejoin. After each step it searches every page’s bytes for each card that page has not seen by then. Its openRoom is the room tests’ own helper, which calls startRoom with director: true:
import { requireAuthority } from "@spawnite/engine/core";import { capturePageTraffic, expectNeverReceived,} from "@spawnite/engine/testing";import { afterEach, expect, it } from "vitest";import { closeOpened, openRoom, playTimeout } from "./helpers/delayedClient.ts";import { dealRound, DeckTrait, drawCard, foldHand, HandTrait, listCards, PileTrait, playCard, readPlayerCards,} from "./outside/cards.ts";
// The card table of `outside/cards.ts` against a real room with its// privacy guard on: four pages through a deal, a card played face up, a// draw, a player who leaves and one who drops and rejoins. No page// receives another player's card, in a trait or anywhere in its bytes.
afterEach(closeOpened);
it( "sends no page another player's card through a deal, a reveal, a draw, a leaver and a rejoin", async () => { const room = await openRoom({ common: false }); const traffic = await capturePageTraffic(room, { players: 4 }); const authority = requireAuthority(room.world); const players = traffic.pages.map(({ player }) => player); // What each page may have read: its player's own cards, and each card // played face up. const seen = traffic.pages.map(() => new Set<string>()); const table = dealRound(authority, players, listCards(), 5); const noteHands = () => traffic.pages.forEach(({ player }, index) => { for (const card of readPlayerCards(table, player)) seen[index].add(card); }); const reveal = (card: string) => seen.forEach((set) => set.add(card)); /** Plays half a second, then searches each page's bytes for every * card its player has not seen by now: a card that arrives before its * reveal fails here, at the moment it leaked. */ const playAndSearch = async () => { await traffic.play(0.5); for (const [index, page] of traffic.pages.entries()) for (const card of listCards()) if (!seen[index].has(card)) expect( page.isTextEverReceived(card), `page ${page.number} and ${card}`, ).toBe(false); }; noteHands(); await playAndSearch();
const [first] = readPlayerCards(table, players[0]); expect(playCard(authority, table, players[0], first)).toBe(true); reveal(first); drawCard(authority, table, players[1]); noteHands(); await playAndSearch();
await traffic.page(4).leave(); foldHand(authority, table, players[3]); await playAndSearch();
await traffic.page(3).rejoin(); // The rejoin's frames are searched before the draw adds a card to // what the player has seen. await playAndSearch(); drawCard(authority, table, players[2]); noteHands(); await playAndSearch();
expectNeverReceived( traffic, ({ page, trait, owner }) => trait === HandTrait && owner !== page.player, ); expectNeverReceived(traffic, ({ trait }) => trait === DeckTrait); for (const page of traffic.pages) { const hand = table.hands.get(page.player); // The player's own hand reached the page, so the rule above read // something. if (hand) expect(page.isTraitEverReceived(hand, HandTrait)).toBe(true); expect(page.isTraitEverReceived(table.deck, DeckTrait)).toBe(false); expect(page.isTraitEverReceived(table.pile, PileTrait)).toBe(true); } // The rejoin's welcome is read as any frame is. expect( traffic.page(3).frames.filter(({ welcome }) => welcome), ).toHaveLength(2); expect(traffic.page(1).isTextEverReceived(first)).toBe(true); expect(traffic.page(2).isTextEverReceived(first)).toBe(true); }, playTimeout,);
it( "fails naming the page, the frame and the value where a page received what the rule forbids", async () => { const room = await openRoom({ common: false }); const traffic = await capturePageTraffic(room, { players: 2 }); const players = traffic.pages.map(({ player }) => player); dealRound(requireAuthority(room.world), players, listCards(), 1); await traffic.play(0.5);
expect(() => expectNeverReceived(traffic, ({ trait }) => trait === HandTrait), ).toThrow( /^expectNeverReceived: page 1 \(Page 1\) received the trait cardsHand of the entity "[^"]+" in its frame \d+, at tick \d+: \{"cards":"ace-of-spades"\}\./, ); }, playTimeout,);