0
Fork 0
mirror of https://github.com/TanStack/ai.git synced 2026-11-18 19:34:58 +00:00
ai/docs/ui/react.md
Alem Tuzlak a4ab03e213
feat(ui): add typed headless createChatUI adapters (#1252)
* feat(ui): add typed headless createUI adapters

* docs(ui): document typed props, context, and interrupt placement

Teach ToolProps, RegisteredInterruptProps, and UI.useChat. Show tool approvals inline in the tool or in the interrupt list. Put registered generic interrupts under interrupts.generic next to fallback. Unbound interrupts use fallback. Check interrupt.kind when the copy must differ.

* feat(ui): pin InterruptProps and add the typed chatbot example

InterruptProps takes a tool name or a registered interrupt id. A tool approval renders in the tool when interrupts.tools omits that name. examples/ts-react-ui-chatbot shows parts, list vs in-tool approval, BYOK, and transcription.

* fix(ui): export createChatUI and type-check Vue and Svelte examples

Rename the factory to createChatUI. Register every guitar tool in the Vue and Svelte examples so defineComponents type-checks. Point the UI docs at gpt-5.6 and @tanstack/ai-svelte-ui 0.2.0.

* feat(ui): move createChatUI onto framework /ui subpaths

Chat UI now lives at @tanstack/ai-react/ui, @tanstack/ai-solid/ui,
@tanstack/ai-vue/ui, and @tanstack/ai-svelte/ui.

The published @tanstack/ai-react-ui, @tanstack/ai-solid-ui, and
@tanstack/ai-vue-ui packages re-export those subpaths until 1.0.0.
@tanstack/ai-svelte-ui was never published, so that package is gone.

* feat(ui): add createChatHook and move Chat UI onto /ui (#1275)

* feat(ui): add createChatHook and move Chat UI onto /ui (#1263)

* feat(client): add createChatHook bound useChat factory

* feat(ui): align createChatUI with Form and Table factories

* feat(ui): move chat UI onto framework /ui subpaths

Fold the *-ui packages into @tanstack/ai-react/ui, @tanstack/ai-solid/ui, @tanstack/ai-vue/ui, and @tanstack/ai-svelte/ui.

createChatHook({ options, chatComponents }) returns useAppChat (Svelte: createAppChat). useAppChat mixes AppChat onto the instance so screens render <chat.AppChat />.

* ci: apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* feat(ui): deprecate ai-*-ui packages in favor of /ui

Restore @tanstack/ai-react-ui, ai-solid-ui, ai-vue-ui, and ai-svelte-ui as
thin re-exports of the framework /ui subpath until 1.0.0.

Document createChatHook, chat.AppChat, and the import path change.

* ci: apply automated fixes

* chore(ui): drop unpublished @tanstack/ai-svelte-ui

That package never shipped on npm. Svelte chat UI lives on
@tanstack/ai-svelte/ui. Keep deprecated shims only for the
published react, solid, and vue UI packages.

* ci: apply automated fixes

* fix(ui): green up the CI suite for createChatHook

Nine tasks were failing on this branch. Fixes, in order of substance:

- `ai-vue`/`ai-solid` ship their `/ui` subpath as source (Vue SFCs and
  Solid JSX must be compiled by the consumer), so `create-ui` is
  type-checked against the *consumer's* tsconfig. Both referenced a bare
  `process`, which broke any consumer without `@types/node` (this is what
  failed `ts-vue-chat`). Declare `process` locally, matching the
  `src/env.d.ts` shape the devtools packages already use, so the literal
  `process.env.NODE_ENV` bundlers substitute stays intact and the branch
  is still constant-folded in production.
- `ts-react-ui-chatbot` imported `useChatContext` from `@/chat/ui-context`,
  which only exports the raw contexts. It comes off the factory in
  `./ui-components`, the way `layout.tsx` already imports it.
- Docs: `docs/ui/react.md`'s widget-picking snippet referenced `UI` and
  `message` that no fence defined, and `p.getWeather` for a widget the
  example factory never registered. Grouped it with the factory fence and
  registered `getWeather`/`text`, so the snippet now type-checks against
  the real API instead of only looking right.
- Docs: `docs/ui/vue.md`'s `StatusLine` and `ui` formed an inference cycle.
  Declare `StatusLine` after `ui` and annotate it; `h(StatusLine)` only
  runs at render time, so the runtime order is unchanged.
- Split the mixed value/type imports in `ai-react`/`ai-solid` `create-ui`
  and drop the inline `import()` type in the Solid test (oxlint).
- Drop devDeps the deprecation commit orphaned in the `ai-*-ui` packages,
  and alphabetize `ai-vue`'s (knip, sherif).

`pnpm test:ci` and `pnpm test:dts` both pass across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(ui): group createChatHook options and pass layout slots as components (#1282)

* feat(ui)!: hand layout and message components, not render thunks

`layout` now receives `Messages`, `Interrupts`, and `Input`; `message`
receives `Parts`. `renderMessages`, `renderInterrupts`, `renderInput`,
and `renderParts` are gone — this API ships first in this PR, so there
is nothing released to migrate.

React and Solid only. Vue and Svelte compose through slots and snippets
and already had empty `LayoutProps`.

`Messages` and `Interrupts` were already factory-closure declarations, so
passing them directly is strictly more stable than the `useCallback`
thunks they replace. `Parts` was the hard part: it closes over the
message, so the naive version builds a new component per render and
React remounts every part on each stream chunk. It now reads a
message-scoped context that `MessageView` provides, which makes it one
component for the factory's lifetime. `create-ui-stability.test.tsx`
pins that: the same `Parts` identity must survive a re-render with a new
message object.

`Input` is on the layout props only when the config registers an
`input`, so rendering one you never registered is a compile error rather
than a silent no-op. This is inferred from a `TInput` parameter on the
`input` property; a self-referential config constraint was tried first
and silently collapses to `false`.

Two inference caveats, both found by making the examples compile:

- Referencing the factory's own result inside its config
  (`UI.useChatContext()`) is circular and blocks inference. The examples
  and the e2e route now use `createChatHookContexts()`, already the
  documented cycle-breaker.
- An inline `function` expression for `input` also blocks it. Arrows and
  named references infer fine, so the examples hoist the component and
  both UI docs call the trap out.

The default falls back to a union rather than `undefined` so that when
inference does degrade, `input` stays assignable and only `Input` goes
missing — a false negative instead of a rejected config.

Two doc snippets rendered an input they never registered; the new types
caught them.

`pnpm test:ci` and `pnpm test:dts` pass across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ui): warn instead of crashing on an unregistered Input

The conditional `Input` type hides the prop when no `input` is
registered, but that inference degrades on some config shapes, and the
runtime had no component to render in that case — React threw
"Element type is invalid" on an undefined element. Always supply a
component and warn once instead, matching the existing
"Missing tools.<name> component" warning. The floor is now consistent:
you find out at build time where inference works, and on the first dev
render where it doesn't.

The inference trigger turned out to be narrower than the previous commit
claimed. It is source order, not the `function` keyword: an inline
`function` expression for `input` infers fine as long as it is listed
before `layout`. Hoisting the component out of the config bought nothing
— the config literal is evaluated once at module scope, so an inline
component is already a stable reference — so the examples and the e2e
route go back to inline named components, ordered `input` first. Both UI
docs now describe the ordering rule rather than telling people to hoist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(ui)!: split createChatHook options into named component groups

`chatComponents` is gone. Registration is now flat on the factory call,
one group per kind:

  createChatHook({
    options,
    context: { chatContext, partContext, interruptContext },
    components: { input, layout, message },
    toolsComponents: { ... },
    interruptsComponents: { tools: { ... }, generic: { ... } },
    partsComponents: { ... },
  })

`createChatUI` takes the same shape as its second argument, so both
entry points register widgets identically. All four adapters (React,
Solid, Vue, Svelte) move together. Vue and Svelte keep their flat
internal runtime shape; the new config is mapped onto it at the factory
boundary, so nothing downstream of that changes.

`partsComponents` is plural, unlike the original sketch — the registries
are `parts`/`tools`/`interrupts` and the maps hold many entries;
`PartProps` and `ChatUIPartKey` stay singular because they describe one
part.

This also removes the `Input` inference fragility rather than
documenting around it. `layout` and `input` are now siblings inside
`components`, so TypeScript resolves that inner literal as a unit and
fixes `TInput` before contextually typing `layout`. Declaration order no
longer matters and an inline `function` expression works, both of which
broke inference when these keys sat at the config's top level. The
ordering caveat is out of both UI docs, and a type test pins the case
that used to fail so a future flattening cannot regress it silently.

Per instruction, no migration guidance was added anywhere; the existing
`docs/migration/create-ui.md` page covers the older package move only
and has been updated to the new shape rather than extended.

`pnpm test:ci` and `pnpm test:dts` pass across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs: drop migration guidance for the unreleased chat UI API

`createChatHook` and `createChatUI` have never been published, so
teaching them as something to migrate to was wrong. I checked before
cutting: `@tanstack/ai-react-ui@0.8.22` (and Solid 0.7.21, Vue 0.2.40)
export only the older `Chat` / `ChatMessages` / `ChatInput` compound
components, with no `createChatHook` anywhere.

So the page keeps the one migration that is real — swapping
`@tanstack/ai-*-ui` for the framework `/ui` subpath, which those
published packages do need — and loses the Before/After, Steps, and
Gotchas sections that walked through adopting the new factory. The new
API is documented in the UI guides as a new API.

The `Chat` component's `@deprecated` notices pointed at that page for
`createChatHook` guidance, so they now point at the matching UI guide.
The `docs/api/*` pages no longer advertise the migration page as reading
for the typed chat UI. The `*-ui` shim packages still link there, which
is still exactly what that page covers.

Also brings this branch in line with repo rules I had been working
without, having only picked up the worktree's CLAUDE.md late:

- Removed the em dashes the docs skill forbids from text added here.
- Bumped `updatedAt` in `docs/config.json` for the five pages with real
  content changes. The four `docs/api/*` pages only lost a stale link,
  which the rule classes as a factual fix that must not bump.
- Rewrote the `create-chat-hook` changeset to describe the shipping
  option groups instead of the old `chatComponents` shape, and aligned
  `typed-headless-chat-ui` with the new names. Since none of this has
  released, these describe the API rather than a change to it.

`pnpm test:ci` and `pnpm test:dts` pass across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(e2e): pin the Parts subtree against remounting mid-stream

`CLAUDE.md` requires E2E coverage for a behavior change and this stack
had none. The behavior worth guarding is the reason `Parts` reads a
message-scoped context instead of closing over the message: a `Parts`
rebuilt per render makes React remount every part on each stream chunk,
throwing away local state in tool and part widgets.

The purchase tool widget on `/headless-ui` now stamps a per-mount
sequence into `data-mount-seq`, and the spec asserts it stays at 1 across
the tool-call chunks and again across the resume stream after approval.

Verified the test actually catches the regression rather than just
passing: reverting `Parts` to a per-render closure and rebuilding takes
the widget to 7 mounts, and the assertion fails on the first check.

Full suite: 638 passed, 10 failed. Both failing specs
(`multi-turn-structured` across providers, and the flaky
`durable-takeover`) fail identically on the PR base `ad5c6c28d` with none
of this stack's changes present, verified in a scratch worktree. They run
against `examples/ts-react-chat`, which uses `useChat` and never touches
the `/ui` surface. `multi-turn-structured` is a fixture-playback problem:
turn 3 receives turn 2's recipe.

`pnpm test:ci` and `pnpm test:dts` pass across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(ui): add five chat UI recipes

The framework guides open with one example that registers tools,
interrupts, structured output, input and parts at once. A reader wiring
their first chat box has to skip past all of it. These five pages each do
one thing, in order:

1. `basic-chat` — layout, message, text part. No tools.
2. `format-a-tool` — one tool, branching on `part.state`.
3. `tool-approval` — `needsApproval`, inline or in the list.
4. `custom-interrupt` — `defineInterrupt` with your own schemas.
5. `request-context` — `forwardedProps` from screen to route.

Two gaps these close: there was no starting point smaller than the full
example, and nothing documented sending per-request context from the
chat UI. `docs/advanced/runtime-context.md` covers only the server half,
so the new page shows both and says plainly that `forwardedProps` is
client-controlled and must not be trusted for identity.

React only. The Solid, Vue and Svelte guides already point at the React
page for the full map, and each now links here too.

Named `recipes`, not `examples`: `scripts/verify-links.ts` treats any
path containing `/examples/` as a directory link for the site's app
examples, so `docs/ui/examples/*.md` reported every internal link
broken.

While writing these I checked the API instead of trusting the existing
prose, and corrected two things in my own drafts: the terminal tool state
is `complete`, not `output-available`, and `ToolCallPart` has no
`errorMessage` field. I also confirmed the grouped `ToolProps` snippet is
really type-checked by breaking it on purpose and watching kiira fail.

All 1183 doc snippets typecheck. `pnpm test:ci` and `pnpm test:dts` pass
across all 86 projects.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ci: apply automated fixes

* feat(ui): add Queue layout slot and QueueProps

Layout receives a stable Queue component that maps pending sends. Each item has cancelQueued bound. Register the row with components.queue and QueueProps.

* ci: apply automated fixes

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Alem Tuzlak <t.zlak@hotmail.com>

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jack Herrington <jack.herrington@netlify.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jack Herrington <jherr@pobox.com>

* fix(sandbox): do not leave completed runs marked detached

* feat(ui): add createChatHook on Preact, Octane, and Angular /ui

* ci: apply automated fixes

* fix(angular): compile Chat UI as an ng-packagr secondary entry

ng-packagr compiled src/ui twice and crashed with referencedFiles. Move the /ui sources to ui/ next to src. Import the primary package by name. Point export types at the generated d.ts file. Type the Preact and Octane doc snippets so kiira can check them.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jack Herrington <jack.herrington@netlify.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jack Herrington <jherr@pobox.com>
2026-09-01 15:58:34 +02:00

20 KiB

title id order description keywords
React Chat UI typed-headless-ui-react 1 Build a typed, headless React chat UI with createChatHook. Your chat options control the types of tools, parts, and interrupts.
tanstack ai
createChatHook
react
headless ui
useAppChat
ToolProps

Install @tanstack/ai-react. Import the UI factory from @tanstack/ai-react/ui. Call createChatHook({ options, ...components }) once at module scope. This matches Form createFormHook and Table createTableHook: widgets register on the factory, mix onto Part / Interrupt / Input, and automatic dispatch still walks the message list.

Deprecated. Do not install @tanstack/ai-react-ui. That package re-exports this subpath until 1.0.0. See Chat UI packages.

The factory returns useAppChat and useChatContext. Call useAppChat() in the screen to create the instance. Render <chat.AppChat />. Call useChatContext() inside a mapped component when it needs live chat. That value is the instance that chat.AppChat provides.

You supply every visible component. There is no default markup, style, or copy.

The factory needs a toolsComponents entry for every tool name in chatOptions. It also needs an interruptsComponents.generic entry for every interrupt id. generic.fallback is optional.

Want a smaller starting point? The chat UI recipes build one thing at a time, from a plain chat box up to per-request context.

Server

import { chat, toServerSentEventsResponse } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'

export async function POST(request: Request) {
  const json: unknown = await request.json()
  if (typeof json !== 'object' || json === null || !('messages' in json)) {
    return new Response('Invalid body', { status: 400 })
  }
  const messages = json.messages
  const stream = chat({
    adapter: openaiText('gpt-5.6'),
    messages: Array.isArray(messages) ? messages : [],
  })
  return toServerSentEventsResponse(stream)
}

Client

import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook } from '@tanstack/ai-react/ui'
import { defineInterrupt, toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

const getWeather = toolDefinition({
  name: 'getWeather',
  description: 'Look up weather',
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({ temperature: z.number() }),
}).client()

const purchaseItem = toolDefinition({
  name: 'purchaseItem',
  description: 'Buy an item',
  needsApproval: true,
  inputSchema: z.object({ item: z.string() }),
  outputSchema: z.object({ ok: z.boolean() }),
}).client()

const choosePlan = defineInterrupt({
  id: 'choosePlan',
  payloadSchema: z.object({ title: z.string() }),
  responseSchema: z.string(),
})

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  tools: [getWeather, purchaseItem],
  interrupts: [choosePlan],
  outputSchema: z.object({ answer: z.string() }),
}

const { useAppChat, useChatContext } = createChatHook({
  options: chatOptions,
  components: {
  layout: function Layout({ Messages, Interrupts, Input, Queue }) {
    const chat = useChatContext()
    if (chat.error) return <p>{chat.error.message}</p>
    if (chat.isLoading && chat.messages.length === 0) return <p>Loading</p>
    if (chat.messages.length === 0) return <p>Empty</p>
    return (
      <main>
        <Messages />
        <Interrupts />
        <Queue />
        <Input />
      </main>
    )
  },
  message: function Message({ message, Parts }) {
    return <article data-role={message.role}><Parts /></article>
  },
  input: function Input() {
    const chat = useChatContext()
    return (
      <form
        onSubmit={(event) => {
          event.preventDefault()
          const form = event.currentTarget
          const field = form.elements.namedItem('message')
          if (!(field instanceof HTMLInputElement)) return
          void chat.sendMessage(field.value)
          field.value = ''
        }}
      >
        <input name="message" />
        <button type="submit">Send</button>
      </form>
    )
  },
  queue: function QueueItem({ item }) {
    const label = typeof item.content === 'string' ? item.content : 'Queued'
    return (
      <div>
        {label}
        <button type="button" onClick={() => item.cancelQueued()}>
          Cancel
        </button>
      </div>
    )
  },
  },
  partsComponents: {
  text: ({ part }) => <p>{part.content}</p>,
  structuredOutput: ({ part }) => <pre>{part.raw}</pre>,
  toolResult: ({ part }) => <em>{String(part.content)}</em>,
  fallback: ({ part }) => <span>{part.type}</span>,
  },
  toolsComponents: {
  getWeather: ({ part, result }) => {
    if (part.state === 'awaiting-input') return <p>Waiting</p>
    if (part.state === 'input-streaming') return <p>Streaming input</p>
    if (part.state === 'input-complete') return <p>{part.input?.city}</p>
    if (part.state === 'approval-requested') return <p>Need approval</p>
    if (part.state === 'approval-responded') return <p>Responded</p>
    if (part.state === 'error') return <p>Error</p>
    return (
      <p>
        {part.input?.city}: {String(part.output?.temperature ?? result?.content)}
      </p>
    )
  },
  purchaseItem: ({ part, interrupt }) => (
    <div>
      {part.input?.item}
      {interrupt?.status === 'pending' ? (
        <button onClick={() => interrupt.resolveInterrupt(true)}>
          Approve
        </button>
      ) : null}
    </div>
  ),
  },
  interruptsComponents: {
  generic: {
    choosePlan: ({ interrupt }) => (
      <button onClick={() => interrupt.resolveInterrupt('approved')}>
        {interrupt.payload?.title ?? 'Choose plan'}
      </button>
    ),
    fallback: ({ interrupt }) => <p>{interrupt.reason}</p>,
  },
  },
})

export function Support() {
  const chat = useAppChat({ threadId: 'support-1' })
  return <chat.AppChat />
}

export function Sidebar() {
  const chat = useAppChat({ threadId: 'sidebar' })
  return <chat.AppChat />
}

<Queue /> maps pending sends. Register queue on components. Each item has cancelQueued() bound, so you do not pass the id. Type a queue item with QueueProps<typeof chatOptions>.

layout receives Messages, Interrupts, Queue, and Input as components. Render them as <Messages />, not as calls. Input is only on the props when the config registers an input, so rendering an input you never registered is a compile error instead of a silent no-op.

List input before layout. When input is an inline function expression written after layout, TypeScript cannot yet tell that an input is registered, and Input goes missing from the layout props. Putting input first fixes it; so does using an arrow or a named reference. If it does slip through, rendering <Input /> without a registered input warns once in development rather than failing silently.

Type a component in its own file

A tool map grows fast. Move a tool into its own file and type the props with ToolProps.

ToolProps takes your chatOptions type and the tool name. Then part.input and part.output stay exact.

Part components work the same way. PartProps<typeof chatOptions, 'text'> already has a text part. You do not check part.type. Use 'structuredOutput', 'thinking', 'toolResult', and the other keys from the partsComponents map. fallback still sees every part type.

import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook, type PartProps, type ToolProps } from '@tanstack/ai-react/ui'
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

const getWeather = toolDefinition({
  name: 'getWeather',
  description: 'Look up weather',
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({ temperature: z.number() }),
}).client()

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  tools: [getWeather],
}

export function WeatherTool({
  part,
  result,
}: ToolProps<typeof chatOptions, 'getWeather'>) {
  if (part.state === 'awaiting-input') return <p>Waiting</p>
  if (part.state === 'input-streaming') return <p>Streaming input</p>
  if (part.state === 'error') return <p>Error</p>
  return (
    <p>
      {part.input?.city}: {String(part.output?.temperature ?? result?.content)}
    </p>
  )
}

export function TextPart({ part }: PartProps<typeof chatOptions, 'text'>) {
  return <p>{part.content}</p>
}

export const { useAppChat } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Messages }) => <Messages />,
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { text: TextPart, fallback: () => null },
  toolsComponents: { getWeather: WeatherTool },
})
  1. Put chatOptions in a shared module.
  2. Import ToolProps or PartProps from @tanstack/ai-react/ui.
  3. Type the component with ToolProps<typeof chatOptions, 'getWeather'> or PartProps<typeof chatOptions, 'text'>.
  4. Pass that component into tools.getWeather or parts.text.

For an interrupt, use InterruptProps. Pass a tool name or a registered interrupt id as the second type argument. Then you do not check interrupt.kind.

  • A tool approval: InterruptProps<typeof chatOptions, 'purchaseItem'>. Then interrupt.toolName is 'purchaseItem'.
  • A registered generic interrupt: InterruptProps<typeof chatOptions, 'choosePlan'>. Then interrupt.payload and interrupt.resolveInterrupt match the definition.
import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook, type InterruptProps } from '@tanstack/ai-react/ui'
import { defineInterrupt } from '@tanstack/ai'
import { z } from 'zod'

const choosePlan = defineInterrupt({
  id: 'choosePlan',
  payloadSchema: z.object({ title: z.string() }),
  responseSchema: z.string(),
})

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  interrupts: [choosePlan],
}

export function ChoosePlan({
  interrupt,
}: InterruptProps<typeof chatOptions, 'choosePlan'>) {
  return (
    <button onClick={() => interrupt.resolveInterrupt('approved')}>
      {interrupt.payload?.title ?? 'Choose plan'}
    </button>
  )
}

export const { useAppChat } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Interrupts }) => <Interrupts />,
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { fallback: () => null },
  interruptsComponents: {
    generic: {
      choosePlan: ChoosePlan,
    },
  },
})

Other prop types from the same package:

  • LayoutProps
  • MessageProps
  • InputProps
  • QueueProps for one queued send. item.cancelQueued() drops that item.
  • PartProps with a part key such as 'text'
  • InterruptProps for tool approvals, registered generic interrupts, and generic.fallback. Pass a tool name or interrupt id as the second type argument.

Read chat from useChatContext()

Mapped components do not receive chat as a prop. Call useChatContext() inside a component when it needs live chat. That call opts the component into chat re-renders. Nested children can call it too. Widgets in other files should call createChatHookContexts() first so they do not import the factory result (circular import).

import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook } from '@tanstack/ai-react/ui'

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
}

function StatusLine() {
  const chat = useChatContext()
  if (chat.error) return <p>{chat.error.message}</p>
  if (chat.isLoading) return <p>Loading</p>
  return <p>{chat.messages.length} messages</p>
}

const { useAppChat, useChatContext } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Messages }) => (
      <main>
        <StatusLine />
        <Messages />
      </main>
    ),
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { fallback: () => null },
})

export function ChatScreen() {
  const chat = useAppChat()
  return <chat.AppChat />
}

Call useChatContext() only inside AppChat or Provider. A call outside that tree throws.

useAppChat from createChatHook owns the state. useChatContext() only reads the instance that chat.AppChat provides.

When a widget lives in another file, call createChatHookContexts() first and pass chatContext, partContext, and interruptContext under context. Then that file can import useChatContext from the contexts module.

Part and interrupt widgets take part and interrupt as props. Type them with PartProps, ToolProps, or InterruptProps. Do not read those values from context.

Tool approvals: inline or list

A tool with needsApproval: true can render its approval in two places.

Inline, next to the tool

Read interrupt on the tool. Render the approval in that same component. Do not register interrupts.tools for that name. A mapped tool keeps its approval off the list.

interrupt is already the approval for that tool name. You do not check interrupt.kind.

import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook, type ToolProps } from '@tanstack/ai-react/ui'
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

const purchaseItem = toolDefinition({
  name: 'purchaseItem',
  description: 'Buy an item',
  needsApproval: true,
  inputSchema: z.object({ item: z.string() }),
  outputSchema: z.object({ ok: z.boolean() }),
}).client()

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  tools: [purchaseItem],
}

function PurchaseItem({
  part,
  interrupt,
}: ToolProps<typeof chatOptions, 'purchaseItem'>) {
  return (
    <div>
      {part.input?.item}
      {interrupt?.status === 'pending' ? (
        <button onClick={() => interrupt.resolveInterrupt(true)}>
          Approve
        </button>
      ) : null}
    </div>
  )
}

const { useAppChat } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Messages, Interrupts }) => (
      <main>
        <Messages />
        <Interrupts />
      </main>
    ),
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { fallback: () => null },
  toolsComponents: {
    purchaseItem: PurchaseItem,
  },
})

export function InlineApprovalChat() {
  const chat = useAppChat()
  return <chat.AppChat />
}

To split the approval into its own file, type it with InterruptProps<typeof chatOptions, 'purchaseItem'>. Render that component from the tool.

List, in <Interrupts />

Register the approval under interrupts.tools. That component appears in the interrupt list. Do not also render interrupt on the tool unless you want it in both places.

import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook } from '@tanstack/ai-react/ui'
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

const purchaseItem = toolDefinition({
  name: 'purchaseItem',
  description: 'Buy an item',
  needsApproval: true,
  inputSchema: z.object({ item: z.string() }),
  outputSchema: z.object({ ok: z.boolean() }),
}).client()

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  tools: [purchaseItem],
}

const { useAppChat } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Messages, Interrupts }) => (
      <main>
        <Messages />
        <Interrupts />
      </main>
    ),
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { fallback: () => null },
  toolsComponents: {
    purchaseItem: ({ part }) => <div>{part.input?.item}</div>,
  },
  interruptsComponents: {
    tools: {
      purchaseItem: ({ interrupt }) => (
        <button onClick={() => interrupt.resolveInterrupt(true)}>
          Approve
        </button>
      ),
    },
  },
})

export function ListApprovalChat() {
  const chat = useAppChat()
  return <chat.AppChat />
}

Generic interrupts

Generic interrupts always render in the list (<Interrupts /> / <UI.Interrupts>). They never render inside a tool.

Map them under interruptsComponents.generic:

  • A registered id such as choosePlan: the component for that definition
  • fallback: every other list interrupt, including an unknown generic id and an unbound interrupt this chat does not own
import { fetchServerSentEvents } from '@tanstack/ai-react'
import { createChatHook } from '@tanstack/ai-react/ui'
import { defineInterrupt } from '@tanstack/ai'
import { z } from 'zod'

const choosePlan = defineInterrupt({
  id: 'choosePlan',
  payloadSchema: z.object({ title: z.string() }),
  responseSchema: z.string(),
})

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  interrupts: [choosePlan],
}

const { useAppChat } = createChatHook({
  options: chatOptions,
  components: {
    layout: ({ Interrupts }) => <Interrupts />,
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: { fallback: () => null },
  interruptsComponents: {
    generic: {
      choosePlan: ({ interrupt }) => (
        <button onClick={() => interrupt.resolveInterrupt('approved')}>
          {interrupt.payload?.title ?? 'Choose plan'}
        </button>
      ),
      fallback: ({ interrupt }) =>
        interrupt.kind === 'unbound' ? (
          <p>Paused elsewhere: {interrupt.reason}</p>
        ) : (
          <p>{interrupt.reason}</p>
        ),
    },
  },
})

export function GenericInterruptChat() {
  const chat = useAppChat()
  return <chat.AppChat />
}

You can mix this map with interrupts.tools in the same factory call.

Manual traversal

createChatUI is the lower-level kit. Use it when you walk messages yourself. Screens still call createChatHook.

import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
import { createChatUI } from '@tanstack/ai-react/ui'
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

const getWeather = toolDefinition({
  name: 'getWeather',
  description: 'Look up weather',
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({ temperature: z.number() }),
}).client()

const chatOptions = {
  connection: fetchServerSentEvents('/api/chat'),
  tools: [getWeather],
}

const UI = createChatUI(chatOptions, {
  components: {
    layout: ({ Messages }) => <Messages />,
    message: ({ Parts }) => <article><Parts /></article>,
  },
  partsComponents: {
    text: ({ part }) => <p>{part.content}</p>,
    fallback: () => null,
  },
  toolsComponents: {
    getWeather: ({ part }) => <p>{part.input?.city}</p>,
  },
})

export function ManualChat() {
  const chat = useChat(chatOptions)
  return (
    <UI.Provider chat={chat}>
      <UI.Messages>
        {(messages) =>
          messages.map((message) => (
            <UI.Message key={message.id} message={message}>
              {(parts) =>
                parts.map((part, index) => (
                  <span key={index}>{part.key}</span>
                ))
              }
            </UI.Message>
          ))
        }
      </UI.Messages>
    </UI.Provider>
  )
}

Unknown runtime tool names warn once in development and render nothing. Add a parts.fallback for unknown part types.

Automatic dispatch is the default. You can also pick a registered widget at the call site, like Form field.TextField and Table cell.TextCell:

import type { MessageProps } from '@tanstack/ai-react/ui'

function PickedWidgets({
  message,
}: {
  message: MessageProps<typeof chatOptions>['message']
}) {
  return (
    <UI.Message message={message}>
      {(parts) =>
        parts.map((part, index) => (
          <UI.Part key={index} part={part}>
            {(p) => (part.key === 'toolCall' ? <p.getWeather /> : <p.Render />)}
          </UI.Part>
        ))
      }
    </UI.Message>
  )
}

p.getWeather and p.text are the widgets you passed to the factory. p.Render walks this one part the automatic way. UI.Input is mixed onto the kit when you register input.

If widgets live in other files, call createChatHookContexts() first and pass chatContext, partContext, and interruptContext under context. That breaks the circular import, the same way Form uses createFormHookContexts.

See also Solid, Vue, Svelte, and custom adapters.