# Playtests

> Put a coding agent in a room as a second player, playing through the game's own page in a Chromium it drives, with commands, reflexes, screenshots and voice chat, using @irtio/playtest and its MCP server.

A **playtest** puts a coding agent in a room as a second player, beside
you: it plays through the game's own page in a Chromium it drives, with
commands the game defines, reflexes it writes on the spot, screenshots
and voice chat. The package `@irtio/playtest` runs it, as an MCP server
for Claude Code and other MCP clients.

## Playtest players

A multiplayer game needs more than one player to test, and the person
building it is often alone. In a playtest, you play in your own browser
and the coding agent plays a **playtest player**: a Chromium page on the
game's site that joins as a person does, through the game's own menus,
with an ordinary player ID. The room can't tell it from a person, so it
tests the path players take. It isn't a bot: a room's
[bots](/docs/room/guides/bots) run in room code, and
[simulated players](/docs/tools/simulate) run in process against a test
clock.

You say "come over here and jump on the red crate", and the coding agent
walks over and jumps, says what it saw, and reports a bug when its view
and yours disagree. What it does in the game it does through the page:

- **Commands**, such as walking to a point, which the game's playtest
  module defines and the coding agent runs one at a time.
- **Reflexes**, standing orders such as "shoot any goblin that comes
  through this door", which run in the page every frame beside the
  command.
- **Code it sends**, plain JavaScript run in the page with the same
  access as the module's code, for something you ask for mid-game.
- **Screenshots** and the module's description of what the player sees,
  as JSON.
- **Voice chat** both ways: it hears what the room lets it hear and
  speaks through the game's own microphone.

Each playtest player has its own browser storage, so its own guest: two
playtest players are two players, and neither is your guest. Its name is
whatever the module's `join` types into the game. It reaches your room
the way a second person would, from the URL you're on or one with a join
code you read out; the game's own flow does the rest, and the playtest
never creates or picks rooms.

A playtest plays the project under [`irt dev`](/docs/tools/cli#irt-dev---port-7350),
which writes its address to `.irt/dev/url` in the project for the MCP
server to read.

## Setup

Install the package and Playwright in the project, then Chromium:

```sh
npm install -D @irtio/playtest playwright
npx playwright install chromium
```

Playwright is a peer dependency, so the project picks its version and
installs Chromium once. The speech engines come with `@irtio/playtest`
as optional dependencies, about 400 MB of `node_modules` with their
prebuilt binaries for your platform. Nothing needs compiling.

On Linux x64, onnxruntime-node, which the speech engines run on,
downloads CUDA binaries as it installs unless you skip them:

```sh
ONNXRUNTIME_NODE_INSTALL_CUDA=skip npm install -D @irtio/playtest playwright
```

Where that download fails, npm leaves the speech engines out and the
install succeeds anyway. Playtests then work without voice, and the
speech status says to reinstall with the variable set.

Add the MCP server from the project directory, the one with
`irt.config.ts`:

```sh
claude mcp add irt-playtest -- npx -y @irtio/playtest mcp
```

Add `--scope project` to write it to the project's `.mcp.json`. Clients
that take a JSON config need an entry like this one:

```json
{
  "mcpServers": {
    "irt-playtest": {
      "command": "npx",
      "args": ["-y", "@irtio/playtest", "mcp"]
    }
  }
}
```

The server starts in the project directory and reads the `playtest`
field of `irt.config.ts`. It works beside [`irt mcp`](/docs/tools/mcp),
and neither needs the other. In a directory without `irt.config.ts` it
starts with the built-in commands only, and `play_join` takes full URLs.

## Playtest module

The **playtest module** is a file of the project's that tells a playtest
player how to join, what to report and what it can do. Name it in
`irt.config.ts`:

```ts
// irt.config.ts
import { defineConfig } from "@irtio/cli/config";

export default defineConfig({
  project: "dungeon",
  rooms: { default: "src/room.ts" },
  site: { dir: "dist", build: "npm run build:web" },
  playtest: {
    module: "playtest/dungeon.ts",
    speech: { voice: "af_heart" },
  },
});
```

`playtest.module` is the module's path, and `playtest.speech` is
optional; see [Voice](#voice). `irt build` and `irt deploy` check the
field's shape and otherwise ignore it.

The examples on this page play a dungeon game with this schema:

```ts
// src/schema.ts
import { call, defineCalls, defineSchema, entity } from "@irtio/client";

export const Hero = entity("hero", { owner: "string", x: "f32", y: "f32", health: "u8" }, { key: "owner" });
export const Goblin = entity("goblin", { x: "f32", y: "f32", weapon: "string" });

export const schema = defineSchema({
  entities: [Hero, Goblin],
  calls: defineCalls({ move: call({ dx: "i8", dy: "i8" }) }),
});
```

The module's default export is `definePlaytest()` from
`@irtio/playtest`. This one joins through the game's menu, describes the
heroes and goblins, and gives the coding agent a command and a reflex:

```ts
// playtest/dungeon.ts
import { definePlaytest } from "@irtio/playtest";
import type { Camera } from "../src/camera.js";
import { Goblin, Hero } from "../src/schema.js";

export default definePlaytest({
  async join(ctx, { name }) {
    await ctx.page.fill("#name", name);
    await ctx.page.click("text=Play");
  },

  describe(ctx) {
    const me = ctx.room.entities.get(Hero, ctx.room.player);
    return {
      me: me && { x: me.x, y: me.y, health: me.health },
      heroes: [...ctx.room.entities.all(Hero)].map((h) => ({ player: h.owner, x: h.x, y: h.y })),
      goblins: [...ctx.room.entities.all(Goblin)].map((g) => ({ id: g.id, x: g.x, y: g.y, weapon: g.weapon })),
    };
  },

  labels(ctx) {
    const camera = ctx.exposed.camera as Camera;
    return [...ctx.room.entities.all(Goblin)].map((g) => ({ ...camera.toScreen(g.x, g.y), text: `goblin ${g.id}` }));
  },

  commands: {
    walkTo: {
      description: "Walk to a point in world units, stopping within 1 unit of it",
      args: { x: "number", y: "number" },
      async run(ctx, { x, y }) {
        while (!ctx.signal.aborted) {
          const me = ctx.room.entities.get(Hero, ctx.room.player);
          if (!me) throw new Error("the hero hasn't spawned");
          if (Math.hypot(x - me.x, y - me.y) < 1) return { x: me.x, y: me.y };
          const keys: string[] = [];
          if (Math.abs(x - me.x) > 0.5) keys.push(x > me.x ? "ArrowRight" : "ArrowLeft");
          if (Math.abs(y - me.y) > 0.5) keys.push(y > me.y ? "ArrowDown" : "ArrowUp");
          await ctx.hold(keys, 100);
        }
      },
    },
    shoot: {
      description: "Click on a goblin by id, which fires at it",
      args: { id: "number" },
      async run(ctx, { id }) {
        const goblin = [...ctx.room.entities.all(Goblin)].find((g) => g.id === id);
        if (!goblin) throw new Error(`goblin ${id} isn't in view`);
        const camera = ctx.exposed.camera as Camera;
        await ctx.page.click(camera.toScreen(goblin.x, goblin.y));
      },
    },
  },

  reflexes: {
    guard: {
      description: "Shoot armed goblins that come within r units of a point, sparing unarmed ones",
      args: { x: "number", y: "number", r: "number" },
      start(ctx, { x, y, r }) {
        ctx.everyFrame(() => {
          for (const g of ctx.room.entities.all(Goblin)) {
            if (g.weapon === "none" || Math.hypot(g.x - x, g.y - y) > r) continue;
            ctx.claim(() => ctx.run("shoot", { id: g.id })).catch((e: unknown) => ctx.emit("missed", { goblin: g.id, error: String(e) }));
          }
        });
      },
    },
  },

  events(ctx) {
    let health: number | undefined;
    ctx.everyFrame(() => {
      const me = ctx.room.entities.get(Hero, ctx.room.player);
      if (me && health !== undefined && me.health < health) ctx.emit("hurt", { health: me.health });
      health = me?.health;
    });
  },
});
```

When the module's file, or a file it imports, changes, the MCP server
bundles it again and injects it into every playtest player's page
without reloading it, so connections, positions and reflexes from code
the coding agent sent survive. The module's own command and reflexes are
stopped and not restarted, and a `module` event says so. A module that
fails to bundle leaves the one before in place, and the error is a
`module` event.

### `definePlaytest()` fields

`definePlaytest()` takes an object with any of these properties:

`join(ctx, { name })` Optional
: Takes the page from its first load to a joined room, through the
  game's own menus, typing `name`. Without it, the page is expected to
  connect by itself from its URL. The room is the URL's business: `join`
  reads `location` when it needs to. The playtest player has joined once
  the page has a connected room client, within 30 seconds.

`describe(ctx)` Optional
: What this player sees, as JSON. `play_describe` returns it, and
  `play_join`, `play_do` and `play_listen` return it after they finish.
  Without it, the description is the room's ID, the player ID, the
  connection's state and how many entities the client holds.

`labels(ctx)` Optional
: An array of `{ x, y, text }` in CSS pixels, drawn over a screenshot
  when the coding agent asks `play_look` for labels.

`commands` Optional
: The game's commands by name, each `{ description, args, run(ctx, args) }`.
  See [Commands and reflexes](#commands-and-reflexes).

`reflexes` Optional
: The game's reflexes by name, each `{ description, args, start(ctx, args) }`.

`events(ctx)` Optional
: Runs after each join, to subscribe to what the game wants reported
  with `ctx.emit()`. Its subscriptions end when the page loads again or
  the module is injected again, and it runs again after either.

A command's or reflex's `description` is what the coding agent reads to
choose it, so it's required. Its `args` are a flat object of `"number"`,
`"string"` or `"boolean"`, or any of those followed by `?` for an
optional one, such as `{ x: "number", spareUnarmed: "boolean?" }`. The
tools check the coding agent's arguments against them, and the
arguments are typed in `run()` and `start()`.

### Context

Commands, reflexes, the module's other functions and code the coding
agent sends all get the same `ctx`:

`room`
: The page's newest connected `RoomClient`, from the client SDK.
  Undefined until the page has connected. The client SDK registers each
  client the page connects, so this needs nothing from the game.

`rooms`
: Every connected `RoomClient` in the page that isn't closed, oldest
  first.

`kind(name)`
: The page's schema's entity kind by name, for sent code, which can't
  import the schema. Throws, naming the kinds there are, for a name the
  schema doesn't have.

`exposed`
: What the game passed to [`expose()`](#client-hooks), by name.

`page`
: Input through Playwright, so the game gets trusted input events, as
  from a person: `click(selector)` or `click({ x, y })`,
  `fill(selector, text)`, `press(key)`, `type(text)`,
  `hold(keys, ms)`, `move(x, y)`, `mouseDown(button?)` and
  `mouseUp(button?)`, each returning a `Promise`. Points are CSS pixels.
  `hold()` resolves to `{ interrupted }`, `true` when a reflex's claim
  took the input before the time was up.

`hold(keys, ms)`
: Shorthand for `page.hold()`.

`run(command, args)`
: Runs one of the module's commands as a function, inside this code,
  without replacing the player's command. Resolves with what it returns.

`frame()`, `wait(ms)` and `until(test, ms)`
: Wait for the next animation frame, a time, or until `test()` returns
  something truthy, checked every frame. `until()` rejects after `ms`,
  10 seconds by default.

`everyFrame(fn)`
: Calls `fn` every animation frame until this code stops.

`on(event, fn)`
: Calls `fn` with an event's data until this code stops: the game's own
  from `ctx.emit()`, or `presence` and `connection`, as in
  [Events](#events).

`claim(fn)`
: Takes the player's input while `fn` runs; see [Input](#input).

`say(text, { gap? })`, `notify(text, data?, { look?, gap? })` and `emit(name, data)`
: Report to the person or the coding agent; see
  [Reports from the page](#reports-from-the-page).

`watch(select, options)` and `watchScreen(options)`
: Watch entities or the screen; see [Watches](#watches).

`pixels`
: Helpers for tests on captured pixels; see
  [Screen watches](#screen-watches).

`signal`
: An `AbortSignal`, aborted when this code stops: it ends, throws, times
  out, is replaced or turned off, or the player leaves.

Subscriptions from `everyFrame()`, `on()`, `watch()` and `watchScreen()`
end on their own when the code that made them stops, so a reflex needs
no cleanup. Everything here sees what this player's client sees, and
nothing else: entities the room's interest doesn't send it aren't there.

### Kinds in the module

The module is bundled apart from the site, so a kind it imports from the
schema is a different object from the page's own. `ctx.room` finds kinds
by name, so `ctx.room.entities.all(Goblin)` with the module's `Goblin`
finds the page's goblins. Import the schema the room and the page use,
and the module is type-checked against it.

### Client hooks

`@irtio/client` has two functions for playtests. Both do nothing in a
page the playtest didn't open.

- `expose(name, value)` hands the module something of the game's that
  the client SDK doesn't have, as `ctx.exposed[name]`, such as its
  camera.
- `isPlaytest()` returns `true` in a playtest player's page, so the
  game can tell people a player is a coding agent.

The camera in this example turns world units into CSS pixels, which the
module's `labels()` and `shoot` need:

```ts
// src/camera.ts
export class Camera {
  x = 0;
  y = 0;
  scale = 32;

  toScreen(x: number, y: number): { x: number; y: number } {
    return { x: (x - this.x) * this.scale + innerWidth / 2, y: (y - this.y) * this.scale + innerHeight / 2 };
  }
}
```

```ts
// src/main.ts
import { connect, expose, isPlaytest } from "@irtio/client";
import { Camera } from "./camera.js";
import { schema } from "./schema.js";

const camera = new Camera();
expose("camera", camera);

const room = await connect("crypt", { schema });
// Lets the room show everyone that this hero is played by a coding agent
room.send({ type: "intro", playtest: isPlaytest() });
```

The playtest sets its hooks up before the game's own scripts run, so a
call to `expose()` at load reaches it.

### Module outside the site

A command like "shoot the nearest enemy" is an aimbot. Shipped in the
site, it would hand one to every player who opens the console. So the
playtest module is never part of the site: keep it outside the site's
files, and the MCP server bundles it from the project directory and
injects it into each playtest player's page. `irt build` and
`irt deploy` never see it, and code the coding agent sends is only ever
injected too. `expose()` ships in the site, but it does nothing in a
page the playtest didn't open.

## Commands and reflexes

A playtest player runs two kinds of code at once:

- A **command** is a goal: walk to, follow, open. One runs at a time,
  and a new one aborts the one running. It runs until it returns,
  throws or times out, 30 seconds by default and at most 120, and has
  the input unless a reflex claims it.
- A **reflex** is a standing order: guard, dodge, tell me when. Any
  number run at once, each by name, and a new one with a name replaces
  the one running under it. It runs until it's turned off or replaced,
  it throws, or the player leaves, and has the input only while it
  claims it.

A new command replacing the last is what makes "follow me" and then
"stop" work. A reflex beside the command is what makes "walk to the
crate, and shoot anything that attacks you on the way" work. A coding
agent takes seconds a turn, so anything that has to happen within a
frame of something in the game belongs in a reflex.

Besides the module's commands, every game has the built-in commands,
for menus and for games whose module defines nothing yet: `click`
(`{ selector }` or `{ x, y }`), `press` (`{ key }`), `type`
(`{ text }`), `hold` (`{ keys, ms }`, with keys comma-separated, such as
`"ArrowUp,Space"`) and `move` (`{ x, y }`).

A command's result is sent to the coding agent as JSON, so return plain
data.

Commands and reflexes run in the page at its frame rate. Headless
Chromium draws WebGL in software, so a light scene runs at about 30
frames a second and a heavy one at a few, and every-frame code runs at
that rate too.

### Input

The command has the input by default. `ctx.claim(fn)` gives a reflex the
input while `fn` runs, and the command's own input calls wait until it
ends; the command isn't aborted, so the walk carries on after the shot.

- One claim runs at a time. A claim while another holds the input
  resolves to `false` at once, without running `fn`, so a reflex that
  claims every frame shoots when it can and doesn't queue up shots.
  Otherwise it resolves to `true` when `fn` ends.
- A claim lasts at most 5 seconds, so a reflex can't keep the input by
  mistake.
- Keys and buttons the command held are released when a claim takes the
  input, and its `hold()` returns early with `interrupted: true`. What's
  held is released again when a claim ends, a command stops, the module
  is injected again or the player leaves.
- A reflex's input call outside a claim throws.

### Sent code

The coding agent doesn't have to edit the module to give the page new
code. `play_do` and `play_reflex` take `source`: the body of an async
function of `ctx` and `args`, with the same `ctx` as the module's code.
For something you ask for mid-game, it's one tool call, and the code
runs on the next frame. When a reflex proves useful or you ask for it
again, the coding agent moves it into the module, where it's
type-checked against the schema and kept in the project.

Sent code is plain JavaScript, not TypeScript, and runs as it is, so it
can't import anything: `ctx.kind()`, `ctx.run()` and `ctx.exposed` are
how it reaches the schema, the module's commands and the game. A syntax
error or a throw stops it, and the error is the tool's result or an
event. This reflex guards a door and records the goblins it spares:

```js
const door = { x: 42, y: 10, r: 3 };
const spared = new Set();
ctx.everyFrame(() => {
  for (const g of ctx.room.entities.all(ctx.kind("goblin"))) {
    if (Math.hypot(g.x - door.x, g.y - door.y) > door.r) continue;
    if (g.weapon === "none") {
      if (!spared.has(g.id)) ctx.emit("spared", { goblin: g.id });
      spared.add(g.id);
      continue;
    }
    ctx.claim(() => ctx.run("shoot", { id: g.id }));
  }
});
```

Code runs on the page's main thread, so a loop that never awaits, such
as `while (true) {}`, freezes the page. The MCP server notices a page
that hasn't answered for 5 seconds, stops its script, reloads it, joins
again with the module's `join`, and reports an `error` event naming the
command and reflexes that were running. The playtest player keeps its
browser storage, so it's the same guest again. Loops that await
`ctx.frame()` are fine.

## Reports from the page

Code in the page reports in three ways, by how fast it has to reach
someone:

`ctx.emit(name, data)`
: Adds an `emit` event to the player's queue, which the next
  `play_listen` returns. It doesn't wake the coding agent. Use it for a
  record of what happened, such as shots and spared goblins. Code in the
  page can subscribe to it with `ctx.on(name, fn)`.

`ctx.say(text, { gap? })`
: Speaks a line on voice chat at once, without the coding agent, under a
  second after the call. Use it for a line written in advance, such as
  "goblin at the door". A `said` event tells the coding agent what was
  said in its name, and whether anyone could hear it.

`ctx.notify(text, data?, { look?, gap? })`
: Wakes the coding agent, ending a waiting `play_listen` at once with a
  `notify` event that has the text, the data and the name of the code
  that sent it. With `look: true` it takes a screenshot at that moment
  and returns it with the event, since what was on screen is gone by the
  time the coding agent asks. Use it for something the coding agent
  must interpret before anyone answers; its reply takes a turn of 3 to
  10 seconds.

Limits keep code from flooding either side. Each command or reflex can
`say` at most once every 2 seconds and `notify` at most once every 5.
Calls inside those windows are merged into the next one allowed: their
texts and data are kept in order, up to 20, and a `more` field counts
the rest. Three goblins in a second are one line: "Goblin coming in with
a club. Goblin coming in, unarmed. Goblin coming in with a bow."

`gap` sets the window in milliseconds for one command's or reflex's
lines, such as a rhythm game's callouts: `ctx.say("left", { gap: 500 })`.
It can't go below 500 ms for `say` or 2 seconds for `notify`, and a
lower one is raised to that. A command run with `ctx.run()` counts
against its caller's window.

A coding agent that's busy with something else, not waiting in
`play_listen`, learns of a `notify` when it next calls any play tool:
every result carries `notifications`, the count of `notify` and
`speech` events waiting, and the tools tell the coding agent to listen
when it isn't 0.

## Watches

A watch tells code in the page when something changes, so the coding
agent can ask "tell me if anything in this room changes" and get one
`notify` with what changed instead of polling.

### Entity watches

`ctx.watch(select, { settle?, ignore?, onChange })` calls `select()`
every frame for the entities to watch, and calls `onChange(changes)`
with what changed among them: `entered` and `left`, each entity with
its `id`, `kind` and `values`, and `changed`, each with the `fields`
that changed and their values `before` and `after`. It waits until
nothing has changed for `settle` milliseconds, 500 by default, before
calling back, so a gate that rises over a second reports once, with
where it started and where it ended. `ignore` names fields not to
count, such as an animation timer.

```js
ctx.watch(() => [...ctx.room.entities.all(ctx.kind("tile"))].filter((t) => t.x > 40 && t.x < 60), {
  ignore: ["glow"],
  onChange: (changes) => ctx.notify("Something in the puzzle chamber changed", changes, { look: true }),
});
```

A playtest player sees only what the room's interest sends its client,
so it watches what it's near. A change that's only drawn, with no
entity behind it, isn't in the client's state; watch the screen for it.

### Screen watches

`ctx.watchScreen(options)` captures a region of the page at an interval
and runs a test on its pixels, for what the client's state doesn't
hold: a light coming on, something passing through a doorway, a
particle effect that should play. It takes an object with these
properties:

`region` Optional
: `{ x, y, width, height }` in the page's CSS pixels. Defaults to the
  whole viewport.

`every` Optional
: Milliseconds between captures, at least 50. Defaults to 250.

`test(now, before)`
: Runs in the page on each capture, an `ImageData`, with the capture
  before it, `undefined` the first time. Anything truthy it returns is a
  match.

`onMatch(result, now)`
: Runs on a match, with what `test()` returned.

`settle` Optional
: Milliseconds with no match after a match before `onMatch()` can run
  again, so a flicker reports once. Defaults to 0.

```js
ctx.watchScreen({
  region: { x: 610, y: 220, width: 80, height: 140 },
  every: 100,
  test: (now, before) => before && ctx.pixels.changed(now, before, { threshold: 24 }) > 0.05,
  onMatch: () => ctx.notify("Something moved through the doorway", null, { look: true }),
});
```

`ctx.pixels` has the helpers most tests need, each over `ImageData`:

- `changed(a, b, { threshold? })`: the fraction of pixels whose colour
  differs by more than `threshold` in a channel, 16 by default out of
  255
- `brightness(image)`: the mean luminance, 0 to 1
- `meanColour(image)`: `{ r, g, b }`, each 0 to 255
- `count(image, fn)`: how many pixels `fn(r, g, b, a)` returns `true` for

A capture is Chromium's screenshot of the region, so the test sees what
a person would see on that page, overlays and canvas alike. `play_look`
with `grid: true` draws a grid of CSS pixel coordinates, to read a
region off. The region is fixed on the page, so it follows the camera,
not the world.

A player's screen watches share at most 20 captures a second, and a
watch that asks for more is slowed to its share. A capture waits for
the page's next frame, so a page that renders slowly gets fewer.
`play_describe` shows each watch's share and the interval it really
gets. A flash of light wants 50 to 100 ms; lights in a hall that change
now and then want 500.

## Tools

`npx @irtio/playtest mcp` serves these tools. Every result is JSON that
names its `player` and carries `notifications`; a failed call's result
has `error`, saying what went wrong.

`play_join`
: Opens a playtest player on `url`, a path on the site `irt dev` serves,
  such as `/`, or a full URL, such as one with a join code in it, and
  runs the module's `join` with `name`, at most 40 characters, which
  defaults to the handle. `visible: true` opens the page in a window
  you can watch, where there's a display. Returns `player`, the handle
  (`p1`, `p2` and so on), `playerId`, `room` and `describe`, with
  `speech`, the speech engines' state, when the page joined voice, and
  `module` when the module failed to bundle.

`play_catalog`
: The module's commands and reflexes with their descriptions and
  arguments, the built-in commands, and the `ctx` members sent code can
  use. It reads the module's commands from a player's page, so join
  first.

`play_do`
: Runs a command for `player`: the module's or a built-in by `command`
  with `args`, or `source`, sent code, as a one-off command. Waits until
  it ends and returns its `result`, its `error`, `timedOut` or
  `aborted`, with `describe`. With `wait: false` it returns at once, and
  the command's end arrives as a `command` event. `timeout` is in
  seconds, 30 by default and at most 120. It waits at most 50 seconds;
  a command still running then keeps running, the result says so, and
  its end arrives as a `command` event.

`play_reflex`
: Starts or replaces a reflex by `name`: the module's with `args`, or
  `source`, sent code, under a name the coding agent chooses. A reflex
  whose code throws at once fails the call; one that throws later stops
  with a `reflex` event.

`play_reflex_off`
: Stops a reflex by `name`, or all of them without one, and returns the
  names it stopped.

`play_describe`
: The player's `describe`, and its `state`: the connection, the running
  command and its reflexes, each with whether it came from the module,
  sent code or the built-ins, its screen watches, the reflex holding a
  claim, and on voice whom it hears and whether its microphone is on.

`play_look`
: A JPEG screenshot of the player's page, 960 by 540 CSS pixels by
  default. `width` scales it, 160 to 1280 pixels. `labels: true` draws
  the module's labels, and `grid: true` a grid of CSS pixel
  coordinates.

`play_listen`
: Everything queued for the player since the last call, as `events`,
  then `describe`. It waits up to `timeout` seconds, 20 by default and
  at most 50, while no `speech` or `notify` event is queued, and returns
  at once on one; other events come back with it but don't end the
  wait. It returns at most the newest 3 screenshots.

`play_say`
: Speaks `text`, at most 500 characters, on voice chat as the player.
  Waits until it's been spoken, at most 50 seconds in all, unless
  `wait` is `false`. Returns `spoken: false` with the `reason` when
  nobody could hear it; see [Speech](#speech).

`play_leave`
: Closes the player's page, so its connection closes as a person's does
  when they close the tab.

`play_describe` costs the coding agent far fewer tokens than
`play_look`: a screenshot at 960 by 540 is about 700 input tokens, and a
description is usually a tenth of that. The tools tell the coding agent
to look only for what text can't show.

## Listening loop

MCP tools answer only when they're called, so a coding agent waiting for
you sits in `play_listen`:

1. It calls `play_join` with the page you're on.
2. It calls `play_listen`, which returns when you speak or code in the
   page notifies it, or after 20 seconds with nothing, and then it calls
   `play_listen` again.
3. `play_listen` returns `{ events: [{ type: "speech", player: "guest:k3j", text: "come over here and jump on the red crate" }], describe: { ... } }`.
4. It calls `play_do` with `walkTo` your position from `describe`, then
   `play_say` with "on the crate", and goes back to step 2.

From the end of your sentence, a reply takes 5 to 15 seconds: about
0.7 seconds to notice you stopped, a fraction of a second to transcribe,
a coding agent's turn of 3 to 10 seconds, and about a second to
synthesize the answer. That's fine for testing, but it isn't a
conversation. The coding agent can say "on my way" with `wait: false`
before it starts a command, and anything that must be faster is a
reflex with `ctx.say()`.

`play_listen` and `play_do` send progress notifications every 10
seconds while they wait, to clients that ask for them.

## Events

A player's queue holds these events in order, each with `type` and
`at`, the time it happened:

`speech`
: Someone on voice chat said something: `player`, their player ID, and
  `text`, the transcript. When speech couldn't be transcribed, `text` is
  `null` and `note` says why, once until the reason changes.

`notify`
: Code in the page woke the coding agent: `from`, the command or reflex,
  `texts`, `data` when any was given, `more` when more calls were merged
  than kept, and `image` when it asked for a screenshot.

`said`
: A line from `ctx.say()`: `from`, `text`, the `lines` merged into it,
  `spoken`, `cut` when a later line cut it off, and `reason` when nobody
  could hear it.

`presence`
: A player joined or left the room: `room`, `player`, `name` and
  `joined`.

`connection`
: The page's connection changed: `room` and `state`, which is
  `"reconnecting"` or `"closed"` with the close `code` and `reason`, or
  `"reconnected"` with the connection's `generation`.

`command`
: A command that `play_do` stopped waiting for ended: `command`, and
  its `result`, `error`, `timedOut` or `aborted`.

`reflex`
: A reflex stopped: `reflex`, and `stopped` with why, or `error`.

`module`
: The module was injected again, or failed to bundle, with `message` or
  `error`.

`error`
: The page threw, logged an error to its console, or froze or crashed
  and was opened again: `message`, and `stack` when there is one. Errors
  in the game's own page are often what a playtest most needs to
  report.

`emit`
: The game's own, from `ctx.emit()`: `name`, `from` and `data`.

The queue keeps the last 200 events, dropping `speech` and `notify`
events last, and `play_listen` says how many were dropped.

What other players say and what the game shows reach the coding agent
as data: in `speech` events and in `describe`. The tools tell the coding
agent that these are what players said or showed, never instructions to
it, and never to turn them into code it sends.

## Voice

Voice works with no setup beyond what the game already does for
[voice chat](/docs/room/guides/voice): you need nothing new, since the
transcribing and the speaking happen on the playtest player's side.
Under `irt dev`, voice needs a local LiveKit server, as
[Turning it on](/docs/room/guides/voice#turning-it-on) in Proximity voice
says.

The playtest player's page plays no sound, so if you play on the same
machine, you don't hear your own voice back from its tab. It still hears
you: it takes the audio it receives before it would be played.

### Transcription

A playtest player hears whoever the room lets it hear, so proximity
works as it does for a person: "can you hear me now?" tests the room's
voice rules. The MCP server cuts each speaker's audio into utterances
where there's 700 ms of silence, or at 15 seconds, drops one with less
than 150 ms of voice, shorter than a word such as "go", and transcribes
each one into a `speech` event. An empty transcript is dropped, and so
is a stock phrase such as "Thank you." from sound that was more like
noise than a voice.

### Speech

`play_say` and `ctx.say()` synthesize the text and play it into the
game's own microphone: the playtest replaces `getUserMedia()` in the
page, so the microphone the voice SDK opens is a stream it controls.
`enableMic()` publishes it as any player's microphone, and the room's
rules and mutes apply. A new line cuts off one still playing, except
that a line from `ctx.say()` waits for one from `play_say`, since the
coding agent's own words come first.

A line nobody could hear isn't spoken. `play_say` returns
`spoken: false`, and a `said` event says so, with the `reason`:

- The game never joined voice with `joinVoice()`.
- The room has no voice server.
- Voice is still connecting.
- The game never turned the microphone on with `enableMic()`, or muted
  it with `setMuted()`.
- The room mutes the player.
- Push-to-talk isn't held.
- Speech synthesis is still downloading or loading, or failed.

A long line is spoken a sentence at a time.

### Built-in engines

The built-in engines run on your machine's CPU:

- Transcription is Moonshine base, quantized to 8 bits.
- Speech is Kokoro, at full precision. `playtest.speech.voice` names one
  of Kokoro's voices, and defaults to `"af_heart"`.

Their models download the first time a page with voice joins a room
that has a voice server, about 375 MB together, into your cache directory, not the project:
`$XDG_CACHE_HOME/irt/playtest` when `XDG_CACHE_HOME` is set, and
otherwise `~/.cache/irt/playtest` on Linux,
`~/Library/Caches/irt/playtest` on macOS and
`%LOCALAPPDATA%\irt\playtest` on Windows. Set `IRT_PLAYTEST_CACHE` to keep them somewhere else, and
`HF_HUB_OFFLINE=1` to load them from the cache without the network.

`play_join`, `play_describe` and `play_say` report each engine's state
in `speech`, as `listen` and `speak`: `"not loaded"`, `"downloading"`
with `progress` in percent, `"loading"`, `"ready"` or `"failed"` with
the `error`. Until speech synthesis is ready, `play_say` returns
`spoken: false` with the reason, and until transcription is ready,
speech isn't transcribed, which a `speech` event says.

The engines run in a process of their own, one request at a time. A
request that takes longer than 30 seconds is stopped and the engines
start again. An engine that fails to load, or whose process stops,
loads again on its next use, up to 3 times in a row before it gives up
until the MCP server restarts. The engines stop when the last playtest
player leaves. Each playtest player transcribes what it hears, so
several playtest players that hear you cost more.

### Shell engines

To use another engine, such as a cloud API or a native one, set
`playtest.speech.listen` or `playtest.speech.speak` to a shell command.
It replaces the built-in engine for that direction, and `{wav}` in it is
replaced with the path of an audio file:

- `listen` reads the WAV file, 16-bit mono at 16 kHz, and prints its
  transcript.
- `speak` reads the text on its standard input and writes the WAV file:
  8, 16, 24 or 32-bit PCM or 32-bit float, mixed to mono if it has more
  channels.

```ts
playtest: {
  module: "playtest/dungeon.ts",
  speech: {
    listen: "whisper-cli -m ~/models/ggml-base.en.bin -nt -np -f {wav}",
    speak: "piper --model ~/models/en_US-amy-medium.onnx --output_file {wav}",
  },
},
```

The commands run one at a time, in order, through `sh`. One that takes
longer than 30 seconds is killed, with anything it started.

## Limits

- A playtest MCP server runs at most 8 playtest players, so a coding
  agent can fill a four-player match with three of them and you.
- A playtest player's page closes after 10 minutes with no tool call
  for it, so a coding agent that stopped doesn't keep a room awake. A
  running reflex doesn't count as a call.
- A playtest player joins within 30 seconds, or `play_join` fails.
- `play_listen`, `play_do` and `play_say` wait at most 50 seconds, under
  the 60-second request timeout of MCP's TypeScript SDK client.
- A command times out after 30 seconds by default, and at most 120.
- A claim lasts at most 5 seconds.
- `say` runs at most once every 2 seconds and `notify` once every 5 per
  command or reflex, with a `gap` of at least 500 ms and 2 seconds.
- A player's screen watches share 20 captures a second, each at least
  50 ms apart.
- A queue keeps 200 events, and `play_listen` returns 3 screenshots.
- A page that doesn't answer for 5 seconds is reloaded.
- `play_say` takes at most 500 characters.
- At most 6 utterances wait for transcription, and more are dropped. A
  speech request takes at most 30 seconds.

## Common mistakes

- **Putting the playtest module in the site's files.** Its commands are
  an aimbot for anyone who opens the console. Keep it outside the
  directory `site.dir` names, as `playtest/` beside `src/`.
- **Writing a loop in sent code that never awaits.** It freezes the
  page, which the MCP server reloads after 5 seconds. Await
  `ctx.frame()` in every loop.
- **Calling `ctx.page` from a reflex without `ctx.claim()`.** A reflex's
  input calls throw outside a claim, so the command keeps the input.
- **Doing what has to happen within a frame from the coding agent.**
  A turn takes seconds. Start a reflex that reacts, and `ctx.say()` a
  line written in advance.
- **Waking the coding agent for a record.** `ctx.notify()` costs a turn.
  Use `ctx.emit()` for what can wait for the next `play_listen`.
- **Expecting a playtest player to see the whole room.** It sees what
  the room's interest sends its client, like any player. Read the room
  in the [`irt dev` inspector](/docs/tools/dev-tools#inspector) for the
  rest.
- **Testing voice without the microphone on.** `play_say` needs the game
  to have joined voice and turned the microphone on, as a person's
  client would; the `reason` it returns says which step is missing.

## See also

- [Simulating players](/docs/tools/simulate), for dozens of scripted
  players and invariants every tick
- [MCP server](/docs/tools/mcp), for your project's builds, rooms and
  logs
- [Proximity voice](/docs/room/guides/voice)
- [Building with a coding agent](/docs/guides/agents)
