# Test with bot clients

> Start real Minecraft clients that join your dev server, give them Effect bundles that play your game, and read both the client's and the server's recordings in an end-to-end test.

Stories and replays prove the rules. A bot client proves the whole game: a real Minecraft client joins the real server, walks, clicks and reads chat, and both sides record what happened. You write the bot the way you write a game, as an Effect UI component with Commands.

> **Preview:**
> `mk daemon` and `mk client` ship with the CLI. Bot bundles use `@minekube/client`, which is not in the CLI release yet, so writing your own bot needs a [Minekube checkout](https://github.com/minekube/minekube) today. The examples in this page come from it.

## Start a client

The Minekube daemon runs Minecraft clients with Fabric and the Minekube client runtime. Start it once, then start a client in it:

```sh
mk daemon
mk client --name Bot
```

The client joins the dev server as the offline player `Bot`, with its window hidden. Its log and recordings stream to your terminal and into the [devtools](https://minekube.com/games/testing/devtools). Pass `--show-window` to watch it, and `--server` to join another server. See the [CLI reference](https://minekube.com/games/reference/cli#mk-client) for every flag.

Each client has its own game directory, `clients/<name>` in the Minekube home, with its logs, its recordings and its bundles.

## Write a bot

A bot has the same two halves as a game. The rules decide what to do next and import no Java. The client half carries out the Commands with the Minecraft client's own API, typed from the client jar.

The bot of the [launcher example](https://minekube.com/games/examples/launcher) finds the sign, walks to it, right-clicks it and notes how high it flew:

```ts title="client/LauncherBot.ts"

const Position = Schema.Struct({ x: Schema.Int, y: Schema.Int, z: Schema.Int });

export const BotMessage = UiSchema.TaggedEnum({
  FoundSign: { sign: Position },
  Arrived: {},
  Launched: { rise: Schema.Finite },
});

export class FindSign extends Command.Service<FindSign>()("launcher-bot/FindSign", { success: BotMessage }) {}
export class WalkTo extends Command.Service<WalkTo>()("launcher-bot/WalkTo", { args: { sign: Position }, success: BotMessage }) {}
export class ClickSign extends Command.Service<ClickSign>()("launcher-bot/ClickSign", { args: { sign: Position }, success: BotMessage }) {}

export const LauncherBot = Component.define({
  name: "LauncherBot",
  model: Schema.Struct({ sign: Schema.NullOr(Position), rise: Schema.NullOr(Schema.Finite) }),
  message: BotMessage,
}).logic({
  init: ($) => $.set({ sign: null, rise: null }).run(FindSign.make()),
  update: {
    FoundSign: ($, { sign }) => $.evolve({ sign }).run(WalkTo.make({ sign })),
    Arrived: ($) => ($.model.sign === null ? $.model : $.run(ClickSign.make({ sign: $.model.sign }))),
    Launched: ($, { rise }) => $.evolve({ rise }),
  },
});
```

Each Command has a `success` message, so the bot's next step follows from the answer. The client half implements the Commands with the `MinecraftClient` service, which gives the running `Minecraft` instance. This is the walk:

```ts title="client/bot.ts"
WalkTo.toLayer(Effect.gen(function* () {
  const { minecraft } = yield* MinecraftClient;
  return ({ sign }) =>
    Effect.gen(function* () {
      const player = minecraft.player;
      const target = Vec3.atCenterOf(new BlockPos(sign.x, sign.y, sign.z));
      while (player.position().distanceTo(target) > 3) {
        player.lookAt(EntityAnchor.EYES, target);
        minecraft.options.keyUp.setDown(true);
        yield* tick;
      }
      minecraft.options.keyUp.setDown(false);
      return BotMessage.Arrived();
    });
}))
```

The bundle mounts the component with the Commands provided:

```ts title="client/bot.ts"
const Player = Client.component(LauncherBot).make({ view: () => View.text("") });

export default Client.make(Client.mount(Player, {}).pipe(Effect.provide(Commands)));
```

`Client.component`, `Client.mount` and `Client.make` come from `@minekube/client`, as `Paper.component`, `Paper.mount` and `Paper.make` come from `@minekube/paper` for a game. Because the rules are a component, you test the bot with a [Story](https://minekube.com/games/testing/rules#test-a-command-that-returns-a-message) before it ever starts a client.

## Install a bot in a client

A client runs every bundle in `minekube/bundles/` of its game directory and swaps a bundle when its file changes, like games on a server. You install bundles in one of two ways:

- **Through the daemon API.** `POST /clients` starts a client with a `bundles` record, from bundle id to JavaScript. `PUT /clients/:name/bundles/:bundle` installs one more bundle while the client plays, and `DELETE` removes it.
- **As a file.** Write the built bundle to `clients/<name>/minekube/bundles/<id>.js` in the Minekube home.

## Read what happens

`GET /clients/:name/events` streams the client's events as Server-Sent Events:

| Event | Carries |
| --- | --- |
| `State` | `starting`, `running`, `exited` or `failed`, with the exit code or the reason |
| `Log` | One line of the client's log |
| `Recorded` | One frame of a bundle's recording, with the bundle's id |

The daemon listens on `127.0.0.1:4775` only. Its OpenAPI document is at `/openapi.json`, and a reference page is at `/docs`.

## Write an end-to-end test

An end-to-end test starts a client with the bot, waits for the bot's own recording to report the result, and then checks the server's recording of the same moment. The launcher's test in `examples/launcher/launcher.e2e.ts` does this:

```ts title="launcher.e2e.ts"
const bot = yield* buildBundle(project, path.join(project, "client/bot.ts"), "@minekube/client/prelude");
const api = yield* HttpApiClient.make(Api);
yield* api.clients.create({ payload: { name: "Bot", server: "localhost:25569", bundles: { "launcher-bot": bot } } });

// The bot's own recording in the client says how high it flew.
const events = yield* api.clients.events({ params: { name: "Bot" } });
const rise = yield* events.pipe(
  Stream.mapEffect((event) =>
    event._tag === "State" && (event.state === "exited" || event.state === "failed")
      ? Effect.die(new Error(`the client ${event.state} before the bot launched`))
      : Effect.succeed(event._tag === "Recorded" && event.frame._tag === "Update" ? decodeLaunched(event.frame.message) : undefined)
  ),
  Stream.filter((launch) => launch !== undefined && launch._tag === "Some"),
  Stream.runHead,
  Effect.flatMap((launch) => Effect.fromOption(launch)),
  Effect.map((launch) => launch.value.rise),
  Effect.timeout("3 minutes"),
);
```

Then it reads `plugins/Minekube/recordings/launcher` on the dev server and expects exactly one `ClickedSign` from `Bot` that issued `launcher/Launch`. Both sides of one click are checked, each from its own recording.

The test runs the daemon in its own process with `Daemon.layer()`, so it needs no `mk daemon`. It needs the dev server with the game installed and Java 25.

## Test with several players

The [browser wall example](https://minekube.com/games/examples/browser-wall) starts two clients, `Alex` and `Sam`. Each runs a viewer bundle that reports which maps its client received. The test installs action bundles while the clients play, so one clicks and the other scrolls. It then checks that each player saw only their own change, down to which maps changed, and that the second player keeps going after the first one leaves.

## Related

- [The agent loop](https://minekube.com/games/testing/agent-loop): how a coding agent uses bots to check its own work.
- [Watch and share a world](https://minekube.com/games/local-development/watch-and-share): see what a client sees in a browser.
