# Bot studio

> An editor for animated agent avatars: pick a flat shape and a colour, switch its face between Idle, Thinking and Happy, and export the spec.

A dark studio with a big bot on the left and a picker on the right. The bot is drawn from a few lines of JSON: one of 22 flat silhouettes (a cat, a cloud, a robot, a leaf…) in one of eleven colours, with a simple face. Under it, Idle, Thinking and Happy change that face: the pill eyes blink, look up while the dots rise, or squash into ^^ as the bot hops and rocks. The panel picks the shape from a grid and the colour from a row of swatches, makes a bot from an agent’s name, or reads a spec pasted in, even one with a shape of its own; Export and Copy hand it on as an SVG, a PNG, SVG markup or JSON.

A React component by Bruno Delorence: https://brunodelorence.com/components/bot-studio. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: AI.

## Anatomy

1. **Stage**: The studio, near-black at night and warm off-white by day. Two columns that stack under 700 px.
2. **Avatar**: The bot drawn from its spec: the silhouette in the chosen colour and the face for the state. 30% of the stage’s width.
3. **State switch**: A radio group of three: Idle, Thinking, Happy. The chosen one sits on a pill.
4. **Export and Copy**: Two menu buttons: an SVG or a 512-px PNG to download; the spec as JSON or the SVG markup to the clipboard.
5. **Panel**: Tabs on top, a page under them and the swatch row at the foot. The three pages share one cell, so the panel keeps its height.
6. **Tabs**: Bot, Generate and Import: a tablist with a pill on the open tab.
7. **Chosen shape**: In the chosen colour, with a ring that follows its silhouette: the same pieces stroked wider underneath, a gap in the panel’s colour between.
8. **Swatches**: Eleven colours as a radio group, then the rainbow ring for any colour and the reset to the shape’s own.

## Properties

### State (`defaultSpec.state`)

1. **Idle (default)**: Waiting: pills, a blink, a slow breath.
2. **Thinking**: Working: eyes up, three dots.
3. **Happy**: Done: ^^ eyes, a hop and a rock.

Drive the state from what the agent is doing, not from a timer: Thinking while a reply streams, Happy for a moment when it lands, then Idle.

### Opening tab (`defaultTab`)

1. **Bot (default)**: The grid and the swatches: picking by eye.
2. **Generate**: From the agent’s name, for a first bot in one step.
3. **Import**: A spec pasted in, for bots made elsewhere.

Open on Bot. Open on Generate where the agent’s name was just typed, as the last step of making one.

## When to use

- Giving each agent in a product a face of its own: a picker in its settings, next to its name and instructions.
- Showing what an agent is doing with a face instead of a spinner: `Thinking` while it works, `Happy` when it is done, `Idle` the rest of the time.
- Handing an avatar to other code as data: the spec is a few lines of JSON, and Export makes a static SVG or PNG from it.
- Onboarding, where the first agent someone makes should feel like theirs in two clicks.

## When not to use

- People’s avatars. A bot face reads as a machine; use photos or initials for humans.
- A status that needs words: “Waiting for approval”, “3 of 5 steps”. Show the face, but say the status in text beside it.
- Dense lists with dozens of agents on screen: run the figure as a still (`live` off) or a static SVG, so it doesn’t blink in every row.
- Brand marks. The shapes are friendly and generic on purpose; a logo needs its own drawing.

### The spec

- **Four fields**: `version` (1), `shape` (a built-in id such as `cat`, or `{ name, paths, face }`), `color` (`#rrggbb`) and `state`.
- **Your own shape** is up to 12 strings of SVG path data in a 100 × 100 box, filled; `face` is `[x, y, scale]`, where the eyes go. Only path commands and numbers are accepted.
- **The same spec everywhere**: the live `BotFigure`, the downloaded SVG (`botToSvg`) and Import all read it, so a bot made here looks the same in a chat header or a file.

### Picking a colour

- **A new shape brings its own colour**, the one its tile shows; a swatch after that recolours it.
- **The rainbow ring** opens the system’s colour picker for any colour; the reset button brings back the shape’s own.
- **Light colours get a hairline**, so a white bot still has an edge on a light page.

## Do’s and don’ts

- **Do**: Tie the face to real work: Thinking while the agent is busy, Happy when it finishes.
- **Don’t**: Leave a bot on Happy. A face that rocks forever stops meaning “done” and starts to distract.
- **Do**: Show the agent’s name next to its face, and say its status in words where it matters.
- **Don’t**: Let the face carry a status alone: not everyone can see the eyes change.

## Content

The words are few: the states, the shape and colour names in tooltips, the menu items and the messages under Import.

- **State names are one word**, in title case: `Idle`, `Thinking`, `Happy`.
- **Shape names are plain nouns**: `Cat`, `Cloud`, `Robot`. An imported shape names itself, up to 24 characters.
- **Errors say what to fix**: ““color” should be a hex colour like #f39b1f.”, not “Invalid input”.

## Installation

Install it with the shadcn CLI, into components/bot-studio of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/bot-studio.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/bot-studio
```

Or copy all the source files below into one folder of your project. Either way it needs React 19.2 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { useState } from 'react';
import { BotFigure, resolveShape, type BotSpec } from './bot-avatar';
import { BotStudio } from './bot-studio';

export function AgentFace() {
  const [bot, setBot] = useState<BotSpec>({
    version: 1,
    shape: 'cloud',
    color: '#1fbfa2',
    state: 'idle',
  });
  return (
    <>
      <BotStudio defaultSpec={bot} onSpecChange={setBot} autoplay={false} />
      {/* The same spec, anywhere else: */}
      <BotFigure shape={resolveShape(bot.shape)} color={bot.color} state="thinking" live />
    </>
  );
}
```

## States

- **Idle**: Two 9 × 24 pills; the body breathes by 1.5% over 3.6 s and the eyes blink every few seconds.
- **Thinking**: The eyes narrow to 62% and look up and to the right, drifting; three dots rise in turn above the head.
- **Happy**: The pills squash into ^^ arcs; the bot hops once, then rocks ±3° on a 1.3 s loop.
- **Recoloured**: A swatch over the shape’s own colour: the tile in the grid takes it too, and the reset button wakes up.
- **Generate**: An agent’s name hashed to a shape and a colour, so “Scout” is always the same bot.
- **Import**: The spec as JSON, with a shape id or path data of its own; errors are said in words under the field.
- **Light**: With `colorScheme="light"`: an off-white stage and a white panel. The white bot gets a hairline.
- **Narrow**: Under 700 px the avatar sits over the panel, the panel full width.

## How it works

- A bot is a spec: { version: 1, shape, color, state }. The shape is a built-in id or { name, paths, face } of its own; the same object draws the live figure, the static SVG file and the PNG (the SVG drawn onto a 512-px canvas).
- Each of the 22 shapes is a few pieces in a 100 × 100 box: filled paths, stroked lines (a tail, a handle, an antenna) and filled polygons stroked in their own colour for round corners. The chosen tile’s outline is the same pieces stroked 16 units wider underneath, then 9 wider in the panel’s colour, so the ring follows the silhouette with a gap.
- The eyes are 9 × 24 pills 24 units apart at the shape’s face point. Each state is CSS on the same elements: into Happy the pills squash to a sixth in 110 ms and the ^^ arcs grow out of the dash on a 200 ms overshoot; back to Idle the arcs go first and the pills grow out after 70 ms.
- Idle breathes (1.5% over 3.6 s) and blinks for 170 ms at a random moment every 2.4 to 5.2 s. Happy hops once (560 ms of squash, stretch and landing, Web Animations API) and rocks ±3° on a 1.3 s loop. Thinking narrows the eyes to 62%, looks up and drifts over 2.8 s, tilts 4° over 3.2 s, and raises three dots 180 ms apart.
- A new shape pops in from 86% with a 4% overshoot in 320 ms and brings its own colour; a swatch recolours it with a 220 ms fill transition, and the tile in the grid takes the colour too.
- Generate hashes the agent’s name (FNV-1a) to a shape and a colour, so the same name always gives the same bot. Import checks every field and accepts only path commands and numbers in custom path data.
- Sizes follow the stage’s width with container query units, from a 2000-px reference: the avatar 30% of it, the panel 40% (340 to 470 px) with five tiles to a row; under 700 px the avatar stacks over a full-width panel.
- While on screen and untouched, a demo pointer makes the bot happy, tries the leaf, pink and the bubble, goes back to idle and thinking, and returns to the cat; any input from the reader stops it.

## API reference

- **defaultSpec** (`Partial<BotSpec>`): The bot it starts with: { shape, color, state }. Fields left out come from the amber cat, idle; a shape given alone brings its own colour.
- **onSpecChange** (`(spec: BotSpec) => void`): Called with the whole spec after every change.
- **defaultTab** (`'bot' | 'generate' | 'import'`, default `'bot'`): The panel’s tab at first.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer tries states, shapes and colours; any input from the reader stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): A class for the stage.

## Accessibility

### Keyboard

- The shapes, the swatches and the states are radio groups, one tab stop each. The arrows move and choose; in the grid ↑ and ↓ move a row. Home and End go to the ends.
- The tabs are a tablist: ← and → move between them and open them.
- Export and Copy are menu buttons: Enter, Space or ↓ opens one on its first item, ↑ on its last; Escape closes it and gives the focus back.
- Every control shows a 2-px focus ring; tiles and swatches also show their name on keyboard focus.

### Screen readers

- The avatar is an image named by its spec: “Cat bot, amber, idle”.
- Each tile and swatch is a radio named by its shape or colour; the rainbow ring is a colour input named Custom colour.
- A polite live region says each change (“Shape: Leaf”, “State: Happy”) and the result of Copy, Export, Generate and Import.

### Motion

With reduced motion the bot is drawn still in every state: no blink, hop, rock, drift or rising dots (the dots stay, unmoving), and the demo does not play.

### Colour and contrast

The eyes are near-black on every colour of the palette, the lightest of which gets a hairline on a light stage. The chosen swatch is marked by a ring, not by its colour, and every swatch has its colour’s name.

### In this build

- The shapes, the swatches and the states are radio groups with one tab stop each: the arrows move and choose, ↑ and ↓ a row in the shape grid, Home and End the ends.
- The panel’s tabs are a tablist; the hidden pages are inert. Export and Copy are menu buttons with arrow keys, Escape and focus return.
- The avatar is an image named by its spec (“Cat bot, amber, idle”); every tile and swatch is named, and shows its name in a tooltip on hover and on keyboard focus.
- A polite live region says each change and the result of Copy, Export, Generate and Import. Import’s errors are tied to the field with aria-describedby and aria-invalid.
- Every control shows a 2-px focus ring on keyboard focus. The demo pointer is hidden from screen readers.
- With reduced motion the bot is drawn still in every state: no blink, hop, rock, drift or pop, and the demo does not play.

## Source

### bot-studio/bot-studio.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import { ActionMenu } from './action-menu';
import {
  BotFigure,
  botToSvg,
  DEFAULT_SPEC,
  parseSpec,
  resolveShape,
  shapeName,
  specToJson,
  STATES,
  type BotSpec,
  type BotState,
  type CustomShape,
} from './bot-avatar';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Glyph } from './glyphs';
import { COLORS, SHAPES, type ShapeDef } from './shapes';
import { useAutoplay } from './use-autoplay';
import styles from './bot-studio.module.css';

/*
 * Bot studio: an editor for animated bot avatars. The big avatar on the left is drawn from a
 * small spec (shape, colour, state); the panel on the right picks the shape from a grid of 22
 * flat silhouettes and the colour from a row of swatches, makes one from an agent's name, or
 * reads a spec pasted in. Under the avatar, Idle · Thinking · Happy switches its face, and
 * Export ▾ / Copy ▾ hand the spec on as an SVG or PNG file, SVG markup or JSON.
 *
 * - Picking a shape gives it its own colour, as the tile shows it; a swatch then recolours it
 *   (the reset button brings the shape's colour back). The chosen tile takes the chosen colour
 *   and an outline that follows its silhouette.
 * - The face and motion of each state are in bot-avatar.tsx: the eyes blink, squash into ^^ or
 *   look up, and the body breathes, hops and rocks, or tilts.
 * - Shapes, swatches and states are radio groups: one tab stop each, the arrows move and choose
 *   (↑ ↓ move a row in the grid). The tabs are a tablist. A polite live region says what changed.
 * - While on screen and untouched, a demo pointer switches the state, tries shapes and colours,
 *   and comes back to the cat; any input from the reader stops it for good.
 */

export type StudioTab = 'bot' | 'generate' | 'import';

const TABS: { id: StudioTab; name: string }[] = [
  { id: 'bot', name: 'Bot' },
  { id: 'generate', name: 'Generate' },
  { id: 'import', name: 'Import' },
];

/** The grid's columns, for ↑ and ↓. */
const COLUMNS = 5;

/** Names to try in Generate. */
const NAMES = ['Scout', 'Ledger', 'Juniper', 'Tally', 'Atlas', 'Pixel'];

/** What + puts in Import: a spec with a shape of its own, to show the format. */
const EXAMPLE: BotSpec = {
  version: 1,
  shape: {
    name: 'Pebble',
    paths: ['M18 60C18 36 33 22 54 22C73 22 84 37 84 55C84 75 69 86 48 86C29 86 18 76 18 60Z'],
    face: [51, 54, 1],
  },
  color: '#1fbfa2',
  state: 'idle',
};

/** FNV-1a: the same name always gives the same bot. */
function hash(text: string) {
  let h = 0x811c9dc5;
  for (const ch of text.trim().toLowerCase()) {
    h ^= ch.codePointAt(0)!;
    h = Math.imul(h, 0x01000193) >>> 0;
  }
  return h;
}

/** The spec to start from: the amber cat, idle, under what was given; a shape alone brings its own colour. */
function startSpec(given: Partial<BotSpec> = {}): BotSpec {
  const shape = given.shape ?? DEFAULT_SPEC.shape;
  return {
    ...DEFAULT_SPEC,
    ...given,
    version: 1,
    shape,
    color: given.color ?? (given.shape ? resolveShape(shape).color : DEFAULT_SPEC.color),
  };
}

const colourName = (hex: string) =>
  COLORS.find((c) => c.value === hex)?.name ?? `custom ${hex.toUpperCase()}`;

/** The live region's words for a spec. */
const describe = (spec: BotSpec) =>
  `${shapeName(spec.shape)}, ${colourName(spec.color)}, ${STATES.find((s) => s.id === spec.state)!.name}`;

function download(name: string, blob: Blob) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

/** Moves through a radio group with the arrows; returns the new index, or null for other keys. */
function arrowIndex(event: ReactKeyboardEvent, at: number, count: number, columns = count) {
  // Only from a radio: the + tile sits in the grid but isn't one of its options.
  if ((event.target as HTMLElement).getAttribute('role') !== 'radio') return null;
  const moves: Record<string, number> = {
    ArrowRight: at + 1,
    ArrowLeft: at - 1,
    ArrowDown: columns < count ? at + columns : at + 1,
    ArrowUp: columns < count ? at - columns : at - 1,
    Home: 0,
    End: count - 1,
  };
  if (!(event.key in moves)) return null;
  event.preventDefault();
  let next = moves[event.key];
  if (columns < count && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
    // A row up or down stays in the grid; off the end it stops at the edge.
    next = Math.min(Math.max(next, 0), count - 1);
  } else next = (next + count) % count;
  return next;
}

/** Focuses the radio at `index` inside `group`. */
const focusRadio = (group: HTMLElement | null, index: number) =>
  group?.querySelectorAll<HTMLElement>('[role="radio"]')[index]?.focus();

export function BotStudio({
  defaultSpec,
  onSpecChange,
  defaultTab = 'bot',
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The bot it starts with; any field left out comes from the amber cat, idle. */
  defaultSpec?: Partial<BotSpec>;
  /** Called with the whole spec after every change. */
  onSpecChange?: (spec: BotSpec) => void;
  /** The panel's tab at first. */
  defaultTab?: StudioTab;
  /** While on screen and untouched, a demo pointer tries states, shapes and colours. */
  autoplay?: boolean;
  /** Light or dark colours, or the reader's; without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const pointer = useRef<HTMLSpanElement>(null);
  const grid = useRef<HTMLDivElement>(null);
  const swatchRow = useRef<HTMLDivElement>(null);
  const stateRow = useRef<HTMLDivElement>(null);
  const tabRow = useRef<HTMLDivElement>(null);
  const importField = useRef<HTMLTextAreaElement>(null);

  const [spec, setSpecState] = useState<BotSpec>(() => startSpec(defaultSpec));
  const [custom, setCustom] = useState<CustomShape | null>(() =>
    defaultSpec && typeof defaultSpec.shape === 'object' ? defaultSpec.shape : null,
  );
  const [tab, setTab] = useState<StudioTab>(defaultTab);
  const [name, setName] = useState('');
  const [importText, setImportText] = useState(() => specToJson(startSpec(defaultSpec)));
  const [importError, setImportError] = useState('');
  const [message, setMessage] = useState('');

  const shape = useMemo(() => resolveShape(spec.shape), [spec.shape]);
  const customShape = useMemo(() => (custom ? resolveShape(custom) : null), [custom]);
  const tiles: ShapeDef[] = customShape ? [...SHAPES, customShape] : SHAPES;
  const shapeIndex =
    typeof spec.shape === 'string'
      ? SHAPES.findIndex((s) => s.id === spec.shape)
      : tiles.length - 1;
  const colourIndex = COLORS.findIndex((c) => c.value === spec.color);

  const update = (next: BotSpec, words: string) => {
    setSpecState(next);
    setMessage(words);
    onSpecChange?.(next);
  };

  const pickShape = (index: number) => {
    const def = tiles[index];
    if (!def) return;
    const next: BotSpec = {
      ...spec,
      shape: def.id === 'custom' && custom ? custom : def.id,
      color: def.color,
    };
    update(next, `Shape: ${def.name}`);
  };
  const pickColour = (hex: string) => update({ ...spec, color: hex }, `Colour: ${colourName(hex)}`);
  const pickState = (state: BotState) =>
    update({ ...spec, state }, `State: ${STATES.find((s) => s.id === state)!.name}`);

  const generate = (from: string) => {
    const h = hash(from);
    const def = SHAPES[h % SHAPES.length];
    const colour = COLORS[(h >>> 8) % COLORS.length].value;
    update(
      { ...spec, shape: def.id, color: colour },
      `${from.trim()} is a ${colourName(colour).toLowerCase()} ${def.name.toLowerCase()}`,
    );
  };
  const shuffle = () => {
    const def = SHAPES[Math.floor(Math.random() * SHAPES.length)];
    const colour = COLORS[Math.floor(Math.random() * COLORS.length)].value;
    update(
      { ...spec, shape: def.id, color: colour },
      `Shuffled: ${describe({ ...spec, shape: def.id, color: colour })}`,
    );
  };

  const applyImport = () => {
    const result = parseSpec(importText);
    if ('error' in result) {
      setImportError(result.error);
      return;
    }
    setImportError('');
    if (typeof result.spec.shape === 'object') setCustom(result.spec.shape);
    update(result.spec, `Imported: ${describe(result.spec)}`);
  };

  const showTab = (next: StudioTab) => {
    setTab(next);
    if (next === 'import' && next !== tab) {
      setImportText(specToJson(spec));
      setImportError('');
    }
  };

  const copy = async (text: string, what: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setMessage(`${what} copied`);
    } catch {
      setMessage(`Couldn’t copy the ${what.toLowerCase()}`);
    }
  };
  const fileName = shapeName(spec.shape)
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-');
  const exportPng = async () => {
    const img = new Image();
    img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(botToSvg(spec, 512))}`;
    await img.decode();
    const canvas = document.createElement('canvas');
    canvas.width = canvas.height = 512;
    canvas.getContext('2d')!.drawImage(img, 0, 0, 512, 512);
    canvas.toBlob((blob) => {
      if (!blob) return;
      download(`${fileName}-bot.png`, blob);
      setMessage('PNG downloaded');
    });
  };

  // The demo: a pointer over the real controls, calling the same handlers a click would.
  const demoAct = useEffectEvent(
    (act: { state: BotState } | { shape: string } | { colour: string } | { reset: true }) => {
      if ('state' in act) pickState(act.state);
      else if ('shape' in act) pickShape(SHAPES.findIndex((s) => s.id === act.shape));
      else if ('colour' in act) pickColour(act.colour);
      else {
        setTab('bot');
        update(startSpec(defaultSpec), describe(startSpec(defaultSpec)));
      }
    },
  );
  const demo = autoplay && playing;
  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      /** The middle of a control, in the stage's own px. */
      const at = (selector: string, dx = 0, dy = 0): Point => {
        const frame = stage.getBoundingClientRect();
        const scale = frame.width / stage.offsetWidth || 1;
        const rect = stage.querySelector(selector)?.getBoundingClientRect();
        if (!rect) return { x: frame.width / 2, y: frame.height / 2 };
        return {
          x: (rect.left + rect.width / 2 - frame.left) / scale + dx,
          y: (rect.top + rect.height / 2 - frame.top) / scale + dy,
        };
      };
      const click = async (selector: string, act: Parameters<typeof demoAct>[0], ms = 700) => {
        await glide(at(selector, 2, 3), ms);
        glyph('hand');
        await wait(220);
        demoAct(act);
        await wait(160);
      };
      const tile = (id: string) => `[data-demo="shape-${id}"]`;
      const swatch = (id: string) => `[data-demo="colour-${id}"]`;
      for (;;) {
        await wait(1400);
        await click('[data-demo="state-happy"]', { state: 'happy' }, 900);
        await wait(1800);
        glyph('arrow');
        await click(tile('leaf'), { shape: 'leaf' }, 900);
        await wait(1100);
        await click(swatch('pink'), { colour: COLORS[9].value }, 800);
        await wait(1300);
        await click(tile('bubble'), { shape: 'bubble' }, 700);
        await wait(1200);
        glyph('arrow');
        await click('[data-demo="state-idle"]', { state: 'idle' }, 1000);
        await wait(2200);
        await click('[data-demo="state-thinking"]', { state: 'thinking' }, 500);
        glyph('arrow');
        await wait(2600);
        await click(tile('cat'), { shape: 'cat' }, 1000);
        await wait(500);
        await click('[data-demo="state-idle"]', { reset: true }, 1000);
        glyph('arrow');
        await glide(at('[data-part="avatar"]', 120, 60), 900);
      }
    });
    return () => stop();
  }, [demo, root]);

  const onGridKey = (event: ReactKeyboardEvent) => {
    const next = arrowIndex(event, shapeIndex, tiles.length, COLUMNS);
    if (next === null) return;
    pickShape(next);
    focusRadio(grid.current, next);
  };
  const onSwatchKey = (event: ReactKeyboardEvent) => {
    const next = arrowIndex(event, Math.max(colourIndex, 0), COLORS.length);
    if (next === null) return;
    pickColour(COLORS[next].value);
    focusRadio(swatchRow.current, next);
  };
  const stateIndex = STATES.findIndex((s) => s.id === spec.state);
  const onStateKey = (event: ReactKeyboardEvent) => {
    const next = arrowIndex(event, stateIndex, STATES.length);
    if (next === null) return;
    pickState(STATES[next].id);
    focusRadio(stateRow.current, next);
  };
  const onTabKey = (event: ReactKeyboardEvent) => {
    const at = TABS.findIndex((t) => t.id === tab);
    const moves: Record<string, number> = {
      ArrowRight: at + 1,
      ArrowLeft: at - 1,
      Home: 0,
      End: -1,
    };
    if (!(event.key in moves)) return;
    event.preventDefault();
    const next = (moves[event.key] + TABS.length) % TABS.length;
    showTab(TABS[next].id);
    tabRow.current?.querySelectorAll<HTMLElement>('[role="tab"]')[next]?.focus();
  };

  const ids = useId();
  const title = `${shapeName(spec.shape)} bot, ${colourName(spec.color).toLowerCase()}, ${STATES[stateIndex].name.toLowerCase()}`;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <div className={styles.layout}>
        <section className={styles.studio} aria-label="Preview">
          <div className={styles.avatar} data-part="avatar">
            <BotFigure shape={shape} color={spec.color} state={spec.state} live title={title} />
          </div>
          <div
            ref={stateRow}
            className={styles.states}
            role="radiogroup"
            tabIndex={-1}
            aria-label="State"
            data-part="states"
            onKeyDown={onStateKey}
          >
            {STATES.map((s) => (
              <button
                key={s.id}
                type="button"
                role="radio"
                aria-checked={s.id === spec.state}
                tabIndex={s.id === spec.state ? 0 : -1}
                className={styles.state}
                data-demo={`state-${s.id}`}
                onClick={() => pickState(s.id)}
              >
                {s.name}
              </button>
            ))}
          </div>
          <div className={styles.actions} data-part="actions">
            <ActionMenu
              label="Export"
              part="export"
              icon={<Glyph name="download" />}
              items={[
                {
                  id: 'svg',
                  label: 'SVG file',
                  hint: '.svg',
                  run: () => {
                    download(
                      `${fileName}-bot.svg`,
                      new Blob([botToSvg(spec)], { type: 'image/svg+xml' }),
                    );
                    setMessage('SVG downloaded');
                  },
                },
                { id: 'png', label: 'PNG image', hint: '512 px', run: () => void exportPng() },
              ]}
            />
            <ActionMenu
              label="Copy"
              part="copy"
              icon={<Glyph name="copy" />}
              items={[
                {
                  id: 'json',
                  label: 'Spec',
                  hint: 'JSON',
                  run: () => void copy(specToJson(spec), 'Spec'),
                },
                {
                  id: 'svg',
                  label: 'SVG markup',
                  hint: '<svg>',
                  run: () => void copy(botToSvg(spec), 'SVG'),
                },
              ]}
            />
          </div>
        </section>

        <section className={styles.panel} aria-label="Bot settings" data-part="panel">
          <div
            ref={tabRow}
            className={styles.tabs}
            role="tablist"
            tabIndex={-1}
            aria-label="Make a bot"
            data-part="tabs"
            onKeyDown={onTabKey}
          >
            {TABS.map((t) => (
              <button
                key={t.id}
                type="button"
                role="tab"
                id={`${ids}-tab-${t.id}`}
                aria-selected={t.id === tab}
                aria-controls={`${ids}-panel-${t.id}`}
                tabIndex={t.id === tab ? 0 : -1}
                className={styles.tab}
                onClick={() => showTab(t.id)}
              >
                {t.name}
              </button>
            ))}
          </div>

          <div className={styles.body}>
            <div
              role="tabpanel"
              id={`${ids}-panel-bot`}
              aria-labelledby={`${ids}-tab-bot`}
              className={styles.page}
              data-shown={tab === 'bot'}
              inert={tab !== 'bot'}
            >
              <div
                ref={grid}
                className={styles.grid}
                role="radiogroup"
                tabIndex={-1}
                aria-label="Shape"
                data-part="shapes"
                onKeyDown={onGridKey}
              >
                {tiles.map((def, i) => {
                  const chosen = i === shapeIndex;
                  return (
                    <button
                      key={def.id}
                      type="button"
                      role="radio"
                      aria-checked={chosen}
                      aria-label={def.name}
                      tabIndex={chosen ? 0 : -1}
                      className={styles.tile}
                      data-tip={def.name}
                      data-part={chosen ? 'chosen-shape' : 'shape'}
                      data-demo={`shape-${def.id}`}
                      onClick={() => pickShape(i)}
                    >
                      <BotFigure
                        className={styles.tileFigure}
                        shape={def}
                        color={chosen ? spec.color : def.color}
                        ring={
                          chosen ? { colour: 'var(--tile-ring)', gap: 'var(--panel)' } : undefined
                        }
                      />
                    </button>
                  );
                })}
                <button
                  type="button"
                  className={`${styles.tile} ${styles.add}`}
                  aria-label="Add a shape of your own"
                  data-tip="Your own shape"
                  onClick={() => {
                    setTab('import');
                    setImportText(specToJson(EXAMPLE));
                    setImportError('');
                    requestAnimationFrame(() => importField.current?.focus());
                  }}
                >
                  <span className={styles.addRing}>
                    <Glyph name="plus" />
                  </span>
                </button>
              </div>
            </div>

            <div
              role="tabpanel"
              id={`${ids}-panel-generate`}
              aria-labelledby={`${ids}-tab-generate`}
              className={`${styles.page} ${styles.form}`}
              data-shown={tab === 'generate'}
              inert={tab !== 'generate'}
            >
              <form
                className={styles.field}
                onSubmit={(event) => {
                  event.preventDefault();
                  if (name.trim()) generate(name);
                }}
              >
                <label htmlFor={`${ids}-name`} className={styles.label}>
                  Agent name
                </label>
                <div className={styles.inputRow}>
                  <input
                    id={`${ids}-name`}
                    className={styles.input}
                    value={name}
                    placeholder="Scout"
                    autoComplete="off"
                    spellCheck={false}
                    onChange={(event) => setName(event.target.value)}
                  />
                  <button type="submit" className={styles.primary} disabled={!name.trim()}>
                    Generate
                  </button>
                </div>
                <p className={styles.hint}>The same name always gives the same bot.</p>
              </form>
              <div className={styles.chips} role="group" aria-label="Try a name">
                {NAMES.map((n) => (
                  <button
                    key={n}
                    type="button"
                    className={styles.chip}
                    onClick={() => {
                      setName(n);
                      generate(n);
                    }}
                  >
                    {n}
                  </button>
                ))}
              </div>
              <button type="button" className={styles.secondary} onClick={shuffle}>
                <Glyph name="shuffle" />
                Shuffle
              </button>
            </div>

            <div
              role="tabpanel"
              id={`${ids}-panel-import`}
              aria-labelledby={`${ids}-tab-import`}
              className={`${styles.page} ${styles.form}`}
              data-shown={tab === 'import'}
              inert={tab !== 'import'}
            >
              <label htmlFor={`${ids}-spec`} className={styles.label}>
                Spec (JSON)
              </label>
              <textarea
                ref={importField}
                id={`${ids}-spec`}
                className={styles.code}
                value={importText}
                spellCheck={false}
                aria-invalid={importError ? true : undefined}
                aria-describedby={`${ids}-spec-note`}
                onChange={(event) => setImportText(event.target.value)}
              />
              <div className={styles.inputRow}>
                <p id={`${ids}-spec-note`} className={styles.hint} data-error={!!importError}>
                  {importError ||
                    'A shape id or your own paths in a 100-unit box, a hex colour and a state.'}
                </p>
                <button type="button" className={styles.primary} onClick={applyImport}>
                  Apply
                </button>
              </div>
            </div>
          </div>

          <div className={styles.footer}>
            <div
              ref={swatchRow}
              className={styles.swatches}
              role="radiogroup"
              tabIndex={-1}
              aria-label="Colour"
              data-part="swatches"
              onKeyDown={onSwatchKey}
            >
              {COLORS.map((c, i) => (
                <button
                  key={c.id}
                  type="button"
                  role="radio"
                  aria-checked={i === colourIndex}
                  aria-label={c.name}
                  tabIndex={i === Math.max(colourIndex, 0) ? 0 : -1}
                  className={styles.swatch}
                  style={{ background: c.value }}
                  data-tip={c.name}
                  data-demo={`colour-${c.id}`}
                  data-light={c.id === 'white' || undefined}
                  onClick={() => pickColour(c.value)}
                />
              ))}
            </div>
            <label
              className={`${styles.swatch} ${styles.custom}`}
              data-tip="Custom"
              data-checked={colourIndex < 0}
            >
              <input
                type="color"
                className={styles.colourInput}
                aria-label="Custom colour"
                value={spec.color}
                onChange={(event) => pickColour(event.target.value.toLowerCase())}
              />
            </label>
            <button
              type="button"
              className={`${styles.swatch} ${styles.reset}`}
              aria-label={`Reset to the ${shape.name.toLowerCase()}’s colour`}
              data-tip="Reset"
              disabled={spec.color === shape.color}
              onClick={() => pickColour(shape.color)}
            >
              <Glyph name="reset" />
            </button>
          </div>
        </section>
      </div>

      <div className={styles.pointerLayer} aria-hidden="true">
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
      <p className={styles.hidden} aria-live="polite">
        {message}
      </p>
    </div>
  );
}
```

### bot-studio/bot-studio.module.css

```css
/* Bot studio (bot-studio.tsx): a dark studio, the big avatar on the left with its state switch
   and Export / Copy under it, the picker panel on the right.

   Sizes follow the stage's width (container query units), from measurements of a 2000-px-wide
   studio: the avatar's shape a quarter of the stage, the panel two fifths (793 px there) with a
   44-px radius, its tiles on a 148-px pitch and its swatches 46 px. Under 700 px the two columns
   stack, the panel full width.

   Colours are the tokens below, light-dark(light, dark): the component takes the color-scheme
   it inherits from the page, or the one its colorScheme prop sets. The bots keep their colours
   in both schemes; their eyes are always near-black. */

.root {
  --stage: light-dark(#f3f3f1, #101010);
  --ink: light-dark(#1b1b1b, #ededed);
  --muted: light-dark(#6c6c6c, #8d8d8d);
  --panel: light-dark(#ffffff, #1a1a1a);
  --panel-edge: light-dark(rgb(0 0 0 / 0.08), rgb(255 255 255 / 0.07));
  --panel-shadow: light-dark(rgb(0 0 0 / 0.06), rgb(0 0 0 / 0.4));
  --rule: light-dark(rgb(0 0 0 / 0.07), rgb(255 255 255 / 0.06));
  --chip: light-dark(#ececea, #262626);
  --chip-hover: light-dark(#e4e4e2, #2e2e2e);
  --button: light-dark(#ffffff, #1d1d1d);
  --button-edge: light-dark(rgb(0 0 0 / 0.1), rgb(255 255 255 / 0.06));
  --tile-hover: light-dark(rgb(0 0 0 / 0.035), rgb(255 255 255 / 0.04));
  --tile-ring: light-dark(#bdbdbb, #474747);
  --swatch-ring: light-dark(#1b1b1b, #d4d4d4);
  --field: light-dark(#f6f6f4, #121212);
  --field-edge: light-dark(rgb(0 0 0 / 0.12), rgb(255 255 255 / 0.1));
  --tip: light-dark(#1b1b1b, #f0f0f0);
  --tip-ink: light-dark(#fff, #141414);
  --error: light-dark(#c8102e, #ff6b7f);
  --focus: #3b82f6;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);
  position: relative;
  container-type: inline-size;
  width: 100%;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font:
    400 13px/1.4 -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    sans-serif;
  -webkit-tap-highlight-color: transparent;
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

.layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) clamp(340px, 40cqw, 470px);
  align-items: center;
  gap: clamp(20px, 4cqw, 56px);
  min-height: clamp(420px, 66cqw, 760px);
  padding: clamp(24px, 5cqw, 64px) clamp(20px, 4.5cqw, 56px);
}

/* The avatar, its state switch and the two menus. */
.studio {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 0;
}
.avatar {
  /* The figure's box is 120 units for a 100-unit shape: 34% of the stage draws the shape at
     over a quarter of it. */
  width: clamp(190px, 34cqw, 400px);
  aspect-ratio: 1;
}
.avatar svg {
  width: 100%;
  height: 100%;
}

.states {
  display: flex;
  gap: 2px;
  margin-top: clamp(14px, 3cqw, 36px);
}
.state,
.tab {
  height: 30px;
  padding: 0 12px;
  border: 0;
  border-radius: 999px;
  background: transparent;
  color: var(--muted);
  font: inherit;
  font-size: 13.5px;
  cursor: pointer;
  transition:
    background-color 160ms ease,
    color 160ms ease;
}
.state:hover,
.tab:hover {
  color: var(--ink);
}
.state[aria-checked='true'],
.tab[aria-selected='true'] {
  background: var(--chip);
  color: var(--ink);
}

.actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}
.menuWrap {
  position: relative;
}
.action {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 30px;
  padding: 0 10px 0 11px;
  border: 0;
  border-radius: 999px;
  background: var(--button);
  box-shadow: inset 0 0 0 1px var(--button-edge);
  color: var(--ink);
  font: inherit;
  font-weight: 500;
  cursor: pointer;
}
.action:hover {
  background: var(--chip-hover);
}
.action svg {
  width: 14px;
  height: 14px;
}
.action .chevron {
  width: 12px;
  height: 12px;
  color: var(--muted);
  transition: transform 160ms ease;
}
.action[aria-expanded='true'] .chevron {
  transform: rotate(180deg);
}
.menu {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  z-index: 4;
  min-width: 168px;
  padding: 4px;
  border-radius: 12px;
  background: var(--panel);
  box-shadow:
    0 0 0 1px var(--panel-edge),
    0 10px 30px var(--panel-shadow);
  animation: menu-in 140ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
.menu[hidden] {
  display: none;
}
@keyframes menu-in {
  from {
    opacity: 0;
    transform: translateY(-4px) scale(0.98);
  }
}
.menuItem {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  height: 32px;
  padding: 0 10px;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: var(--ink);
  font: inherit;
  text-align: left;
  cursor: pointer;
}
.menuItem:hover,
.menuItem:focus-visible {
  background: var(--chip);
  outline: none;
}
.menuHint {
  color: var(--muted);
  font-size: 12px;
}

/* The panel. */
.panel {
  /* Thirteen swatches in a row, up to 26 px each, 5 px apart, inside 14 px of padding. */
  --gap: 5px;
  --swatch: min(26px, calc((100cqi - 28px - 12 * var(--gap)) / 13));
  container-type: inline-size;
  display: flex;
  flex-direction: column;
  min-width: 0;
  border-radius: clamp(18px, 2.2cqw, 24px);
  background: var(--panel);
  box-shadow:
    0 0 0 1px var(--panel-edge),
    0 18px 50px var(--panel-shadow);
}
.tabs {
  display: flex;
  gap: 2px;
  padding: 7px;
  border-bottom: 1px solid var(--rule);
}

/* The three pages share one cell, so the panel keeps the grid's height on every tab. */
.body {
  display: grid;
}
.page {
  grid-area: 1 / 1;
  min-width: 0;
  visibility: hidden;
}
.page[data-shown='true'] {
  visibility: visible;
}

.grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 2px;
  padding: 14px 12px;
}
.tile {
  position: relative;
  display: grid;
  place-items: center;
  aspect-ratio: 1;
  padding: 0;
  border: 0;
  border-radius: 14px;
  background: transparent;
  cursor: pointer;
  transition: background-color 140ms ease;
}
.tile:hover {
  background: var(--tile-hover);
}
.tileFigure {
  /* 100 shape units in 120: the shape is about four fifths of the tile, two thirds of
     its pitch with the gaps, as measured. */
  width: 98%;
  height: 98%;
  transition: transform 160ms cubic-bezier(0.2, 0.7, 0.3, 1.4);
}
.tile:active .tileFigure {
  transform: scale(0.92);
}
.add {
  color: var(--muted);
}
.addRing {
  display: grid;
  place-items: center;
  width: 50%;
  aspect-ratio: 1;
  border-radius: 50%;
  box-shadow: inset 0 0 0 1.5px var(--tile-ring);
}
.add:hover .addRing {
  color: var(--ink);
}

/* Generate and Import. */
.form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 18px 16px;
}
.field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.label {
  color: var(--muted);
  font-size: 12px;
  font-weight: 500;
}
.inputRow {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}
.input,
.code {
  min-width: 0;
  border: 0;
  border-radius: 10px;
  background: var(--field);
  box-shadow: inset 0 0 0 1px var(--field-edge);
  color: var(--ink);
  font: inherit;
}
.input {
  flex: 1;
  height: 34px;
  padding: 0 11px;
  font-size: 14px;
}
.code {
  flex: 1;
  min-height: 150px;
  padding: 10px 11px;
  resize: none;
  font:
    12px/1.5 ui-monospace,
    'SF Mono',
    Menlo,
    Consolas,
    monospace;
}
.code[aria-invalid='true'] {
  box-shadow: inset 0 0 0 1.5px var(--error);
}
.input::placeholder {
  color: var(--muted);
}
.primary,
.secondary,
.chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  height: 34px;
  padding: 0 14px;
  border: 0;
  border-radius: 999px;
  font: inherit;
  font-weight: 500;
  cursor: pointer;
}
.primary {
  flex: none;
  background: var(--ink);
  color: var(--panel);
}
.primary:disabled {
  opacity: 0.4;
  cursor: default;
}
.secondary {
  align-self: flex-start;
  background: var(--chip);
  color: var(--ink);
}
.secondary:hover,
.chip:hover {
  background: var(--chip-hover);
}
.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.chip {
  height: 28px;
  padding: 0 11px;
  background: var(--chip);
  color: var(--ink);
  font-weight: 400;
}
.hint {
  flex: 1;
  margin: 0;
  color: var(--muted);
  font-size: 12px;
}
.hint[data-error='true'] {
  color: var(--error);
}

/* The swatch row. */
.footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--gap);
  margin-top: auto;
  padding: 11px 14px 13px;
  border-top: 1px solid var(--rule);
}
.swatches {
  display: flex;
  gap: var(--gap);
}
.swatch {
  position: relative;
  display: grid;
  place-items: center;
  flex: none;
  width: var(--swatch);
  height: var(--swatch);
  padding: 0;
  border: 0;
  border-radius: 50%;
  cursor: pointer;
  transition: transform 140ms cubic-bezier(0.2, 0.7, 0.3, 1.4);
}
.swatch:hover {
  transform: scale(1.08);
}
.swatch[data-light] {
  box-shadow: inset 0 0 0 1px var(--panel-edge);
}
.swatch[aria-checked='true'],
.custom[data-checked='true'] {
  box-shadow:
    0 0 0 2px var(--panel),
    0 0 0 3.5px var(--swatch-ring);
}
.custom {
  /* The rainbow ring: any colour, through the system's picker. */
  background:
    radial-gradient(circle, var(--panel) 52%, transparent 54%),
    conic-gradient(#f2571f, #f39b1f, #27c25c, #1fbfa2, #2668ea, #7c3fec, #dd2d8f, #f2571f);
}
.colourInput {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  padding: 0;
  border: 0;
  border-radius: 50%;
  opacity: 0;
  cursor: pointer;
}
.reset {
  background: transparent;
  box-shadow: inset 0 0 0 1.5px var(--rule);
  color: var(--muted);
}
.reset svg {
  width: 55%;
  height: 55%;
}
.reset:disabled {
  opacity: 0.45;
  cursor: default;
  transform: none;
}

/* Tooltips: the name of a shape under its tile, of a colour above its swatch. */
.tile[data-tip]::after,
.swatch[data-tip]::after {
  content: attr(data-tip);
  position: absolute;
  left: 50%;
  z-index: 3;
  padding: 3px 7px;
  border-radius: 6px;
  background: var(--tip);
  color: var(--tip-ink);
  font-size: 11.5px;
  font-weight: 500;
  white-space: nowrap;
  pointer-events: none;
  opacity: 0;
  transform: translate(-50%, 2px);
  transition:
    opacity 120ms ease,
    transform 120ms ease;
}
.tile[data-tip]::after {
  top: calc(100% - 8px);
}
.swatch[data-tip]::after {
  bottom: calc(100% + 8px);
}
@media (hover: hover) {
  .tile:hover::after,
  .swatch:hover::after {
    opacity: 1;
    transform: translate(-50%, 0);
    transition-delay: 350ms;
  }
}
.tile:focus-visible::after,
.swatch:focus-visible::after,
.custom:focus-within::after {
  opacity: 1;
  transform: translate(-50%, 0);
}

/* Focus. */
.state:focus-visible,
.tab:focus-visible,
.action:focus-visible,
.tile:focus-visible,
.primary:focus-visible,
.secondary:focus-visible,
.chip:focus-visible,
.input:focus-visible,
.code:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.swatch:focus-visible,
.custom:has(:focus-visible) {
  outline: 2px solid var(--focus);
  outline-offset: 4px;
}

/* One column on a narrow stage: the avatar over the panel. */
@container (max-width: 700px) {
  .layout {
    grid-template-columns: minmax(0, 1fr);
    min-height: 0;
    padding: 24px 16px 16px;
  }
  .avatar {
    width: clamp(170px, 52cqw, 260px);
  }
}

/* The demo pointer, over everything; one of its glyphs shows at a time. */
.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 5;
  pointer-events: none;
}
.pointer {
  width: 22px;
  height: 22px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

.hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  .state,
  .tab,
  .tile,
  .tileFigure,
  .swatch,
  .action .chevron,
  .tile[data-tip]::after,
  .swatch[data-tip]::after {
    transition-duration: 0s;
  }
  .menu {
    animation: none;
  }
  .tile:active .tileFigure,
  .swatch:hover {
    transform: none;
  }
}
```

### bot-studio/bot-avatar.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useEffect, useRef, useState } from 'react';
import { SHAPE_IDS, shapeById, SHAPES, type Face, type Piece, type ShapeDef } from './shapes';
import styles from './bot-avatar.module.css';

/*
 * The bot spec and its renderer. A bot is a small JSON object: a shape (one of the built-in ids,
 * or path data of its own), a colour and a state. The same spec draws the live avatar here, a
 * static SVG file (botToSvg), and comes back in through parseSpec.
 *
 * The face is two eyes on top of the silhouette, at the shape's `face` point. Each state is a
 * layer of CSS on the same few elements, so a change of state is a transition, not a redraw:
 * - Idle: 9 × 24 pills; the body breathes (1.5% over 3.6 s) and the eyes blink every 2.4–5.2 s
 *   (170 ms, the lids down to a tenth).
 * - Happy: the pills squash to a dash in 110 ms and the ^^ arcs open out of it; the body hops
 *   once (560 ms, squash and stretch) and rocks ±3° on a 1.3 s loop.
 * - Thinking: the eyes narrow and look up, drifting side to side; the head tilts slowly and three
 *   dots rise in turn at its top right.
 * With reduced motion every state is drawn still: no blink, hop, rock or drift.
 */

export type BotState = 'idle' | 'thinking' | 'happy';

export const STATES: { id: BotState; name: string }[] = [
  { id: 'idle', name: 'Idle' },
  { id: 'thinking', name: 'Thinking' },
  { id: 'happy', name: 'Happy' },
];

/** A shape of the spec's own: filled path data in the 100 × 100 box, and where its eyes go. */
export type CustomShape = { name: string; paths: string[]; face?: Face };

export type BotSpec = {
  version: 1;
  shape: string | CustomShape;
  /** #rrggbb */
  color: string;
  state: BotState;
};

export const DEFAULT_SPEC: BotSpec = { version: 1, shape: 'cat', color: '#f39b1f', state: 'idle' };

/** Only path commands and numbers: imported path data can't carry anything else into the page. */
const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9\s,.eE+-]+$/;
const HEX = /^#[0-9a-f]{6}$/i;

/** The shape a spec names, built in or its own. */
export function resolveShape(shape: BotSpec['shape']): ShapeDef {
  if (typeof shape === 'string') return shapeById(shape) ?? SHAPES[0];
  // One drawing per custom shape object, so the figure sees the same shape on every render (and
  // pops only when the shape really changes).
  let def = drawn.get(shape);
  if (!def) {
    def = {
      id: 'custom',
      name: shape.name,
      color: '#6e6e6e',
      face: shape.face ?? [50, 50, 1],
      pieces: shape.paths.map((d) => ({ d })),
    };
    drawn.set(shape, def);
  }
  return def;
}
const drawn = new WeakMap<CustomShape, ShapeDef>();

export const shapeName = (shape: BotSpec['shape']) =>
  typeof shape === 'string' ? (shapeById(shape)?.name ?? shape) : shape.name;

export const specToJson = (spec: BotSpec) => JSON.stringify(spec, null, 2);

/** Reads a spec from JSON; a string in `error` says what is wrong, in words for the reader. */
export function parseSpec(text: string): { spec: BotSpec } | { error: string } {
  let data: unknown;
  try {
    data = JSON.parse(text);
  } catch {
    return { error: 'This isn’t valid JSON.' };
  }
  if (!data || typeof data !== 'object') return { error: 'The spec should be an object.' };
  const raw = data as Record<string, unknown>;
  const state = raw.state ?? 'idle';
  if (!STATES.some((s) => s.id === state)) {
    return { error: '“state” should be idle, thinking or happy.' };
  }
  if (typeof raw.color !== 'string' || !HEX.test(raw.color)) {
    return { error: '“color” should be a hex colour like #f39b1f.' };
  }
  let shape: BotSpec['shape'];
  if (typeof raw.shape === 'string') {
    if (!SHAPE_IDS.includes(raw.shape)) return { error: `There is no shape “${raw.shape}”.` };
    shape = raw.shape;
  } else if (raw.shape && typeof raw.shape === 'object') {
    const custom = raw.shape as Record<string, unknown>;
    const paths = custom.paths;
    if (
      !Array.isArray(paths) ||
      !paths.length ||
      paths.length > 12 ||
      !paths.every((d) => typeof d === 'string' && d.length < 4000 && PATH_DATA.test(d))
    ) {
      return { error: '“shape.paths” should be 1 to 12 strings of SVG path data.' };
    }
    const face = custom.face;
    const okFace =
      face === undefined ||
      (Array.isArray(face) && face.length === 3 && face.every((v) => Number.isFinite(v)));
    if (!okFace) return { error: '“shape.face” should be [x, y, scale].' };
    shape = {
      name:
        typeof custom.name === 'string' && custom.name.trim() ? custom.name.slice(0, 24) : 'Custom',
      paths: paths as string[],
      ...(face ? { face: face as Face } : {}),
    };
  } else {
    return { error: '“shape” should be a shape id or an object with paths.' };
  }
  return { spec: { version: 1, shape, color: raw.color.toLowerCase(), state: state as BotState } };
}

/** Light colours get a hairline, so a white bot doesn't vanish on a light page. */
export function isLight(hex: string) {
  const v = parseInt(hex.slice(1), 16);
  const [r, g, b] = [(v >> 16) & 255, (v >> 8) & 255, v & 255];
  return 0.2126 * r + 0.7152 * g + 0.0722 * b > 205;
}

const INK = '#141414';
/** The eyes, in face units around the face point. */
const EYES = [-12, 12];
const ARC = (x: number) => `M${x - 6.5} 3.5C${x - 4} -4 ${x + 4} -4 ${x + 6.5} 3.5`;

/** A static SVG of the spec, for the file download and the clipboard. */
export function botToSvg(spec: BotSpec, size = 512) {
  const shape = resolveShape(spec.shape);
  const [fx, fy, fs] = shape.face;
  const piece = (p: Piece, colour: string, extra = 0) => {
    const filled = p.fill !== false;
    const width = (p.w ?? 0) + extra;
    const stroke = width ? ` stroke="${colour}" stroke-width="${width}"` : '';
    return `<path d="${p.d}" fill="${filled ? colour : 'none'}"${stroke}/>`;
  };
  const edge = isLight(spec.color)
    ? shape.pieces.map((p) => piece(p, 'rgba(0,0,0,0.14)', 2.4)).join('')
    : '';
  const body = shape.pieces.map((p) => piece(p, spec.color)).join('');
  let face: string;
  if (spec.state === 'happy') {
    face = EYES.map(
      (x) => `<path d="${ARC(x)}" fill="none" stroke="${INK}" stroke-width="4.6"/>`,
    ).join('');
  } else {
    const h = spec.state === 'thinking' ? 15 : 24;
    const shift = spec.state === 'thinking' ? ' transform="translate(3 -5)"' : '';
    face = `<g${shift}>${EYES.map(
      (x) => `<rect x="${x - 4.5}" y="${-h / 2}" width="9" height="${h}" rx="4.5" fill="${INK}"/>`,
    ).join('')}</g>`;
  }
  const dots =
    spec.state === 'thinking'
      ? [80, 89, 98]
          .map((x, i) => `<circle cx="${x}" cy="${-2 - i * 3}" r="3.2" fill="#8a8a8a"/>`)
          .join('')
      : '';
  return [
    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -14 120 120" width="${size}" height="${size}">`,
    `<title>${escapeXml(shapeName(spec.shape))} bot</title>`,
    `<g stroke-linecap="round" stroke-linejoin="round">${edge}${body}</g>`,
    `<g transform="translate(${fx} ${fy}) scale(${fs})" stroke-linecap="round">${face}</g>`,
    dots,
    `</svg>`,
  ].join('');
}

const escapeXml = (text: string) =>
  text.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);

/** The pieces, filled in `colour`, or stroked `extra` wider for a ring under them. */
function Pieces({
  pieces,
  colour,
  extra = 0,
}: {
  pieces: Piece[];
  colour: string;
  extra?: number;
}) {
  return pieces.map((p, i) => {
    const filled = p.fill !== false;
    const width = (p.w ?? 0) + extra;
    return (
      <path
        key={i}
        d={p.d}
        style={{ fill: filled ? colour : 'none', stroke: width ? colour : 'none' }}
        strokeWidth={width || undefined}
      />
    );
  });
}

/** The eyes in all their forms; the state on the figure shows one. */
function Eyes({ face, blink }: { face: Face; blink?: boolean }) {
  const [x, y, s] = face;
  return (
    <g transform={`translate(${x} ${y}) scale(${s})`}>
      <g className={styles.look}>
        <g className={styles.lid} data-blink={blink || undefined}>
          {EYES.map((ex) => (
            <rect
              key={ex}
              className={styles.eye}
              x={ex - 4.5}
              y={-12}
              width={9}
              height={24}
              rx={4.5}
            />
          ))}
          {EYES.map((ex) => (
            <path key={ex} className={styles.arc} d={ARC(ex)} />
          ))}
        </g>
      </g>
    </g>
  );
}

/**
 * A bot, drawn from its shape, colour and state. `live` animates it (blink, hop, rock, the pop
 * on a change of shape); without it, it is a still, as in the picker's tiles. `ring` draws the
 * selected tile's outline, a gap and a ring that follow the silhouette.
 */
export function BotFigure({
  shape,
  color,
  state = 'idle',
  live = false,
  ring,
  className = '',
  title,
}: {
  shape: ShapeDef;
  color: string;
  state?: BotState;
  live?: boolean;
  ring?: { colour: string; gap: string };
  className?: string;
  /** Names the drawing for screen readers; without it, it is decorative. */
  title?: string;
}) {
  const hop = useRef<SVGGElement>(null);
  const morph = useRef<SVGGElement>(null);
  const blink = useBlink(live && state !== 'happy');
  const last = useRef({ state, shape });

  // The hop into Happy and the pop on a new shape are one-offs, played with the Web Animations
  // API so the looping CSS animations underneath carry on.
  useEffect(() => {
    const was = last.current;
    last.current = { state, shape };
    if (!live || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if (state === 'happy' && was.state !== 'happy') {
      hop.current?.animate(
        [
          { transform: 'none' },
          { transform: 'translateY(0) scale(1.06, 0.92)', offset: 0.18 },
          { transform: 'translateY(-9px) scale(0.96, 1.06)', offset: 0.5 },
          { transform: 'translateY(0) scale(1.05, 0.95)', offset: 0.8 },
          { transform: 'none' },
        ],
        { duration: 560, easing: 'cubic-bezier(0.3, 0, 0.3, 1)' },
      );
    }
    // Built-in shapes are the same objects every time, and an imported one is kept in state, so
    // a new object is a new shape.
    if (shape !== was.shape) {
      morph.current?.animate(
        [
          { transform: 'scale(0.86)' },
          { transform: 'scale(1.04)', offset: 0.6 },
          { transform: 'none' },
        ],
        { duration: 320, easing: 'cubic-bezier(0.2, 0.7, 0.3, 1)' },
      );
    }
  }, [state, shape, live]);

  const light = isLight(color);
  return (
    <svg
      className={`${styles.figure} ${className}`}
      viewBox="-10 -14 120 120"
      data-state={state}
      data-live={live || undefined}
      role={title ? 'img' : undefined}
      aria-label={title}
      aria-hidden={title ? undefined : true}
      focusable="false"
    >
      <g ref={hop} className={styles.hop}>
        <g className={styles.sway}>
          <g ref={morph} className={styles.morph}>
            {ring && (
              <g className={styles.ring}>
                <Pieces pieces={shape.pieces} colour={ring.colour} extra={16} />
                <Pieces pieces={shape.pieces} colour={ring.gap} extra={9} />
              </g>
            )}
            {light && (
              <g className={styles.edge}>
                <Pieces pieces={shape.pieces} colour="var(--bot-hairline)" extra={2.4} />
              </g>
            )}
            <g className={styles.body}>
              <Pieces pieces={shape.pieces} colour={color} />
            </g>
            <Eyes face={shape.face} blink={blink} />
          </g>
        </g>
      </g>
      {live && (
        <g className={styles.dots}>
          {[80, 89, 98].map((x, i) => (
            <circle
              key={x}
              cx={x}
              cy={-2 - i * 3}
              r={3.2}
              style={{ animationDelay: `${i * 180}ms` }}
            />
          ))}
        </g>
      )}
    </svg>
  );
}

/** True for 170 ms at a random moment every 2.4–5.2 s, while `on`; never under reduced motion. */
function useBlink(on: boolean) {
  const [shut, setShut] = useState(false);
  useEffect(() => {
    if (!on) return;
    const motion = matchMedia('(prefers-reduced-motion: reduce)');
    let timer = 0;
    const next = () => {
      timer = window.setTimeout(
        () => {
          if (!motion.matches && !document.hidden) setShut(true);
          timer = window.setTimeout(() => {
            setShut(false);
            next();
          }, 170);
        },
        2400 + Math.random() * 2800,
      );
    };
    next();
    return () => {
      window.clearTimeout(timer);
      setShut(false);
    };
  }, [on]);
  return shut;
}
```

### bot-studio/bot-avatar.module.css

```css
/* The bot figure (bot-avatar.tsx): the silhouette, the eyes, and the motion of each state.
   Lengths inside the SVG are its own units (the shape's box is 100 across); the transforms that
   move whole groups use fill-box, so each turns and squashes about its own bottom or middle. */

.figure {
  --bot-ink: #141414;
  --bot-hairline: rgb(0 0 0 / 0.14);
  --bot-dots: light-dark(#a3a3a3, #6f6f6f);
  display: block;
  overflow: visible;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.hop,
.sway,
.morph {
  transform-box: fill-box;
  transform-origin: 50% 100%;
}
.morph {
  transform-origin: 50% 60%;
}

.body path {
  transition:
    fill 220ms ease,
    stroke 220ms ease;
}

/* The eyes: the pills, and the ^^ arcs out of sight under them. */
.look,
.lid,
.eye,
.arc {
  transform-box: fill-box;
  transform-origin: center;
}
.eye {
  /* The pill's height and top are CSS (SVG 2 geometry properties), so a change of state shortens
     the pill and keeps its round ends, where a scale would flatten them. */
  y: -12px;
  height: 24px;
  fill: var(--bot-ink);
  /* Back from Happy: the arcs go first, then the pills grow out of the dash. */
  transition:
    y 170ms cubic-bezier(0.2, 0.8, 0.3, 1.25) 70ms,
    height 170ms cubic-bezier(0.2, 0.8, 0.3, 1.25) 70ms,
    opacity 0s 70ms;
}
.arc {
  fill: none;
  stroke: var(--bot-ink);
  stroke-width: 4.6;
  opacity: 0;
  transform: scaleY(0.2);
  transition:
    opacity 60ms ease,
    transform 60ms ease;
}
.look {
  transition: transform 260ms cubic-bezier(0.3, 0.7, 0.3, 1);
}
.lid[data-blink] {
  animation: blink 170ms ease-in-out;
}
@keyframes blink {
  45% {
    transform: scaleY(0.1);
  }
}

/* Happy: the pills shrink to a 4-unit dash in 110 ms, then the arcs open out of it. */
.figure[data-state='happy'] .eye {
  y: -2px;
  height: 4px;
  opacity: 0;
  transition:
    y 110ms cubic-bezier(0.5, 0, 0.8, 0.4),
    height 110ms cubic-bezier(0.5, 0, 0.8, 0.4),
    opacity 0s 120ms;
}
.figure[data-state='happy'] .arc {
  opacity: 1;
  transform: none;
  transition:
    opacity 0s 110ms,
    transform 200ms cubic-bezier(0.2, 0.8, 0.3, 1.3) 110ms;
}

/* Thinking: shorter eyes (15 of 24 units), looking up and to the right. */
.figure[data-state='thinking'] .eye {
  y: -7.5px;
  height: 15px;
}
.figure[data-state='thinking'] .look {
  transform: translate(3px, -5px);
}

/* The dots over a thinking bot, rising in turn. */
.dots circle {
  fill: var(--bot-dots);
  opacity: 0;
  transform-box: fill-box;
  transform-origin: center;
  transition: opacity 200ms ease;
}
.figure[data-state='thinking'] .dots circle {
  opacity: 0.35;
  animation: dot 1.2s ease-in-out infinite;
}
@keyframes dot {
  30% {
    opacity: 1;
    transform: translateY(-2.5px);
  }
  60% {
    opacity: 0.35;
    transform: none;
  }
}

/* The loops, on the live avatar only. */
.figure[data-live][data-state='idle'] .sway {
  animation: breathe 3.6s ease-in-out infinite;
}
.figure[data-live][data-state='happy'] .sway {
  animation: rock 1.3s ease-in-out infinite;
}
.figure[data-live][data-state='thinking'] .sway {
  animation: ponder 3.2s ease-in-out infinite;
}
.figure[data-live][data-state='thinking'] .look {
  animation: drift 2.8s ease-in-out infinite;
}
@keyframes breathe {
  50% {
    transform: scale(1.015, 0.985);
  }
}
@keyframes rock {
  25% {
    transform: rotate(-3deg);
  }
  75% {
    transform: rotate(3deg);
  }
}
@keyframes ponder {
  50% {
    transform: rotate(4deg);
  }
}
@keyframes drift {
  0%,
  100% {
    transform: translate(3px, -5px);
  }
  45%,
  55% {
    transform: translate(-3px, -5px);
  }
}

@media (prefers-reduced-motion: reduce) {
  .figure *,
  .figure[data-state] * {
    animation: none !important;
    transition-duration: 0s !important;
    transition-delay: 0s !important;
  }
  .figure[data-state='thinking'] .dots circle {
    opacity: 0.8;
  }
}
```

### bot-studio/shapes.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The bot shapes: flat silhouettes in a 100 × 100 box, each made of a few pieces, so no path has
 * to be one hand-traced outline. A piece is filled, or a stroked line (a tail, a handle, an
 * antenna), or both: a filled polygon stroked in its own colour gets round corners for free. The
 * selected tile's ring is the same pieces stroked wider underneath, so it follows the silhouette.
 *
 * `face` is where the eyes sit and how big they are: [x, y, scale], in the same box. At scale 1
 * the eyes are 9 × 24 pills, 24 apart, as on the cat.
 */

export type Piece = {
  d: string;
  /** False for a line: stroked only. */
  fill?: boolean;
  /** The stroke's width: a line's thickness, or the rounding of a filled piece's corners. */
  w?: number;
};

export type Face = [x: number, y: number, scale: number];

export type ShapeDef = {
  id: string;
  name: string;
  /** The palette colour it is shown in until another is picked. */
  color: string;
  face: Face;
  pieces: Piece[];
};

const n = (value: number) => Number(value.toFixed(2));

const circle = (cx: number, cy: number, r: number): Piece => ({
  d: `M${n(cx - r)} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0Z`,
});

const ellipse = (cx: number, cy: number, rx: number, ry: number): Piece => ({
  d: `M${n(cx - rx)} ${cy}a${rx} ${ry} 0 1 0 ${2 * rx} 0a${rx} ${ry} 0 1 0 ${-2 * rx} 0Z`,
});

const rect = (x: number, y: number, w: number, h: number, r: number): Piece => ({
  d:
    `M${x + r} ${y}h${w - 2 * r}a${r} ${r} 0 0 1 ${r} ${r}v${h - 2 * r}` +
    `a${r} ${r} 0 0 1 ${-r} ${r}h${-(w - 2 * r)}a${r} ${r} 0 0 1 ${-r} ${-r}` +
    `v${-(h - 2 * r)}a${r} ${r} 0 0 1 ${r} ${-r}Z`,
});

const line = (d: string, w: number): Piece => ({ d, fill: false, w });

/** A filled shape whose corners are rounded by a stroke of its own colour. */
const soft = (d: string, w: number): Piece => ({ d, w });

/** A star of `points` points, its tips at `outer` and its notches at `inner`. */
function star(cx: number, cy: number, outer: number, inner: number, points = 5): string {
  const corners: string[] = [];
  for (let i = 0; i < points * 2; i += 1) {
    const r = i % 2 ? inner : outer;
    const a = (Math.PI * i) / points - Math.PI / 2;
    corners.push(`${n(cx + r * Math.cos(a))} ${n(cy + r * Math.sin(a))}`);
  }
  return `M${corners.join('L')}Z`;
}

/** The palette, in the order of the swatch row. */
export const COLORS = [
  { id: 'white', name: 'White', value: '#f4f4f2' },
  { id: 'brown', name: 'Brown', value: '#9b5a3a' },
  { id: 'red', name: 'Red', value: '#e31c4b' },
  { id: 'orange', name: 'Orange', value: '#f2571f' },
  { id: 'amber', name: 'Amber', value: '#f39b1f' },
  { id: 'green', name: 'Green', value: '#27c25c' },
  { id: 'teal', name: 'Teal', value: '#1fbfa2' },
  { id: 'blue', name: 'Blue', value: '#2668ea' },
  { id: 'violet', name: 'Violet', value: '#7c3fec' },
  { id: 'pink', name: 'Pink', value: '#dd2d8f' },
  { id: 'grey', name: 'Grey', value: '#6e6e6e' },
] as const;

const C = Object.fromEntries(COLORS.map((c) => [c.id, c.value])) as Record<
  (typeof COLORS)[number]['id'],
  string
>;

/** The shapes, in the order of the grid: by colour, light to dark round the wheel. */
export const SHAPES: ShapeDef[] = [
  {
    id: 'ghost',
    name: 'Ghost',
    color: C.white,
    face: [50, 44, 0.95],
    pieces: [
      {
        d: 'M24 50C24 30 35 15 50 15C65 15 76 30 76 50V81C76 88 70 90 66 85C63 81 59 81 57 85C54 90 46 90 43 85C41 81 37 81 34 85C30 90 24 88 24 81Z',
      },
    ],
  },
  {
    id: 'bear',
    name: 'Bear',
    color: C.brown,
    face: [50, 56, 1],
    pieces: [circle(27, 29, 11), circle(73, 29, 11), ellipse(50, 57, 35, 30)],
  },
  {
    id: 'parcel',
    name: 'Parcel',
    color: C.brown,
    face: [50, 60, 0.95],
    pieces: [rect(17, 34, 66, 54, 9), rect(12, 20, 76, 20, 7), rect(45, 14, 10, 10, 3)],
  },
  {
    id: 'house',
    name: 'House',
    color: C.red,
    face: [50, 64, 0.85],
    pieces: [rect(64, 16, 11, 22, 3), soft('M14 50L50 18L86 50Z', 10), rect(22, 44, 56, 44, 9)],
  },
  {
    id: 'mushroom',
    name: 'Mushroom',
    color: C.red,
    face: [50, 39, 0.9],
    pieces: [
      rect(35, 50, 30, 40, 13),
      {
        d: 'M9 50C9 29 27 14 50 14C73 14 91 29 91 50C91 56 87 58 81 58H19C13 58 9 56 9 50Z',
      },
    ],
  },
  {
    id: 'screen',
    name: 'Screen',
    color: C.orange,
    face: [50, 51, 1],
    pieces: [
      line('M41 26L31 11', 5),
      line('M59 26L69 11', 5),
      line('M33 74L28 88', 7),
      line('M67 74L72 88', 7),
      rect(13, 24, 74, 54, 14),
    ],
  },
  {
    id: 'flame',
    name: 'Flame',
    color: C.orange,
    face: [50, 64, 0.85],
    pieces: [
      {
        d: 'M51 9C58 24 76 34 77 57C78 77 66 91 50 91C34 91 22 79 23 60C24 48 31 41 35 32C39 40 42 45 46 46C45 33 46 21 51 9Z',
      },
    ],
  },
  {
    id: 'cat',
    name: 'Cat',
    color: C.amber,
    face: [49, 47, 1],
    pieces: [
      line('M70 86C84 87 90 76 86 66', 9),
      rect(21, 56, 52, 36, 15),
      {
        d: 'M13 50C11 36 14 22 19 12C27 14 34 19 39 25C45 24 53 24 59 25C64 19 71 14 79 12C84 22 87 36 85 50C85 64 71 72 49 72C27 72 13 64 13 50Z',
      },
    ],
  },
  {
    id: 'star',
    name: 'Star',
    color: C.amber,
    face: [50, 56, 0.8],
    pieces: [soft(star(50, 55, 40, 19), 10)],
  },
  {
    id: 'bulb',
    name: 'Bulb',
    color: C.amber,
    face: [50, 40, 0.95],
    pieces: [rect(39, 72, 22, 16, 6), soft('M37 56H63L59 73H41Z', 6), circle(50, 40, 28)],
  },
  {
    id: 'leaf',
    name: 'Leaf',
    color: C.green,
    face: [46, 56, 0.9],
    pieces: [
      line('M24 79L12 91', 6),
      { d: 'M82 12C84 40 77 62 60 76C46 88 29 89 18 82C14 70 16 52 30 38C44 24 63 15 82 12Z' },
    ],
  },
  {
    id: 'frog',
    name: 'Frog',
    color: C.green,
    face: [50, 56, 1],
    pieces: [circle(30, 37, 13), circle(70, 37, 13), ellipse(50, 61, 39, 26)],
  },
  {
    id: 'cactus',
    name: 'Cactus',
    color: C.teal,
    face: [50, 40, 0.8],
    pieces: [line('M38 58H26V42', 12), line('M62 50H74V32', 12), rect(36, 12, 28, 80, 14)],
  },
  {
    id: 'cloud',
    name: 'Cloud',
    color: C.teal,
    face: [52, 56, 0.95],
    pieces: [circle(34, 56, 18), circle(55, 44, 23), circle(73, 58, 15), rect(16, 56, 72, 25, 12)],
  },
  {
    id: 'gem',
    name: 'Gem',
    color: C.teal,
    face: [50, 42, 0.85],
    pieces: [soft('M29 21H71L87 40L50 84L13 40Z', 8)],
  },
  {
    id: 'drop',
    name: 'Drop',
    color: C.blue,
    face: [50, 62, 0.95],
    pieces: [
      { d: 'M50 9C62 27 79 43 79 62C79 78 66 91 50 91C34 91 21 78 21 62C21 43 38 27 50 9Z' },
    ],
  },
  {
    id: 'planet',
    name: 'Planet',
    color: C.blue,
    face: [50, 50, 0.95],
    pieces: [line('M10 64C6 56 90 32 90 40C93 47 14 72 10 64Z', 6), circle(50, 50, 29)],
  },
  {
    id: 'bubble',
    name: 'Bubble',
    color: C.violet,
    face: [50, 45, 1],
    pieces: [soft('M27 64L22 87L47 68Z', 5), rect(13, 18, 74, 54, 17)],
  },
  {
    id: 'octopus',
    name: 'Octopus',
    color: C.violet,
    face: [50, 43, 0.95],
    pieces: [
      line('M25 58C23 70 19 77 13 82', 8),
      line('M40 60C40 73 38 81 33 88', 8),
      line('M60 60C60 73 62 81 67 88', 8),
      line('M75 58C77 70 81 77 87 82', 8),
      { d: 'M18 50C18 29 32 15 50 15C68 15 82 29 82 50V63H18Z' },
    ],
  },
  {
    id: 'heart',
    name: 'Heart',
    color: C.pink,
    face: [50, 46, 0.95],
    pieces: [
      {
        d: 'M50 86C30 73 11 59 11 38C11 26 20 16 32 16C40 16 46 20 50 27C54 20 60 16 68 16C80 16 89 26 89 38C89 59 70 73 50 86Z',
      },
    ],
  },
  {
    id: 'bunny',
    name: 'Bunny',
    color: C.pink,
    face: [50, 64, 0.95],
    pieces: [rect(28, 7, 14, 44, 7), rect(58, 7, 14, 44, 7), ellipse(50, 64, 33, 27)],
  },
  {
    id: 'robot',
    name: 'Robot',
    color: C.grey,
    face: [50, 57, 1],
    pieces: [
      line('M50 32V19', 5),
      circle(50, 15, 6.5),
      rect(11, 47, 11, 20, 5),
      rect(78, 47, 11, 20, 5),
      rect(19, 31, 62, 52, 15),
    ],
  },
];

export const SHAPE_IDS = SHAPES.map((shape) => shape.id);

export function shapeById(id: string): ShapeDef | undefined {
  return SHAPES.find((shape) => shape.id === id);
}
```

### bot-studio/action-menu.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import { Glyph } from './glyphs';
import styles from './bot-studio.module.css';

/*
 * Export ▾ and Copy ▾: a menu button (the ARIA pattern). Enter, Space or ↓ opens it with the
 * focus on the first item, ↑ on the last; the arrows, Home and End move, Escape or Tab closes it
 * and a press anywhere else too. Choosing an item runs it and gives the focus back to the button.
 */

/** Focuses the menu's item at `index`, counting from the end when it is negative. */
function focusIn(menu: HTMLElement | null, index: number) {
  const all = menu?.querySelectorAll<HTMLElement>('[role="menuitem"]');
  if (!all?.length) return;
  all[(index + all.length) % all.length].focus();
}

export type MenuItem = { id: string; label: string; hint: string; run: () => void };

export function ActionMenu({
  label,
  icon,
  items,
  part,
}: {
  label: string;
  icon: ReactNode;
  items: MenuItem[];
  part: string;
}) {
  const [open, setOpen] = useState(false);
  const button = useRef<HTMLButtonElement>(null);
  const list = useRef<HTMLDivElement>(null);
  const menuId = useId();

  const focusItem = (index: number) => focusIn(list.current, index);
  const start = useRef(0);

  useEffect(() => {
    if (!open) return;
    focusIn(list.current, start.current);
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!button.current?.contains(target) && !list.current?.contains(target)) setOpen(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [open]);

  const openAt = (index: number) => {
    start.current = index;
    setOpen(true);
  };

  const onButtonKey = (event: KeyboardEvent) => {
    if (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      openAt(0);
    } else if (event.key === 'ArrowUp') {
      event.preventDefault();
      openAt(-1);
    }
  };

  const onMenuKey = (event: KeyboardEvent) => {
    const all = [...(list.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])];
    const at = all.indexOf(document.activeElement as HTMLElement);
    const moves: Record<string, number> = {
      ArrowDown: at + 1,
      ArrowUp: at - 1,
      Home: 0,
      End: -1,
    };
    if (event.key in moves) {
      event.preventDefault();
      focusItem(moves[event.key]);
    } else if (event.key === 'Escape') {
      event.preventDefault();
      setOpen(false);
      button.current?.focus();
    } else if (event.key === 'Tab') {
      setOpen(false);
    }
  };

  return (
    <div className={styles.menuWrap} data-part={part}>
      <button
        ref={button}
        type="button"
        className={styles.action}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={menuId}
        data-demo={part}
        onClick={() => (open ? setOpen(false) : openAt(0))}
        onKeyDown={onButtonKey}
      >
        {icon}
        <span>{label}</span>
        <Glyph name="chevron" className={styles.chevron} />
      </button>
      <div
        ref={list}
        id={menuId}
        role="menu"
        tabIndex={-1}
        aria-label={label}
        className={styles.menu}
        data-open={open}
        hidden={!open}
        onKeyDown={onMenuKey}
      >
        {items.map((item) => (
          <button
            key={item.id}
            type="button"
            role="menuitem"
            tabIndex={-1}
            className={styles.menuItem}
            onClick={() => {
              setOpen(false);
              button.current?.focus();
              item.run();
            }}
          >
            <span>{item.label}</span>
            <span className={styles.menuHint}>{item.hint}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
```

### bot-studio/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The studio's small icons, drawn on a 16-unit grid in the current text colour. All decorative:
 * the control around each one carries its name.
 */

type Name = 'download' | 'copy' | 'chevron' | 'plus' | 'reset' | 'shuffle';

const PATHS: Record<Name, string> = {
  download: 'M8 2.5v7.5M4.8 7 8 10.2 11.2 7M3 13.5h10',
  copy: 'M5.5 5.5V4a1.5 1.5 0 0 1 1.5-1.5h5A1.5 1.5 0 0 1 13.5 4v5a1.5 1.5 0 0 1-1.5 1.5h-1.5M4 5.5h5A1.5 1.5 0 0 1 10.5 7v5A1.5 1.5 0 0 1 9 13.5H4A1.5 1.5 0 0 1 2.5 12V7A1.5 1.5 0 0 1 4 5.5z',
  chevron: 'M4.5 6.5 8 10l3.5-3.5',
  plus: 'M8 3v10M3 8h10',
  reset: 'M3.2 8a4.8 4.8 0 1 0 1.5-3.5M3.2 2.6v2.6h2.6',
  shuffle:
    'M2.5 4.5h2c3 0 4 7 7 7h2M11.5 9.5l2 2-2 2M2.5 11.5h2c1.2 0 2-.9 2.7-2.2M9 6.6c.6-1.2 1.3-2.1 2.5-2.1h2M11.5 2.5l2 2-2 2',
};

export function Glyph({ name, className }: { name: Name; className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 16 16"
      width="16"
      height="16"
      aria-hidden="true"
      focusable="false"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d={PATHS[name]} />
    </svg>
  );
}
```

### bot-studio/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (bot-studio.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over a control. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### bot-studio/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```