> ## 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.

# Test and troubleshoot

> Write automated tests for an extension, have the Agent run tests and inspect, and track down why an extension isn't working by symptom.

This page covers three things: how to write tests for an extension, how to have the Agent run them and read the results of `inspect`, and how to find the cause by symptom when an extension doesn't behave as expected. Testing, preview, and inspection all run through the Agent calling the `extension` tool. You tell the Agent what to do in the conversation.

## Write tests

Put test files under `hooks/` with names ending in `.test.tsx`, for example `hooks/register.test.tsx`. The extension module doesn't import test files. A test file imports test utilities only from `@minimax/mcode-plugin-extension/testing`, and imports the `register` under test from `./register`.

A test follows these basic steps:

1. Use `mount()` to load the module in a real extension host and draw the given site.
2. Use `find()` to look for elements in the drawn element tree and check what they show.
3. Use `press()` to press buttons, type text, or flip switches the way a user would.
4. Check `site.state()`, `site.effects`, and `site.diagnostics`.

Tests run in an isolated host, where the fakes you pass to `mount()` play the session, model, MCP servers, and message box. Wherever the module needs an answer from the host, a fake answers. See [Answer for the host: fakes](#fakes).

This page refers to three places in an extension:

* **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 in the main window under every panel. It replaces the wallpaper while a theme is active. Its site name in code is `backdrop`.

### Full example

The extension below shows on the status band how many tools this session has called, and a button fills that number into the message box. When the message box already has text, it doesn't overwrite it and shows a toast instead.

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

export { state } from './state';

export const register: Register = (on) => {
  // Add one each time an Agent (sub-agents included) calls a tool; the status band redraws when ctx.state changes
  on('tool.call', (ctx, e) => ctx.state.update('count', (count) => count + 1));

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      <Box direction="row" wrap gap="2" align="center">
        <Text size="sm" tone="secondary">{`Tool calls this session: ${ctx.state.get('count')}`}</Text>
        {/* The button's key lets a press that arrives after a redraw still find it */}
        <Button
          key="fill-count"
          label="Fill message box"
          icon="edit"
          variant="plain"
          onPress={async () => {
            const result = await ctx.prompt.fill({
              text: `Tool calls this session: ${ctx.state.get('count')}.`,
            });
            // replace doesn't overwrite a message box that already has text; tell the user why
            if (!result.written && result.reason === 'draft') {
              await ctx.ui.toast('The message box already has text, so nothing was filled in', { tone: 'warning' });
            }
          }}
        />
      </Box>
      {await next()}
    </Box>
  ));
};
```

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

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

// Tell the editor which keys ctx.state has and what type each value is
declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.test.tsx theme={null}
import { expect, find, mount, press, test } from '@minimax/mcode-plugin-extension/testing';

import { register } from './register';

test('the status band shows the count, and the button fills it into an empty message box', async () => {
  // In tests, state stands in for observe events: set it directly and check what's drawn
  const site = await mount({ register, site: 'above-prompt', state: { count: 3 } });
  expect(find(site, { text: 'Tool calls this session: 3' })).toBeDefined();

  await press(site, { label: 'Fill message box' });

  // site.effects records the side effects sent to the UI: here, a single fill
  expect(
    site.effects.map((effect) =>
      effect.type === 'prompt.fill' ? `${effect.mode}:${effect.text}` : effect.type,
    ),
  ).toEqual(['replace:Tool calls this session: 3.']);
  expect(site.diagnostics).toEqual([]);
});

test('when the message box already has text, it shows a toast instead of overwriting', async () => {
  // composer fake: with a non-empty draft, a replace fill doesn't write
  const site = await mount({
    register,
    site: 'above-prompt',
    composer: { draft: 'Can you look at this error?' },
  });

  await press(site, { label: 'Fill message box' });

  expect(site.effects.map((effect) => effect.type)).toEqual(['ui.toast']);
  expect(site.effects.map((effect) => (effect.type === 'ui.toast' ? effect.text : ''))).toEqual([
    'The message box already has text, so nothing was filled in',
  ]);
});
```

### Load a site: `mount`

| Call | Use |
| - | - |
| `mount({ register, site: 'above-prompt' })` | Draw the status band. No `id` needed |
| `mount({ register, site: 'above-prompt', mods: [otherRegister] })` Coming soon | Draw the full two-step status band: each plugin's own row first, then the `above-prompt-list` arrangement. The `register` functions in `mods` load as other plugins, so you can check how your row looks next to theirs |
| `mount({ register, site: 'above-prompt-list', props: { rows } })` Coming soon | Test the arrangement alone: hand the given `rows` (`{ plugin, tree }[]`) to your `above-prompt-list` layer and check how it filters and reorders them |
| `mount({ register, site: 'pane', id: 'board' })` | Draw the panel whose `id` is `board` |
| `mount({ register, slot: 'pane', key: '<plugin-name>/board' })` | Same as above, naming the panel by its full key |
| `mount({ register, site: 'backdrop' })` | Draw the [backdrop](https://agent.minimax.io/docs/extension/interface.md#backdrop). No `id` needed. In this form `e.props` is an empty object, so a backdrop layer that filters on `e.props.plugin` and `e.props.scene` goes straight to `next()` |
| `mount({ register, slot: 'backdrop', key: 'backdrop', props: { plugin: '<plugin-id>', scene: 'night', revision: 1 } })` | Draw the backdrop with the given `e.props`. Use this form to test what a backdrop layer draws |

To mount a panel, give an `id` or a full key. With neither, `mount` throws. `register` must be the function imported from `./register`.

`mount` activates your plugin, so the `session.start` hook runs once first (with `e.cwd` set to `'/workspace'`). What it does is recorded in `site.effects`. For example, a panel opened in `session.start` leaves a `ui.open` entry. For other observe events (`turn.start`, `tool.call`, and so on), `state` stands in for their effect. Pass a `state` to `mount` and test what the screen shows in that state. There are two exceptions: fire `turn.complete` when a sub-agent finishes with [`completeAgent`](#agent-test), and fire `command.run` with [`runCommand`](#command-test).

Without `mods`, your plugin is the only layer on the site in a test, and `await next()` returns nothing. Coming soon Modules in `mods` skip validation: code that passes there, such as a `ctx.command.register` whose `name` isn't a literal, is refused by `test` and `preview` in a plugin of its own.

When `mount` starts, it takes a snapshot of its arguments. It copies only the object's own enumerable properties, reads each getter once, and keeps `this` pointing to the original object when a method is called. So write fakes as plain objects. Methods on a class instance's prototype aren't copied.

### Find elements and press buttons

| API | What it does |
| - | - |
| `find(site, query)` | Finds the first matching element on the current screen. Returns `undefined` if none matches |
| `findAll(site, query)` | Finds all matching elements, for example `findAll(site, { type: 'Button' })` |
| `site.tree()` | The element tree of the current screen. `[]` when nothing is drawn |
| `press(site, query)` | Runs the callback of the element it finds, and returns after the redraw finishes |
| `press(site, input, value)` | For `Input`: types `value` and presses Enter. If the text changed, it calls `onInput(value)` first, then `onSubmit(value)` |
| `waitFor(() => …, { timeoutMs? })` | Runs an assertion repeatedly until it passes |
| `unmount(site)` | Ends this mount |

A `query` can match by `key`, `label`, `text` (a string or a regular expression), or `type`. `press` also accepts a node returned by `find`. What `press` does for each element:

* `Button` calls `onPress`;
* `Switch` calls `onChange`. Without a `value`, it passes the opposite of the current `checked`;
* `Select` calls `onSelect`. You must give the option's `value`;
* `press` works on these three elements. Calling it on any other element throws an error.

### Check the results

| Read | Contents |
| - | - |
| `site.state()` | The current `ctx.state`. The `state` passed to `mount` is merged over the `defineState` defaults |
| `site.effects` | The side effects the extension sent to the UI, in order. See the table below |
| `site.diagnostics` | Diagnostics from the host and the validator for this site: `{ code, message, fix?, plugin? }` |

Each entry in `site.effects` has a `type` and a `plugin`. The other fields are:

| `type` | Other fields | From |
| - | - | - |
| `ui.toast` | `text` | `ctx.ui.toast` |
| `prompt.fill` | `text`, `mode` (`replace` or `append`) | A `ctx.prompt.fill` that actually wrote |
| `ui.open` | `id`, `title`, `focus?` | `ctx.ui.open` |
| `ui.close` | `id` | `ctx.ui.close` |
| `agent.spawn` | `spec` (the arguments passed to `spawn`) | `ctx.agent.spawn` |
| `theme.set` | `scene` (`backdrop.scene`, or `''` without `backdrop`), `colors?` (the anchors you wrote, with colors normalized to full lowercase hex, so `#FFF` is recorded as `#ffffff`) | `ctx.theme.set` |
| `theme.clear` | None | `ctx.theme.clear` |

In tests, `ctx.theme.set` runs the same checks as the real host: invalid arguments throw `ARGUMENT_INVALID`, and too little contrast between text and background colors throws [`THEME_PALETTE_REJECTED`](https://agent.minimax.io/docs/extension/errors#runtime). Neither leaves a `theme.set` entry. So `ctx.theme` needs no fake. A command's answer isn't a `ctx.ui.toast` and doesn't appear in `site.effects`. See [Test commands](#command-test).

Write assertions with `expect(x)`. It supports `toBe`, `toEqual`, `toBeTruthy`, `toBeDefined`, `toContain`, and `toMatch`. Put `.not` in front to negate.

### Answer for the host: fakes

| Field passed to `mount` | Which call it answers | When omitted |
| - | - | - |
| `mcp: (server, tool, args) => result` | `ctx.mcp.call`, returning `{ content, isError? }` | A hook that calls `ctx.mcp.call` fails |
| `composer: { draft?, suggest? }` | `ctx.prompt.read` reads `draft`; a `replace` `ctx.prompt.fill` returns `reason: 'draft'` when `draft` isn't empty; `suggest(text)` answers `ctx.prompt.suggest` | The draft is empty, and `suggest` returns `{ isShown: true }` |
| `usage: { startedAt, context, rateLimits }` | `ctx.session.usage()` | A 200 000 token window, not measured yet |
| `model: (request) => result` | `ctx.model.complete` | Returns `{ isAnswered: false, reason: 'model-unavailable' }` |
| `agent: { list?, spawn? }` | `ctx.agent.list` and `ctx.agent.spawn` | `list` returns an empty array; `spawn` returns `{ agentId: 'agent-1', model: 'test/model' }` |
| `clock: 'fake' \| 'real'` | Timers on `ctx.clock` | `'fake'`: time moves forward and timers fire only when you `await site.advance(ms)` |
| `state: { … }` | The initial value of `ctx.state` | The `defineState` defaults |

For example, to test a status band that changes color with context usage, pass `usage` like this:

```ts theme={null}
const site = await mount({
  register,
  site: 'above-prompt',
  usage: { startedAt: 0, context: { window: 200000, tokens: 170000, percent: 85 }, rateLimits: [] },
});
```

To test the failure branch of a model call, have `model` return a reason:

```ts theme={null}
model: async () => ({ isAnswered: false, reason: 'timeout' }),
```

In tests, `ctx.store` is an in-memory store and `ctx.ui.invalidate` redraws as usual. Neither needs a fake.

### Test sub-agents

`completeAgent(site, { agentId, answer, reason? })` simulates a sub-agent finishing and sends `turn.complete` to the plugin that started it. `reason` defaults to `'answer'` and also sets the event's `status`.

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

export { state } from './state';

export const register: Register = (on) => {
  // When a sub-agent finishes, only the plugin that started it receives the answer
  on('turn.complete', async (ctx, e) => {
    if (e.agentId === undefined || e.agentId !== ctx.state.get('agentId')) return;
    await ctx.state.set('summary', e.answer ?? 'No reply received');
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      <Box direction="row" wrap gap="2" align="center">
        <Text size="sm" tone="secondary">{ctx.state.get('summary') || 'No summary yet'}</Text>
        <Button
          key="summarize"
          label="Summarize changes"
          icon="search"
          variant="plain"
          onPress={async () => {
            const { agentId } = await ctx.agent.spawn({
              prompt: 'Summarize the uncommitted changes in the current workspace in one sentence',
              agentType: 'explore',
            });
            await ctx.state.set('agentId', agentId);
          }}
        />
      </Box>
      {await next()}
    </Box>
  ));
};
```

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

export const state = defineState({
  agentId: { default: '' },
  summary: { default: '' },
});

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

```tsx hooks/register.test.tsx theme={null}
import {
  completeAgent,
  expect,
  find,
  mount,
  press,
  test,
  waitFor,
} from '@minimax/mcode-plugin-extension/testing';

import { register } from './register';

test('starts a sub-agent and shows its reply when it finishes', async () => {
  // agent fake: answers ctx.agent.spawn in place of the real host
  const site = await mount({
    register,
    site: 'above-prompt',
    agent: { spawn: () => ({ agentId: 'agent-7', model: 'test/model' }) },
  });

  await press(site, { label: 'Summarize changes' });
  expect(site.effects.map((effect) => effect.type)).toEqual(['agent.spawn']);
  expect(site.state()).toEqual({ agentId: 'agent-7', summary: '' });

  // Simulate the sub-agent finishing: fires the turn.complete the starter receives
  await completeAgent(site, { agentId: 'agent-7', answer: 'Changed two files' });
  // waitFor keeps checking the assertion until the redraw finishes
  await waitFor(() => expect(find(site, { text: 'Changed two files' })).toBeDefined());
});
```

### Test commands

Coming soon

`runCommand(site, name, args?)` runs a command as if the user typed `/<name> <args>`, and returns the `command.run` hook's answer `{ text }`, the sentence the UI would show. Without `args`, it's `''`. `listCommands(site)` returns the list `ctx.command.list()` would return. For how to register and answer a command, see [Add a slash command](https://agent.minimax.io/docs/extension/api.md#command).

When a run fails, `runCommand` fails with the same code the user would see:

| Code | Cause |
| - | - |
| `COMMAND_UNHANDLED` | No `command.run` hook answered the command. Also recorded in `site.diagnostics` |
| `COMMAND_FAILED` | The `command.run` hook threw, timed out, or the process restarted. Also recorded in `site.diagnostics`, next to the hook's own diagnostic |
| `COMMAND_UNKNOWN` | No plugin registered this name |
| `COMMAND_ARGS_TOO_LONG` | `args` is longer than 4096 characters after trimming leading and trailing whitespace |

Tests have no Skills, so only built-in command names are taken.

The extension below registers a `/todo` command and shows its argument on the status band:

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

export { state } from './state';

export const register: Register = (on) => {
  // Register commands in session.start; the name may be taken, so wrap it in try/catch
  on('session.start', async (ctx) => {
    try {
      await ctx.command.register({
        name: 'todo',
        description: 'Note a to-do and show it on the status band',
        argumentHint: '[text]',
      });
    } catch (error) {
      console.warn(String(error));
    }
  });

  // e.args is the text after the command name, with leading and trailing whitespace trimmed
  on('command.run', { command: 'todo' }, async (ctx, e) => {
    if (e.args === '') return { text: 'Usage: /todo what to note' };
    await ctx.state.set('todo', e.args);
    return { text: `Noted: ${e.args}` };
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      {ctx.state.get('todo') ? (
        <Text size="sm" tone="secondary">{`To-do: ${ctx.state.get('todo')}`}</Text>
      ) : undefined}
      {await next()}
    </Box>
  ));
};
```

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

export const state = defineState({ todo: { default: '' } });

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

```tsx hooks/register.test.tsx theme={null}
import {
  expect,
  find,
  listCommands,
  mount,
  runCommand,
  test,
  waitFor,
} from '@minimax/mcode-plugin-extension/testing';

import { register } from './register';

test('/todo notes a to-do and shows it on the status band', async () => {
  // mount runs session.start first, which registers the command
  const site = await mount({ register, site: 'above-prompt' });
  expect((await listCommands(site)).map((command) => command.name)).toEqual(['todo']);

  // Run the command as if the user typed "/todo Update the release notes"; the return value is the text the UI shows
  const answer = await runCommand(site, 'todo', 'Update the release notes');
  expect(answer).toEqual({ text: 'Noted: Update the release notes' });

  await waitFor(() => expect(find(site, { text: 'To-do: Update the release notes' })).toBeDefined());
  // The UI shows the command's answer; it isn't a ctx.ui.toast, so it's not in effects
  expect(site.effects).toEqual([]);
  expect(site.diagnostics).toEqual([]);
});

test('shows usage when there are no arguments', async () => {
  const site = await mount({ register, site: 'above-prompt' });
  // Without args, it's an empty string, the same as picking the command straight from the / menu
  expect(await runCommand(site, 'todo')).toEqual({ text: 'Usage: /todo what to note' });
  expect(site.state()).toEqual({ todo: '' });
});
```

### Common errors in tests

| Error | Cause |
| - | - |
| `ctx.mcp.call(<server>, <tool>): pass mount({ mcp }) to answer it` | The module called MCP, but `mount` got no `mcp` |
| `mount({ site: 'pane' }) requires id, or key '<pluginId>/<id>'` | No `id` was given when mounting a panel |
| `No element matches …` | The `press` query found no element |
| `<Text> cannot be pressed`, `<Button> has no onPress callback` | You pressed an element that can't be pressed, or a button with no callback |
| `press(<Select>) needs the option value` | No option value was given when pressing a `Select` |
| `EXTENSION_HANDLE_STALE` | The screen had already redrawn when the press arrived, and no single matching control exists on the new screen. Usually neither the control nor its ancestors have a `key` |
| `TREE_INVALID` (in `site.diagnostics`) | The screen has an element or property this site doesn't accept, such as an `<Input>` on the status band. The real UI replaces that part with a placeholder notice |
| `EXTENSION_SVG_REFUSED` (in `site.diagnostics`) | The `source` of an `<Svg>` on the backdrop failed the SVG check (an `<Svg>` in the status band or a panel has only its props checked, not this). `message` names the category and the content, such as `Svg refused: external-reference (@import)`. This layer's output is rejected, and other layers draw as usual. See [Backdrop](https://agent.minimax.io/docs/extension/interface.md#backdrop) for how to write it |
| `EXTENSION_ROWS_INVALID` (in `site.diagnostics`) Coming soon | An `above-prompt-list` layer passed `next` rows other than the ones it received: it changed a row's content, made up a row, or passed the same row twice. That list layer is skipped. See [status band row arrangement](https://agent.minimax.io/docs/extension/interface.md#above-prompt-list) |
| `THEME_PALETTE_REJECTED` | In the `colors` of `ctx.theme.set`, a text anchor (`text-*`) has a contrast ratio below 3:1 against a surface anchor (`surface-*`) in the same set |
| `COMMAND_UNHANDLED`, `COMMAND_FAILED`, `COMMAND_UNKNOWN` | `runCommand` failed. See [Test commands](#command-test) |
| `test "…" timed out after 10000 ms` | A single test ran longer than 10 seconds |

## Run tests

Tell the Agent "run the extension tests" and it calls the `extension` tool:

```json theme={null}
{ "action": "test", "pluginId": "tool-tally" }
```

`test` has two steps:

1. It first validates the whole package by the `preview` rules. If validation fails, it returns the diagnostics right away (`status: 'invalid'`) and runs no tests.
2. Once validation passes, it runs every test file in the package in a real extension host, each file on its own. The results list each test's `passed` or `failed` by file, with failure messages, diagnostics, and logs, plus totals for passed and failed. If a test file itself fails to compile, that file's diagnostics are listed and it counts as one failure.

By default `test` reads the development folder returned by `init`. You can also add `sourcePath` (an absolute path) to test a package in another folder. When `sourcePath` points outside the development folder, the test would run code that wasn't written in the development folder, so a permission card appears, as with `preview`. The tests run only after the user agrees.

> [!TIP]
>
> Get `test` passing with no diagnostics before you `preview`. That way the first version the user sees works.

### Type checking

`test` and `preview` transpile source to JavaScript and run a static scan. **Type checking is a separate step**. A type error can still pass validation and only show up at runtime, so check types in either of these ways:

* Open the development folder in your editor. The `.minimax-plugin/types/` written by `init` and the `tsconfig.json` at the root let the editor flag type errors directly.
* If TypeScript is installed on your machine, run this in the package folder:

```bash theme={null}
npx tsc -p .minimax-plugin/types
```

## Check state with inspect

After the extension is previewed and the user has pressed buttons or run a turn, have the Agent call `inspect`:

```json theme={null}
{ "action": "inspect", "pluginId": "tool-tally" }
```

The result has three parts.

### `source`: what validation saw

The result of static validation of the development folder. It doesn't run extension code. This part is missing before `init`.

| Field | Contents |
| - | - |
| `entries` | Registered sites, such as the status band and each panel |
| `hooks` | Registered events |
| `calls` | The `ctx` methods and MCP servers the code uses, that is, the `calls:` declaration |
| `state` | Keys declared by `defineState` |
| `diagnostics` | Validation errors and warnings for the current source |

Look at `source.diagnostics` first. An error here means the current source can't load, and the automatic reload at the end of the next turn will also be rejected. Before install, when you tell the user what the extension will do, take the registered sites, events, and called servers from here too.

### `preview`: the version running in this session

The preview version running in this session. This part is missing when there's no preview.

| Field | Meaning |
| - | - |
| `stale` | `true` means the files changed after the running version. Normally it reloads automatically at the end of this turn |
| `keptReload` | The last reload at the end of a turn failed, and the old version kept running. `keptReload.diagnostics` is why it failed, and `keptReload.at` is when (Unix ms). **A failed reload only shows up here** |
| `editorTypesFinding` | Why `.minimax-plugin/types/` couldn't be refreshed. The preview itself is already in effect. Fix that folder and `preview` again |
| `overlayFindings` | Skills or MCP servers in this version that couldn't join the session |

### `runtime`: what happened at runtime

| Field | Contents |
| - | - |
| `diagnostics` | Runtime diagnostics in time order. Each is `{ at, code, message, fix?, slot?, key? }`, where `slot` and `key` identify the site |
| `console` | Lines from `console.log` and similar calls in the extension: `{ at, level, text }` |
| `disabledHooks` | Hooks disabled after repeated failures |
| `disabled` | `true` means the whole plugin is paused in this session |
| `traces` | Records of the last few draws, listing for each layer whether the plugin called `next`, the result, and the time taken |
| `sites` | Parts the window couldn't draw and replaced with a placeholder, grouped by site. See below |

The usual order when you troubleshoot: `source.diagnostics` → `preview.keptReload` → `runtime.diagnostics` → `runtime.console`. When a placeholder shows in the UI, also check `runtime.sites`.

#### `runtime.sites`: parts the window replaced with a placeholder

Coming soon

`runtime.diagnostics` records problems the runtime (the extension process side) found. After a screen reaches the window, the window checks it again and replaces any part it can't draw with a placeholder. Those records are in `runtime.sites`, one item per site:

```ts theme={null}
{ slot, key, fallbacks: [{ renderSeq, path, reason, detail? }] }
```

| Field | Meaning |
| - | - |
| `slot`, `key` | Which site, such as `above-prompt`, `backdrop`, or a panel |
| `renderSeq` | Which draw, matching the same `renderSeq` in `runtime.traces` |
| `path` | Where the replaced subtree sits in the element tree. `''` means the whole tree |
| `reason` | The reason, such as `invalid-props`, `unsupported-element`, or `tree-limits`. For the two `<Svg>` reasons, see [SVG the window rejects](https://agent.minimax.io/docs/extension/errors.md#svg-fallback) |
| `detail` | The exact prop or content, at most 200 characters |

Only draws your plugin took part in are listed. Records are in time order, newest last, with at most 16 per site. **Old records aren't cleared after you fix the problem**: compare the `renderSeq` of the last record with the `renderSeq` of this site's latest draw in `runtime.traces`. Only when they're equal is the problem still there. These records don't count toward a pause.

### Diagnostic shape and the fix loop

A diagnostic from validation is:

```ts theme={null}
{ code, file, line, column, message, fix, level }
```

`file`, `line`, and `column` point to the source location, `message` describes the problem, `fix` is the change to make, and `level` is `'error'` or `'warning'`. Runtime diagnostics have no source location and use `slot` and `key` to identify the site.

There's only one fix loop: **make the change in `fix`, then run the same action again**. If `test` reported it, run `test` again; if `preview` reported it, run `preview` again. For what every diagnostic code means and how to fix it, see [Diagnostic codes](https://agent.minimax.io/docs/extension/errors.md).

`EXTENSION_PACKAGE_SKIPPED`, `EXTENSION_SHADOWING`, `COMMAND_RETIRED`, `COMMAND_ANSWER_INVALID`, and `COMMAND_TEXT_TRUNCATED` are warnings and don't block preview or the current action. Every other diagnostic does.

## Troubleshoot by symptom

### The status band doesn't show

| Symptom | Cause | What to do |
| - | - | - |
| It has never appeared | This session has no preview of the extension, or it was withdrawn | Have the Agent `inspect`. If there's no `preview` part, `preview` again |
| No change after editing code | The reload failed and the old version is still running | See [Changes didn't load](#reload-kept) |
| It doesn't show in some cases | The draw returned `next()` or nothing, for example `return next()` before context is measured | Check the conditional branches in the draw, and test with `mount` plus the matching `state` or `usage` |
| Shows "Part of an extension can't be displayed" | The screen has an element or property this site doesn't accept, or exceeds the element tree limits | Use the eight elements the status band accepts: `<Box>`, `<Text>`, `<Button>`, `<Tag>`, `<Spinner>`, plus `<Progress>`, `<Link>`, and `<Svg>` Coming soon. Tests report `TREE_INVALID`; after a preview, check [`runtime.sites`](#runtime-sites) |
| Shows "Paused · this session" | The extension was paused | See [The extension is paused](#paused) |
| Only other plugins' content shows | Your hook failed before `next()`, so its layer was skipped: it threw (`thrown`), its synchronous code ran longer than 2 seconds (`timeout`), or its own time exceeded 10 seconds (`EXTENSION_HOOK_EXPIRED`) | Check `runtime.diagnostics`. Do slow work outside the draw: draw a placeholder first, then call `ctx.ui.invalidate()` once the data arrives |
| Every plugin's content disappears at once | One draw took longer than 30 seconds (`EXTENSION_RENDER_DEADLINE`). The whole render chain is discarded, and the site falls back to the host's default view | Check `runtime.diagnostics`. Make slow MCP calls outside the draw: draw a placeholder first, then call `ctx.ui.invalidate()` once the data arrives |
| Only another preview plugin's content shows, and your layer is missing | That preview plugin comes before yours and doesn't call `next`. In the render chain, previews come before installed plugins, and a layer that doesn't call `next` hides the layers after it | Look in `runtime.traces` for the layer whose `calledNext` is `false` |

### Other plugins are hidden

**Symptom**: after your extension appears, other plugins' status band or panel content disappears.

**Cause**: the draw doesn't call `next`. Several plugins draw a site in layers. `await next()` returns what the layers after yours drew. If you don't put it in your element tree, every layer after you is hidden. Validation warns with [`EXTENSION_SHADOWING`](https://agent.minimax.io/docs/extension/errors#package).

**What to do**: put `await next()` in the element tree once, usually as the last child of a column `Box`. If you don't want to add anything, `return next()`. You can call `next` only once per invocation. A second call reports [`EXTENSION_NEXT_TWICE`](https://agent.minimax.io/docs/extension/errors#runtime). See [Render chain](https://agent.minimax.io/docs/extension/interface.md#render-chain).

Coming soon Once the status band is drawn in two steps, each plugin's `above-prompt` draws its own row on its own and can't hide other plugins' rows, so leaving out `next` there no longer warns. Sites on the render chain, `above-prompt-list`, `pane`, and `backdrop`, still need `next`. See [status band row arrangement](https://agent.minimax.io/docs/extension/interface.md#above-prompt-list).

### Changes didn't load

**Symptom**: you changed a file, but the UI is still the old one.

**Cause**: changes after a preview reload only **at the end of a turn**. They don't take effect the moment you save a file. If the new code fails validation, the reload is rejected and the old version keeps running, with no notice in the UI.

**What to do**:

1. If you're still in the same turn, wait for it to end.
2. Have the Agent `inspect`. `preview.stale` set to `true` means the files are newer than the running version. A `preview.keptReload` means the reload was rejected.
3. Apply the `fix` from each entry in `keptReload.diagnostics`, then let a turn end, or `preview` again directly.

If `register` throws while loading, it reports [`EXTENSION_REGISTER_FAILED`](https://agent.minimax.io/docs/extension/errors#runtime), and the old version keeps running until you fix it.

### The extension is paused

**Symptom**: the status band or panel shows "Paused · this session" with a "Retry" button, and a reason below:

| Reason in the UI | Meaning |
| - | - |
| Failed or timed out 3 times in a row; paused in this session | A hook threw or timed out 3 times in a row (a single run took more than 10 seconds of its own time, or synchronous code ran more than 2 seconds) |
| The plugin hung, crashed or failed to load; paused in this session | The extension process hung or crashed (an infinite loop, memory that keeps growing), or the module failed to load |

If there's a "Last error" line, it's the error message from the last failure.

**Cause**: the circuit breaker disabled the hook or the whole plugin. The diagnostic code is [`EXTENSION_DISABLED`](https://agent.minimax.io/docs/extension/errors#runtime). A pause only affects the current session. Other sessions aren't affected. When a site has several plugins, the paused layer is skipped and the other plugins draw as usual. The pause notice shows only when every layer is paused.

**What to do**:

1. Have the Agent `inspect`. Check `runtime.disabledHooks`, `runtime.disabled`, and `runtime.diagnostics` to find the failing hook. Common diagnostics are `thrown` (an error was thrown), `timeout` (synchronous code timed out), [`EXTENSION_HOOK_EXPIRED`](https://agent.minimax.io/docs/extension/errors#runtime) (more than 10 seconds), and [`EXTENSION_WORKER_CRASHED`](https://agent.minimax.io/docs/extension/errors#runtime) (the process restarted).
2. After you fix the code, `preview` again, or click "Retry" in the UI. If the retry fails, the UI shows "Retry didn't go through. Try again later".

### Pressing a button does nothing

| Cause | How to confirm | What to do |
| - | - | - |
| The screen had already redrawn when the press arrived, and no single matching control exists on the new screen (neither the button nor its ancestors have a `key`, or the control is gone), so the press is dropped ([`EXTENSION_HANDLE_STALE`](https://agent.minimax.io/docs/extension/errors#runtime)) | No notice in the UI and no record in `inspect`. In tests, `press` fails with `EXTENSION_HANDLE_STALE` | Add a `key` to each list row, to buttons whose callback triggers a redraw, and to `Input`, `Select`, and `Switch`. See [Key rules](https://agent.minimax.io/docs/extension/interface.md#keys) |
| The callback threw or timed out | `runtime.diagnostics` records the original code, such as `thrown`, `timeout`, or `EXTENSION_HOOK_EXPIRED`. `EXTENSION_HOOK_FAILED` appears only in the result returned to the UI and in the error from `press` in tests | Fix it using `message`. `console` may also have clues |
| The callback declares its own `ctx` parameter, such as `onPress={(ctx) => …}` | An error at runtime | Write the callback as `onPress={() => …}` and use the `ctx` of the enclosing hook |
| This plugin's previous hook hasn't finished, so the press is queued. Most often an MCP permission card is pending | The permission card is still in the UI, or a hook is running slowly | Handle the card, or make the hook finish sooner. Each plugin can queue up to 10 button actions per session (including the one running) |
| Clicking too fast, with 10 button actions already queued | The UI shows "Too many actions. Try again later", and the diagnostic is [`GESTURE_QUEUE_FULL`](https://agent.minimax.io/docs/extension/errors#runtime) | Cut down repeated actions, or set the button to `disabled` while it's working |
| The press didn't complete | The UI shows "The action didn't go through. Try again" | Check `runtime.diagnostics` |
| The button has `disabled` set, or has no `onPress` | Read the code | Remove `disabled` or add the callback |

### Permission denied or call cancelled

`ctx.mcp.call` follows the Agent's permission rules. An existing allow rule lets it through, a deny rule denies it, and anything else shows a permission card. The card's allow option, "Only this chat", allows only this one call, and the next call asks again. No matter how the user responds, no permission rule is saved.

| Diagnostic | Cause | What to do |
| - | - | - |
| [`PERMISSION_DENIED`](https://agent.minimax.io/docs/extension/errors#runtime) | A permission rule denied it, or the user denied or closed the card, or stopped the turn | Don't retry automatically. Tell the user what the call needs and let them decide again |
| [`CANCELLED`](https://agent.minimax.io/docs/extension/errors#runtime) | The `signal` you passed was aborted, or the preview was withdrawn or reloaded while waiting for permission. A draw that ends while waiting on a card also cancels | Nothing to change in the extension. The next call can try again |
| [`PERMISSION_REQUIRED`](https://agent.minimax.io/docs/extension/errors#runtime) | The permission check itself failed | Retry, or ask the user to add an allow rule for this server tool |
| [`CALL_NOT_DECLARED`](https://agent.minimax.io/docs/extension/errors#runtime) | A method or server outside `calls:` was called at runtime, usually because a dynamic form kept the static scan from recognizing it | Rewrite it in the full `ctx.<domain>.<method>(…)` form with a literal server name, then `preview` |

A preview version doesn't inherit the installed version's allow rules. So it's normal for the installed version to show no card while the preview version does.

### Call rate exceeded

| Symptom | Cause | What to do |
| - | - | - |
| `ctx.mcp.call` reports [`MCP_CALL_RATE_LIMITED`](https://agent.minimax.io/docs/extension/errors#runtime) | Each plugin can make at most 60 calls a minute | Combine requests, or cache results in `ctx.state` |
| The UI shows "Too many actions. Try again later" | 10 button actions already queued (`GESTURE_QUEUE_FULL`) | Cut down rapid repeated actions |
| Some observe events are missing | An earlier hook hadn't finished (most often it was waiting on a permission card), 32 observe events were queued, and the newer ones were dropped. `runtime.diagnostics` records one [`GESTURE_QUEUE_FULL`](https://agent.minimax.io/docs/extension/errors#runtime) per dropped event, and `message` names the event | Make observe event hooks finish quickly. Call tools that need permission from user-triggered places such as button callbacks |
| `ctx.agent.spawn` reports [`AGENT_CONCURRENCY_LIMIT`](https://agent.minimax.io/docs/extension/errors#runtime) | This plugin's running sub-agents in this session reached the session's sub-agent limit | Wait for `turn.complete` from one of the sub-agents before starting another |

### A toast didn't appear

**Symptom**: you called `ctx.ui.toast`, but no toast appeared and the call didn't fail.

**Cause**: each plugin can show at most 6 toasts a minute. Extra ones are dropped until the one-minute window rolls over. Each run of consecutive drops records one [`toast.dropped`](https://agent.minimax.io/docs/extension/errors#runtime) in `runtime.diagnostics` when it starts. Text longer than 500 characters is also truncated.

**What to do**: show a toast only when the user needs to know the result. Put state that keeps changing on the status band.

### `prompt.fill` didn't write

When `ctx.prompt.fill` returns `{ written: false, reason }`, handle it by `reason`:

| `reason` | Cause | What to do |
| - | - | - |
| `draft` | The default `replace` mode only writes into an empty message box, and the user has already typed something | Use `mode: 'append'` to add to the end, or tell the user |
| `modal` | A dialog is open in the UI | Try again later |
| `no-composer` | No message box is available right now | Call it again from a later user action |

Even when it returns `written: true`, the write is best effort. A `replace` that happens while the user is typing is dropped to keep the user's text. If a dialog opens at the moment of the write, both modes are dropped. `ctx.prompt.fill` only fills in text. Sending is up to the user.

Likewise, when `ctx.prompt.suggest` returns `isShown: false`, check `reason` (`draft-not-empty`, `turn-running`, `dismissed`, `no-turn`, `no-composer`). When `ctx.prompt.read` reports [`PROMPT_READ_UNAVAILABLE`](https://agent.minimax.io/docs/extension/errors#runtime), no message box responded within 2 seconds. See [Fill text into the message box](https://agent.minimax.io/docs/extension/api.md#prompt-fill).

### A command doesn't appear in the `/` menu

Plugin commands are listed in the `/` menu of the message box after built-in commands and Skills, labeled with the plugin's display name. If you don't see your command:

| Cause | How to confirm | What to do |
| - | - | - |
| It wasn't registered in `session.start`. A command belongs to the current session and the Activation that registered it, so every Activation has to register it again | Check where the code calls `ctx.command.register` | Call `ctx.command.register` in `on('session.start', …)`, once per command |
| The name is taken: a built-in command or a Skill uses it ([`COMMAND_NAME_RESERVED`](https://agent.minimax.io/docs/extension/errors#runtime)), or another plugin registered it first in this session ([`COMMAND_NAME_TAKEN`](https://agent.minimax.io/docs/extension/errors#runtime), with that plugin named in `message`) | `register` rejects it. If you wrap it in `try/catch` and `console.warn`, check `runtime.console`; if you don't catch it, `runtime.diagnostics` has a `thrown` | Pick another name and change the `command.run` matcher with it. Names are compared case-insensitively |
| The name breaks the naming rules, or is a built-in command name | `test` and `preview` report [`EXTENSION_COMMAND_NAME_INVALID`](https://agent.minimax.io/docs/extension/errors#package) | Use 1 to 64 letters, digits, `_`, or `-`, without `/` |
| A registration limit was hit | `register` rejects it with [`COMMAND_LIMIT_REACHED`](https://agent.minimax.io/docs/extension/errors#runtime) | At most 32 plugin commands per session, and at most 64 `register` calls that change commands per Activation. Register each command once in `session.start`, not in a loop or an event |
| The plugin just reloaded | The new version registers again in its own `session.start`, so the menu may be missing these commands briefly | Wait a moment and open the menu again |
| The conversation hasn't sent its first message yet | A new conversation page has a session only after the first message is sent, and `session.start` runs then | Use the command after sending the first message |
| You're editing an earlier message or a queued message | The menu lists no commands then, and a typed `/<name>` is saved as plain text | Type the command in a new message |

If typing `/<name>` runs a built-in command or Skill with the same name, a Skill took that name after you registered: when typed, the Skill wins, but picking your item from the menu still runs your command.

### A command shows no response or an error

After the user runs a command, the UI shows the result in a toast. When something goes wrong, it shows one of these notices (using the command `/todo` as an example):

| UI notice | Code | Cause | What to do |
| - | - | - | - |
| /todo didn't respond | [`COMMAND_UNHANDLED`](https://agent.minimax.io/docs/extension/errors#runtime) | No `command.run` hook answered the command | Add `on('command.run', { command: '<name>' }, …)` with the same name as in `ctx.command.register` |
| /todo failed | [`COMMAND_FAILED`](https://agent.minimax.io/docs/extension/errors#runtime) | The `command.run` hook threw, timed out, or the process restarted | Check the hook's own diagnostic just before it (`thrown`, `timeout`, `EXTENSION_HOOK_EXPIRED`, or `EXTENSION_WORKER_CRASHED`). Catch errors you can handle in the hook and answer with `{ text }` |
| /todo timed out and may have run already | [`COMMAND_TIMEOUT`](https://agent.minimax.io/docs/extension/errors#runtime) | No answer within 15 seconds: the command was queued behind earlier button actions and commands from this plugin, or the hook itself is too slow | Make the hook answer quickly, and move slow `ctx.model.complete` and `ctx.mcp.call` calls out. A timed-out hook may already have run, so the command must be safe to run twice |
| /todo is unavailable: the plugin is paused | [`COMMAND_PAUSED`](https://agent.minimax.io/docs/extension/errors#runtime) | The circuit breaker paused this hook | Fix the error that caused the pause, then `preview`. See [The extension is paused](#paused) |
| /todo did not run: the plugin is busy, try again | `COMMAND_BUSY` | The queue shared by button actions and commands is full (10). `runtime.diagnostics` records it as `GESTURE_QUEUE_FULL` | Make button callbacks and `command.run` hooks finish quickly |
| /todo is unavailable: the plugin is reloading or disabled | [`COMMAND_RETIRED`](https://agent.minimax.io/docs/extension/errors#runtime) | The plugin is leaving the session or being replaced by a new version | Nothing to change for a reload. The new version registers again in `session.start` |
| The arguments of /todo are too long | `COMMAND_ARGS_TOO_LONG` | The arguments are longer than 4096 characters after trimming leading and trailing whitespace | Have the user shorten the arguments |
| /todo no longer exists | `COMMAND_UNKNOWN` | No plugin in this session registered this name | See [A command doesn't appear in the `/` menu](#command-missing) |

If the command ran but nothing showed, check the hook's return value. Returning nothing or `{}` shows nothing. A return value other than `{ text }` (with extra keys, or a `text` that isn't a string) also shows nothing and records [`COMMAND_ANSWER_INVALID`](https://agent.minimax.io/docs/extension/errors#runtime). An answer longer than 500 characters is truncated and records [`COMMAND_TEXT_TRUNCATED`](https://agent.minimax.io/docs/extension/errors#runtime).

### The backdrop doesn't show

If you don't see the backdrop you drew:

| Cause | How to confirm | What to do |
| - | - | - |
| The current session has no theme, or the theme was set without `backdrop` | The backdrop is drawn only when the session has a plugin theme. Without one, the user's own wallpaper shows | Call `ctx.theme.set({ backdrop: { scene: '…' } })`. The theme is kept only in memory and the host doesn't restore it, so save it in `ctx.store` and set it again in `session.start`. See [Set a theme](https://agent.minimax.io/docs/extension/api.md#theme) |
| The theme was replaced | Each session has one theme, and another plugin's `ctx.theme.set` replaces yours as a whole. Withdrawing, disabling, or uninstalling a plugin also removes the theme it set | Set it again when needed |
| `scene` doesn't match | Every plugin's backdrop layer runs, and each layer checks `e.props.plugin` and `e.props.scene` to tell whether the theme is its own. When the `scene` it checks differs from the one in `ctx.theme.set`, it only does `return next()` | Make the two `scene` values identical, and compare `plugin` with `ctx.plugin.id` |
| The `<Svg>` was rejected | In tests, `site.diagnostics` has [`EXTENSION_SVG_REFUSED`](https://agent.minimax.io/docs/extension/errors#runtime); after a preview, it's in `runtime.diagnostics`. What the window rejects is recorded in [`runtime.sites`](#runtime-sites), with reason `invalid-svg` or `unsafe-svg` | Fix `source` using `message`: reference only the image's own elements (`#id`, `url(#id)`), and don't embed bitmaps, HTML, or fonts. Keep `width` and `height` at 4096 or less, and `source` at 131 072 characters or less. For the full rules, see [Backdrop](https://agent.minimax.io/docs/extension/interface.md#backdrop) |
| Every backdrop layer is paused | The backdrop falls back to the wallpaper, with no pause notice | See [The extension is paused](#paused) |

A rejected `<Svg>` isn't a failure and doesn't pause the hook. Once you fix `source`, the next draw shows it.

### Setting a theme fails

| Error | Cause | What to do |
| - | - | - |
| [`THEME_PALETTE_REJECTED`](https://agent.minimax.io/docs/extension/errors#runtime) | Computed from the colors you wrote (before any correction), a text anchor has a contrast ratio below 3:1 against a surface anchor in the same set. `message` names the two colors and the ratio, and, when colors are split by light and dark mode, the mode, such as `theme.set colors.dark: …` | Change one of the two colors `message` names to raise the contrast |
| `ARGUMENT_INVALID` | Invalid arguments: no field given, a field the host doesn't recognize, a `scene` that is empty or longer than 64 characters, a number out of range, a color that isn't hex, fewer than 2 anchors or a missing `surface-0` / `text-primary`, or `light` / `dark` mixed with anchors | Fix it using `message`. For value ranges, see the [Extensions reference](https://agent.minimax.io/docs/extension/reference.md#limits) |
| [`THEME_PALETTE_ADJUSTED`](https://agent.minimax.io/docs/extension/errors#other-codes) (not an error) | The theme took effect, but the host corrected some colors: a text color was darkened or lightened to get as close to 4.5:1 as possible, or an anchor you didn't set used the host default | To keep your own colors, raise the contrast between each text color and the surface color it sits on to 4.5:1 or more, then `preview`. A line saying an anchor used the host default means you didn't set that anchor; add it to `colors` |

When the theme is rejected, it stays as it was. Only `ctx.theme.clear()` removes a theme.

### Other cases

| Symptom | Cause | What to do |
| - | - | - |
| The panel shows "Already open in another view" | This site is already open in another view ([`VIEW_LEASE_HELD`](https://agent.minimax.io/docs/extension/errors#runtime)) | Close the other view, then reopen this one |
| The panel shows "`<plugin-name>` has nothing to show here yet" | No layer drew anything in the open panel | Check that the `ui.render` for that `id` returns content |
| Reports [`INVOCATION_SETTLED`](https://agent.minimax.io/docs/extension/errors#runtime) | `ctx` was called after the callback finished, for example in a Promise that wasn't awaited, or at module top level | Keep the work in the callback's `await` chain |
| `console` output is missing lines | Each plugin can log at most 200 lines a minute. Extra lines are dropped and a `console.dropped` is recorded | Log less |

## Next steps

> [card] [Diagnostic codes](https://agent.minimax.io/docs/extension/errors.md)
>
> What each diagnostic code means and how to fix it.

> [card] [Extensions reference](https://agent.minimax.io/docs/extension/reference.md)
>
> Quick reference for events, ctx methods, elements, and limits.

> [card] [Interface: sites and elements](https://agent.minimax.io/docs/extension/interface.md)
>
> The render chain, keys, and redraw rules.

> [card] [Extension API](https://agent.minimax.io/docs/extension/api.md)
>
> How to use each ctx method and what it returns.
