# TanStack AI

Connect a TanStack AI chat and handle native tool approvals.

## Connect TanStack AI

[Install Ghost UI and its view dependencies](/libraries/ai#installation), then add the matched TanStack v1 packages.

```bash
npm install @tanstack/ai@1.4.0 @tanstack/ai-client@1.1.0 @tanstack/ai-react@1.0.2
```

Pass your HTTP or AG-UI ConnectionAdapter to the example. TanStack uses it to send requests, receive the stream, and handle cancellation.

```tsx
import { useChat } from "@tanstack/ai-react";
import type { ConnectionAdapter } from "@tanstack/ai-client";
import { createTanStackAdapter } from "@collectivecreation/ghost-ui/chat-adapter-tanstack";
import { useChatAdapter } from "@collectivecreation/ghost-ui/chat-runtime-react";
import { Button } from "@collectivecreation/ghost-ui/components/button";
import { Message, MessageBody } from "@collectivecreation/ghost-ui/components/message";
import { MessageParts } from "@collectivecreation/ghost-ui/components/message-parts";
const adapter = createTanStackAdapter();
export function TanStackConversation({ connection }: { connection: ConnectionAdapter }) {
  const chat = useChat({ connection, threadId: "brief" });
  const runtime = useChatAdapter(adapter, chat, { identity: { threadId: "brief", revision: 0 } });
  const { messages, controller } = runtime;
  return <section aria-label="Conversation">
    {messages.map(message => <Message key={message.id} actor={message.actor} aria-label={message.actor}><MessageBody>
      <MessageParts parts={message.parts} />
    </MessageBody></Message>)}
    <Button type="button" disabled={runtime.capabilities.send.support !== "supported" || !runtime.capabilities.send.available}
      onClick={() => void controller.send({ text: "Summarize the brief", attachments: [] })}>Summarize</Button>
    {controller.status === "streaming" && <Button type="button" onClick={() => void controller.stop?.()}>Stop</Button>}
    {controller.error && <p role="alert">Could not complete the request.</p>}
  </section>;
}

```

## Commands and extension points

Keep messages and transport in TanStack’s hook. The adapter connects send, stop, and regeneration of the latest answer. Provide setMessages for local edit and resend. Editing truncates local history before resending, so reconcile saved history and failed resends in your app.

Supply the adapter's normalization options for deliberate part mappings and reasoning summaries. Supply runtime availability to disable actions for application policy. Attachments need the explicit outbound converter described in [runtime integration](/libraries/ai-runtime#attachments); unsupported files are rejected rather than dropped.

## Approve a native interrupt

Register the same tool definitions on client and server. For tools with a yes/no approval and no extra response fields, pass the native hook into this view. bindApproval({ interrupt, getCurrent }) checks the current interrupt ID, tool call, thread, interrupted run, generation, lifecycle and expiry before calling its native resolveInterrupt(approved). Keep a live getter; a saved handle cannot authorize a replacement run.

```tsx
import { useRef } from "react";
import type { UseChatReturn } from "@tanstack/ai-react";
import { createTanStackAdapter, type TanStackChat } from "@collectivecreation/ghost-ui/chat-adapter-tanstack";
import { ToolApproval } from "@collectivecreation/ghost-ui/components/tool";

const adapter = createTanStackAdapter();
export function TanStackApprovals({ chat }: { chat: Pick<TanStackChat, "interrupts" | "resuming"> & Pick<UseChatReturn, "interruptErrors"> }) {
  const current = useRef(chat);
  current.current = chat;
  return <section aria-label="Pending decisions">
    {chat.interrupts.map(interrupt => {
      if (interrupt.kind !== "tool-approval") {
        return <p key={interrupt.id}>{interrupt.message ?? interrupt.reason}</p>;
      }
      const decide = adapter.bindApproval({ interrupt, getCurrent: () => current.current });
      return <ToolApproval key={`${interrupt.threadId}:${interrupt.interruptedRunId}:${interrupt.generation}:${interrupt.id}`}
        approvalId={interrupt.id} prompt={interrupt.message ?? `Allow ${interrupt.toolName}?`}
        disabled={!interrupt.canResolve || chat.resuming || interrupt.status !== "pending" || interrupt.errors.length > 0}
        onApprove={() => decide(true)} onDeny={() => decide(false)}>
        {interrupt.status === "staged" && <p role="status">Decision recorded. Waiting for the other items.</p>}
        {interrupt.errors.map((error, index) => <p key={index} role="alert">{error.message}</p>)}
      </ToolApproval>;
    })}
    {chat.interruptErrors.map((error, index) => <p key={index} role="alert">{error.message}</p>)}
  </section>;
}

```

A decision can wait while other items in the batch are unanswered. The last valid decision submits the batch. Wait for the execution result before showing success. Use resolveInterrupt(false) to deny a tool and cancel() to cancel the item without a decision.

Use TanStack’s resolveInterrupts, clearResolution, retryInterrupts, and typed forms for batch review, recovery, or extra fields. Ghost’s boolean binding rejects required payloads and unknown decision schemas. Handle generic and unbound pauses in your app. Keep native errors visible when there’s no actionable item.

See the [interactive native example](/ai-elements/activity#tanstack), [native approval forms](https://tanstack.com/ai/latest/docs/interrupts/tool-approval) and [batch lifecycle](https://tanstack.com/ai/latest/docs/interrupts/multiple).

## Upgrade from TanStack 0.x

Upgrade the server and client together to the checked v1 versions. Replace the old Ghost binding { approvalId, addToolApprovalResponse, getCurrent } with { interrupt, getCurrent }, where interrupt is the matching bound tool-approval item from chat.interrupts. The new getter returns the current native interrupts and resuming values. A full-hook useChatAdapter(adapter, chat, options) binding supplies these directly; hand-picked bindings must include both to expose the shared approval command.

Forward parentRunId and resume on the server. Finish or discard 0.x pauses before upgrading because v1 uses a different wire format. Keep your previous app source, tool definitions, and lockfile together for rollback. The examples previously used @tanstack/ai@0.54.0, @tanstack/ai-client@0.31.1, and @tanstack/ai-react@0.24.1. See [TanStack’s v1 migration guide](https://tanstack.com/ai/latest/docs/interrupts/migration) for server changes and [Migrate AI views](/libraries/ai-migration) for UI changes.

## Troubleshooting and native APIs

A missing answer usually indicates a protocol/transport mismatch. Inspect native errors first, then capability support/availability. Keep one hook owner per context and advance the [identity revision](/libraries/ai-threads) on replacement. Retain the native hook for capabilities whose semantics are richer than a generic message command.

[TanStack AI documentation](https://tanstack.com/ai/latest/docs) covers connection adapters, client tools and state. The AG-UI connection is optional; [direct AG-UI](/libraries/ai-runtime-ag-ui) preserves an existing HttpAgent client.

## AG-UI through a TanStack connection

Keep this route when TanStack already owns your chat client. Supply your authenticated endpoint and real thread ID. The connection decodes AG-UI through TanStack; it does not adopt a second native AG-UI client. For an existing HttpAgent and its shared state, choose the [direct client](/libraries/ai-runtime-ag-ui).

```tsx
import { useMemo, useState } from "react";
import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
import { createTanStackAdapter } from "@collectivecreation/ghost-ui/chat-adapter-tanstack";
import { useChatAdapter } from "@collectivecreation/ghost-ui/chat-runtime-react";
import { Message, MessageBody } from "@collectivecreation/ghost-ui/components/message";
import { MessageParts } from "@collectivecreation/ghost-ui/components/message-parts";
import { Button } from "@collectivecreation/ghost-ui/components/button";

const adapter = createTanStackAdapter();
type Props = { endpoint: string; threadId: string; revision: number; fetchClient?: typeof fetch };
export function AgUiConversation({ endpoint, threadId, revision, fetchClient }: Props) {
  const connection = useMemo(() => fetchServerSentEvents(endpoint, { fetchClient }), [endpoint, fetchClient]);
  const chat = useChat({ connection, threadId });
  const [commandError, setCommandError] = useState<string>();
  const runtime = useChatAdapter(adapter, {
    messages: chat.messages, status: chat.status, error: chat.error,
    sendMessage: chat.sendMessage, stop: chat.stop,
  }, { identity: { threadId, revision } });
  const { messages, controller } = runtime;
  async function send() {
    setCommandError(undefined);
    try { await controller.send({ text: "Summarize the brief", attachments: [] }); }
    catch { setCommandError("Could not send the request."); }
  }
  return <section aria-label="Conversation">
    {messages.map(message => <Message key={message.id} actor={message.actor}><MessageBody>
      <MessageParts parts={message.parts} />
    </MessageBody></Message>)}
    <Button disabled={runtime.capabilities.send.support !== "supported" || !runtime.capabilities.send.available}
      onClick={() => void send()}>Summarize</Button>
    {(controller.status === "submitting" || controller.status === "streaming") && <Button onClick={() => void controller.stop?.()}>Stop</Button>}
    {(commandError || controller.error) && <p role="alert">{commandError || "Could not complete the request."}</p>}
  </section>;
}

```
