# Chat

Build a chat from the AI components, with the AI SDK or TanStack AI.

This guide builds a chat in four files: the chat itself, a message, a message's reasoning and a
tool call. Replies stream in with their reasoning, tool calls and Markdown. Users can attach files,
and stop, copy or retry a reply. Each step has a version for the [AI SDK](https://ai-sdk.dev) and
one for [TanStack AI](https://tanstack.com/ai). Pick your library, and every step switches to match.

## Installation

Add the components and your AI library, then a route for the chat to send its messages to.

**AI SDK**

```bash
npx shadcn@latest add @jarvis/conversation @jarvis/message @jarvis/markdown @jarvis/citation @jarvis/trace @jarvis/tool @jarvis/prompt-input @jarvis/suggestion @jarvis/empty @jarvis/button @jarvis/copy-button
```

```bash
npm install ai @ai-sdk/react lucide-react
```

`useChat` sends the conversation to `/api/chat`. Set up that route as the
[AI SDK's docs](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot) show. The route's
`toUIMessageStreamResponse()` sends the model's reasoning by default. Pass it `sendSources: true` to
also send the sources a reply used. To have replies cite those sources, ask the model in the system
prompt to cite each one as a numbered link to its URL, such as
`[1](https://example.com/docs/rate-limits)`.

**TanStack AI**

```bash
npx shadcn@latest add @jarvis/conversation @jarvis/message @jarvis/markdown @jarvis/trace @jarvis/tool @jarvis/prompt-input @jarvis/suggestion @jarvis/empty @jarvis/button @jarvis/copy-button
```

```bash
npm install @tanstack/ai @tanstack/ai-react @tanstack/ai-anthropic lucide-react
```

`useChat` sends the conversation to `/api/chat`, where `chat()` streams the reply back, as TanStack
AI's [quick start](https://tanstack.com/ai/latest/docs/getting-started/quick-start) shows. Any
adapter works in place of Anthropic's.

```ts title="app/api/chat/route.ts"
import { chat, chatParamsFromRequest, toServerSentEventsResponse } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

import { serverTools } from "@/lib/server-tools";

export async function POST(request: Request) {
  const { messages, threadId, parentRunId, resume } = await chatParamsFromRequest(request);
  const abortController = new AbortController();

  const stream = chat({
    adapter: anthropicText("claude-opus-5-5"),
    systemPrompts: ["You are a helpful assistant."],
    messages,
    threadId,
    parentRunId,
    resume,
    tools: serverTools,
    reasoning: "medium",
    abortController,
  });

  return toServerSentEventsResponse(stream, { abortController });
}
```

`chatParamsFromRequest` reads the request that `useChat` sends. Pass its `parentRunId` and `resume`
on to `chat()` so that a reply paused for the person's approval continues once they answer.
`reasoning` asks the model to think first and streams its reasoning as `thinking` parts.
`serverTools` holds your tools' `.server()` implementations, made from the
[tool definitions](https://tanstack.com/ai/latest/docs/tools/tools) in `lib/tools.ts`. The browser
needs those definitions too.

## The chat

**AI SDK**

```tsx title="components/chat.tsx"
"use client";

import { useChat } from "@ai-sdk/react";
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
import { RefreshCwIcon } from "lucide-react";

import { ChatMessage } from "@/components/chat-message";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
  ConversationScrollButton,
} from "@/components/ui/conversation";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Message, MessageBubble, MessageContent, MessageFooter } from "@/components/ui/message";
import {
  PromptInput,
  PromptInputAttach,
  PromptInputAttachments,
  PromptInputActions,
  PromptInputSubmit,
  PromptInputTextarea,
} from "@/components/ui/prompt-input";
import { Suggestion, SuggestionGroup } from "@/components/ui/suggestion";
import { TraceLine, TraceTitle } from "@/components/ui/trace";

const prompts = ["What can you do?", "Summarize my week", "Draft a status update"];

function toFileList(files: File[]) {
  const transfer = new DataTransfer();
  for (const file of files) transfer.items.add(file);
  return transfer.files;
}

export function Chat() {
  const { messages, status, error, sendMessage, stop, regenerate, addToolApprovalResponse } =
    useChat({ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses });
  const busy = status === "submitted" || status === "streaming";

  return (
    <div className="flex h-dvh flex-col">
      <Conversation>
        <ConversationContent aria-busy={busy} className="mx-auto w-full max-w-2xl">
          {messages.length === 0 && (
            <Empty>
              <EmptyHeader>
                <EmptyTitle>How can I help?</EmptyTitle>
                <EmptyDescription>Ask a question or attach a file.</EmptyDescription>
              </EmptyHeader>
            </Empty>
          )}
          {messages.map((message, index) => {
            const last = index === messages.length - 1;
            return (
              <ConversationItem key={message.id} anchor={message.role === "user"}>
                <ChatMessage
                  message={message}
                  streaming={busy && last}
                  onApproval={(id, approved) => addToolApprovalResponse({ id, approved })}
                  onRegenerate={last && status === "ready" ? () => regenerate() : undefined}
                />
              </ConversationItem>
            );
          })}
          {status === "submitted" && (
            <ConversationItem>
              <TraceLine status="running">
                <TraceTitle>Thinking</TraceTitle>
              </TraceLine>
            </ConversationItem>
          )}
          {error && (
            <ConversationItem>
              <Message>
                <MessageContent>
                  <MessageBubble variant="destructive" role="alert">
                    The reply couldn’t be finished.
                  </MessageBubble>
                  <MessageFooter>
                    <Button variant="ghost" size="xs" onClick={() => regenerate()}>
                      <RefreshCwIcon />
                      Retry
                    </Button>
                  </MessageFooter>
                </MessageContent>
              </Message>
            </ConversationItem>
          )}
        </ConversationContent>
        <ConversationScrollButton />
      </Conversation>
      <div className="mx-auto flex w-full max-w-2xl flex-col gap-3 px-4 pt-1 pb-4">
        {messages.length === 0 && (
          <SuggestionGroup>
            {prompts.map((prompt) => (
              <Suggestion key={prompt} value={prompt} onSelect={(text) => sendMessage({ text })} />
            ))}
          </SuggestionGroup>
        )}
        <PromptInput
          status={status}
          onStop={stop}
          onSubmit={({ text, files }) => sendMessage({ text, files: toFileList(files) })}
        >
          <PromptInputAttachments accept="image/*,application/pdf" />
          <PromptInputTextarea placeholder="Ask anything…" />
          <PromptInputActions>
            <PromptInputAttach />
          </PromptInputActions>
          <PromptInputActions align="end">
            <PromptInputSubmit />
          </PromptInputActions>
        </PromptInput>
      </div>
    </div>
  );
}
```

`sendMessage` takes files either as a `FileList`, which it reads into the message for you, or as
`FileUIPart`s you've read yourself. `PromptInput` passes the attached files as an array, so
`toFileList` converts them to a `FileList`. `sendAutomaticallyWhen` resends the conversation once
the person answers a tool's approval request, so the model can continue.

**TanStack AI**

```tsx title="components/chat.tsx"
"use client";

import type { ContentPart } from "@tanstack/ai";
import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
import { RefreshCwIcon } from "lucide-react";

import { ChatMessage } from "@/components/chat-message";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
  ConversationScrollButton,
} from "@/components/ui/conversation";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Message, MessageBubble, MessageContent, MessageFooter } from "@/components/ui/message";
import {
  PromptInput,
  PromptInputAttach,
  PromptInputAttachments,
  PromptInputActions,
  PromptInputSubmit,
  PromptInputTextarea,
} from "@/components/ui/prompt-input";
import { Suggestion, SuggestionGroup } from "@/components/ui/suggestion";
import { TraceLine, TraceTitle } from "@/components/ui/trace";
import { toolDefinitions } from "@/lib/tools";

const prompts = ["What can you do?", "Summarize my week", "Draft a status update"];

function readFile(file: File) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(",")[1]);
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

async function toContent(text: string, files: File[]) {
  const content: ContentPart[] = text ? [{ type: "text", content: text }] : [];
  for (const file of files) {
    const source = { type: "data" as const, value: await readFile(file), mimeType: file.type };
    content.push({ type: file.type.startsWith("image/") ? "image" : "document", source });
  }
  return { content };
}

export function Chat({ threadId }: { threadId: string }) {
  const { messages, status, error, interrupts, sendMessage, stop, reload } = useChat({
    connection: fetchServerSentEvents("/api/chat"),
    threadId,
    tools: toolDefinitions,
  });
  const busy = status === "submitted" || status === "streaming";

  function respond(toolCallId: string, approved: boolean) {
    for (const interrupt of interrupts) {
      if (interrupt.kind === "tool-approval" && interrupt.toolCallId === toolCallId) {
        interrupt.resolveInterrupt(approved);
      }
    }
  }

  return (
    <div className="flex h-dvh flex-col">
      <Conversation>
        <ConversationContent aria-busy={busy} className="mx-auto w-full max-w-2xl">
          {messages.length === 0 && (
            <Empty>
              <EmptyHeader>
                <EmptyTitle>How can I help?</EmptyTitle>
                <EmptyDescription>Ask a question or attach a file.</EmptyDescription>
              </EmptyHeader>
            </Empty>
          )}
          {messages.map((message, index) => {
            const last = index === messages.length - 1;
            return (
              <ConversationItem key={message.id} anchor={message.role === "user"}>
                <ChatMessage
                  message={message}
                  streaming={busy && last}
                  onApproval={respond}
                  onRegenerate={last && status === "ready" ? () => reload() : undefined}
                />
              </ConversationItem>
            );
          })}
          {status === "submitted" && (
            <ConversationItem>
              <TraceLine status="running">
                <TraceTitle>Thinking</TraceTitle>
              </TraceLine>
            </ConversationItem>
          )}
          {error && (
            <ConversationItem>
              <Message>
                <MessageContent>
                  <MessageBubble variant="destructive" role="alert">
                    The reply couldn’t be finished.
                  </MessageBubble>
                  <MessageFooter>
                    <Button variant="ghost" size="xs" onClick={() => reload()}>
                      <RefreshCwIcon />
                      Retry
                    </Button>
                  </MessageFooter>
                </MessageContent>
              </Message>
            </ConversationItem>
          )}
        </ConversationContent>
        <ConversationScrollButton />
      </Conversation>
      <div className="mx-auto flex w-full max-w-2xl flex-col gap-3 px-4 pt-1 pb-4">
        {messages.length === 0 && (
          <SuggestionGroup>
            {prompts.map((prompt) => (
              <Suggestion key={prompt} value={prompt} onSelect={(text) => sendMessage(text)} />
            ))}
          </SuggestionGroup>
        )}
        <PromptInput
          status={status}
          onStop={stop}
          onSubmit={async ({ text, files }) =>
            sendMessage(files.length > 0 ? await toContent(text, files) : text)
          }
        >
          <PromptInputAttachments accept="image/*,application/pdf" />
          <PromptInputTextarea placeholder="Ask anything…" />
          <PromptInputActions>
            <PromptInputAttach />
          </PromptInputActions>
          <PromptInputActions align="end">
            <PromptInputSubmit />
          </PromptInputActions>
        </PromptInput>
      </div>
    </div>
  );
}
```

`useChat` takes a `connection` to the route and the conversation's `threadId`. `Chat` receives the
`threadId` as a prop from the page that renders it. `reload()` regenerates the last reply.

`sendMessage` takes the person's text as a string, or a message whose `content` holds their text
and files as parts. `toContent` reads each attached file as base64 into an image part, or into a
document part for a PDF.

A tool call that needs approval pauses the reply with an interrupt. `respond` resolves the interrupt
for the call the person answered, and the reply continues once every interrupt is resolved.
`useChat` only accepts answers for tools it knows about, so pass it `toolDefinitions` from
`lib/tools.ts`: the definitions of the tools the route implements.

Each message is a `ConversationItem`. The person's messages are `anchor`s that mark where each turn
starts, so a new question settles near the top and its reply fills in below it.
`ConversationContent` stays `aria-busy` while a reply arrives, so screen readers read the reply once
it's done rather than paragraph by paragraph. Not every screen reader waits for `aria-busy`, so
[Conversation's usage](https://ui.jarv.is/components/conversation.md) also announces the finished reply in a
status region.

`status` drives the rest of the chat, and both libraries use the same status names.
[`PromptInput`](https://ui.jarv.is/components/prompt-input.md) takes `status` as is and turns its submit button into a
stop button while a reply arrives. While `status` is `submitted`, before the reply's first part
arrives, a "Thinking" [`TraceLine`](https://ui.jarv.is/components/trace.md) holds the reply's place. While the chat is
busy, the last message is the one being written, so it's marked `streaming`. Only the last reply
can be regenerated, and only once the chat is `ready` again. If a reply fails, `error` is set, and
an error message offers to regenerate the reply.

## Messages

**AI SDK**

```tsx title="components/chat-message.tsx"
"use client";

import {
  isFileUIPart,
  isReasoningUIPart,
  isTextUIPart,
  isToolUIPart,
  type DynamicToolUIPart,
  type ReasoningUIPart,
  type SourceUrlUIPart,
  type TextUIPart,
  type ToolUIPart,
  type UIMessage,
} from "ai";
import { RefreshCwIcon } from "lucide-react";
import * as React from "react";

import { Reasoning } from "@/components/reasoning";
import { ToolCall } from "@/components/tool-call";
import { Button } from "@/components/ui/button";
import {
  Citation,
  CitationContent,
  CitationSource,
  CitationTitle,
  CitationTrigger,
} from "@/components/ui/citation";
import { CopyButton } from "@/components/ui/copy-button";
import { Markdown, MarkdownLink, type MarkdownComponents } from "@/components/ui/markdown";
import { Message, MessageBubble, MessageContent, MessageFooter } from "@/components/ui/message";
import { Trace } from "@/components/ui/trace";

type Step = ReasoningUIPart | ToolUIPart | DynamicToolUIPart;

const SourcesContext = React.createContext<SourceUrlUIPart[]>([]);

function Link(props: React.ComponentProps<"a">) {
  const source = React.useContext(SourcesContext).find((source) => source.url === props.href);
  if (!source) return <MarkdownLink {...props} />;

  const site = new URL(source.url).hostname;
  return (
    <Citation>
      <CitationTrigger href={source.url} aria-label={source.title ?? site}>
        {props.children}
      </CitationTrigger>
      <CitationContent>
        <CitationSource>{site}</CitationSource>
        {source.title && <CitationTitle>{source.title}</CitationTitle>}
      </CitationContent>
    </Citation>
  );
}

const components: MarkdownComponents = { a: Link };

export function ChatMessage({
  message,
  streaming,
  onApproval,
  onRegenerate,
}: {
  message: UIMessage;
  streaming: boolean;
  onApproval: (id: string, approved: boolean) => unknown;
  onRegenerate?: () => unknown;
}) {
  if (message.role === "user") {
    return (
      <Message align="end">
        <MessageContent>
          {message.parts.map((part, index) =>
            isTextUIPart(part) ? (
              <MessageBubble key={index}>{part.text}</MessageBubble>
            ) : isFileUIPart(part) ? (
              <MessageBubble key={index} variant="outline">
                {part.filename ?? "Attachment"}
              </MessageBubble>
            ) : null,
          )}
        </MessageContent>
      </Message>
    );
  }

  const groups: (TextUIPart | Step[])[] = [];
  for (const part of message.parts) {
    const last = groups.at(-1);
    if (isTextUIPart(part)) groups.push(part);
    else if (!isReasoningUIPart(part) && !isToolUIPart(part)) continue;
    else if (Array.isArray(last)) last.push(part);
    else groups.push([part]);
  }

  const sources = message.parts.filter(
    (part): part is SourceUrlUIPart => part.type === "source-url",
  );
  const text = message.parts
    .filter(isTextUIPart)
    .map((part) => part.text)
    .join("\n\n");

  return (
    <Message>
      <MessageContent className="gap-3">
        <SourcesContext value={sources}>
          {groups.map((group, index) =>
            Array.isArray(group) ? (
              <Trace key={index}>
                {group.map((part, step) =>
                  isReasoningUIPart(part) ? (
                    <Reasoning key={step} text={part.text} streaming={part.state === "streaming"} />
                  ) : (
                    <ToolCall key={part.toolCallId} part={part} onApproval={onApproval} />
                  ),
                )}
              </Trace>
            ) : (
              <Markdown key={index} streaming={group.state === "streaming"} components={components}>
                {group.text}
              </Markdown>
            ),
          )}
        </SourcesContext>
        {!streaming && text && (
          <MessageFooter>
            <CopyButton value={text} size="icon-xs" aria-label="Copy reply" />
            {onRegenerate && (
              <Button variant="ghost" size="icon-xs" aria-label="Regenerate" onClick={onRegenerate}>
                <RefreshCwIcon />
              </Button>
            )}
          </MessageFooter>
        )}
      </MessageContent>
    </Message>
  );
}
```

The AI SDK starts each step with a `step-start` part and sends sources as separate parts. The loop
skips every part that's neither text nor a step, so these parts don't split a run of steps. Text
renders as [`Markdown`](https://ui.jarv.is/components/markdown.md), which streams while the part's `state` is
`streaming`.

`Link` turns a reply's numbered links into [citations](https://ui.jarv.is/components/citation.md). It looks up
each link among the message's `source-url` parts, which `SourcesContext` passes down. Links that
aren't sources render as `Markdown`'s own `MarkdownLink`. `components` is defined once, outside the
component, since `Markdown` renders the whole reply again whenever it receives a new `components`
object.

**TanStack AI**

```tsx title="components/chat-message.tsx"
"use client";

import type { UIMessage } from "@tanstack/ai-react";
import { RefreshCwIcon } from "lucide-react";

import { Reasoning } from "@/components/reasoning";
import { ToolCall } from "@/components/tool-call";
import { Button } from "@/components/ui/button";
import { CopyButton } from "@/components/ui/copy-button";
import { Markdown } from "@/components/ui/markdown";
import { Message, MessageBubble, MessageContent, MessageFooter } from "@/components/ui/message";
import { Trace } from "@/components/ui/trace";

type Part = UIMessage["parts"][number];
type TextPart = Extract<Part, { type: "text" }>;
type Step = Extract<Part, { type: "thinking" | "tool-call" }>;
type ToolResultPart = Extract<Part, { type: "tool-result" }>;

export function ChatMessage({
  message,
  streaming,
  onApproval,
  onRegenerate,
}: {
  message: UIMessage;
  streaming: boolean;
  onApproval: (toolCallId: string, approved: boolean) => unknown;
  onRegenerate?: () => unknown;
}) {
  if (message.role === "user") {
    return (
      <Message align="end">
        <MessageContent>
          {message.parts.map((part, index) =>
            part.type === "text" ? (
              <MessageBubble key={index}>{part.content}</MessageBubble>
            ) : part.type === "image" || part.type === "document" ? (
              <MessageBubble key={index} variant="outline">
                {part.type === "image" ? "Image" : "Document"}
              </MessageBubble>
            ) : null,
          )}
        </MessageContent>
      </Message>
    );
  }

  const groups: (TextPart | Step[])[] = [];
  const results = new Map<string, ToolResultPart>();
  for (const part of message.parts) {
    const last = groups.at(-1);
    if (part.type === "tool-result") results.set(part.toolCallId, part);
    else if (part.type === "text") groups.push(part);
    else if (part.type !== "thinking" && part.type !== "tool-call") continue;
    else if (Array.isArray(last)) last.push(part);
    else groups.push([part]);
  }

  const current = streaming ? message.parts.at(-1) : undefined;
  const text = message.parts
    .filter((part) => part.type === "text")
    .map((part) => part.content)
    .join("\n\n");

  return (
    <Message>
      <MessageContent className="gap-3">
        {groups.map((group, index) =>
          Array.isArray(group) ? (
            <Trace key={index}>
              {group.map((part, step) =>
                part.type === "thinking" ? (
                  <Reasoning key={step} text={part.content} streaming={part === current} />
                ) : (
                  <ToolCall
                    key={part.id}
                    part={part}
                    result={results.get(part.id)}
                    onApproval={onApproval}
                  />
                ),
              )}
            </Trace>
          ) : (
            <Markdown key={index} streaming={group === current}>
              {group.content}
            </Markdown>
          ),
        )}
        {!streaming && text && (
          <MessageFooter>
            <CopyButton value={text} size="icon-xs" aria-label="Copy reply" />
            {onRegenerate && (
              <Button variant="ghost" size="icon-xs" aria-label="Regenerate" onClick={onRegenerate}>
                <RefreshCwIcon />
              </Button>
            )}
          </MessageFooter>
        )}
      </MessageContent>
    </Message>
  );
}
```

Text and thinking parts hold their text in `content` and have no `state` of their own. A part
streams while it's `current`: the last part of the message being written. Each tool call's result
arrives as a `tool-result` part after the call. The loop stores the result by its call's ID for
`ToolCall`, instead of letting it split a run of steps. File parts don't carry a file name, so the
person's message labels them by kind.

TanStack AI doesn't send the sources a reply used, so the reply's links stay plain links. To cite
sources, return them from the tool that finds them and look up the links in that tool's output, as
the AI SDK version does with its `source-url` parts.

The person's text goes in a [Message](https://ui.jarv.is/components/message.md) bubble, and each of their files in an
outlined bubble. A reply's reasoning and tool calls are steps. Consecutive steps share a
[`Trace`](https://ui.jarv.is/components/trace.md) above the text they lead to, and only text ends a run of steps.

Once a reply is done, its footer has a [Copy Button](https://ui.jarv.is/components/copy-button.md) for its text, and a
button to regenerate the reply when `Chat` passes `onRegenerate`.

## Reasoning

Copy the `Reasoning` component into `components/reasoning.tsx`. Its code is below the example in
[Trace's Reasoning section](https://ui.jarv.is/components/trace.md).

## Tool calls

**AI SDK**

```tsx title="components/tool-call.tsx"
"use client";

import { getToolName, type DynamicToolUIPart, type ToolUIPart } from "ai";
import { WrenchIcon } from "lucide-react";

import {
  Tool,
  ToolApproval,
  ToolContent,
  ToolError,
  ToolIcon,
  ToolInput,
  ToolOutput,
  ToolTitle,
  ToolTrigger,
  type ToolState,
} from "@/components/ui/tool";

type ToolPart = ToolUIPart | DynamicToolUIPart;

function toolState(part: ToolPart): ToolState {
  switch (part.state) {
    case "input-streaming":
      return "pending";
    case "input-available":
      return "running";
    case "approval-requested":
      return part.approval.isAutomatic ? "running" : "approval-requested";
    case "approval-responded":
      return part.approval.approved ? "running" : "denied";
    case "output-available":
      return "done";
    case "output-error":
      return "error";
    case "output-denied":
      return "denied";
  }
}

export function ToolCall({
  part,
  onApproval,
}: {
  part: ToolPart;
  onApproval: (id: string, approved: boolean) => unknown;
}) {
  const name = getToolName(part);

  return (
    <Tool state={toolState(part)}>
      <ToolTrigger>
        <ToolIcon>
          <WrenchIcon />
        </ToolIcon>
        <ToolTitle>{part.title ?? name}</ToolTitle>
      </ToolTrigger>
      <ToolContent>
        <ToolInput value={part.input} />
        {part.state === "output-available" && <ToolOutput value={part.output} />}
        {part.state === "output-error" && <ToolError>{part.errorText}</ToolError>}
      </ToolContent>
      {part.state === "approval-requested" && (
        <ToolApproval
          onApprove={() => onApproval(part.approval.id, true)}
          onDeny={() => onApproval(part.approval.id, false)}
        >
          Allow {name} to run?
        </ToolApproval>
      )}
    </Tool>
  );
}
```

`toolState` maps the AI SDK's tool states onto [Tool's](https://ui.jarv.is/components/tool.md). A
call the AI SDK approves automatically shows as running, and a denied call shows as denied.
`ToolApproval` shows only while the call is waiting for the person's answer.
`addToolApprovalResponse` also takes a `reason` to tell the model why a call was denied.

**TanStack AI**

```tsx title="components/tool-call.tsx"
"use client";

import { parsePartialJSON, type UIMessage } from "@tanstack/ai-react";
import { WrenchIcon } from "lucide-react";

import {
  Tool,
  ToolApproval,
  ToolContent,
  ToolError,
  ToolIcon,
  ToolInput,
  ToolOutput,
  ToolTitle,
  ToolTrigger,
  type ToolState,
} from "@/components/ui/tool";

type Part = UIMessage["parts"][number];
type ToolCallPart = Extract<Part, { type: "tool-call" }>;
type ToolResultPart = Extract<Part, { type: "tool-result" }>;

function toolState(part: ToolCallPart, result?: ToolResultPart): ToolState {
  switch (part.state) {
    case "awaiting-input":
    case "input-streaming":
      return "pending";
    case "input-complete":
      return "running";
    case "approval-requested":
      return "approval-requested";
    case "approval-responded":
      return part.approval?.approved ? "running" : "denied";
    case "complete":
      return "done";
    case "error":
      return result?.outcome ? "denied" : "error";
  }
}

export function ToolCall({
  part,
  result,
  onApproval,
}: {
  part: ToolCallPart;
  result?: ToolResultPart;
  onApproval: (toolCallId: string, approved: boolean) => unknown;
}) {
  const state = toolState(part, result);

  return (
    <Tool state={state}>
      <ToolTrigger>
        <ToolIcon>
          <WrenchIcon />
        </ToolIcon>
        <ToolTitle>{part.name}</ToolTitle>
      </ToolTrigger>
      <ToolContent>
        <ToolInput value={part.input ?? parsePartialJSON(part.arguments)} />
        {state === "done" && <ToolOutput value={part.output} />}
        {state === "error" && <ToolError>{result?.error}</ToolError>}
      </ToolContent>
      {state === "approval-requested" && (
        <ToolApproval
          onApprove={() => onApproval(part.id, true)}
          onDeny={() => onApproval(part.id, false)}
        >
          Allow {part.name} to run?
        </ToolApproval>
      )}
    </Tool>
  );
}
```

`toolState` maps TanStack AI's tool states onto [Tool's](https://ui.jarv.is/components/tool.md). A
call ends in `error` when it fails, and also when the person denies or stops it. In those two cases
the result has an `outcome` of `denied` or `cancelled`, so a result with an `outcome` shows as
denied. A call has its `input` only once the input is complete, so until then `parsePartialJSON`
parses the part of `arguments` that has arrived. `ToolApproval` shows only while the call is waiting
for the person's answer.

Here the title is the tool's name. Where you can, write your own title for each tool and state,
such as "Ran pnpm build" or "Searched the docs", since screen readers don't announce the line's
color and motion.
