# React Native

> Build with CopilotKit in React Native: quickstart, Metro and polyfill setup, frontend tools, generative UI, and device deployment.

`@copilotkit/react-native` gives you CopilotKit's provider and hooks for React Native, plus optional pre-built chat components. This guide builds a fully custom chat UI with the hooks, backed by a [Copilot Runtime](/react-native/claude-sdk-python/backend/copilot-runtime) endpoint on your server.

The package has three main import surfaces: `/headless` (provider + hooks, no native peer dependencies, **1.64.0+**), the root barrel, and `/components` (the rendered chat UI). It also has the opt-in, experimental `/generative-ui`. See [Import surfaces](#import-surfaces) for what each one pulls in; this guide uses `/headless` throughout.

## Start with your coding agent [#start-with-your-coding-agent]

Use this prompt to set up CopilotKit in your React Native app, configure Metro and polyfills, and verify chat against your Runtime. You can also follow the manual steps below.

<PageAgentPrompt />

## Prerequisites [#prerequisites]

- An OpenAI API key (or another model provider supported by [Model Selection](/model-selection))
- React Native 0.70+ (bare CLI or Expo)
- Node.js 20+
- `@react-native-community/cli` in your `devDependencies` **if you are on React Native 0.87 or later**, which does not bundle it. A freshly `init`ed app already has it; an app you have upgraded may not, and without it `react-native bundle` and `react-native start` stop with a message naming the missing package.

## Getting started [#getting-started]

<Steps>
    <Step>
        ### Create your React Native app [#create-your-react-native-app]

        If you don't have one already:

        ```bash
        npx @react-native-community/cli@latest init MyCopilotApp
        cd MyCopilotApp
        ```
    </Step>
    <Step>
        ### Install CopilotKit [#install-copilotkit]

        Install the React Native frontend package, `zod` and `@copilotkit/runtime` for your local Copilot Runtime server. Every entry of `@copilotkit/react-native` needs `zod` 3.25 or later, because `@copilotkit/react-core` requires it as a peer dependency. `@copilotkit/react-native` itself still declares `zod` an optional peer at `>=3.0.0` (narrowing that would be a breaking change), so your package manager does not enforce 3.25 for you. The commands install zod 3 (`zod@^3.25`): the `child()` and `childList()` helpers of [generative UI](#generative-ui-with-your-own-components) return zod 3 schemas, and a zod 4 schema cannot hold one, so a catalog that uses them must be written with zod 3:

        <Tabs groupId="package-manager" items={['npm', 'pnpm', 'yarn']}>
            <Tab value="npm">
                ```bash
                npm install @copilotkit/react-native @copilotkit/runtime "zod@^3.25"
                npm install -D tsx typescript @types/node
                ```
            </Tab>
            <Tab value="pnpm">
                ```bash
                pnpm add @copilotkit/react-native @copilotkit/runtime "zod@^3.25"
                pnpm add -D tsx typescript @types/node
                ```
            </Tab>
            <Tab value="yarn">
                ```bash
                yarn add @copilotkit/react-native @copilotkit/runtime "zod@^3.25"
                yarn add -D tsx typescript @types/node
                ```
            </Tab>
        </Tabs>

        This guide needs `@copilotkit/react-native` 1.64.0 or later. To see your version, run `npm ls @copilotkit/react-native`. For older versions, see [Import surfaces](#import-surfaces).

        <Callout type="info" title="TypeScript: use bundler module resolution">
            The `/headless`, `/components`, `/generative-ui` and `/polyfills` subpaths are published through the package `exports` map, which TypeScript's legacy `"moduleResolution": "node"` (`node10`) ignores. Under that setting, type checking fails with `Cannot find module '@copilotkit/react-native/headless'` even though Metro bundles the app. Set `"moduleResolution": "bundler"` in `tsconfig.json`; if `module` is `commonjs` or unset, also set `"module": "esnext"`. `@react-native/typescript-config` and Expo's base config already use `bundler`.
        </Callout>
    </Step>
    <Step>
        ### Add polyfills [#add-polyfills]

        React Native's JS runtime (Hermes) lacks several Web APIs that CopilotKit depends on. The package installs these polyfills itself on first import, but two things must happen **at the very top of your entry point, before any CopilotKit import**: a secure random source, then the polyfill barrel.

        Install the secure RNG first:

        ```bash
        npm install react-native-get-random-values
        ```

        ```js title="index.js"
        import "react-native-get-random-values"; // [!code highlight:2] secure RNG — must be first
        import "@copilotkit/react-native/polyfills";

        import { AppRegistry } from "react-native";
        import App from "./App";
        import { name as appName } from "./app.json";

        AppRegistry.registerComponent(appName, () => App);
        ```

        <Callout type="warn" title="Import order is load-bearing for crypto">
          CopilotKit's `crypto` polyfill and `react-native-get-random-values` both install only if `crypto.getRandomValues` is still undefined, so the first writer wins. If any CopilotKit module is evaluated first, CopilotKit's **non-cryptographic** `Math.random` fallback is locked in permanently and `react-native-get-random-values` becomes a silent no-op. Keep it on the first line. See [Polyfills](#polyfills).
        </Callout>

        <Callout type="info" title="Granular polyfills">
          If you already polyfill some of these APIs (e.g. `ReadableStream`), you can import only what you need instead of the barrel:

          ```js
          import "@copilotkit/react-native/polyfills/streams";
          import "@copilotkit/react-native/polyfills/encoding";
          import "@copilotkit/react-native/polyfills/crypto";
          import "@copilotkit/react-native/polyfills/dom";
          import "@copilotkit/react-native/polyfills/location";
          ```
        </Callout>
    </Step>
    <Step>
        ### Create the Copilot Runtime [#create-the-copilot-runtime]

        Add a small Node server that hosts Copilot Runtime at `/api/copilotkit` and registers a `default` built-in agent:

        ```ts title="server.ts"
        import { createServer } from "node:http";
        import { BuiltInAgent, CopilotRuntime } from "@copilotkit/runtime/v2";
        import { createCopilotNodeListener } from "@copilotkit/runtime/v2/node";

        const runtime = new CopilotRuntime({
          agents: {
            default: new BuiltInAgent({
              model: "openai:gpt-6-luna",
              prompt: "You are a helpful assistant for a React Native app.",
            }),
          },
        });

        const port = Number(process.env.PORT ?? 8200);

        createServer(
          createCopilotNodeListener({
            runtime,
            basePath: "/api/copilotkit",
            cors: true,
          }),
        ).listen(port, () => {
          console.log(
            `Copilot Runtime listening at http://localhost:${port}/api/copilotkit`,
          );
        });
        ```
    </Step>
    <Step>
        ### Wrap your app with CopilotKitProvider [#wrap-your-app-with-copilotkitprovider]

        Point the provider at the runtime endpoint. Android emulators reach the host machine at `10.0.2.2`; iOS simulators can use `localhost`.

        ```tsx title="App.tsx"
        import { CopilotKitProvider } from "@copilotkit/react-native/headless"; // [!code highlight]
        import { Platform } from "react-native";
        import { ChatScreen } from "./src/ChatScreen";

        const runtimeUrl =
          Platform.OS === "android"
            ? "http://10.0.2.2:8200/api/copilotkit"
            : "http://localhost:8200/api/copilotkit";

        export default function App() {
          return (
            <CopilotKitProvider runtimeUrl={runtimeUrl}> {/* [!code highlight] */}
              <ChatScreen />
            </CopilotKitProvider>
          );
        }
        ```

        <Callout type="info" title="Testing on a physical device">
          Replace `localhost` or `10.0.2.2` with your development machine's LAN IP address, for example `http://192.168.1.23:8200/api/copilotkit`.
        </Callout>
    </Step>
    <Step>
        ### Build your chat UI [#build-your-chat-ui]

        The platform-agnostic hooks work the same way here as on the web. Below is a minimal chat screen using `useAgent` and `useCopilotKit`:

        ```tsx title="src/ChatScreen.tsx"
        import { useCallback, useRef, useState } from "react";
        import {
          FlatList,
          KeyboardAvoidingView,
          Platform,
          Text,
          TextInput,
          TouchableOpacity,
          View,
        } from "react-native";
        import { useAgent, useCopilotKit } from "@copilotkit/react-native/headless"; // [!code highlight]

        export function ChatScreen() {
          const [inputText, setInputText] = useState("");
          const flatListRef = useRef<FlatList>(null);

          const { copilotkit } = useCopilotKit(); // [!code highlight:2]
          const { agent } = useAgent({ agentId: "default" });

          const messages = agent?.messages ?? [];
          const isLoading = agent?.isRunning ?? false;
          const chatMessages = messages.flatMap((message) => {
            if (
              (message.role === "user" || message.role === "assistant") &&
              typeof message.content === "string" &&
              message.content.length > 0
            ) {
              return [
                {
                  id: message.id,
                  content: message.content,
                },
              ];
            }
            return [];
          });

          const handleSend = useCallback(async () => {
            const text = inputText.trim();
            if (!text || isLoading || !agent) return;

            setInputText("");
            agent.addMessage({ // [!code highlight:5]
              id: `user-${Date.now()}`,
              role: "user",
              content: text,
            });
            await copilotkit.runAgent({ agent }); // [!code highlight]
          }, [inputText, isLoading, agent, copilotkit]);

          return (
            <KeyboardAvoidingView
              style={{ flex: 1 }}
              behavior={Platform.OS === "ios" ? "padding" : "height"}
            >
              <FlatList
                ref={flatListRef}
                data={chatMessages}
                renderItem={({ item }) => (
                  <View style={{ padding: 12, maxWidth: "80%" }}>
                    <Text>{item.content}</Text>
                  </View>
                )}
                keyExtractor={(item, i) => item.id ?? String(i)}
                onContentSizeChange={() =>
                  flatListRef.current?.scrollToEnd({ animated: true })
                }
              />
              <View style={{ flexDirection: "row", padding: 8 }}>
                <TextInput
                  style={{ flex: 1, borderWidth: 1, borderRadius: 8, padding: 8 }}
                  value={inputText}
                  onChangeText={setInputText}
                  placeholder="Type a message..."
                />
                <TouchableOpacity onPress={handleSend} style={{ padding: 8 }}>
                  <Text>Send</Text>
                </TouchableOpacity>
              </View>
            </KeyboardAvoidingView>
          );
        }
        ```

        <Callout type="info" title="Headless by design">
          `@copilotkit/react-native/headless` provides hooks, not UI components, so you have full control over your chat interface using standard React Native components. If you'd rather not build one, a rendered chat is available from `@copilotkit/react-native/components`. See [Import surfaces](#import-surfaces).
        </Callout>
    </Step>
    <Step>
        ### Run the runtime and app [#run-the-runtime-and-app]

        Start Copilot Runtime in one terminal:

        ```bash
        export OPENAI_API_KEY=sk-...
        npx tsx server.ts
        ```

        Run the React Native app in another terminal:

        <Tabs groupId="platform" items={['iOS', 'Android']}>
            <Tab value="iOS">
                ```bash
                npx react-native run-ios
                ```
            </Tab>
            <Tab value="Android">
                ```bash
                npx react-native run-android
                ```
            </Tab>
        </Tabs>
    </Step>
    <Step>
        ### Start chatting [#start-chatting]

        Type a message and tap **Send**. The assistant reply appears under your message.

        Your React Native app is now connected to Copilot Runtime. The shared hooks are available here:

        - `useAgent` - connect to an agent and manage messages
        - `useFrontendTool` - let the agent call functions in your app
        - `useHumanInTheLoop` - add approval flows for agent actions
        - `useCopilotKit` - access the CopilotKit instance directly
        - `useRenderTool` - draw UI for a tool call you don't own, by name or with a `"*"` fallback (see [Frontend tools](#frontend-tools-and-generative-ui))

        <Accordions className="mb-4">
            <Accordion title="Troubleshooting">
                - **Metro can't resolve modules**: Clear the cache with `npx react-native start --reset-cache`.
                - **Streaming not working**: Make sure polyfills are imported before any CopilotKit code in your entry point.
                - **No response from the runtime**: Confirm the runtime server is running, `http://localhost:8200/api/copilotkit/info` returns the `default` agent, and the device can reach `runtimeUrl`. For physical devices, use your machine's LAN IP instead of `localhost`.
                - **Model auth errors**: Confirm `OPENAI_API_KEY` is set in the terminal running `npx tsx server.ts`.
                - **`Property 'ReadableStream' doesn't exist`** (or the same for `TextEncoder`, `DOMException` or `Headers`): the polyfills did not install. Before **1.70.0**, the `polyfills` barrel was published empty. The build dropped all five polyfill imports out of it, so following the setup above installed nothing and the first runtime call failed. Upgrade to the latest version, or, if you are pinned, use the [granular imports](#polyfills), which were never affected. This is the *opposite* of the conflict case below: here you have no polyfill at all, not a competing one.
                - **Existing polyfill conflicts**: Use the granular imports instead of the barrel `polyfills` import.
            </Accordion>
        </Accordions>
    </Step>
</Steps>

## Import surfaces [#import-surfaces]

The quickstart above is enough for a development build. Read this section and the ones after it when you prepare a release build, connect from a physical device, or add tools and voice.

`@copilotkit/react-native` has three main JavaScript entry points. The opt-in `/generative-ui` and `/polyfills` entries are under "Supporting entry points" below. The three differ in what UI they give you and in which native peer dependencies Metro has to resolve. The second difference matters most for release bundles.

| Import | Available since | What you get | Native peers Metro must resolve |
|--------|-----------------|--------------|---------------------------------|
| `@copilotkit/react-native/headless` | **1.64.0** | `CopilotKitProvider` and every platform-agnostic hook. No components. | **None** |
| `@copilotkit/react-native` (root) | all versions | Everything in `/headless`, plus `useAttachments`, the two context-only chat wrappers (`CopilotChat`, `CopilotModal`) and the `CopilotSidebar` / `CopilotPopup` chrome | `expo-document-picker`, `expo-file-system` (via `useAttachments`) |
| `@copilotkit/react-native/components` | **1.58.0** | The **rendered** chat UI: a `CopilotChat` with a message list, a bottom-sheet `CopilotModal`, `CopilotMarkdown`, `AssistantMessage`, `UserMessage` | `@gorhom/bottom-sheet` (which itself needs `react-native-reanimated` + `react-native-gesture-handler`), `react-native-streamdown` |

Supporting entry points:

| Import | Description |
|--------|-------------|
| `@copilotkit/react-native/generative-ui` | Experimental. [Generative UI](#generative-ui-with-your-own-components): `GenerativeUIProvider`, `GenerativeUIActivity`, `GenerativeUISurface` and the catalog API (`createGenerativeUI`). Opt-in: the other entries never import it. No native peers. Like every entry, it needs `zod` 3.25 or later. Not in 1.85.0 or any earlier version: it first ships in the release after 1.85.0, and on an older pin Metro fails with `Unable to resolve module @copilotkit/react-native/generative-ui`. |
| `@copilotkit/react-native/polyfills` | Barrel that installs every polyfill (streams, encoding, crypto, dom, location) plus the streaming-fetch shim |
| `@copilotkit/react-native/polyfills/{streams,encoding,crypto,dom,location}` | Granular subpaths for installing a single polyfill |
| `@copilotkit/runtime` | Server-side runtime (`CopilotRuntime` / `BuiltInAgent` / `createCopilotNodeListener`) used to host your agent |

<Callout type="warn" title="`CopilotChat` means two different things">
  The root barrel's `CopilotChat` and `CopilotModal` are **context-only wrappers**: they render only context and `children`, no messages and no tool UI. The versions that actually draw a chat are the same-named exports from `@copilotkit/react-native/components`. If you imported `CopilotChat` expecting a chat and got a blank screen, you imported the root one.
</Callout>

These are static re-exports. Metro resolves the peers of a surface at bundle time, even if you never call the code. A custom-UI app that imports the root barrel must install or stub `expo-document-picker` and `expo-file-system`. Otherwise the release bundle fails with `Unable to resolve module expo-document-picker`. Importing from `/headless` avoids that entirely, which is why this guide uses it:

```tsx title="App.tsx"
import {
  CopilotKitProvider,
  useAgent,
  useFrontendTool,
} from "@copilotkit/react-native/headless"; // [!code highlight]
```

On `@copilotkit/react-native` 1.63.x and earlier there is no `/headless`. The subpath was added in 1.64.0 precisely to make this custom-UI case possible without the chat and attachment peers. The root barrel is still the package's default, full surface, and it exports the same provider and hooks on every version; `/headless` is the lean alternative, not a replacement. On a pinned older version, import from the root and install or stub `expo-document-picker` and `expo-file-system`.

Importing the provider auto-installs the polyfills: `/headless` runs the polyfill barrel as its first statement, and the root barrel gets it through its `/headless` re-export. `/components` does **not** install them itself. It relies on the provider you import alongside it (from `/headless` or the root). And because the root barrel re-exports everything from `/headless`, existing `@copilotkit/react-native` imports keep working unchanged.

### Which hooks are shared, and which aren't [#which-hooks-are-shared-and-which-arent]

The **package** (both `/headless` and the root barrel) re-exports the platform-agnostic hooks from `@copilotkit/react-core`: `useAgent`, `useFrontendTool`, `useHumanInTheLoop`, `useInterrupt`, `useSuggestions`, `useConfigureSuggestions`, `useAgentContext`, `useThreads`, `useCapabilities`, `useComponent`, `useCopilotKit`, and `useRenderToolCall`. These behave the same as on the web.

`useRenderTool` comes from `@copilotkit/react-core` too, and behaves the same as on the web. If your code passes `description` or `handler` to `useRenderTool`, see [Migrating from the old React Native `useRenderTool`](/reference/react-native/hooks/useRenderTool#migrating-from-the-old-react-native-userendertool).

`useFrontendTool` and `useRenderTool` register different things, the same as on the web:

| Hook | What it registers | Takes `description` and `handler` | `render` returns |
|------|-------------------|-----------------------------------|------------------|
| `useFrontendTool` | A tool that the model can call, plus an optional renderer | Yes | A component type. A bare string also type-checks. |
| `useRenderTool` | A renderer only, for a tool call that another part owns, such as a server-side tool. `name: "*"` makes it the fallback for every tool call. | No | `ReactElement \| null` |

Both hooks write into the same react-core renderer registry, which the rendered chat reads. A bare string from a `useFrontendTool` renderer type-checks but throws inside a `FlatList`. Annotate the renderer with the opt-in [`FrontendToolRenderFunction<T>`](/reference/react-native/hooks/useFrontendTool#the-render-type-react-native-needs) to catch it.

**Most of the web rendering hooks are deliberately not exported**: `useDefaultRenderTool` (its built-in card renders `<div>` / `<svg>`), `useRenderCustomMessages`, and `useRenderActivityMessage` (both link the web chat-message stack). `useRenderToolCall` **is** exported, though. It is platform-agnostic, pulls no DOM, and returns `ReactElement | null`, which is exactly what `FlatList`'s `renderItem` needs, so you can draw a registered tool call on any surface rather than only inside the chat.

<Callout type="warn" title="Rendering data on screen does not give the agent access to it">
  `useAgentContext` is in the shared list above, and it is the one whose absence fails *silently*. A screen that renders a list has put that list in the view tree, not in the agent's context. Those are separate steps. An agent wired without the second one still answers: the prose is coherent, the tool UI paints, the values look plausible, and nothing errors. On the web you would at least have a console to inspect. Here you do not.

  Register the data with `useAgentContext`, and write the agent's instructions to refuse to answer about records that context does not carry. Then check one answer against the records your app actually holds. If it names anything else, the context never arrived, however right the screen looks.
</Callout>

## Metro configuration for release bundles [#metro-configuration-for-release-bundles]

With package exports enabled, a release bundle can fail with `Unable to resolve module node:crypto` (or another `node:` specifier) pointing at `jose`. This surfaces **only at bundle time**, never at typecheck.

`jose` is not a direct dependency. It arrives transitively through telemetry: `@copilotkit/shared` → `@segment/analytics-node` → `jose`. `jose` publishes separate Node and browser builds behind its `exports` map, and its Node build imports `node:`-prefixed modules that Hermes cannot bundle.

The fix is to resolve **`jose` specifically** against its `browser` condition, using `resolveRequest`:

```js title="metro.config.js"
const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config");

const config = {
  resolver: {
    resolveRequest: (context, moduleImport, platform) => {
      // jose reaches the bundle via @copilotkit/shared -> @segment/analytics-node.
      // Its Node build imports node:* modules that Hermes can't bundle.
      if (moduleImport === "jose" || moduleImport.startsWith("jose/")) {
        return context.resolveRequest(
          { ...context, unstable_conditionNames: ["browser"] }, // [!code highlight]
          moduleImport,
          platform,
        );
      }
      return context.resolveRequest(context, moduleImport, platform);
    },
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

On Expo, swap in `getDefaultConfig` from `expo/metro-config`; the `resolver` block is identical.

<Callout type="warn" title="Don't assert `browser` globally">
  It's tempting to set `resolver.unstable_conditionNames = ["browser", ...]` instead. Avoid it:

  - `unstable_conditionNames` is an **unordered set of asserted conditions**, not a priority list. The winning target is chosen by the key order in *each package's own* `exports` map, so reordering this array changes nothing.
  - It applies **globally**, so every dual-build dependency in your graph switches to its browser build, not just `jose`.
  - Metro's React Native default is `["require", "react-native"]`. Replacing it wholesale drops the `react-native` condition, which changes resolution for any package that ships one.

  Scoping with `resolveRequest` keeps Metro's defaults intact everywhere else.
</Callout>

<Callout type="info" title="Do you need `unstable_enablePackageExports`?">
  Package `exports` resolution is **enabled by default from Metro 0.82 / React Native 0.79**, so no flag is needed there. It arrived opt-in in React Native 0.72 (Metro 0.76.1). On React Native 0.72 to 0.78, set `resolver.unstable_enablePackageExports = true`, which is also what lets Metro resolve this package's `/headless`, `/components`, `/generative-ui`, and `/polyfills` subpaths. React Native below 0.72 has no package-exports support.
</Callout>

<Callout type="success" title="Headless removes the need to stub">
  Importing from [`@copilotkit/react-native/headless`](#import-surfaces) means Metro never resolves the chat or attachment peer dependencies, so you don't need `@gorhom/bottom-sheet`, `expo-document-picker`, or `expo-file-system` at all. The `jose` resolver above is independent of that choice. You need it either way.
</Callout>

## Polyfills [#polyfills]

Hermes lacks several Web APIs CopilotKit relies on: `ReadableStream` / `WritableStream` / `TransformStream`, `TextEncoder` / `TextDecoder`, `DOMException` and `Headers`, `crypto.getRandomValues`, and `window.location`. It also lacks streaming `fetch` bodies (`response.body.getReader()`), which AG-UI's SSE transport needs.

Importing the provider installs these automatically: `/headless` runs the polyfill barrel as its first statement (and the root barrel gets it through `/headless`), also installing an XHR-based streaming-fetch shim on load. The `/components` surface does **not** install them on its own, so it relies on the provider imported alongside it. Each polyfill is skipped if the global it defines already exists, so importing more than once is safe.

Keep the explicit `import "@copilotkit/react-native/polyfills"` from the quickstart at the top of your entry point anyway. Because every polyfill is **first writer wins**, the entry point is the only place you control what gets installed before CopilotKit's own defaults do. This is what makes the secure-RNG ordering below work.

For granular control (for example, if you already polyfill `ReadableStream` yourself), import only the pieces you need instead of the barrel:

```js
import "@copilotkit/react-native/polyfills/streams";
import "@copilotkit/react-native/polyfills/encoding";
import "@copilotkit/react-native/polyfills/crypto";
import "@copilotkit/react-native/polyfills/dom";
import "@copilotkit/react-native/polyfills/location";
```

<Callout type="warn" title="The bundled crypto polyfill is not cryptographically secure">
  CopilotKit's `crypto` polyfill backs `crypto.getRandomValues` with `Math.random`. That is enough for the message and run IDs it generates. The polyfill logs a warning on install. For production, install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values) and import it on the **first line of your entry point, before any CopilotKit import**:

  ```js title="index.js"
  import "react-native-get-random-values"; // [!code highlight] secure RNG — must be first
  import "@copilotkit/react-native/polyfills";
  // ...
  ```

  This ordering is a hard requirement, not a precaution. Both implementations install only when `crypto.getRandomValues` is undefined, so whichever loads first wins permanently. If any CopilotKit module is evaluated first, the `Math.random` fallback is locked in and `react-native-get-random-values` silently becomes a no-op. You get no warning and no error, and every ID stays non-cryptographic for the life of the process.
</Callout>

## Provider options [#provider-options]

`CopilotKitProvider` is a context-only provider (it renders no view of its own), so it composes cleanly as the outermost wrapper around your app. `runtimeUrl` is the only required prop, but several others are available:

| Prop | Type | Description |
|------|------|-------------|
| `runtimeUrl` | `string` | URL of the Copilot Runtime endpoint (**required**) |
| `headers` | `Record<string, string> \| (() => Record<string, string>)` | Custom headers sent with every request. Use this for auth, such as an `Authorization` bearer token. A function form is called **when the provider renders**, not per request (see the callout below) |
| `credentials` | `RequestCredentials` | Fetch credentials mode, e.g. `"include"` to send HTTP-only cookies on cross-origin requests |
| `messageFilter` | `(messages, context) => messages` | Rewrites the message list sent to runtime agents on every run, for example `(messages) => messages.slice(-1)` for an agent that stores the conversation itself. Changes the request only, not the messages the UI renders |
| `properties` | `Record<string, unknown>` | Custom properties forwarded to agents (e.g. a scoped user id) |
| `onError` | `(event) => void` | Called for all error types (runtime connection, agent, tool). Defaults to `console.error` |
| `debug` | `DebugConfig` | Enables verbose client-side event logging |
| `defaultThrottleMs` | `number` | Default re-render throttle for streaming updates; individual `useAgent` calls can override |
| `useSingleEndpoint` | `boolean` | Whether the runtime uses a single-route endpoint (defaults to auto-detect) |
| `messageFilter` | `CopilotKitMessageFilter` | Rewrites the message list sent to runtime agents on each run. The transcript the UI shows does not change. |

```tsx title="App.tsx"
<CopilotKitProvider
  runtimeUrl={runtimeUrl}
  headers={{ Authorization: `Bearer ${token}` }} // [!code highlight]
  properties={{ userId }}
>
  <ChatScreen />
</CopilotKitProvider>
```

<Callout type="warn" title="Rotating auth tokens: `headers` is resolved on render, not per request">
  If you pass a function, the provider calls it **in its render body**, memoizes the result, and pushes that object into the core, which snapshots it onto each agent. Nothing re-reads the function at request time.

  So a refreshed token is only picked up if the provider **re-renders** and the resulting headers differ. Drive the token from React state (or context) so a refresh triggers a render:

  ```tsx
  const [token, setToken] = useState(initialToken);

  <CopilotKitProvider runtimeUrl={runtimeUrl} headers={{ Authorization: `Bearer ${token}` }}>
  ```

  A token kept in a ref, module variable, or async SDK cache with no accompanying render will keep sending the **stale** value indefinitely. If you can't re-render, call `copilotkit.setHeaders({ ... })` directly when the token rotates.

  The web provider's `headers` builder now runs when each request is sent, and also accepts an async function. Neither applies here yet: the React Native provider still evaluates its builder at render time and only accepts a sync function.
</Callout>

<Callout type="info" title="Cloud props aren't wired on React Native yet">
  The web provider's `publicApiKey` / `licenseToken` cloud props are not supported by the React Native provider. Point `runtimeUrl` at your own Copilot Runtime.
</Callout>

## Runtime and model wiring [#runtime-and-model-wiring]

The runtime from the quickstart hosts a `BuiltInAgent` and serves it with `createCopilotNodeListener`, which plugs straight into Node's built-in `node:http` `createServer`, with no Hono or Express dependency. `createCopilotNodeListener({ runtime, basePath, cors })` returns a request listener.

`cors: true` adds `Access-Control-*` response headers and answers `OPTIONS` preflights. That matters for **browser** clients (Expo Web or `react-native-web`), but it has no bearing on whether a native iOS or Android build can reach the server: CORS is enforced by the browser, and React Native's native networking stack (`NSURLSession` / OkHttp) neither sends an `Origin` header nor consults `Access-Control-Allow-Origin`. Native reachability is decided by the server's bind address, LAN routing and firewall, and platform transport security. See [Connecting from a device or bench](#connecting-from-a-device-or-bench).

`BuiltInAgent` accepts a model **string** in `provider:model` (or `provider/model`) form for OpenAI, Anthropic, and Google:

```ts
new BuiltInAgent({ model: "openai:gpt-6-luna", prompt: "..." });      // OPENAI_API_KEY
new BuiltInAgent({ model: "anthropic:claude-sonnet-4-6", prompt: "..." }); // ANTHROPIC_API_KEY
new BuiltInAgent({ model: "google:gemini-3.8-flash", prompt: "..." }); // GOOGLE_API_KEY
```

The string form reads the matching provider API key from the environment. You can also pass `apiKey` on the config, or an already-constructed AI SDK `LanguageModel` instance in place of the string.

### OpenAI-compatible endpoints [#openai-compatible-endpoints]

To point the string model form at an OpenAI-compatible endpoint (a gateway, Azure OpenAI, a self-hosted server, etc.), set the base-URL environment variable. The runtime honors it when it constructs the provider:

```bash
export OPENAI_BASE_URL=https://your-gateway.example.com/v1
export OPENAI_API_KEY=sk-...
npx tsx server.ts
```

On a host other than OpenAI or Azure, `openai:` models use the Chat Completions API. To keep the Responses API through a gateway in front of OpenAI, also set `COPILOTKIT_OPENAI_API=responses`. See [Model Selection](/model-selection#openai-compatible-endpoints).

The same applies to `ANTHROPIC_BASE_URL` and `GOOGLE_GENERATIVE_AI_BASE_URL`. When the variable is unset, the provider falls back to its default endpoint, so this is fully backward compatible. You do **not** need to build a custom model instance just to change the base URL.

<Callout type="info" title="Other BuiltInAgent options">
  Beyond `model` and `prompt`, `BuiltInAgent` accepts `maxSteps` (tool-calling iterations, default `1`), `tools` (server-executed tools via `defineTool`), `temperature`, `maxOutputTokens`, `providerOptions` (e.g. OpenAI `reasoningEffort`), and `mcpServers` / `mcpClients`. Tools that mutate the app's UI belong on the **client** via `useFrontendTool` (below), not in the server `tools` list.
</Callout>

## Connecting from a device or bench [#connecting-from-a-device-or-bench]

`runtimeUrl` must be an address the **device** can reach. `localhost` on a physical device or emulator resolves to the device itself, not your dev machine.

| Setup | `runtimeUrl` host |
|-------|-------------------|
| iOS simulator | `localhost` reaches the host machine |
| Android emulator | `10.0.2.2` is the emulator's alias for the host's `localhost` |
| Android device over USB | run `adb reverse tcp:8200 tcp:8200`, then use `localhost` on the device. `adb reverse` is Android-only. There is no iOS equivalent |
| iOS device | your dev machine's LAN IP, on the same Wi-Fi network, plus the [ATS exception](#plaintext-http-on-a-physical-device) a plain `http://` address needs |
| Physical device on the same LAN (a bench) | your dev machine's LAN IP, e.g. `http://192.168.1.23:8200/api/copilotkit` |
| Production | a hosted runtime URL over HTTPS |

The quickstart already branches on `Platform.OS` for the simulator/emulator case. Keep the URL a single named constant with a comment so it's easy to swap per environment.

### Plaintext HTTP on a physical device [#plaintext-http-on-a-physical-device]

Both platforms block plaintext (non-TLS) HTTP by default, so a device silently fails to reach a plain `http://<lan-ip>` dev runtime. These are dev-only affordances. A hosted TLS runtime needs none of them.

On Expo, configure both through `app.json` so they survive the `android/` and `ios/` regeneration that `expo prebuild` performs (never hand-edit the generated `AndroidManifest.xml` or `Info.plist`, because the next prebuild discards them). Install the config plugin first:

```bash
npx expo install expo-build-properties
```

**Android**: an Android *release* build needs cleartext opted in:

```jsonc title="app.json"
{
  "expo": {
    "plugins": [
      ["expo-build-properties", { "android": { "usesCleartextTraffic": true } }]
    ]
  }
}
```

**iOS**: App Transport Security applies to debug *and* release builds alike, and `expo-build-properties` has no iOS ATS option, so this goes in `ios.infoPlist`. Since iOS 17, ATS refuses raw IP addresses unless the address is listed in `NSExceptionDomains`, so name your dev machine's IP explicitly (no port):

```jsonc title="app.json"
{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSAppTransportSecurity": {
          "NSExceptionDomains": {
            "192.168.1.23": { "NSExceptionAllowsInsecureHTTPLoads": true }
          }
        },
        "NSLocalNetworkUsageDescription": "Connects to the local Copilot Runtime during development."
      }
    }
  }
}
```

`NSLocalNetworkUsageDescription` is required separately: iOS gates local-network access behind a user permission prompt, and without the string the connection fails regardless of ATS.

<Callout type="warn" title="Keep these out of production builds">
  `usesCleartextTraffic` and an ATS exception are bench affordances. Scope them to a dev build (a separate Expo profile or app variant), and ship production against an HTTPS runtime with neither. On Android you can tighten further by scoping cleartext to just the dev host with a network-security-config.
</Callout>

<Callout type="info" title="`NSAllowsLocalNetworking` isn't enough on its own">
  Expo and React Native templates already ship `NSAllowsLocalNetworking: true`, which covers `.local` hostnames and unqualified names, but **not** raw IP addresses on iOS 17+. Its presence also causes `NSAllowsArbitraryLoads` to be ignored. The `NSExceptionDomains` entry above is the form that actually works for a LAN IP.
</Callout>

## Frontend tools and generative UI [#frontend-tools-and-generative-ui]

Frontend tools let the agent call functions in your app (and render UI) while the model runs. Register them with `useFrontendTool`. To let the agent compose UI from a catalog of your own components instead, see [Generative UI with your own components](#generative-ui-with-your-own-components). `parameters` is a [Standard Schema](https://standardschema.dev), so a `zod` schema is the expected shape. Use the `zod` 3.25 or later that you installed in the quickstart: `@copilotkit/react-core` requires that version as a peer dependency, although `@copilotkit/react-native` declares `zod` an optional peer at `>=3.0.0`.

```tsx title="src/useComposeStage.ts"
import { useFrontendTool } from "@copilotkit/react-native/headless";
import { z } from "zod";

export function useComposeStage() {
  useFrontendTool({
    name: "composeStage",
    description: "Render POI panels on the screen.",
    agentId: "default", // scope the tool to one agent
    parameters: z.object({
      mode: z.enum(["home", "nearby", "hotels"]),
      panels: z.array(
        z.object({ title: z.string(), body: z.string().optional() }),
      ),
    }),
    handler: async (args) => {
      // Runs on the device. Push args into your own state/reducer here.
      return "rendered";
    },
  });
}
```

Because the tool is registered on the device, the model's call reaches your `handler` on the client. The handler is the ideal place to drive a state reducer that your React Native views render declaratively (the agent sends *state*, the client owns rendering). Discriminated-union / `oneOf` / `anyOf` param schemas are preserved through the runtime's schema conversion, so `z.discriminatedUnion(...)` params work. It's still good practice to normalize defensively in the handler. Coerce a partially populated tool call into valid state rather than letting a malformed one render broken UI.

<Callout type="warn" title="Choose the hook by who owns the tool, not by where the UI goes">
  Both hooks write to the **same** place: react-core's renderer registry, which the rendered React Native chat (`@copilotkit/react-native/components`) reads through `useRenderToolCall`. So inline chat UI is available from either: a `render` passed to `useFrontendTool` *is* drawn there. What differs is whether a **tool** gets registered.

  Use `useFrontendTool` for a tool your app owns: it advertises the tool to the model and runs your `handler` on the device. Pass `render` alongside the handler when you also want it drawn in the chat.

  ```tsx
  import { useFrontendTool } from "@copilotkit/react-native/headless";

  useFrontendTool({
    name: "composeStage",
    description: "Render POI panels on the screen.",
    parameters: z.object({ mode: z.string() }),
    handler: async (args) => { /* drive your own state */ return "rendered"; },
    render: ({ args, status }) => (
      <StagePreview mode={args.mode} pending={status !== "complete"} />
    ),
  });
  ```

  Use [`useRenderTool`](/reference/react-native/hooks/useRenderTool) when the tool is **not** yours: a server-side tool you only want to draw, or `name: "*"` as a fallback for every tool call with no renderer of its own. It registers no tool, takes no `description` and no `handler`, and exposes arguments as `parameters`:

  ```tsx
  import { useRenderTool } from "@copilotkit/react-native/headless";

  useRenderTool(
    {
      name: "lookupPlaces",
      parameters: z.object({ mode: z.string() }),
      render: ({ parameters, status }) => (
        <StagePreview mode={parameters.mode} pending={status !== "complete"} />
      ),
    },
    [],
  );
  ```

  `useRenderTool`'s `render` must return `ReactElement | null`, so returning `null` draws nothing. `useFrontendTool`'s `render` is a component type that also accepts a bare string, which typechecks and then throws inside a `FlatList`. Return an element or `null` there too, and annotate the renderer with the opt-in [`FrontendToolRenderFunction<T>`](/reference/react-native/hooks/useFrontendTool#the-render-type-react-native-needs) if you want the compiler to hold you to it.

  A `useRenderTool` call with `description` or `handler` does not type-check. Rename it to `useFrontendTool`. [Migration notes](/reference/react-native/hooks/useRenderTool#migrating-from-the-old-react-native-userendertool).

  `status` is `"inProgress"` / `"executing"` / `"complete"` in both hooks. It is typed as string literals in `useRenderTool`'s render props and as `ToolCallStatus` enum members in `useFrontendTool`'s. **You do not have to care which.** A string-enum member is assignable to its own literal type, so the string and the member compare interchangeably against either shape, and both forms narrow. `ToolCallStatus` is exported as a value from `/headless` if you prefer the members.

  For agent-authored content whose length you can't predict, render it in a `ScrollView` with a `maxHeight` set to the available band. It sizes to content when short and scrolls when long, so it never hard-clips.
</Callout>

### Sending a turn and reading run state [#sending-a-turn-and-reading-run-state]

Running a user turn is the two-step the quickstart shows: `agent.addMessage(...)` then `copilotkit.runAgent({ agent })` (the runner lives on the core, not the agent). To cancel an in-flight run, call `copilotkit.stopAgent({ agent })`.

When another component needs only the run flag (a "thinking" indicator, for example), subscribe with `useAgent` (a plain read that registers nothing) and read `agent.isRunning`. Call the tool-registering hook exactly **once** per agent so a tool isn't registered twice.

To pin a `useAgent` call to one thread, pass three props together: a new local `agentId`, the `runtimeAgentId` it routes to, and the `threadId`. For example, `useAgent({ agentId: "chat-1", runtimeAgentId: "default", threadId })`. A `threadId` without `runtimeAgentId` throws an error. See [`useAgent`](/reference/react-native/hooks/useAgent).

## Generative UI with your own components [#generative-ui-with-your-own-components]

Frontend tools render UI you wrote for one tool. With generative UI, the agent composes the UI itself from a **catalog** of your own React Native components, fills in their props, and updates them while it streams. It is the [components and surfaces](/generative-ui/components) feature of the web, with native host views. The runtime needs no change by default: when the app sends a catalog with at least one component, `CopilotRuntime` gives the run a `render_ui` tool and checks every operation before it streams it to the device. A server can turn this off with the runtime option `generativeUI: false`, or limit it to some agents with `generativeUI: { agents: [...] }`; see [Transports](/generative-ui/components/transports#tool-transport). The built-in agent from the quickstart already passes the run's tools and context to its model.

You start with the chat screen from the quickstart. You end with an agent that renders your native components in that chat, and a home screen that a background agent run composes, with no chat on it.

<Callout type="warn" title="Experimental, and narrower than the web">
  `@copilotkit/react-native/generative-ui` is experimental. On React Native:

  - **Tool transport only.** The [markdown transport](/generative-ui/components/markdown-mode) is not available.
  - **No standard catalog.** Bring your own native components; `standardUI` is DOM-only.
  - **Not inside the prebuilt `CopilotChat`.** The rendered chat from `/components` does not draw surfaces yet. Render them in your own message list with `GenerativeUIActivity`, as below.
  - **No `theme`.** The web theme is a set of CSS variables, so `GenerativeUIProvider` has no `theme` prop. Style the components of your catalog instead. A `theme`, or a `transport` other than `"tool"`, that gets past the types (from JavaScript or through a cast) is dropped, with a warning in development.
  - **No `openUrl`.** The built-in `openUrl` function fails with "openUrl is not available on this platform". To open a link, declare a catalog function of your own that calls `Linking.openURL`.
  - **English plurals.** Hermes has no `Intl.PluralRules`, so the built-in `pluralize` function picks its form with the English rule there: `one` for 1 and -1, `other` for any other number (`zero` still applies to 0).
</Callout>

<Steps>
    <Step>
        ### Declare a catalog [#declare-a-catalog]

        A catalog lists the components that the agent can use, each with a description and a schema of its props. A component receives typed props, and a slot (`children` here) arrives as React nodes. Declare it once, at module level. The props schemas use the `zod` 3.25 or later from the quickstart; every entry of the package needs that version, although `@copilotkit/react-native` declares `zod` an optional peer at `>=3.0.0`, so install it if you have not already (`npm install "zod@^3.25"`). A catalog that uses `child()` or `childList()` must use zod 3, as the quickstart installs.

        ```tsx title="src/bankUI.tsx"
        import { StyleSheet, Text, View } from "react-native";
        import { z } from "zod";
        import {
          createGenerativeUI,
          type GenerativeUIComponentProps,
        } from "@copilotkit/react-native/generative-ui";

        function Section({ title, children }: GenerativeUIComponentProps<typeof bankUI, "Section">) {
          return (
            <View style={styles.section}>
              {title ? <Text style={styles.sectionTitle}>{title}</Text> : null}
              {children}
            </View>
          );
        }

        function BalanceCard({ account, amount, currency }: GenerativeUIComponentProps<typeof bankUI, "BalanceCard">) {
          return (
            <View style={styles.card}>
              <Text style={styles.label}>{account}</Text>
              <Text style={styles.amount}>
                {amount.toLocaleString("en-US", { style: "currency", currency })}
              </Text>
            </View>
          );
        }

        function InsightCard({ headline, detail }: GenerativeUIComponentProps<typeof bankUI, "InsightCard">) {
          return (
            <View style={styles.card}>
              <Text style={styles.headline}>{headline}</Text>
              {detail ? <Text style={styles.label}>{detail}</Text> : null}
            </View>
          );
        }

        export const bankUI = createGenerativeUI({
          id: "acme/bank@1",
          components: {
            Section: {
              component: Section,
              description: "A titled group of cards, stacked vertically. Put the ids of its cards in children.",
              props: z.object({ title: z.string().optional() }),
              slots: { children: "multiple" },
            },
            BalanceCard: {
              component: BalanceCard,
              description: "The balance of one account. Copy the values from the accounts in the context.",
              props: z.object({
                account: z.string(),
                amount: z.number(),
                // An enum, not any string: toLocaleString throws a RangeError on a
                // currency code that is not well formed, such as "dollars".
                currency: z.enum(["USD", "EUR", "GBP"]),
              }),
            },
            InsightCard: {
              component: InsightCard,
              description: "One short observation about the user's money, with an optional detail line.",
              props: z.object({ headline: z.string(), detail: z.string().optional() }),
            },
          },
        });

        const styles = StyleSheet.create({
          section: { marginVertical: 8 },
          sectionTitle: { fontSize: 17, fontWeight: "600" },
          // Margins rather than `gap`, which needs React Native 0.71.
          card: { marginTop: 8, padding: 12, borderRadius: 12, backgroundColor: "#f4f4f5" },
          label: { color: "#52525b" },
          amount: { fontSize: 22, fontWeight: "700" },
          headline: { fontWeight: "600" },
        });
        ```

        [Catalogs](/generative-ui/components/catalogs) covers the rest of a component declaration: child references, `extends`, and exporting the catalog. [State and actions](/generative-ui/components/state-and-actions) connects the components to app state and to your own functions.
    </Step>
    <Step>
        ### Add the provider [#add-the-provider]

        `GenerativeUIProvider` goes inside `CopilotKitProvider`. It sends the catalog with every agent run on the `CopilotKitProvider`'s core, wherever in the component tree the run starts, and keeps the surfaces that those runs render. Mount exactly one `GenerativeUIProvider` with a `ui` for each `CopilotKitProvider`, above every screen that shows generative UI, rather than one per screen: each one sets the catalog and the named areas of every run on the core, so two of them override each other (in development, the second one warns):

        ```tsx title="App.tsx"
        import { Platform } from "react-native";
        import { CopilotKitProvider } from "@copilotkit/react-native/headless";
        import { GenerativeUIProvider } from "@copilotkit/react-native/generative-ui"; // [!code highlight]
        import { bankUI } from "./src/bankUI";
        import { ChatScreen } from "./src/ChatScreen";

        const runtimeUrl =
          Platform.OS === "android"
            ? "http://10.0.2.2:8200/api/copilotkit"
            : "http://localhost:8200/api/copilotkit";

        export default function App() {
          return (
            <CopilotKitProvider runtimeUrl={runtimeUrl}>
              <GenerativeUIProvider ui={bankUI}> {/* [!code highlight] */}
                <ChatScreen />
              </GenerativeUIProvider>
            </CopilotKitProvider>
          );
        }
        ```

        To give generative UI only to some agents, pass their ids in `agentIds`. Placing the provider lower in the tree does not narrow it. To report component errors, or draw your own fallback, pass `errorBoundary`. See the [`GenerativeUIProvider` reference](/reference/react-native/components/GenerativeUIProvider).
    </Step>
    <Step>
        ### Render surfaces in your message list [#render-surfaces-in-your-message-list]

        Every surface the agent renders arrives as an **activity message** in `agent.messages`, next to the user and assistant messages, and is updated in place while the agent streams. `isGenerativeUIActivity` picks those messages out, and `GenerativeUIActivity` draws one.

        First, a helper that sends one turn. A failed run does not reject: `copilotkit.runAgent` resolves, and the error goes to the `onError` subscribers of the core. So the helper listens, while the run lasts, for an error of its agent that ends the run. A failed tool call is not one: the core reports it to `onError` too, but its error goes back to the model and the run goes on, so the helper ignores it. When the run fails, the helper takes back the messages that the turn added, such as the user message and any partial reply (`takeBack`). It keeps the surfaces of the run, in the chat and in a [named area](#named-areas-of-a-screen) alike, so they stay on screen until the agent replaces or deletes them: the provider never forgets a surface, the next run still lists it for the model, and the runtime rejects a new `createSurface` with its id. Removing a surface's activity message would only hide it, and an update that the model then sends to it would not show. The take-back is local as well: a runtime that stores the thread may still have the user message, and connecting to that thread again brings it back. The helper counts every run failure of its agent while it waits, so start one run of an agent at a time.

        ```tsx title="src/agentTurns.ts"
        import {
          CopilotKitCoreErrorCode,
          type useAgent,
          type useCopilotKit,
        } from "@copilotkit/react-native/headless";
        import {
          isGenerativeUIActivity,
          type GenerativeUIActivityMessage,
        } from "@copilotkit/react-native/generative-ui";

        type CopilotKit = ReturnType<typeof useCopilotKit>["copilotkit"];
        type Agent = ReturnType<typeof useAgent>["agent"];

        /**
         * The errors that end a run. A failed tool call is not one of them
         * (TOOL_HANDLER_FAILED, TOOL_ARGUMENT_PARSE_FAILED): its error goes back to
         * the model as the result of the call, and the run goes on.
         */
        const RUN_FAILURES: ReadonlySet<CopilotKitCoreErrorCode> = new Set([
          CopilotKitCoreErrorCode.AGENT_RUN_FAILED,
          CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,
          CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,
          CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,
        ]);

        // Date.now() alone repeats within a millisecond; with a counter, ids do not.
        let sent = 0;

        /**
         * Sends one user message and runs the agent. Resolves with the run's error,
         * or undefined; it never rejects. It counts every run failure of this agent
         * while it waits, so start one run of an agent at a time.
         */
        export async function runTurn(
          copilotkit: CopilotKit,
          agent: Agent,
          content: string,
        ) {
          const before = agent.messages.map((message) => message.id);
          const { threadId } = agent;
          let failure: Error | undefined;
          const subscription = copilotkit.subscribe({
            onError: ({ error, code, context }) => {
              if (context.agentId === agent.agentId && RUN_FAILURES.has(code)) {
                failure ??= error;
              }
            },
          });
          try {
            sent += 1;
            agent.addMessage({
              id: `user-${Date.now()}-${sent}`,
              role: "user",
              content,
            });
            await copilotkit.runAgent({ agent });
          } catch (error) {
            failure ??= error instanceof Error ? error : new Error(String(error));
          } finally {
            subscription.unsubscribe();
          }
          try {
            if (failure) takeBack(agent, before, threadId);
          } catch (error) {
            console.error("Could not take the failed turn back:", error);
          }
          return failure;
        }

        /**
         * Removes the messages added since `before` (their ids), such as the user
         * message and a partial reply. It keeps the surfaces: the provider keeps
         * every surface that a run rendered, and the model still sees it, so the
         * screen shows it too.
         */
        export function takeBack(
          agent: Agent,
          before: readonly string[],
          threadId: string | undefined,
        ) {
          // The agent moved to another thread: those messages are not this turn's.
          if (agent.threadId !== threadId) return;
          const kept = new Set(before);
          agent.setMessages(
            agent.messages.filter(
              (message) => kept.has(message.id) || isGenerativeUIActivity(message),
            ),
          );
        }

        /**
         * An activity message that GenerativeUIActivity draws: its surface is aimed at
         * the chat (the target it shows) and the agent has not deleted it.
         */
        export function isChatSurface(message: GenerativeUIActivityMessage) {
          if (!isGenerativeUIActivity(message)) return false;
          const content = message.content as {
            target?: unknown;
            operations?: unknown;
          } | null;
          const operations = Array.isArray(content?.operations)
            ? content.operations
            : [];
          return (
            content?.target === "chat" &&
            !operations.some(
              (op) => typeof op === "object" && op !== null && "deleteSurface" in op,
            )
          );
        }
        ```

        Then the chat screen:

        ```tsx title="src/ChatScreen.tsx"
        import { useRef, useState } from "react";
        import {
          FlatList,
          Text,
          TextInput,
          TouchableOpacity,
          View,
        } from "react-native";
        import { useAgent, useCopilotKit } from "@copilotkit/react-native/headless";
        import {
          GenerativeUIActivity,
          isGenerativeUIActivity,
        } from "@copilotkit/react-native/generative-ui";
        import { isChatSurface, runTurn } from "./agentTurns";

        // A separator rather than `gap`, which needs React Native 0.71.
        const Separator = () => <View style={{ height: 8 }} />;

        export function ChatScreen() {
          const [text, setText] = useState("");
          const [error, setError] = useState<string>();
          const { copilotkit } = useCopilotKit();
          // Until the runtime connects, `agent` is a stand-in (`isReady` is false). The
          // registered agent replaces it, so a message sent to the stand-in is lost.
          const { agent, isReady } = useAgent({ agentId: "default" });
          // Set at once, so a second tap before the next render does not send twice.
          const sending = useRef(false);
          const [isSending, setIsSending] = useState(false);
          // One run of this agent at a time, including a run that a click on a surface
          // started.
          const busy = isSending || agent.isRunning;
          const canSend = isReady && !busy;

          // A row only for what renders: a surface aimed at a named area renders in its
          // GenerativeUISurface, and a deleted surface renders nothing.
          const messages = agent.messages.filter(
            (message) =>
              isChatSurface(message) ||
              ((message.role === "user" || message.role === "assistant") &&
                typeof message.content === "string" &&
                message.content.length > 0),
          );

          const send = async () => {
            const content = text.trim();
            if (!content || !canSend || sending.current) return;
            sending.current = true;
            setIsSending(true);
            setText("");
            setError(undefined);
            try {
              const failure = await runTurn(copilotkit, agent, content);
              if (failure) {
                // runTurn took the message back. Put its text back, unless the user typed again.
                setText((current) => (current === "" ? content : current));
                setError(failure.message);
              }
            } finally {
              sending.current = false;
              setIsSending(false);
            }
          };

          return (
            <View style={{ flex: 1, paddingTop: 48 }}>
              <FlatList
                data={messages}
                keyExtractor={(message) => message.id}
                contentContainerStyle={{ padding: 12 }}
                ItemSeparatorComponent={Separator}
                renderItem={({ item }) =>
                  isGenerativeUIActivity(item) ? (
                    <GenerativeUIActivity message={item} agent={agent} /> // [!code highlight]
                  ) : (
                    <Text
                      style={{
                        alignSelf: item.role === "user" ? "flex-end" : "flex-start",
                      }}
                    >
                      {String(item.content)}
                    </Text>
                  )
                }
              />
              {error ? (
                <Text
                  accessibilityRole="alert"
                  style={{ color: "#dc2626", paddingHorizontal: 12 }}
                >
                  Could not send: {error}
                </Text>
              ) : null}
              <View style={{ flexDirection: "row", padding: 8 }}>
                <TextInput
                  style={{ flex: 1, borderWidth: 1, borderRadius: 8, padding: 8 }}
                  value={text}
                  onChangeText={setText}
                  placeholder={isReady ? "Type a message..." : "Connecting..."}
                />
                <TouchableOpacity
                  onPress={send}
                  disabled={!canSend}
                  accessibilityState={{ disabled: !canSend, busy }}
                  style={{ padding: 8, opacity: canSend ? 1 : 0.4 }}
                >
                  <Text>{busy ? "Replying..." : "Send"}</Text>
                </TouchableOpacity>
              </View>
            </View>
          );
        }
        ```

        The error line shows the error of a run that `send` started, for example a network failure or the agent's `RUN_ERROR`. The same error also reaches the `onError` of `CopilotKitProvider`. Without that prop, the provider only logs it with `console.error`, which nobody sees in a release build, so pass `onError` and send it to your crash reporter. A run that a click on a surface starts ([an event sent to the agent](/generative-ui/components/state-and-actions#send-a-click-to-the-agent)) does not go through `runTurn`: its user message stays when it fails, and its error reaches only the `onError` subscribers of the core, such as the `onError` of `CopilotKitProvider`. While a run of this agent is going, one that `send` started or one that a click on a surface started, Send is disabled; a run of another agent, such as the `home` agent of the next step, does not disable it. A ref, set at once, keeps a second tap that lands before the next render from sending twice.

        `GenerativeUIActivity` renders nothing for a message that carries no surface, so passing it other messages is safe. Like the web chat, it shows only surfaces aimed at the chat (target `"chat"`): a surface aimed at a [named area](#named-areas-of-a-screen) renders in its `GenerativeUISurface`, not twice. It also renders nothing for a surface that the agent deleted, for malformed content, while the agent has no `threadId` yet, when there is no `GenerativeUIProvider` above it or the provider has no `ui`, and when the provider holds no surface for the message. `isChatSurface` leaves out the named-area and deleted surfaces, so they take no row. In development it warns for malformed content, an undefined `agent`, a missing `threadId` and a missing provider or `ui`, not for the other cases. Each instance warns once for each distinct cause, also when the cause goes away and comes back; a message with another id warns again. Its default wrapper adds a short error line when operations of the surface were rejected. To show your own streaming or error state, pass a `Wrapper` component; it gets `surfaceId`, `isStreaming`, `error`, `rejected` and `children`.

        The agent knows nothing about the user's accounts yet. Give it the data with [`useAgentContext`](/reference/react-native/hooks/useAgentContext), in any component under the provider:

        ```tsx
        useAgentContext({
          description: "The user's accounts. Show only these, with these exact balances.",
          value: [
            { account: "Chequing", amount: 3482.1, currency: "USD" },
            { account: "Savings", amount: 6150, currency: "USD" },
          ],
        });
        ```

        Run the app and send "Show my balances". The agent answers with a `Section` of `BalanceCard`s, and a follow-up such as "add a tip about my savings" adds an `InsightCard` to the same surface.
    </Step>
    <Step>
        ### Compose a screen with no chat [#compose-a-screen-with-no-chat]

        A surface does not need a chat. A home screen can start a run of its own agent when it mounts, and show whatever surface that run renders. Add a `home` agent to the runtime from the quickstart:

        ```ts title="server.ts"
        const runtime = new CopilotRuntime({
          agents: {
            default: new BuiltInAgent({
              model: "openai:gpt-6-luna",
              prompt: "You are a helpful assistant for a React Native app.",
            }),
            home: new BuiltInAgent({ // [!code highlight:4]
              model: "openai:gpt-6-luna",
              prompt: "You compose the home screen of a banking app. Render it with one render_ui call into the chat target: the balances first, then one insight.",
            }),
          },
        });
        ```

        Add the agent before you render the screen: once the runtime has connected, `useAgent({ agentId: "home" })` throws while rendering if the runtime declares no `home` agent (for example an older deploy), and the screen's own error states never show. Then render the surfaces of that agent's run. It uses `runTurn`, `takeBack` and `isChatSurface` from the chat step:

        ```tsx title="src/HomeScreen.tsx"
        import { useCallback, useEffect, useRef, useState } from "react";
        import { ActivityIndicator, Pressable, ScrollView, Text } from "react-native";
        import {
          CopilotKitCoreRuntimeConnectionStatus,
          useAgent,
          useCopilotKit,
        } from "@copilotkit/react-native/headless";
        import {
          GenerativeUIActivity,
          useGenerativeUIRuntime,
          type GenerativeUIActivityMessage,
        } from "@copilotkit/react-native/generative-ui";
        import { isChatSurface, runTurn, takeBack } from "./agentTurns";

        /**
         * The chat surfaces that this device built, each message id with its operations,
         * to tell whether a run rendered or updated one here. The operations alone: each
         * call of the agent also refills the list of rejected operations, so a call whose
         * updates were all rejected changes the content but not the surface. A surface
         * whose createSurface the app rejected (`failed`) does not count: the app checks
         * the operations again, prop values included, and GenerativeUIActivity then shows
         * only an error line.
         */
        function chatSurfaces(
          messages: readonly GenerativeUIActivityMessage[],
          failed: (surfaceId: string) => boolean,
        ) {
          const built = new Map<string | undefined, string>();
          for (const message of messages.filter(isChatSurface)) {
            const { surfaceId, operations } = message.content as {
              surfaceId?: unknown;
              operations?: unknown;
            };
            if (typeof surfaceId === "string" && failed(surfaceId)) continue;
            built.set(message.id, JSON.stringify(operations));
          }
          return built;
        }

        export function HomeScreen() {
          const { copilotkit } = useCopilotKit();
          // Until the runtime connects, `agent` is a stand-in (`isReady` is false). The
          // registered agent replaces it, so a run started on the stand-in is lost.
          // Once the runtime has connected, useAgent throws if it has no `home` agent.
          const { agent, isReady } = useAgent({ agentId: "home" });
          const runtime = useGenerativeUIRuntime();
          // The thread it last checked: a ref, so StrictMode's second effect run sees it.
          const checkedThread = useRef<string | undefined>(undefined);
          const composing = useRef(false); // a ref, so a second tap is ignored at once
          const [checked, setChecked] = useState(false);
          const [busy, setBusy] = useState(false);
          const [error, setError] = useState<string>();

          const failed = useCallback(
            (surfaceId: string) =>
              !!runtime?.manager.getFailedSurface(agent.threadId, surfaceId),
            [runtime, agent],
          );

          const compose = useCallback(async () => {
            // A stand-in agent (not ready) would lose the run.
            if (composing.current || !isReady) return;
            composing.current = true;
            setBusy(true);
            setError(undefined);
            try {
              const before = agent.messages.map((message) => message.id);
              const { threadId } = agent;
              const shownBefore = chatSurfaces(agent.messages, failed);
              const failure = await runTurn(
                copilotkit,
                agent,
                "Compose my home screen.",
              );
              const shownAfter = chatSurfaces(agent.messages, failed);
              if (failure) {
                // runTurn took the prompt back, so a retry sends it once.
                setError(failure.message);
              } else if (
                ![...shownAfter].some(
                  ([id, content]) => shownBefore.get(id) !== content,
                )
              ) {
                // This run rendered or updated nothing here. Take its prompt back too.
                takeBack(agent, before, threadId);
                setError("The agent rendered nothing for this screen.");
              }
            } catch (reason) {
              setError(reason instanceof Error ? reason.message : String(reason));
            } finally {
              composing.current = false;
              setBusy(false);
            }
          }, [agent, copilotkit, failed, isReady]);

          // The agent and its messages live in the core and outlive this screen. Run only
          // when the registered agent has no surface here yet and is not running, so a
          // screen that mounts again shows what it has instead of composing it again.
          // Check again when the agent moves to another thread, once it is not running
          // and no compose is under way (`busy` reruns this when one ends).
          useEffect(() => {
            if (
              !isReady ||
              busy ||
              composing.current ||
              agent.isRunning ||
              checkedThread.current === agent.threadId
            ) {
              return;
            }
            checkedThread.current = agent.threadId;
            setChecked(true);
            setError(undefined);
            if (chatSurfaces(agent.messages, failed).size === 0) {
              void compose();
            }
          }, [
            isReady,
            busy,
            agent,
            agent.threadId,
            agent.isRunning,
            compose,
            failed,
          ]);

          const surfaces = agent.messages.filter(isChatSurface); // [!code highlight]
          const built = chatSurfaces(agent.messages, failed);
          const unreachable =
            copilotkit.runtimeConnectionStatus ===
            CopilotKitCoreRuntimeConnectionStatus.Error;
          const waiting = !isReady || !checked || busy || agent.isRunning;

          return (
            <ScrollView contentContainerStyle={{ padding: 16 }}>
              {surfaces.map((message) => (
                <GenerativeUIActivity
                  key={message.id}
                  message={message}
                  agent={agent}
                />
              ))}
              {unreachable ? (
                <Text accessibilityRole="alert">
                  Can't reach the agent. Check the runtime URL.
                </Text>
              ) : waiting ? (
                <ActivityIndicator />
              ) : error || built.size === 0 ? (
                <Pressable accessibilityRole="button" onPress={() => void compose()}>
                  <Text>
                    Couldn't load your home screen{error ? ` (${error})` : ""}. Tap to
                    try again.
                  </Text>
                </Pressable>
              ) : null}
            </ScrollView>
          );
        }
        ```

        Render `HomeScreen` anywhere under `GenerativeUIProvider`, next to a component that calls `useAgentContext` with the accounts. The run's user message and the agent's text never show; the screen shows only the chat surfaces that `isChatSurface` keeps, which fill in while the agent streams. The run waits for `isReady`, so it goes to the agent that the runtime registered. The `home` agent and its messages live in the core, not in the screen, so a screen that mounts again (after the user navigates away and back) shows the surfaces the agent already rendered and starts no run; while a run is still going, it shows the spinner until that run ends. A run that fails, or that renders and updates no chat surface, has its prompt taken back and leaves a retry with the reason rather than a spinner that never stops; each retry sends the prompt once, and a second tap while one runs does nothing. A surface that a failed run rendered stays on screen, above the retry, because the provider and the model keep it (see the [chat step](#render-surfaces-in-your-message-list)); so a retry in which the agent updates that surface instead of rendering a new one counts as rendering. The check compares the operations of the chat surfaces before and after the run, so a surface of an earlier run that the run left alone cannot hide a run that rendered nothing, and neither can a call whose operations were all rejected (it changes only the surface's list of rejected operations). A surface counts only once the device has built it: the app checks each operation again, prop values included, and when it rejects a `createSurface` that the runtime let through, `GenerativeUIActivity` shows only an error line. The screen then treats it as no surface and offers the retry; the model sees the failed surface on the next run and can render it again. When the agent moves to another thread while the screen stays mounted, the screen checks that thread the same way and composes it if it has no surface.

        The agent renders into the chat target (`"chat"`), which is the target `GenerativeUIActivity` shows by default and the only target this screen counts. The chat target is always offered to the agent, even on a screen with no chat. If the app also mounts [named areas](#named-areas-of-a-screen) while this run is active, the agent may aim its surface at one of them instead. That surface renders in the named area, but this screen sees no chat surface, takes the prompt back and shows the retry. The surface stays in the named area. So the prompt above tells the agent to render into the chat target.
    </Step>
</Steps>

### Named areas of a screen [#named-areas-of-a-screen]

`GenerativeUISurface` marks a place in your app where the agent can render, with an `id` and a `description`. The targets are sent when a run starts, so the agent sees this one in each run that starts while it is mounted. It shows `fallback` until the agent renders there, and calls `onGenerationStart` once each time the agent starts to render into it (and when it mounts, its `id` changes, or the active thread changes, while the agent is rendering into it), for example to scroll it into view. A re-render, `<React.StrictMode>` or a new callback does not call it again for the same start, and an error it throws is caught and logged with `console.error`:

```tsx
import { GenerativeUISurface } from "@copilotkit/react-native/generative-ui";

<GenerativeUISurface
  id="insights"
  ui={bankUI}
  description="Under the balances. Show spending insights here."
  components={["InsightCard"]}
  fallback={<InsightsPlaceholder />}
  style={{ marginTop: 16 }}
/>;
```

`style` and the test ID `generative-ui-surface-<id>` are on the view around it, so they apply while the fallback shows too. Like `GenerativeUIActivity`, it takes a `Wrapper`, with the same props; its default draws no view of its own and shows "Part of this UI couldn't be shown." under the surface when operations were rejected.

A named target follows the thread that is active in the provider: the thread of the last run that started on the core, of any agent, also one that `agentIds` leaves out. So it suits a screen that shares its agent with the chat. To show the output of one particular agent, such as the background `home` run above, render that agent's activity message with `GenerativeUIActivity` instead. Unlike `GenerativeUIActivity`, which renders nothing without a provider, `GenerativeUISurface` throws when no `GenerativeUIProvider` is above it. Under a provider without `ui`, it shows its fallback and warns in development. [Surfaces](/generative-ui/components/surfaces) covers descriptions, component limits and one target per item.

The chat target is always offered to the agent, next to your named areas, even when the app has no chat. An app that shows its surfaces only through `GenerativeUISurface`, or uses the prebuilt `CopilotChat` (which does not draw surfaces yet), never shows a surface that the agent aims at the chat. Render the agent's messages with `GenerativeUIActivity` somewhere, or tell the agent in its prompt to render only into your named areas.

### Errors on the device [#errors-on-the-device]

Each component renders inside its own error boundary. A component that throws shows the `NodeFallback` of the provider's `host` (by default `NativeNodeFallback`, a small native view) with the error and a Retry button. Any thrown value is caught, also one that is not an `Error` (a string, `undefined`, `0`): the fallback and `onError` get an `Error` that describes it, with the value as its `cause`. A component whose props fail its schema shows the same host fallback with the reason, but with no Retry button, and your own `errorBoundary.fallback` is not used for it: it recovers when the props become valid: new props from the agent, or a change of the data model or app state that a bound prop reads. The rest of the surface keeps working.

A failing fallback stays in its node too. When your `errorBoundary.fallback` throws, the host's `NodeFallback`, with Retry, shows in its place; when the host's `NodeFallback` throws, that node renders nothing until the host's `NodeFallback` is tried again: when the node fails with another error, or when the agent sends new content for it. Both errors are reported to `onError`. If the surface as a whole fails, a fallback for the whole surface shows instead, with a Retry button when the `SurfaceRoot` of a custom `host` is what threw. Every one of these fallbacks goes away when the agent sends new content for the component or the surface.

To log errors, or to draw your own fallback for a component that throws, pass `errorBoundary` to the provider:

```tsx title="App.tsx"
import { Platform, Pressable, Text } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { GenerativeUIProvider } from "@copilotkit/react-native/generative-ui";
import { bankUI } from "./src/bankUI";
import { ChatScreen } from "./src/ChatScreen";

const runtimeUrl =
  Platform.OS === "android"
    ? "http://10.0.2.2:8200/api/copilotkit"
    : "http://localhost:8200/api/copilotkit";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl={runtimeUrl}>
      <GenerativeUIProvider
        ui={bankUI}
        errorBoundary={{
          onError: (info) => console.warn(info.kind, info.surfaceId, info.error.message),
          fallback: ({ retry }) => (
            <Pressable onPress={retry}>
              <Text>Try again</Text>
            </Pressable>
          ),
        }}
      >
        <ChatScreen />
      </GenerativeUIProvider>
    </CopilotKitProvider>
  );
}
```

There is no Inspector on React Native, so you see errors in these places:

- **`onError`** gets render failures, invalid props, failed events, failed functions that a component called, operations that the app rejected, and a value written through a setter that cannot be copied, such as a function (see [Keep what the user types](/generative-ui/components/state-and-actions#keep-what-the-user-types)). A render failure or invalid props that stay the same while the agent sends new content are reported once, until the node or the surface renders again; a failed event or function is reported on every call. In development each of them is also logged with `console.warn`; in a release build nothing is logged unless you pass `onError`, so send it to your crash reporter.
- **The `Wrapper` of `GenerativeUIActivity`** gets the rejected operations of a chat surface, in its `rejected` and `error` props: those that the runtime rejected and those that the app rejected. The runtime checks every operation before it streams it, so most invalid output from the model ends up here, not in `onError`. The default wrapper shows a short error line. When the app rejected the `createSurface` of a chat surface, the wrapper still renders, with `children` set to `null`.
- **The `Wrapper` of `GenerativeUISurface`** gets the same for a surface aimed at a named area, with the same props. Its default shows "Part of this UI couldn't be shown." under the surface. The exception is a rejected `createSurface`: the surface never exists, so the area keeps showing its fallback and renders no `Wrapper`. When the app rejected it, `onError` gets it, and `<GenerativeUIActivity target="<id>">` on its activity message shows it.
- **Only the model** learns of a `createSurface` that the runtime rejected, in the result of its `render_ui` call. The runtime sends no activity message for a surface it did not create (for an id that a live surface already has, it adds the rejection to that surface), so neither `Wrapper` nor `onError` gets it, in the chat or in a named area. In a named area the fallback simply stays.
- **The model** gets the error of a function that it called itself, as the result of the call. It is not passed to `onError`; in development it is logged with `console.warn`.
- **Development warnings only**: malformed activity content (the provider skips it and `GenerativeUIActivity` renders nothing), a `GenerativeUIActivity` that renders nothing for a missing provider, `ui`, `agent` or `threadId`, and a `GenerativeUISurface` under a provider without `ui` (its fallback shows). An error that `onGenerationStart` throws is logged with `console.error`. None of these reaches `onError` or a `Wrapper`, so a release build shows nothing for them: an empty row, or a fallback.

## Run lifecycle and UI [#run-lifecycle-and-ui]

A client-executed frontend tool renders its UI **mid-run**: the tool fires, your handler paints the screen, and the agent's run keeps going (further reasoning, a trailing summary). So `agent.isRunning` stays `true` past the moment the content is visible, and more so with a reasoning-tier model. Design run-gated UI for this delay:

- Tie a loading overlay strictly to `isRunning` (render nothing when it's `false`) so an errored turn can't leave it stuck on. Keep always-available controls (a home or cancel button) above the overlay so they stay tappable while the run finishes.
- If you gate a reveal animation, trigger it on the **falling edge** of `isRunning` (true → false) rather than on the content-arrived state change. Otherwise, the animation plays while the overlay is still up and the user never sees it.
- Bound the run's tail with `maxSteps` on the agent so it doesn't linger longer than needed.

## Voice and speech-to-text [#voice-and-speech-to-text]

`@copilotkit/voice` has **not** been adapted for React Native, so there's no drop-in voice hook. Voice is a bring-your-own-STT concern: capture a transcript with a React Native speech recognizer, then feed the final text through the same send-a-turn path (`agent.addMessage` + `copilotkit.runAgent`).

<Callout type="warn" title="Don't assume a platform speech recognizer exists">
  Recognizers that wrap the OS speech service (iOS `SFSpeechRecognizer` / Android `SpeechRecognizer`) can be **absent** on de-Googled or automotive hardware, where the call throws rather than degrading. If you target that kind of device, guard the unavailable case and fall back to text input, or embed an on-device recognizer (e.g. Vosk) as a guaranteed floor. Always give voice a deterministic **Send** control rather than relying on silence detection to end a turn.
</Callout>

## Proving it works [#proving-it-works]

On the web you prove an integration by opening a browser and watching the tool UI paint. There is no browser here, so that step does not translate. The substitutes each prove less than they appear to. Three checks together cover it; none of them is sufficient alone.

### 1. The runtime is reachable and its agent answers [#1-the-runtime-is-reachable-and-its-agent-answers]

```bash
npx copilotkit verify --round-trip
```

This sends one request through the runtime and reads the answer back off the thread, so it separates an agent that is *configured* from an agent that *works*, with no browser and no device involved. Run it from the machine hosting the runtime, not from the device. The CLI probes `http://localhost:3000/api/copilotkit` by default, so pass `--runtime-url http://localhost:8200/api/copilotkit` for the runtime this guide sets up, and `--agent <id>` if the runtime declares more than one.

<Callout type="warn" title="What --round-trip does not prove">
  It proves an answer came back. It never proves what the answer said, or *which* deployment answered. See [what `--round-trip` does not prove](/react-native/claude-sdk-python/cli#verify-your-setup) for the full boundary. So this is step one of three, not a green light.
</Callout>

### 2. The tool UI actually renders on the device [#2-the-tool-ui-actually-renders-on-the-device]

Boot an emulator, drive the app, and capture the screen. On Android:

```bash
adb devices                                   # confirm one booted target
adb exec-out screencap -p > proof.png         # capture the rendered screen
adb logcat -d -s ReactNativeJS:E              # no unresolved redbox
```

`adb reverse tcp:8200 tcp:8200` first if you are on a USB device, so `localhost` on the device reaches your runtime. See [Connecting from a device or bench](#connecting-from-a-device-or-bench).

There is no iOS equivalent of `adb` for this. `xcrun simctl io booted screenshot proof.png` is the closest, and it needs full Xcode, because the Command Line Tools alone do not ship `simctl`. If your environment has no emulator at all, say so rather than substituting a browser: a web screenshot proves a different application.

### 3. The answer is about your data [#3-the-answer-is-about-your-data]

The check that catches what the first two cannot. A tool-rendered card over records your app does not hold looks *identical* to a correct one: in a screenshot, in a video, and to anyone unfamiliar with your data.

So read the records your app actually holds, and confirm the answer names those and no others. If it names something else, the failure is upstream of the UI: the context was never registered (see the callout under [Which hooks are shared, and which aren't](#which-hooks-are-shared-and-which-arent)), the agent's instructions ignore it, or the screen loaded its data after the context was registered.

## Known limitations [#known-limitations]

- **Markdown in a custom UI**: the rendered chat on `@copilotkit/react-native/components` renders markdown for you (via `CopilotMarkdown`, backed by `react-native-streamdown`). If you build your own UI, a plain `Text` shows markdown as-is. Reuse `CopilotMarkdown` or bring your own renderer.
- **Inspector**: the [Inspector](/react-native/claude-sdk-python/inspector#where-inspector-runs) is a browser overlay that mounts a custom element into the DOM, so it has no React Native surface and `@copilotkit/react-native` does not ship it. The three checks under [Proving it works](#proving-it-works) cover what it would have shown you.
- **Voice**: `@copilotkit/voice` has not been adapted for React Native; wire your own STT as above.
- **Cloud provider props**: `publicApiKey` / `licenseToken` are not supported on the React Native provider; connect via `runtimeUrl`.
- **Generative UI**: experimental, tool transport only, with no standard catalog and no `theme`. The prebuilt `CopilotChat` does not draw surfaces yet. See [Generative UI with your own components](#generative-ui-with-your-own-components).
- **Web-only rendering hooks**: `useDefaultRenderTool`, `useRenderCustomMessages`, and `useRenderActivityMessage` are not exported, because they render host DOM or link the web chat-message stack. `useRenderToolCall` **is** exported; use it to draw a registered tool call outside the chat.

## Next steps [#next-steps]

- **Model selection:** provider strings, keys, and custom endpoints in [Model Selection](/model-selection)
- **Copilot Runtime:** hosting and configuring the server in [Copilot Runtime](/react-native/claude-sdk-python/backend/copilot-runtime)
- **Agents:** what the built-in agent supports in [Build with agents](/react-native/claude-sdk-python/build-with-agents)
