К основному содержанию
скилл CX Codex

react-native · assistant-ui — скилл для Claude Code: чат assistant-ui в Expo

Скилл для сборки чат-интерфейсов assistant-ui в Expo и чистом React Native: нативные примитивы, рантайм AI SDK и транспорт к бэкенду.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add assistant-ui/skills --skill react-native -a claude-code
Открыть на GitHub

Что делает react-native

Скилл описывает, как собрать мобильный чат на @assistant-ui/react-native и @assistant-ui/ai-sdk. Первый пакет даёт неукрашенные примитивы, которые подключаются к рантайму, второй — рантайм AI SDK v7 и транспорт. Интерфейс собирается из View, Text, Pressable, TextInput и FlatList.

Маршрут модели живёт в отдельном бэкенд-проекте, не внутри бандла Expo. Приложение шлёт UI-сообщения через AssistantChatTransport, бэкенд асинхронно конвертирует их и возвращает поток. Эндпоинт нужен абсолютный: физическое устройство не разрешит собственный localhost в адрес вашего дев-сервера, поэтому относительный URL на телефоне просто не сработает. Адрес держат в EXPO_PUBLIC_CHAT_ENDPOINT_URL.

Внутри — быстрый старт от примера with-expo, ручная установка пакетов, композиция треда и композера, генеративные тулкиты через Metro withAui и разбор частых ошибок. MessagePrimitive.Content по умолчанию выводит текстовые части нативным Text, а не Markdown, так что для разметки от модели нужен свой рендерер. Настройку веб-версии и DOM-примитивов скилл отправляет в соседние ../setup/SKILL.md и ../primitives/SKILL.md.

Какие задачи решает

  • собрать чат-экран в Expo на нативных примитивах
  • подключить рантайм AI SDK v7 к мобильному интерфейсу
  • починить относительный URL эндпоинта, который не работает на устройстве
  • заставить Metro компилировать файлы с "use generative"
  • перенести веб-чат на iOS и Android

Примеры запросов агенту

  • Настрой чат assistant-ui в моём Expo-приложении на нативных примитивах
  • Почему относительный URL эндпоинта не работает на телефоне и как это исправить
  • Metro не компилирует генеративный тулкит — оберни конфиг через withAui

Как установить react-native

1Через Skills CLI (Vercel)

npx skills add assistant-ui/skills --skill react-native -a claude-code

2Вручную: положить файлы

~/.claude/skills/react-native/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/react-native/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора13

thread-list Скилл для assistant-ui: добавляет боковую панель с несколькими диалогами, переключением, переименованием, архивацией и удалением. CX Codex +1 6 200установок update Обновляет существующее приложение на assistant-ui до актуальных версий AI SDK v7 и assistant-ui 0.15.x, применяя нужные миграции. Пригодится, когда после апдейта посыпались ошибки типов или пропали хуки. CX Codex +1 5 900установок cloud Подключает AssistantCloud к приложению на assistant-ui: история тредов между сессиями, обратная связь по сообщениям и загрузка файлов. CX Codex +1 5 000установок react-mcp Скилл для работы с @assistant-ui/react-mcp: подключает MCP-серверы, выбранные пользователем, прямо в браузере и регистрирует их инструменты в чате. CX Codex +1 4 000установок observability Подключает Langfuse, LangSmith или Helicone к бэкенд-роутам assistant-ui на AI SDK и рисует собранные спаны через экспериментальный @assistant-ui/react-o11y. CX Codex +1 4 000установок copilots Скилл для assistant-ui: учит агента читать состояние страницы, кликать по компонентам и менять их состояние через хуки React. CX Codex +1 3 900установок generative-ui Скилл для assistant-ui: модель собирает интерфейс из готовых компонентов во время ответа, а не заполняет заранее написанный вами. CX Codex +1 1 000установок ink Скилл для сборки чат-интерфейсов прямо в терминале: связывает рантайм assistant-ui с рендерером Ink и выводит ответы как ANSI-разметку. CX Codex +1 923установок

Другие версии react-native

Похожие

setup-react-native-storybook storybookjs Скилл автоматизирует развёртывание Storybook 10 в проектах на React Native. Помогает настроить окружение для Expo, чистого React Native CLI или Re.Pack. CX Codex +1 526установок stream-react-native GetStream Скилл для работы с Stream Chat, Video и Feeds в приложениях React Native CLI и Expo: сборка, интеграция, миграции и аудит. CX Codex +1 706установок argent-react-native-app-workflow software-mansion Задаёт пошаговый процесс сборки, запуска и отладки React Native в симуляторе iOS или эмуляторе Android. Помогает поднять Metro и разобрать сбои билда. CX Codex +1 26 400установок vercel-react-native-skills vercel Набор правил по React Native и Expo для ИИ-агента: списки, анимации, навигация. Пригодится, когда агент правит мобильный код и надо, чтобы он делал это одинаково. CX Codex +1 255 200установок react-native-architecture Seth Hobson Скилл для Claude Code, Codex и Cursor: подсказывает структуру проекта, навигацию, нативные модули и офлайн-синхронизацию в React Native на Expo. CX Codex 15 087установок react-native-brownfield-migration callstackincubator Помогает пошагово внедрять React Native или Expo в нативные приложения iOS и Android с помощью @callstack/react-native-brownfield. CX Codex +1 5 200установок

Рядом в теме «Мобильная разработка»

Всё по теме «Мобильная разработка» →

Вопросы о react-native

Как установить скилл react-native в Claude?

Выполните npx skills add assistant-ui/skills --skill react-native -a claude-code. Файл скилла окажется в ~/.claude/skills/react-native/SKILL.md.

Что делает скилл react-native?

Помогает собрать чат assistant-ui в Expo или чистом React Native: нативные примитивы, рантайм и транспорт AI SDK v7, генеративные тулкиты и перенос веб-чата на мобильные платформы.

Почему эндпоинт чата должен быть абсолютным?

Физическое устройство не может разрешить собственный localhost в ваш дев-сервер. Поэтому адрес задают полным и держат в EXPO_PUBLIC_CHAT_ENDPOINT_URL.

Исходный текст

SKILL.md · MIT
---
name: react-native
description: "Build assistant-ui chat experiences for Expo and bare React Native with `@assistant-ui/react-native` and `@assistant-ui/ai-sdk`. Use when setting up an absolute mobile chat endpoint, `AssistantRuntimeProvider`, `useChatRuntime`, `AssistantChatTransport`, native `ThreadPrimitive`, `ComposerPrimitive`, `MessagePrimitive`, thread lists, attachments, React Native styles, `Metro` `withAui` for a `\"use generative\"` toolkit, local or remote thread adapters, or migrating a web chat surface to iOS and Android. Route here when a relative API URL fails on device, a native primitive lacks runtime state, `Metro` does not compile a toolkit, or web Elements are being used in a native app. Route web setup and DOM primitive work to `../setup/SKILL.md` and `../primitives/SKILL.md`."
license: MIT
---

# assistant-ui React Native

**Always consult [assistant-ui.com/llms.txt](https://www.assistant-ui.com/llms.txt) for the latest API.**

`@assistant-ui/react-native` supplies runtime-connected, unstyled React Native primitives. Use them with `View`, `Text`, `Pressable`, `TextInput`, `FlatList`, and native styles to build the chat surface. `@assistant-ui/ai-sdk` supplies the AI SDK v7 runtime and transport. The model route runs in a separate backend project, never inside the Expo bundle.

## Contents

- [References](#references) | [Quick start](#quick-start) | [Manual setup](#manual-setup) | [Native chat composition](#native-chat-composition) | [Generative toolkits](#generative-toolkits) | [Common Gotchas](#common-gotchas) | [Related Skills](#related-skills)

## References

- [./references/primitives.md](./references/primitives.md) -- native primitive namespaces and their parts
- [./references/hooks.md](./references/hooks.md) -- state, runtime, tool, and scoped-provider hooks
- [./references/adapters.md](./references/adapters.md) -- local persistence, attachments, and remote thread lists
- [./references/custom-backend.md](./references/custom-backend.md) -- a streaming model adapter and a backend-owned thread list
- [./references/migration.md](./references/migration.md) -- moving a web runtime to a native UI layer

## Quick start

Start from the maintained Expo example:

```sh
npx assistant-ui@latest create --example with-expo my-app
cd my-app
```

Set an endpoint that the app can reach. It must be an absolute URL. A physical device cannot resolve its own localhost to your development server.

```dotenv
EXPO_PUBLIC_CHAT_ENDPOINT_URL="https://api.example.com/api/chat"
```

Start Expo:

```sh
npx expo start
```

## Manual setup

Install the native runtime and its AI SDK v7 peer packages in an existing Expo app:

```sh
npx expo install @assistant-ui/react-native @assistant-ui/ai-sdk ai@^7 @ai-sdk/react@^4
```

Host the model route separately. The native app posts UI messages to that route through `AssistantChatTransport`; the route converts them asynchronously for AI SDK v7 and returns a UI message stream.

```ts
import { openai } from "@ai-sdk/openai";
import { convertToModelMessages, streamText } from "ai";

export async function POST(request: Request) {
  const { messages } = await request.json();
  const result = streamText({
    model: openai("gpt-5.6-luna"),
    messages: await convertToModelMessages(messages),
  });

  return result.toUIMessageStreamResponse();
}
```

Create the runtime in a hook. Keep the endpoint in the public Expo environment so the compiled app can reach it.

```tsx
import {
  AssistantChatTransport,
  useChatRuntime,
} from "@assistant-ui/ai-sdk";

const chatEndpoint = process.env.EXPO_PUBLIC_CHAT_ENDPOINT_URL;

export function useAppRuntime() {
  if (!chatEndpoint) {
    throw new Error("EXPO_PUBLIC_CHAT_ENDPOINT_URL is required");
  }

  return useChatRuntime({
    transport: new AssistantChatTransport({ api: chatEndpoint }),
  });
}
```

`AssistantChatTransport` forwards frontend tool schemas and system messages. When the backend enables frontend tools, consume the request tools with `frontendTools` from `@assistant-ui/ai-sdk`; see [tools](../tools/SKILL.md) for the shared backend contract.

## Native chat composition

Put the runtime under the native `AssistantRuntimeProvider`, then compose the thread and composer from primitives. `ThreadPrimitive.MessagesFlatList` is the current list primitive and scopes each row to the corresponding message.

```tsx
import {
  AssistantRuntimeProvider,
  AuiIf,
  ComposerPrimitive,
  MessagePrimitive,
  ThreadPrimitive,
  useAuiState,
} from "@assistant-ui/react-native";
import { Text, View } from "react-native";
import { useAppRuntime } from "./use-app-runtime";

function MessageRow() {
  const role = useAuiState((s) => s.message.role);

  return (
    <View
      style={{
        alignSelf: role === "user" ? "flex-end" : "flex-start",
        backgroundColor: role === "user" ? "#007aff" : "#f0f0f0",
        borderRadius: 16,
        margin: 8,
        padding: 12,
      }}
    >
      <MessagePrimitive.Content />
    </View>
  );
}

function Composer() {
  return (
    <ComposerPrimitive.Root style={{ flexDirection: "row", gap: 8, padding: 12 }}>
      <ComposerPrimitive.Input
        multiline
        placeholder="Message..."
        style={{ borderWidth: 1, borderRadius: 20, flex: 1, padding: 10 }}
      />
      <ComposerPrimitive.Send>
        <Text>Send</Text>
      </ComposerPrimitive.Send>
    </ComposerPrimitive.Root>
  );
}

function ChatScreen() {
  return (
    <ThreadPrimitive.Root style={{ flex: 1 }}>
      <AuiIf condition={(s) => s.thread.isEmpty}>
        <Text style={{ padding: 16 }}>Send a message to begin.</Text>
      </AuiIf>
      <ThreadPrimitive.MessagesFlatList autoScroll>
        {() => <MessageRow />}
      </ThreadPrimitive.MessagesFlatList>
      <Composer />
    </ThreadPrimitive.Root>
  );
}

export default function App() {
  const runtime = useAppRuntime();

  return (
    <AssistantRuntimeProvider runtime={runtime}>
      <ChatScreen />
    </AssistantRuntimeProvider>
  );
}
```

`MessagePrimitive.Content` defaults text parts to native `Text`, not Markdown. Pass `renderText` or use `MessagePrimitive.Parts` with a React Native Markdown renderer when the model returns Markdown. For native keyboard handling, place the thread in a `KeyboardAvoidingView` and tune it for the platform.

Use `useAuiState` inside primitive scopes for reactive values. Use `useAui()` with no arguments for imperative actions such as `aui.composer.send()` and `aui.thread.cancelRun()`. Keep selectors to primitives or stable references instead of constructing an object or array in the selector.

## Generative toolkits

`Metro` must compile files that start with `"use generative"`. Install `@assistant-ui/metro` and wrap the default config. Expo gets `getDefaultConfig` from `expo/metro-config`; a bare React Native app gets it from `@react-native/metro-config`.

```js
const { getDefaultConfig } = require("expo/metro-config");
const { withAui } = require("@assistant-ui/metro");

module.exports = withAui(getDefaultConfig(__dirname));
```

For a backendless toolkit, pass the `aui` option through the wrapper so frontend and human tool schemas remain uploadable:

```js
module.exports = withAui({
  ...getDefaultConfig(__dirname),
  aui: { backendless: true },
});
```

Write the toolkit against `@assistant-ui/react-native`, including native `View` and `Text` renderers. The `"use generative"` directive makes the compiler infer tool kind from `execute`. The [tools](../tools/SKILL.md) skill covers backend, frontend, human, provider, external, and stub tool semantics.

## Common Gotchas

**The mobile app posts to /api/chat and never reaches the server**

- Native apps have no browser origin for relative requests. Set `EXPO_PUBLIC_CHAT_ENDPOINT_URL` to the complete route URL.
- Use a host reachable from the simulator or physical device. Device localhost is the device itself.

**The provider is mounted but primitives throw or show no state**

- Create the runtime with `useChatRuntime` or another supported runtime hook, then pass it as `runtime={runtime}` to `AssistantRuntimeProvider`.
- Render primitives below that provider. Message, part, attachment, queue, suggestion, and thread-list-item primitives also need their corresponding parent render scope.

**A web Thread or an Elements import does not render in the Expo app**

- The shadcn Elements catalog is DOM and Tailwind based. Build the native UI with `@assistant-ui/react-native` primitives and React Native styles.

**The message list does not stay at the bottom**

- Use `ThreadPrimitive.MessagesFlatList` with `autoScroll` for new screens. `ThreadPrimitive.Messages` is retained for compatibility and defaults its auto-scroll options to false.

**Toolkits compile as ordinary modules or tool schemas never reach the model**

- Add `withAui` to `Metro` before using `"use generative"`.
- Import the identical generative module in the server build. If there is no server build, set `aui: { backendless: true }`.

**Markdown appears as literal asterisks and fences**

- `MessagePrimitive.Content` uses native `Text` by default. Supply a native Markdown renderer through `renderText`.

## Related Skills

- [setup](../setup/SKILL.md) -- `create`, `initialize`, and configure assistant-ui web projects
- [primitives](../primitives/SKILL.md) -- DOM primitives for web applications, not React Native UI
- [runtime](../runtime/SKILL.md) -- runtime behavior and backend transport concepts shared with native
- [tools](../tools/SKILL.md) -- generative toolkits, their backend route, and custom tool UI

© assistant-ui · MIT · assistant-ui/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой