> ## Documentation Index
> Fetch the complete documentation index at: https://agent.minimax.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Interface: sites and elements

> Where an extension can draw, how to build the status band and panels from elements, when drawings refresh, and the design rules to follow.

For the release status of each capability, see [Capabilities and progress](https://agent.minimax.io/docs/extension/progress.md).

An extension draws its interface with `ui.render` on three sites: the status band, panels and the backdrop. This page covers the rules for each site, how several plugins draw on the same site, the elements and their props, callbacks for buttons and inputs, when a drawing runs again, and the design rules that keep it looking right.

> [!NOTE]
>
> To look up a single prop or limit, go straight to the [extensions reference](https://agent.minimax.io/docs/extension/reference.md). If the type files in `.minimax-plugin/types/` disagree with this page, the type files are correct.

## Three sites

A site is a place where an extension can draw. You name the site in the matcher of `ui.render`, and the host decides which elements that site accepts. An extension can draw on three sites:

* **Status band**: the strip above the message box, inside its border. All plugins share one band, and each draws a line or two in it. Its site name in code is `above-prompt`.
* **Panel**: a tab in the conversation's side panel on the right, next to tabs such as Files and Browser. Its site name in code is `pane`.
* **Backdrop**: the backdrop behind the conversation, a layer behind the conversation and below every panel in the main window. It replaces the wallpaper while a plugin theme is active. Its site name in code is `backdrop`.

| `site` | Where it is in the window | What it accepts | Use it for |
| - | - | - | - |
| `above-prompt` (status band) | A strip above the conversation's message box, inside its border | `<Box>`, `<Text>`, `<Button>`, `<Tag>`, `<Spinner>`, plus `<Progress>`, `<Link>`, and `<Svg>` Coming soon | Status and quick actions for the conversation: context usage, progress, a very short list, a button that opens a panel |
| `above-prompt-list` (arranging the status band's rows) Coming soon | The same band, run after every plugin's row is drawn | Same as `above-prompt`. Usually it draws nothing new and only passes a filtered or reordered `e.props.rows` to `next(e)` | Filtering or reordering the band's rows across plugins, such as hiding other plugins' rows while a `/` command's expanded view is open in its row |
| `pane` (panel) | A tab of your own in the side panel, next to Files and Browser | All 13 elements, full panel height, scrollable | Content that needs room and stays open beside the conversation, such as a board, a log or a form |
| `backdrop` (backdrop) | Behind the conversation and below every panel in the main window, in place of the wallpaper | `<Box>`, `<Text>`, `<Svg>` | The picture of a theme: a scene, a pattern, an animated sky |

Rules that apply to all three sites:

* Each plugin can register only one `ui.render` per site. For `pane`, that means one per `id`, plus at most one without an `id`. A duplicate registration reports `EXTENSION_DUPLICATE_ENTRY`.
* `site` and `id` must be string literals.
* All three sites are drawn through the same [render chain](#render-chain), with exactly the same rules. Coming soon Once the status band is drawn in two steps, `above-prompt` draws only your plugin's own row, and the render chain runs on `above-prompt-list` instead. See [status band row arrangement](#above-prompt-list).

### The status band: `above-prompt`

The status band is the strip above the message box, inside its border and above the user's draft. All plugins share one band, and each draws a line or two in it.

```tsx theme={null}
on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => drawing);
```

* **There's one band per conversation.** Each plugin is one layer, and the layers stack in [render chain](#render-chain) order. `e` is always `{ site: 'above-prompt' }`.
* **The status band can use `<Box>`, `<Text>`, `<Button>`, `<Tag>`, `<Spinner>`, plus `<Progress>`, `<Link>` and `<Svg>`** Coming soon. Any other element is replaced by a placeholder, and tests report `TREE_INVALID`. Put forms and long text in a panel, and put a button that opens the panel in the status band.
* **Its height is capped at about 12 lines of body text**, always cut at a whole line. When there's little content, the band takes only its own height. Past the cap it scrolls inside, with the scrollbar hidden.
* **Its width follows the message box.** Content that's too wide is cut off, so keep labels short. When a row may not fit on one line, use `<Box wrap>` so it wraps.
* **A close button at the end of the row.** Coming soon `<Button key="dismiss" role="dismiss" label="Close" onPress={…} />` draws as a compact `×` button at the end of the row, with `label` as the name screen readers read. `onPress` runs as usual: change `ctx.state` in it, and the next drawing leaves the row out.
* **Focus stays in the message box.** When the user presses a button in the band, focus and the caret stay in the message box.
* **It's separate from the draft.** The band's content isn't part of the draft, and `ctx.prompt.read()` reads only what the user wrote.
* Limits on element count, nesting depth and text length apply to the whole band (see [tree size limits](#tree-limits)).

For complete examples, see [Example: a context usage status band](#example-band) and [Example: a release checklist with a progress bar and a link](#example-progress).

#### Arrange rows across plugins: above-prompt-list

Coming soon

The status band will be drawn in two steps:

1. **`above-prompt` draws your plugin's own row.** Each plugin's `above-prompt` runs on its own, without affecting the others. Return `undefined` to draw no row. `next()` is empty here, so existing code that keeps `await next()` still works. A row that fails validation, or that would push the stacked band past its limits, is dropped on its own, and the other plugins' rows still show.
2. **`above-prompt-list` arranges the drawn rows.** Its `e` is `{ site: 'above-prompt-list', props: { rows } }`, where `e.props.rows` is `readonly { plugin: string; tree: RenderTree }[]` in render chain order. Filter or reorder them, then pass those rows unchanged to `next({ ...e, props: { ...e.props, rows } })`. When no plugin arranges them, the rows stack vertically in order.

`above-prompt-list` goes through the [render chain](#render-chain) with the same rules as the other sites, so its drawing must use `next` too. The rows you pass to `next` must be the rows you received: changing a row's content, making up a row, or passing the same row twice reports `EXTENSION_ROWS_INVALID`, and this list layer is skipped.

In the example below, a plugin expands a view inside its own `above-prompt` row from a `/` command and keeps the open flag in state as `open`. While the expanded view is open, the band keeps only this plugin's row:

```tsx theme={null}
on('ui.render', { site: 'above-prompt-list' }, async (ctx, e, next) => {
  if (!ctx.state.get('open')) return next();
  const mine = e.props.rows.filter((row) => row.plugin === ctx.plugin.id);
  // If a plugin earlier in the chain already filtered your row out, mine is empty: pass everything on
  return mine.length > 0 ? next({ ...e, props: { ...e.props, rows: mine } }) : next();
});
```

Keep the `mine.length > 0` check. When your row wasn't drawn, or a plugin earlier in the chain already filtered it out, `mine` is empty. Then `return next()` instead of passing an empty list on.

### Panels: `pane`

A panel is a tab in the conversation's side panel on the right, next to tabs such as Files and Browser. A plugin opens each of its panels itself and tells them apart by `id`.

Registering the drawing and opening the tab are two separate steps:

```tsx theme={null}
// Register the drawing for panel board. Registering alone shows nothing
on('ui.render', { site: 'pane', id: 'board' }, async (ctx, e, next) => page);

// Open: add a tab to this conversation's side panel
await ctx.ui.open({ id: 'board', title: 'Board', focus: true });

// Close: remove the tab. Closing a panel that isn't open does nothing
await ctx.ui.close('board');
```

* `id` is the name you give the panel: a non-empty string of up to 200 characters. `title` is the text shown on the tab.
* Calling `ctx.ui.open` again with an `id` that's already open only updates the title. It doesn't add a second tab, so opening the same panel twice is safe.
* You can call `ctx.ui.close` from any callback.
* When the arguments are invalid, both `open` and `close` reject with `ARGUMENT_INVALID`.

#### Focus

`focus: true` switches to the tab and expands the side panel. In three cases `focus` has no effect and the tab is only added:

* a dialog is open;
* the user is typing in the message box;
* the window is in the background.

Open an on-demand panel from a button the user presses. If the panel should be there from the start, open it in `session.start` with a fixed `id` and without `focus`.

> [!WARNING]
>
> Don't request `focus` from a hook that the user didn't trigger, such as `session.start`, `turn.complete`, `tool.result` or a timer callback. Otherwise the panel jumps into view when the user hasn't done anything.

#### When the user closes the tab

When the user clicks close on the tab, your `ui.close` hook runs:

```tsx theme={null}
on('ui.close', { id: 'board' }, (ctx, e) => ctx.ui.toast('Board closed'));
```

`e` is `{ sessionId, id }`, with no `turnId` or `agentId`. Only the plugin that opened the tab receives it. Calling `ctx.ui.close` yourself doesn't trigger it. You can leave `id` out of the matcher, and then the hook runs when any of your panels is closed.

#### Panel lifecycle

* **A tab belongs to the plugin that opened it.** That plugin opens and closes it, and a close by the user notifies only that plugin. While the plugin isn't running (for example, when it's paused), the tab shows a paused placeholder.
* **Each plugin can open at most 16 panels in a conversation.** Opening a 17th rejects with `ARGUMENT_INVALID`.
* **The runtime remembers which tabs are open in a conversation.** A window catches up on its next subscribe or snapshot (opening the conversation, coming back to it, reloading or reconnecting): it adds missing tabs without switching to them and drops tabs that were closed in the meantime. When the user closes a tab in one window, other windows don't close it right away. They catch up on their next sync.
* **While the extension reloads, the tab shows a paused placeholder**, and it draws again once the extension is back. Withdrawing an extension removes all of its tabs.
* **After the runtime restarts, reopen tabs in `session.start`.** A restart clears the tabs, and `session.start` runs again. A panel that should be there from the start must be reopened in `session.start` with a fixed `id` and without `focus`.

#### What a panel can hold

* All 13 elements. The page fills the panel and scrolls when there's a lot of content.
* The panel is drawn only while its tab is the selected one. While another tab is selected the panel isn't kept: when the user comes back it's drawn again from state, so `Input` text that wasn't stored in state is gone. A `<Link>` that opens in the in-app browser selects the browser tab, so it leaves the panel the same way.
* When no layer draws anything, the tab shows an empty state.

For a complete example, see [Example: a board panel with loading, empty and error states](#example-pane).

### The backdrop: `backdrop`

Coming soon

The backdrop is a layer behind the conversation and below every panel in the main window. While a plugin theme is active, it replaces the user's wallpaper and gradient. It shows only when the conversation has a plugin theme. A theme is set with `ctx.theme.set({ backdrop: { scene } })`; see [Set a theme](https://agent.minimax.io/docs/extension/api.md#theme). When there's no plugin theme, or after the theme is cleared or the plugin that set it is withdrawn, the user's own wallpaper comes back.

```tsx theme={null}
on('ui.render', { site: 'backdrop' }, async (ctx, e, next) => drawing);
```

* **There's one backdrop per conversation.** Each plugin is one layer, and the layers are ordered by the [render chain](#render-chain). `e` is `{ site: 'backdrop', props }`, and `e.props` is the conversation's current theme:

  | Field | Type | Description |
  | - | - | - |
  | `plugin` | `string` | The id of the plugin that set the current theme |
  | `scene` | `string` | The name that plugin gave the picture, which is `backdrop.scene` in `ctx.theme.set` |
  | `revision` | `number` | The theme's revision number. It goes up on every `set` that changes the theme and on every `clear`. A `set` identical to the current theme doesn't raise it |

* **Each layer draws only its own scene and passes the rest to `next()`.** While the conversation has a plugin theme, every plugin's backdrop layer runs, no matter who set the theme. No plugin owns the backdrop, so first check that `e.props.plugin` is `ctx.plugin.id`, then check `e.props.scene`. If it isn't yours, `return next()`, or you'll cover another plugin's theme. A plugin can have several scenes and picks which one to draw from `e.props.scene`.

  ```tsx theme={null}
  on('ui.render', { site: 'backdrop' }, async (ctx, e, next) => {
    if (e.props.plugin !== ctx.plugin.id || e.props.scene !== 'rain') return next();
    return <Svg source={RAIN_SVG} />;
  });
  ```

* **The backdrop can use `<Box>`, `<Text>` and `<Svg>`.** Draw the picture with [`<Svg>`](#svg). The backdrop sits below everything the user works with and receives no mouse events, so put only the picture and caption text in it.

* **The reading surface (`glass`).** While the backdrop shows, the window puts a reading surface under the reply rows so the conversation doesn't sit directly on the picture. By default it uses the panel color (derived from `surface-1` when the theme's `colors` sets it, otherwise from `surface-0`), at that color's own opacity, plus an 8 px blur on desktop. To change it, use `backdrop.glass` in `ctx.theme.set`: write `{ blur?, tint?, opacity? }`, and fields you leave out keep their defaults. With `false`, no reading surface is drawn and the reply rows sit directly on the picture, so readability is up to you. Text colors are corrected against the theme's own surface colors, not against `tint`, a lower `opacity` or the picture.

* **Draw a still version for reduced motion.** When reduced motion is on in system settings, the host draws a still version of the same SVG: it removes SMIL elements and `<mpath>`, every `animation*` and `transition*` declaration, and `@keyframes` blocks. So put the resting look in the base styles, not only in keyframes. Write animation in the SVG, and don't redraw frame by frame with `ctx.clock`.

* **No placeholder when every layer is paused.** It behaves as if there were no theme: no layer is drawn, the wallpaper stays as it is, and the paused placeholder with "Retry" doesn't show. On the backdrop, keeping the wallpaper is better than covering it with a notice.

* The backdrop redraws when the theme changes.

For a complete example, see [Example: a night sky backdrop](#example-backdrop).

## The render chain

No plugin owns a site by itself. Every plugin whose matcher hits the site is one layer, and the layers are ordered:

1. Plugins previewed in the current conversation come first, then the other plugins in load order.
2. Earlier layers are on the outside.

Every layer's drawing function receives `next`. `await next()` returns what all the layers after yours drew, and the last layer's `next()` draws nothing. Your job is to put that result in your own tree, usually as the last child of a column `Box`:

```tsx hooks/register.tsx theme={null}
on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
  <Box direction="column" gap="1">
    <Text size="sm" tone="secondary">
      My status
    </Text>
    {/* What the plugins after this one drew */}
    {await next()}
  </Box>
));
```

Rules:

* **Leaving out `next` hides every plugin after yours.** When a drawing function never references `next`, validation reports an `EXTENSION_SHADOWING` warning. It doesn't block preview, but it's almost always a mistake.
* **`return next()` means you add nothing** and pass the later layers through unchanged. Use it when you have nothing to show right now.
* **A drawing can call `next` only once.** A second call reports `EXTENSION_NEXT_TWICE`.
* **A layer that throws is skipped.** If it throws before `next()`, that layer is skipped and the other layers draw as usual. If it throws after `next()`, what the later layers drew is kept.
* **A layer that keeps failing is paused.** A layer that fails repeatedly is paused in the current conversation and skipped, and the other layers draw as usual. The paused placeholder with "Retry" shows only when every layer on a site is paused. The backdrop is an exception; see [the backdrop](#backdrop).
* **A button you wrap still belongs to its plugin.** If you put a button that a later plugin drew inside your own `<Box>`, pressing it still runs that plugin's callback. Only the elements you create are yours.
* The host fixes `e` and the site's properties. Each layer draws on the site or panel the host gives it.

Panels use the same chain. Any plugin's `{ site: 'pane', id: 'board' }` is a layer of the `board` panel (the `id` is just a string, not tied to a plugin), and `{ site: 'pane' }` without an `id` is a layer of every panel. The page drawn by the plugin that opened the panel is only one layer too, so the page also needs `await next()`. To add a section to another plugin's panel, match its `id` and keep `await next()` as well. `e.id` is always the panel's `id`.

The backdrop uses the same chain too, but each layer draws only the picture the conversation's theme names and otherwise does `return next()`. See [the backdrop](#backdrop).

## Elements

Import elements from `@minimax/mcode-plugin-extension/ui` and write them as JSX:

```tsx theme={null}
import { Box, Text } from '@minimax/mcode-plugin-extension/ui';

<Box direction="row" gap="2">
  <Text size="sm">Hello</Text>
</Box>;
```

The host draws every element with its own components, so props accept only the token names below, and the host picks the pixels and styles. Colors are token names too, and a few props also accept a hex color; see [colors](#colors). Children that are `undefined`, `null` or a boolean aren't drawn, so you can show or hide an element with `{cond ? <Tag label="…" /> : undefined}`.

| Element | What it does | Where to use it |
| - | - | - |
| `<Box>` | Layout container that lays out other elements in a row or a column | Status band, panel, backdrop |
| `<Text>` | A run of text | Status band, panel, backdrop |
| `<Tag>` | A small label for a state or a category | Status band, panel |
| `<Button>` | A button | Status band, panel |
| `<Spinner>` | A loading spinner | Status band, panel |
| `<Progress>` | A progress bar, or a spinner with text | Status band, panel |
| `<Link>` | A link that opens a web page | Status band, panel |
| `<Markdown>` | Renders a block of Markdown | Panel |
| `<Code>` | A code block | Panel |
| `<Input>` | A text field, single-line or multi-line | Panel |
| `<Select>` | A dropdown | Panel |
| `<Switch>` | A toggle switch | Panel |
| `<Svg>` | An SVG picture | Backdrop, status band, panel Coming soon |

Every element can take a `key` (a string or a number, up to 256 characters). See [rules for `key`](#keys).

### Tokens

| Category | Values |
| - | - |
| Spacing (`padding`, `gap`) | `1`, `1.5`, `2`, `3`, `4`, `5`, `6` (strings) |
| Text size (`size`) | `xs`, `sm`, `base`, `lg` |
| Weight (`weight`) | `default`, `medium`, `semibold` |
| Tone (`tone`, `background`) | `primary`, `secondary`, `tertiary`, `accent`, `danger`, `success`, `warning`. Some props also accept a hex color; see [colors](#colors) |
| Radius (`radius`) | `sm`, `md`, `lg`, `full` |

Some values are valid but don't draw as their names suggest. See [Never use](#never-use).

### Colors

Coming soon

`tone` and `background` on `<Text>`, `background` on `<Box>`, and `tone` on `<Progress>` accept either a tone token or a hex color: `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. Tone tokens follow the light and dark themes. Hex colors are drawn as written in both. Other color props accept only tone tokens: `hover.background` on `<Box>`, `tone` on `<Button>`, and `tone` on `<Tag>`.

Use hex colors only for data. See [design rules](#tokens).

### Box

A layout container. It only arranges its children and takes no callbacks.

| Prop | Type | Description |
| - | - | - |
| `direction` | `'row'` \| `'column'` | Lay out children in a row or a column |
| `gap` | spacing | Space between children |
| `padding` | spacing | Inner padding |
| `paddingX` | spacing | Left and right padding. Overrides `padding` in that direction |
| `paddingY` | spacing | Top and bottom padding. Overrides `padding` in that direction |
| `align` | `'start'` \| `'center'` \| `'end'` \| `'stretch'` | Cross-axis alignment |
| `justify` | `'start'` \| `'center'` \| `'end'` \| `'between'` | Main-axis alignment. `between` pushes children to both ends |
| `wrap` | `boolean` | Wrap when children don't fit |
| `grow` | `boolean` | Fill the remaining space |
| `width` | `string`, such as `"50%"` | A percentage of the parent's width, as a whole number from `"1%"` to `"100%"` |
| `shrink` | `boolean` | When `false`, the box keeps its size even when the row runs out of room |
| `scrollX` | `boolean` | Scroll sideways when the content is wider than this `Box` |
| `border` | `boolean` | Draw a thin border |
| `radius` | radius | Corner radius |
| `background` | tone or hex color | Background color |
| `hover` | `{ background?, display? }` | Style on mouse hover. `background` is the background color while hovered. `display: 'show'` shows the box only while hovered, and `'hide'` hides it while hovered (it still takes up space when hidden) |
| `scope` | `string` | Hover group name. When a `Box` with a `scope` is hovered, every `Box` with `hover` inside it is treated as hovered too. This is how you make a row's buttons appear only while the row is hovered |
| `children` | elements | Child elements |

### Text

| Prop | Type | Description |
| - | - | - |
| `size` | text size | Defaults to `base` |
| `weight` | weight | Defaults to `default` |
| `tone` | tone or hex color | Text color. Defaults to `primary` |
| `background` | tone or hex color | Background color behind the text |
| `truncate` | `boolean` | Cut the text with an ellipsis when it doesn't fit on one line. When unset, the text wraps |
| `maxLines` | `number` | The most lines to show, a whole number from 1 to 100. The rest is cut off. When `truncate` is also set, `maxLines` wins |
| `mono` | `boolean` | Use a monospace font at the same size |
| `tabular` | `boolean` | Fixed-width digits, for numbers that line up in a column or change in place |
| `children` | string, number | The text |

A string placed directly in a `<Box>` is drawn as a `<Text>` with default styles.

### Markdown

For panels.

| Prop | Type | Description |
| - | - | - |
| `text` | `string`, required | Markdown text |
| `dim` | `boolean` | Draw the body in the `secondary` tone, along with quotes, list markers, table headers and inline code. Code blocks keep their own colors |

Links in the Markdown (inline links, reference links and bare addresses) are clickable when the address follows the [`<Link>` address rules](#link), and clicking them works the same as clicking a `<Link>`. Other links show as plain text.

### Code

For panels. The panel is narrow, so keep lines short, or use `wrap` to wrap long lines.

| Prop | Type | Description |
| - | - | - |
| `source` | `string`, required | The code |
| `language` | `string` | Language name for syntax highlighting, such as `ts` |
| `wrap` | `boolean` | When unset, long lines follow the user's own wrap setting, and the code block shows a wrap toggle. Set to `true` or `false` to fix whether this block wraps and hide the toggle |

### Tag

| Prop | Type | Description |
| - | - | - |
| `label` | `string`, required | Tag text |
| `tone` | tone | `success`, `accent`, `warning` and `danger` show a state. Leave it unset for a neutral tag |

### Button

| Prop | Type | Description |
| - | - | - |
| `label` | `string`, required | Button text. Screen readers also read it as the button's name |
| `onPress` | `() => …` | Runs when pressed. See [buttons and inputs](#callbacks). A button without `onPress` shows as disabled |
| `variant` | `'default'` \| `'plain'` | Defaults to `default`, which is filled. `plain` has no background and looks like text with an icon |
| `tone` | tone | Color when `variant` is `default`. The default looks like `secondary` |
| `icon` | icon name | See [icons](#icons). An unknown icon name isn't drawn |
| `size` | text size | Defaults to `sm` |
| `disabled` | `boolean` | Disabled when `true` |
| `role` | `'dismiss'` | Coming soon Draws as a compact `×` icon button at the end of its row, with `label` as the name screen readers read. `onPress` runs as usual, so change `ctx.state` in it to hide the row |

### Input

For panels. A text field, single-line by default and multi-line when `rows` is 2 or more.

| Prop | Type | Description |
| - | - | - |
| `label` | `string` | Label shown above the field |
| `placeholder` | `string` | Hint shown while the field is empty |
| `value` | `string` | The field's value. A field without focus shows `value` after every redraw, and no `value` counts as empty. It also replaces the content after a successful submit, which is the usual way to clear the field after submitting. To keep what the user typed across redraws and tab switches, store it from `onInput` and pass it back as `value`; set that state to `""` to clear the field |
| `rows` | `number` | Number of lines, a whole number from 1 to 12. Defaults to 1. At 2 or more, the field is a fixed-height multi-line field that scrolls inside when the content is long, and the user can't resize it |
| `submitLabel` | `string` | Text of the submit button. Not empty, up to 64 characters. Shows only when `onSubmit` is set: to the right of a single-line field, or below a multi-line one. Pressing it submits the same way Enter does |
| `onInput` | `(value: string) => …` | Runs while typing, at most once per frame |
| `onSubmit` | `(value: string) => …` | Runs on submit with exactly what the user typed: leading and trailing whitespace isn't trimmed, and line breaks are kept. Enter during IME composition doesn't count as a submit |

When neither `onInput` nor `onSubmit` is set, the field shows as disabled.

How Enter works:

* Single-line field: Enter submits.
* Multi-line field with `onSubmit`: Enter, `Cmd+Enter` and `Ctrl+Enter` submit, and `Shift+Enter` adds a line break.
* Multi-line field without `onSubmit`: Enter adds a line break.
* If a redraw changes `rows` from more than 1 to 1 while the user is typing, line breaks in the draft are removed. Going from 1 line to several keeps the text and the focus.

### Select

For panels.

| Prop | Type | Description |
| - | - | - |
| `options` | `{ value: string; label: string }[]`, required | The options |
| `value` | `string` | The selected value |
| `label` | `string` | The name screen readers read. The dropdown doesn't show this text, so put a `<Text>` next to it when it needs a label |
| `onSelect` | `(value: string) => …` | Runs when an option is chosen. Without it, the dropdown shows as disabled |

### Switch

For panels.

| Prop | Type | Description |
| - | - | - |
| `checked` | `boolean`, required | Whether the switch is on |
| `label` | `string` | Text shown next to the switch |
| `onChange` | `(checked: boolean) => …` | Runs when toggled. Without it, the switch shows as disabled (faded) |

### Spinner

| Prop | Type | Description |
| - | - | - |
| `label` | `string` | Text shown next to the spinner, such as "Loading…" |

### Progress

Coming soon

Shows how far a task has got. Draws a progress bar when you know how far along it is, and a spinner when you don't.

| Prop | Type | Description |
| - | - | - |
| `label` | `string`, required | Task name. Not empty, up to 256 characters |
| `value` | `number` | Current progress |
| `max` | `number` | The total. Defaults to 1, so `value={0.4}` is 40% |
| `valueText` | `string` | Text shown in place of the percentage, up to 256 characters, such as `"412 / 900"` |
| `tone` | tone or hex color | Color of the bar |

* **Progress bar**: when `value` is a finite number and `max` is a finite number greater than 0, it draws a bar and a number. The number is `valueText`, or a whole percentage when there's no `valueText`. It shows 0% or 100% only at the exact ends (below 0 shows 0%, above `max` shows 100%), and every value in between shows as 1% to 99%.
* **Spinner**: without `value`, it draws a task in progress: a spinner and `label`, plus `valueText` when set. It also draws this way when `value` or `max` is `NaN` or infinite, or when `max` is 0 or less. A missing `max` counts as 1, but an invalid one doesn't.
* In the status band it takes one line. In a panel, `label` and the number share a line, with the bar below. A number that's too long is cut with an ellipsis.

### Link

Coming soon

Opens a web address.

| Prop | Type | Description |
| - | - | - |
| `href` | `string`, required | The address, up to 2048 characters |
| `label` | `string` | Text shown when there are no children, up to 256 characters |
| `size` | text size | Defaults to the body text size |
| `children` | string, number | Link text |

* The text shown is, in order: the children's text, `label`, then the address itself.
* **Address rules**: the link is clickable when `href` is an `https:` address or `http://localhost` (any port), with no username or password. Any other address shows as plain text, with no error and no diagnostic.
* A click works like clicking a link in the conversation and follows the user's link-opening setting (the in-app browser by default, or the system browser if they changed it). Cmd-click or Ctrl-click opens it in the system browser.

### Svg

Coming soon

An SVG picture. The backdrop, the status band and panels all accept `<Svg>`, but the backdrop displays and checks it differently from the other two. See [how it's displayed](#svg-display) and [rules for the markup](#svg-rules).

| Prop | Type | Description |
| - | - | - |
| `source` | `string`, required | SVG markup. Not empty, up to 131072 characters (counted by JS `String.length`, that is, UTF-16 code units) |
| `alt` | `string` | The name screen readers read, up to 256 characters. Works in the status band and panels; the whole backdrop is hidden from screen readers. Leave it out when the picture is decoration |
| `width` | `number` | Width of the picture's box in CSS pixels, a finite number greater than 0 and at most 4096. When unset, it fills that direction on the backdrop. In the status band and panels it takes the picture's own size, and its width fits the content (`fit-content`) |
| `height` | `number` | Height of the picture's box, with the same range as `width` |

`<Svg>` takes only these four props and no children, and `source` and the sizes must stay within the ranges above. Otherwise the host rejects the whole tree, not just this picture, and tests report `TREE_INVALID` and name the prop. The tree's 200 KB limit counts the SVG markup too, so a tree can hold at most one picture near the size limit.

#### How it's displayed

* **It's displayed as an image** (an `<img>` with a `data:` address). It's a separate document that runs no scripts, loads nothing and can't touch the page. So ids, classes and `<style>` rules in the SVG apply only inside it, and it can't read the page's CSS custom properties.
* **It can animate.** `<style>` can hold CSS animations, transitions and `@keyframes`, and you can use SMIL: `<animate>`, `<animateTransform>`, `<animateMotion>`, `<set>`.
* **It follows the app's colors.** `currentColor` is the host's primary text color, and `prefers-color-scheme`, `light-dark()` and system colors follow the app's light or dark mode. If you don't set them yourself, the host adds a `color` attribute to the root element and puts `color-scheme` at the start of the root element's `style`.
* **On the backdrop, it fills its box and is cropped.** Give the root element `xmlns="http://www.w3.org/2000/svg"`, `viewBox` and `preserveAspectRatio` (use `xMidYMid slice` to fill), and set its size to `width="100%" height="100%"` or leave it out. The image fills its own box and the overflow is cropped (`object-fit: cover`). It redraws when the window is resized, but animations don't restart. `@media (max-width: …)` in the SVG checks the box's displayed size. A root element without `viewBox` draws at its own size and is cropped the same way. When reduced motion is on in system settings, the backdrop draws a still version; see [the backdrop](#backdrop).
* **In the status band and panels, it takes its own size.** On `above-prompt`, `above-prompt-list` and `pane`, `<Svg>` doesn't fill the window. It shows at the picture's natural size in its own `<img>`, and without `width` its width fits the content (`fit-content`). So set `width` and `height` on `<Svg>` or on the SVG's root `<svg>` rather than relying on `viewBox` alone, especially inside a horizontal `<Box direction="row">`. Animations here aren't removed for reduced motion.
* An image the browser can't load hides only itself.

#### Rules for the markup

The checks below apply only on the backdrop. In the status band and panels (`above-prompt`, `above-prompt-list`, `pane`), only the `<Svg>` props (see the prop table above; breaking them rejects the whole tree, recorded by the window as `invalid-svg` and reported by tests as `TREE_INVALID`) and the tree's 200 KB limit are checked. So standard SVG elements all work there, and you can embed `data:` bitmaps, such as `<image href="data:image/webp;base64,…">`.

On the backdrop, `source` goes through two checks that use the same rules, so a picture that passes `test` also draws in the window.

1. **The runtime checks the text the hook returns**, and so does `test`. If any part breaks a rule, the whole picture is rejected with `EXTENSION_SVG_REFUSED`, and the message names the category and the exact content, such as `Svg refused: script-vector (foreignObject)` or `Svg refused: element (a)`. `test` reports it in the site's `diagnostics`. After a preview, once the site has drawn once, it shows in `runtime.diagnostics` of `inspect`. The other layers draw as usual, just without yours. A rejection isn't a failure: no number of repeats pauses your hook, and once you fix `source`, the next drawing shows it.
2. **The window checks again against an allowlist before drawing.** If the picture fails, it shows as a placeholder ("Part of an extension can't be displayed"), with the reason `unsafe-svg`. `runtime.sites` in [`inspect`](https://agent.minimax.io/docs/extension/testing#inspect) lists, per site, what the window couldn't draw, with the reason and details. Entries are in time order with the newest last, and they stay after you fix the problem, so compare an entry's `renderSeq` with the site's latest drawing.

On the backdrop, follow these rules and the markup passes both checks:

* **Use only standard drawing elements.** The root is one `<svg>` in the SVG namespace. Pick elements from these lists. Names are case-sensitive:
  * Shapes and text: `circle`, `ellipse`, `line`, `path`, `polygon`, `polyline`, `rect`, `text`, `textPath`, `tspan`
  * Structure: `svg`, `g`, `defs`, `symbol`, `use`, `title`, `desc`, `style`
  * Paint effects: `linearGradient`, `radialGradient`, `stop`, `pattern`, `mask`, `clipPath`, `marker`, `filter`
  * Filters: `feBlend`, `feColorMatrix`, `feComponentTransfer`, `feComposite`, `feConvolveMatrix`, `feDisplacementMap`, `feDropShadow`, `feFlood`, `feFuncA`, `feFuncB`, `feFuncG`, `feFuncR`, `feGaussianBlur`, `feMerge`, `feMergeNode`, `feMorphology`, `feOffset`, `feTurbulence`
  * Animation: `animate`, `animateMotion`, `animateTransform`, `set`, `mpath`
* **Reference only elements in the picture itself.** Write `href` (or `xlink:href`) only as `#id`, and `url()` only as `url(#id)`.
* **Draw everything in the picture.** Use fonts installed on the system for text. Don't write `data:` addresses or base64 content, don't use `@import`, `@font-face`, `image-set()`, `cross-fade()`, `src()` or `<?xml-stylesheet`, and don't include bitmaps (`image`, `feImage`) or HTML (`foreignObject`).
* **Draw, don't script.** No `<script>`, and no attribute names that start with `on` (such as `onload`).
* **Use only SVG and XLink attributes.** Declare only these two namespaces. From XLink, use only `xlink:href`. `xml:space` and `xml:lang` are allowed.
* **Use common CSS functions and rules.** Color, math, transform, gradient, filter and easing functions are all fine. The allowed at-rules are `@keyframes` (or `@-webkit-keyframes`), `@media` (including `prefers-reduced-motion`), `@supports`, `@container`, `@layer`, `@scope`, `@property`, `@starting-style`, `@counter-style`, `@page`, `@position-try`, `@view-transition` and `@charset`. Other functions, such as `attr()`, aren't allowed.
* **Animations don't change `href` or `style`.** The runtime check refuses an animation of `href` (`EXTENSION_SVG_REFUSED`), and the window check refuses an animation of `style`, so the whole drawing shows as a placeholder. An animation of `media`, an animation of the root element's own `width` or `height`, and `<metadata>` are only removed by the window; the rest of the drawing still shows.
* **Hide nothing.** No backslashes in `<style>` or in tags. Use only the character references `&amp;`, `&lt;`, `&gt;`, `&quot;` and `&apos;`. No control characters and no unpaired surrogates. No DOCTYPE, entity declarations, CDATA or `<?…?>` (a UTF-8 XML declaration at the start of the file is fine, which is what drawing tools export). `<style>` holds only CSS, with no elements or XML comments, and has a closing tag. Quote every attribute value, and keep `<` and `>` out of values.
* **Write well-formed XML.** Every tag is closed and paired, every prefix is declared, `&` is written `&amp;`, `<` in text is written `&lt;`, and each attribute appears only once.
* **Keep it small.** At most 5000 nodes (elements and text, plus the elements each `<use>` clones). A `<use>` doesn't point to another `<use>` or to an element that contains a `<use>`. A `marker` holds at most 16 elements (counting what `<use>` clones inside it), and a `marker` doesn't contain another `marker`. The host doesn't watch how fast the picture plays, so these limits are what keep its cost down.
* **Comments are checked too.** Ordinary XML comments between tags (without `<` or `--`) and closed CSS comments are fine, but `href` or `data:` in a comment or in `<text>` is rejected the same way.

### Tree size limits

The whole tree returned by one drawing has these limits:

| Item | Limit |
| - | - |
| Nodes (elements and strings both count) | 5000 |
| Nesting depth | 24 |
| Serialized size | 200 KB |
| Length of a single string (text, `Markdown.text`, `Code.source` and string props not listed separately below) | 10000 characters |
| Length of `Svg.source` | 131072 characters, counted separately, but still part of the 200 KB above |
| Length of `Link.href` | 2048 characters |
| Length of `key`, `Code.language`, `Box.scope`, `Progress.label`, `Progress.valueText`, `Link.label`, `Svg.alt` | 256 characters |
| Length of `Input.submitLabel` | 64 characters |

## Buttons and inputs

Only hooks receive `ctx`, written as `(ctx, e)` or `(ctx, e, next)`. Element callbacks receive only their own value. When you need `ctx`, use the one from the enclosing hook:

| Callback | Signature |
| - | - |
| `Button.onPress` | `() => …` |
| `Input.onInput` (while typing), `Input.onSubmit` (Enter or the submit button) | `(value: string) => …` |
| `Select.onSelect` | `(value: string) => …` |
| `Switch.onChange` | `(checked: boolean) => …` |

* **Each callback runs as its own Invocation.** The callback uses the `ctx` from the drawing, but the identity and permissions of the call come from the press, not from the drawing. That's why a callback can write `ctx.state`, call `ctx.mcp.call`, show a toast or fill text into the message box.
* **Use the `ctx` from the enclosing hook in a callback.** A callback that declares its own `ctx` parameter, such as `onPress={(ctx) => …}`, doesn't get `ctx` and fails at runtime.
* Callbacks share the 10-second execution budget with hooks, and the same rule that pauses after 3 failures in a row. See [events](https://agent.minimax.io/docs/extension/events.md).

```tsx hooks/register.tsx theme={null}
on('ui.render', { site: 'pane', id: 'search' }, async (ctx, e, next) => (
  <Box direction="column" gap="2">
    {/* onSubmit receives only the typed value; ctx comes from the enclosing hook */}
    <Input key="query" placeholder="Issue number" onSubmit={(value) => ctx.state.set('query', value)} />
    <Text>{`Searching for ${ctx.state.get('query') ?? '-'}`}</Text>
    {await next()}
  </Box>
));
```

### Rules for `key`

Once a drawing updates, the host can find the control in the new drawing that matches a press, keystroke or submit made on the old one only through `key`. It matches on element type, callback prop name (such as `onPress` or `onSubmit`), and key chain. The key chain is made of the control's own `key` and the `key` of each ancestor, and an ancestor without a `key` is represented by its position in its parent. The event is delivered only when exactly one control matches.

* **A control with no `key` on itself or any ancestor never matches.** A press that arrives after a redraw is ignored (`EXTENSION_HANDLE_STALE`), even if the control looks unchanged. The same goes for a control that has disappeared.
* **Give every list row a `key`**, using a stable id rather than the index. Once a row has a `key`, the buttons inside it don't need one.
* **Give a `key` to every control that causes a redraw**: `<Input>`, `<Select>`, `<Switch>`, and any `<Button>` whose callback triggers a redraw. Then the next keystroke, submit or press still reaches it.
* **Sibling keys must be unique.**
* **Change the `key` when the meaning changes.** A keyed control keeps its identity even when its label changes. For example, if "Delete" becomes "Confirm delete" or "Start" becomes "Stop" under the same `key`, a late second click on the old button runs the new meaning. Use a different `key` for each meaning.

Here's a to-do list in a panel. The input has a `key`, each row uses the to-do's id as its `key`, and "Delete" and "Confirm delete" use different keys.

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  todos: { default: [] as { id: string; text: string; done: boolean }[] },
  confirming: { default: '' },
});

declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button, Input, Switch, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  on('ui.render', { site: 'pane', id: 'todo' }, async (ctx, e, next) => (
    <Box direction="column" gap="4">
      <Text size="lg" weight="semibold">
        To-dos
      </Text>
      <Box direction="column" border radius="md" padding="4" gap="3">
        {/* The input needs a key, or a submit after a redraw can't find it */}
        <Input
          key="new-todo"
          label="New to-do"
          placeholder="Type it and press Enter"
          onSubmit={(value) =>
            ctx.state.update('todos', (todos) => [
              ...todos,
              { id: String(ctx.clock.now()), text: value, done: false },
            ])
          }
        />
        {ctx.state.get('todos').map((todo) => (
          // Each row uses a stable id as its key, so the controls inside don't need one
          <Box key={todo.id} direction="row" align="center" justify="between" gap="2">
            <Switch
              checked={todo.done}
              label={todo.text}
              onChange={(checked) =>
                ctx.state.update('todos', (todos) =>
                  todos.map((t) => (t.id === todo.id ? { ...t, done: checked } : t)),
                )
              }
            />
            {ctx.state.get('confirming') === todo.id ? (
              // The meaning changed, so the key changes: a late first click isn't taken as "Confirm delete"
              <Button
                key="confirm-delete"
                label="Confirm delete"
                tone="danger"
                onPress={async () => {
                  await ctx.state.update('todos', (todos) => todos.filter((t) => t.id !== todo.id));
                  await ctx.state.set('confirming', '');
                }}
              />
            ) : (
              <Button
                key="delete"
                label="Delete"
                icon="trash"
                variant="plain"
                onPress={() => ctx.state.set('confirming', todo.id)}
              />
            )}
          </Box>
        ))}
      </Box>
      {await next()}
    </Box>
  ));
};
```

This example only registers the panel's drawing. To show it, you also need to call `ctx.ui.open({ id: 'todo', title: 'To-dos' })` somewhere, such as from a button in the status band.

## Redrawing

The host keeps the last drawing result and reuses it for ordinary repaints. Your drawing function runs again only in these cases:

* when the status band, the tab or the backdrop is shown;
* when a `ctx.state` key read during the drawing changes (for example, `ctx.state.set` in an `onPress`);
* after you call `ctx.ui.invalidate()`;
* when the conversation's theme changes (backdrop only).

The host doesn't track reads of `ctx.store`. After you write to `ctx.store`, call `ctx.ui.invalidate()` yourself if the drawing should reflect the change. Do the same when an observe hook learns something new (for example, when `session.measure` reports that usage changed).

```tsx theme={null}
// Redraw the status band every time usage changes
on('session.measure', (ctx, e) => ctx.ui.invalidate());
```

**Drawing functions should only read.** Read `ctx.state` in them (and `await` reads of `ctx.store`), but don't write:

* A `ctx.state.set` or `ctx.state.update` in the body of a drawing function that validation can detect reports `EXTENSION_RENDER_SIDE_EFFECT` and blocks preview.
* Writing `ctx.state` while a drawing runs reports `STATE_WRITE_IN_RENDER` at runtime.

Move writes into button callbacks, timer callbacks or observe events. Drawing functions also need to be fast: they're bound by the same execution budget as other hooks.

## Design rules

The host draws every element with its own components and picks the pixels. Colors are token names too, except for a few hex colors used for data. Even so, a drawing can still look wrong: some values draw the same as another one, some draw nothing visible, and a crowded status band pushes the message box down. The items below are rules, not suggestions.

### Never use

These values and patterns pass validation, but the host doesn't draw them the way you'd expect.

| Don't write | What the user sees | Write instead |
| - | - | - |
| `<Button variant="plain" tone="…">`, with any `tone` | Every tone draws in the same primary text color | `<Button variant="plain">` without `tone` |
| `<Button tone="success">` / `tone="warning"` | A neutral grey button, same as `secondary` | `tone="secondary"`, and show the state with a `<Tag>` |
| `<Button tone="tertiary">` | A button with no background | `<Button variant="plain" icon="…">` |
| `<Button size="xs">` | The same size as `sm` | `size="sm"` (the default) |
| `<Button label="" icon="…">` outside a one-line status band | A wide grey block | `<Button variant="plain" icon="…" label="…">`, with an icon and a label |
| `<Tag tone="primary">`, `tone="secondary"`, `tone="tertiary"` | Three identical grey tags | No `tone`, for a neutral tag |
| `<Box radius="lg">` | The same radius as `md` | `radius="md"` |
| `<Box background="primary">` | The page color, so no visible background | `background="secondary"`, or `<Box border>` |
| `<Switch>` without `onChange` | A faded, disabled switch | A `<Tag>` for a read-only on/off state |
| A hex `tone` or `background` to show a state | A fixed color that doesn't follow the dark theme | A `<Tag>` with a state `tone` |
| A `<Link>` to an `http://` address other than `localhost` | Plain text that does nothing when clicked | Use an `https:` address |

### Tokens

* **Text size**: `base` for body text in a panel. `sm` for secondary information and for all text in the status band. `xs` only for metadata such as a time or a count. `lg` only for a panel page title.
* **Weight**: `semibold` for a page title, `medium` for a group title or a name to emphasize, and `default` for everything else.
* **Text tone**: `primary` for content, `secondary` for descriptions and hints, `tertiary` only for placeholder or unavailable text, and `accent` for something the user can act on. `danger`, `success` and `warning` mean a state, never decoration.
* **Show state with a `<Tag>`**: `success` for done or passing, `accent` for running, `warning` for needs attention, `danger` for failed. Don't color a `<Text>` to show a state. A `<Tag>` without `tone` is a neutral label (a branch, a count, a category).
* **`<Spinner>`** appears only while work is really in progress. When the work ends, replace it with a `<Tag>` or remove it. Don't leave a spinner in a resting status band.
* **`<Progress>`** is for when you know how far along the work is: set `value` and `max`, and use `valueText` (such as `"412 / 900"`) in place of the percentage when it helps. Without `value`, it's a spinner with text. As with `<Spinner>`, replace it with a `<Tag>` or remove it when the work ends.
* **Hex colors are only for data**: a label's own color, one series in a chart, one bar per category. They look the same in the light and dark themes, so pick colors that read well in both. States still use `<Tag>`, and every other color uses a token.
* **Links**: use `<Link>` for a standalone address (such as "Open PR" in a row). Write links inside a sentence as `<Markdown>` links, because `<Text>` holds only strings. An address that breaks the [address rules](#link) shows as plain text, so use `https:` addresses.
* **`<Svg>`** on the backdrop is a picture, not content: one scene, a few paths, no bitmaps. Backdrop markup is checked against the [markup rules](#svg-rules), so use only shapes, gradients, filters, `<text>` and `<style>`. A rejected picture doesn't show: when the runtime rejects it, the layer is simply missing, and when the window rejects it, a placeholder shows. Backdrop animation is removed for reduced motion, so the picture has to look good still, too. In the status band and panels, `<Svg>` checks only its props, so standard SVG elements and embedded `data:` bitmaps work. It takes its own size there, so set `width` and `height`.
* **Radius**: `md` for a card or a group, `sm` for a small row or a small tag, `full` for a pill.
* **Buttons**: `secondary` (the default) for ordinary actions. `primary` for the one main action of a panel page. `danger` for a destructive action. `<Button variant="plain" icon="…">` for light or repeated actions. Coming soon `role="dismiss"` for the trailing `×` button that closes a status band row or an expanded view inside it, by changing `ctx.state` in its `onPress`, with a `label` for screen readers. A `plain` button always needs an `icon`, or it reads as plain text.

### Status band budget

The status band sits inside the message box, above the user's draft, and every plugin shares it. Each plugin should keep its layer as small as it can.

* **One line is the norm, and two lines per plugin is the maximum.** Put anything more in a panel, and add a button in the status band that opens it.
* **A `<Progress>` takes a line of its own**, and that line counts toward the two.
* **Shape of a line**: name or state text, then `<Tag>`s, then buttons, all in one `<Box direction="row" wrap gap="2" align="center">`.
* **Use only the `sm` text size.** The plugin or topic name can use `weight="medium"`. Other text uses `tone="secondary"`.
* **Give a `<Link>` `size="sm"` too.** Without it, the link draws at the body text size.
* **Three buttons at most**: at most one `secondary` button for the main action, and the others `<Button variant="plain" icon="…">`. Buttons in the status band use only `secondary` and `plain`. Filled `primary`, `accent` or `danger` buttons draw more attention than the message box.
* **A short list has three items at most**, each with a stable `key`. The two-line budget comes first: three separate rows don't fit, so either show fewer items or move the list to a panel.
* **Put `{await next()}` as the last child** so the plugins after yours still draw.

### Panel skeleton

Open an on-demand panel from a user action, usually a button in the status band. For a panel that should be there from the start, call `ctx.ui.open({ id, title })` in `session.start` with a fixed `id` and without `focus`. The tab appears without stealing attention, and opening the same `id` again doesn't add another tab.

A panel page has a fixed skeleton:

1. Title: `<Text size="lg" weight="semibold">`.
2. One line of description, optional: `<Text size="sm" tone="secondary">`.
3. Groups, with `gap="4"` between them. A group is `<Box direction="column" border radius="md" padding="4" gap="3">` and starts with a group title, `<Text size="sm" weight="medium">`.
4. `{await next()}` last.

```tsx theme={null}
<Box direction="column" gap="4">
  <Text size="lg" weight="semibold">Team board</Text>
  <Text size="sm" tone="secondary">Sync notes and get ready for today's standup.</Text>
  <Box direction="column" border radius="md" padding="4" gap="3">
    <Text size="sm" weight="medium">Board notes</Text>
    {/* Group content */}
  </Box>
  {await next()}
</Box>
```

Other rules:

* **List rows**: `<Box direction="row" align="center" justify="between" padding="2" radius="sm" hover={{ background: 'secondary' }}>`, with text on the left and a `<Tag>` or a `plain` button on the right. Rows that can get long use `<Text truncate>`, or `maxLines` to show a preview of a few lines. Numbers that line up in a column use `tabular`.
* **At most one `primary` button per page.** Destructive actions use `danger`. Everything else uses `secondary` or `plain`.
* **Forms**: an `<Input>` has a `label`, and uses `rows` for text longer than one line (with `onSubmit`, Enter submits, so say in the `placeholder` that `Shift+Enter` adds a line break). A `<Switch>` has a `label` and `onChange`. Put one `<Select>` per row, with a `label` that says what it chooses.
* **Code**: keep lines short, or write `<Code wrap>`. The panel is narrow, and long lines that don't wrap need sideways scrolling to read.

### Loading, empty and error states

A panel that depends on data implements loading, empty and error states, and draws only the one that matches the current state. When the data is ready, show the content. Don't put all three states next to it.

| State | What to draw |
| - | - |
| Loading | `<Spinner label="Loading…" />` |
| Empty | One `<Text tone="secondary">` sentence, plus one button that leads to the next step |
| Error | `<Tag label="Failed" tone="danger" />`, a short reason, and a "Retry" button |

### Checklist before publishing

* Nothing from "Never use".
* Status band: two lines at most, three buttons at most, only `sm` text, buttons only `secondary` or `plain`.
* Every state is shown with a `<Tag>`, and no `<Spinner>` or progress bar is left after the work ends.
* Hex colors are used only for data (label colors, chart series), never to show a state.
* Every `plain` button has an `icon`.
* Panel: a title, groups, and the loading, empty and error states.
* Every drawing function includes `await next()` (or `return next()`).

## Icons

Pick a `<Button>`'s `icon` from the names below. A name that isn't on the list draws no icon. You can also get these names from the `Icon` object (such as `Icon.refresh`) and the `ICON_NAMES` array exported by `@minimax/mcode-plugin-extension/ui`.

| Icon names | | | |
| - | - | - | - |
| `plus` | `minus` | `check` | `close` |
| `search` | `refresh` | `settings` | `edit` |
| `trash` | `copy` | `link` | `external-link` |
| `file` | `folder` | `code` | `terminal` |
| `play` | `stop` | `kanban` | `list` |
| `info` | `warning` | `error` | `star` |
| `user` | `clock` | `calendar` | `bug` |
| `branch` | `plugin` | `chevron-right` | `chevron-down` |
| `more` | | | |

Pick the icon that names the action: `refresh` for sync, `external-link` for opening something outside, `kanban` for a board.

## Example: a context usage status band

This example shows the conversation's context usage in the status band and adds a "Compacting soon" tag above 80%. It uses `session.measure` to redraw when usage changes and `ctx.session.usage()` to read the number. Before the first measurement, it returns `next()` and adds nothing.

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Tag, Text } from '@minimax/mcode-plugin-extension/ui';

export const register: Register = (on) => {
  // Fires when a main Agent turn ends and usage changed: redraw the status band
  on('session.measure', (ctx, e) => ctx.ui.invalidate());

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const { context } = await ctx.session.usage();
    // Not measured yet: add nothing and keep only what later plugins drew
    if (context.percent === undefined) return next();
    return (
      <Box direction="column" gap="1">
        <Box direction="row" wrap gap="2" align="center">
          <Text size="sm" tone="secondary">{`Context ${context.percent}%`}</Text>
          {/* Add a warning tag above 80%; an undefined child isn't drawn */}
          {context.percent >= 80 ? <Tag label="Compacting soon" tone="warning" /> : undefined}
        </Box>
        {/* What later plugins drew goes last */}
        {await next()}
      </Box>
    );
  });
};
```

This module keeps no state, so it doesn't need `hooks/state.ts`.

## Example: a release checklist with a progress bar and a link

Coming soon

This example tracks a four-step release checklist in the status band. While it's unfinished, the first line is a progress bar, and the second line has a "Complete a step" button and a link to the release notes. When it's done, the progress bar becomes a "Done" tag. The whole plugin takes two lines at most.

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  done: { default: 0 },
});

declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button, Link, Progress, Tag, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

const STEPS = 4;

export const register: Register = (on) => {
  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const done = ctx.state.get('done');
    return (
      <Box direction="column" gap="1">
        {done < STEPS ? (
          // You know which step you're on: use Progress, which takes a line of its own
          <Progress label="Release checklist" value={done} max={STEPS} valueText={`${done} / ${STEPS}`} />
        ) : undefined}
        <Box direction="row" wrap gap="2" align="center">
          {done < STEPS ? (
            <Button
              key="next-step"
              label="Complete a step"
              onPress={() => ctx.state.update('done', (n) => n + 1)}
            />
          ) : (
            // The work is done, so the progress bar becomes a Tag
            <>
              <Text size="sm" weight="medium">
                Release checklist
              </Text>
              <Tag label="Done" tone="success" />
            </>
          )}
          {/* A Link in the status band also uses sm; the address is https: */}
          <Link href="https://example.com/release-notes" size="sm">
            Release notes
          </Link>
        </Box>
        {await next()}
      </Box>
    );
  });
};
```

## Example: a board panel with loading, empty and error states

This example puts an "Open board" button in the status band. Pressing it opens the `board` panel and switches to it. The panel calls the plugin's bundled `notes` MCP server to sync data, and draws one of four states: loading, empty, error or ready.

> [!NOTE]
>
> This example calls `ctx.mcp.call('notes', 'sync', …)`, so the plugin package must bundle an MCP server named `notes` and declare it in `mcpServers` in the manifest. See [Call MCP](https://agent.minimax.io/docs/extension/api.md#mcp-call). The call goes through the permission rules. When it needs confirmation, the card's allow option, "Only this chat", allows only this one call, and the next call asks again. Whatever the user answers, no permission rule is saved.

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  board: { default: { status: 'empty', text: '', reason: '' } },
});

declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register, RenderTree } from '@minimax/mcode-plugin-extension';
import { Box, Button, Spinner, Tag, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  // Runs when the plugin takes effect in a conversation. State survives a reload, but a sync that
  // was still running has been interrupted, so switch to the error state
  on('session.start', async (ctx, e) => {
    if (ctx.state.get('board').status === 'loading') {
      await ctx.state.set('board', {
        status: 'error',
        text: '',
        reason: 'The last sync was interrupted. Try again.',
      });
    }
  });

  on('ui.render', { site: 'pane', id: 'board' }, async (ctx, e, next) => {
    // Reading board here makes the panel redraw whenever it changes
    const board = ctx.state.get('board');

    // Button callback: runs in the Invocation of the press, so it can write state and call MCP
    const sync = async () => {
      await ctx.state.set('board', { status: 'loading', text: '', reason: '' });
      try {
        const result = await ctx.mcp.call('notes', 'sync', { scope: 'board' });
        const text = result.content
          .map((part) =>
            part.type === 'text' && typeof part.text === 'string' ? part.text.trim() : '',
          )
          .filter(Boolean)
          .join('\n');
        if (result.isError) throw new Error(text || 'Sync failed.');
        await ctx.state.set('board', { status: text ? 'ready' : 'empty', text, reason: '' });
        await ctx.ui.toast('Board synced');
      } catch (error) {
        await ctx.state.set('board', {
          status: 'error',
          text: '',
          reason: (error instanceof Error ? error.message : String(error)) || 'Sync failed.',
        });
      }
    };

    // Loading, error, ready, empty: draw only the one that matches the current state
    let content: RenderTree;
    if (board.status === 'loading') {
      content = <Spinner label="Loading…" />;
    } else if (board.status === 'error') {
      content = (
        <>
          <Tag label="Failed" tone="danger" />
          <Text size="base">{board.reason}</Text>
          <Button key="retry" label="Retry" icon="refresh" onPress={sync} />
        </>
      );
    } else if (board.status === 'ready') {
      content = (
        <>
          <Tag label="Synced" tone="success" />
          <Text size="base">{board.text}</Text>
          <Button key="sync" label="Sync again" icon="refresh" variant="plain" onPress={sync} />
        </>
      );
    } else {
      content = (
        <>
          <Text size="base" tone="secondary">
            No board notes yet. Sync to check for updates.
          </Text>
          <Button key="sync" label="Sync board" icon="refresh" onPress={sync} />
        </>
      );
    }

    // Panel skeleton: title, one line of description, groups, then await next()
    return (
      <Box direction="column" gap="4">
        <Text size="lg" weight="semibold">
          Team board
        </Text>
        <Text size="sm" tone="secondary">
          Sync notes and get ready for today's standup.
        </Text>
        <Box direction="column" border radius="md" padding="4" gap="3">
          <Text size="sm" weight="medium">
            Board notes
          </Text>
          {content}
        </Box>
        <Box direction="column" border radius="md" padding="4" gap="3">
          <Text size="sm" weight="medium">
            Standup
          </Text>
          <Button
            key="write-standup"
            label="Write standup update"
            icon="calendar"
            variant="plain"
            onPress={async () => {
              await ctx.prompt.fill({ text: 'Write a standup update based on my commits since yesterday.' });
            }}
          />
        </Box>
        {await next()}
      </Box>
    );
  });

  // A button in the status band: when the user presses it, open the panel and switch to it
  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      <Box direction="row" wrap gap="2" align="center">
        <Button
          key="open-board"
          label="Open board"
          icon="kanban"
          onPress={() => ctx.ui.open({ id: 'board', title: 'Board', focus: true })}
        />
      </Box>
      {await next()}
    </Box>
  ));

  // The user clicked close on the tab
  on('ui.close', { id: 'board' }, (ctx, e) => ctx.ui.toast('Board closed'));
};
```

A few things to note:

* `sync` is defined inside the drawing function, but it's used only as a button's `onPress` and runs on the press. Its writes to `ctx.state` don't count as writes during a drawing.
* The panel's `focus: true` is in a button callback, so a user action triggers it. To have the panel there from the start, add `await ctx.ui.open({ id: 'board', title: 'Board' })` to `session.start`, without `focus`.
* Both drawing functions end with `await next()`, so other plugins can still add content to the status band and to this panel.

## Example: a night sky backdrop

Coming soon

This example sets a theme named `night` when the conversation starts, and the backdrop layer draws a night sky: a gradient sky, three twinkling stars and a moon. The stars' resting look (`opacity: 0.8`) is in the base styles, so the picture still looks right when reduced motion removes the animation.

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Svg } from '@minimax/mcode-plugin-extension/ui';

// Night sky: a gradient, three twinkling stars and a moon. At rest the stars stay at opacity 0.8
const NIGHT_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" width="100%" height="100%">
  <defs>
    <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0" stop-color="#0b1026"/>
      <stop offset="1" stop-color="#2b3a67"/>
    </linearGradient>
  </defs>
  <style>
    .star { fill: #ffffff; opacity: 0.8; animation: twinkle 3s ease-in-out infinite; }
    .late { animation-delay: 1.5s; }
    @keyframes twinkle { 50% { opacity: 0.2; } }
  </style>
  <rect width="160" height="90" fill="url(#sky)"/>
  <circle class="star" cx="30" cy="20" r="1"/>
  <circle class="star late" cx="90" cy="12" r="1.2"/>
  <circle class="star" cx="140" cy="40" r="0.8"/>
  <circle cx="120" cy="22" r="8" fill="#f5f3ce"/>
</svg>`;

export const register: Register = (on) => {
  // The theme lives only in memory: set it again every time a conversation starts
  on('session.start', async (ctx, e) => {
    await ctx.theme.set({ backdrop: { scene: 'night' } });
  });

  on('ui.render', { site: 'backdrop' }, async (ctx, e, next) => {
    // Every plugin's backdrop layer runs: if the scene isn't yours, pass the later layers through
    if (e.props.plugin !== ctx.plugin.id || e.props.scene !== 'night') return next();
    return <Svg source={NIGHT_SVG} />;
  });
};
```

A few things to note:

* The SVG references only its own gradient (`url(#sky)`) and has no external content, so it passes the [markup rules](#svg-rules).
* The whole backdrop is hidden from screen readers, so there's no `alt`.
* A conversation has only one theme. If another plugin calls `ctx.theme.set` later, its theme replaces this one. Then `e.props.plugin` is no longer your plugin, and the backdrop layer takes `return next()`. For the theme's other fields (`colors`, and `blur`, `dim` and `glass` in `backdrop`), see [Set a theme](https://agent.minimax.io/docs/extension/api.md#theme).
* This module keeps no state, so it doesn't need `hooks/state.ts`.

## Next steps

> [card] [Events (hooks)](https://agent.minimax.io/docs/extension/events.md)
>
> How to write `ui.render` and observe events, when they fire, and how errors are handled.

> [card] [Extension API](https://agent.minimax.io/docs/extension/api.md)
>
> Save state, call MCP, open panels, fill text into the message box and set a theme.

> [card] [Test and troubleshoot](https://agent.minimax.io/docs/extension/testing.md)
>
> Test the status band and panels with `mount`, `find` and `press`.

> [card] [Diagnostic codes](https://agent.minimax.io/docs/extension/errors.md)
>
> What diagnostics such as `EXTENSION_SHADOWING` and `TREE_INVALID` mean and how to fix them.
