Appearance
AIChat
AIChat owns the frame for an assistant UI and places its three regions in a fixed order, the way Layout places Layout.Header and Layout.Column: AIChat.Header (optional) over AIChat.Conversation (required) over AIChat.Composer (optional). Each region carries its own props; the root carries only the chat's status. You compose the transcript inside AIChat.Conversation from the attached parts — AIChat.Message, AIChat.Response, AIChat.Reasoning, AIChat.Tool, AIChat.Sources, and more — against your own useAIChat() state.
It renders no border or background of its own. Wrap it in Card, Sheet, or a Layout.Column for the surrounding surface.
Import
tsx
import { AIChat, useAIChat, createAIGatewayClient } from "@tailor-platform/app-shell";The additional runnable examples also import useState from react, and Button, Card, Select, Text, and type ToolState from @tailor-platform/app-shell. Their icons (ChevronsRightIcon, CopyIcon, EraserIcon, HistoryIcon, RotateCcwIcon, SparklesIcon, and ThumbsUpIcon) come from lucide-react.
Basic usage
This example uses the real useAIChat() hook with a local AIGatewayClient fixture. Send a message to see the waiting state, a streamed reply, and the Stop control. Replies are predefined chunks with a short delay, not model output; no prompts leave your browser and no authentication or API key is needed.
The example also imports useState from react, and Card, Text, and type AIGatewayClient from @tailor-platform/app-shell. Its fixed-height card keeps the transcript scrollable while the header and composer stay in place.
tsx
function BasicUsage() {
const [client] = useState<AIGatewayClient>(() => ({
async *streamChatCompletion({ signal }) {
const chunks = [
"This is a **local demo response**.",
"\n\n",
"The real `useAIChat()` hook ",
"manages this conversation ",
"and receives these chunks ",
"from an in-memory client.",
"\n\n",
"No prompt is sent to a server. ",
"Send another message, ",
"or press **Stop** while the response is streaming.",
];
for (const text of chunks) {
if (signal?.aborted) return;
// Delay fixture chunks so streaming and Stop can be tried without a server.
await new Promise<void>((resolve) => setTimeout(resolve, 180));
if (signal?.aborted) return;
yield { type: "text-delta", text };
}
yield { type: "done" };
},
}));
const { messages, status, error, sendMessage, stop } = useAIChat({ client, model: "demo" });
return (
<div className="flex flex-col gap-3">
{error && <Text.p role="alert">{error.message}</Text.p>}
<Card.Root className="flex h-96 flex-col overflow-hidden">
<AIChat status={status}>
<AIChat.Header title="Assistant" />
<AIChat.Conversation>
{messages.length === 0 ? (
<AIChat.EmptyState
title="Try the assistant"
description="Replies are simulated locally. Send a message, then try Stop."
/>
) : (
messages.map((message) => (
<AIChat.Message key={message.id} from={message.role}>
<AIChat.Response>{message.content}</AIChat.Response>
</AIChat.Message>
))
)}
</AIChat.Conversation>
<AIChat.Composer onSubmit={sendMessage} onStop={stop} />
</AIChat>
</Card.Root>
</div>
);
}Connecting to AI Gateway
For real responses, replace the local client with createAIGatewayClient configured using your application's gateway URI and authenticated client, and select an available model. For example, inside your component, import useMemo from react and use:
tsx
const client = useMemo(
() => createAIGatewayClient({ gatewayUri, authClient }),
[gatewayUri, authClient],
);
const { messages, status, error, sendMessage, stop } = useAIChat({ client, model: "gpt-5" });message.role ("user" | "assistant") from useAIChat lines up directly with AIChat.Message's from prop — no mapping step. AIChat streams for real when the AI Gateway sends real SSE chunks; there is no client-side typewriter effect.
The regions can appear in any source order — the root always renders Header, then Conversation, then Composer. Omit AIChat.Composer for a read-only transcript.
They must be direct children. The root matches them by component identity, so a region wrapped in one of your own components — const AppComposer = () => <AIChat.Composer … /> — is not recognised, and is dropped with a console warning like any other unexpected child. To preset props, export the props instead of the element: <AIChat.Composer {...appComposerProps} />.
Props
AIChat
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | required | AIChat.Header, AIChat.Conversation, and AIChat.Composer, in any order. |
status | "ready" | "submitted" | "streaming" | "error" | "ready" | The chat's state. Plugs directly into useAIChat()'s status; AIChat.Composer reads it. |
className | string | - | Merged onto the root. It already fills a block parent (h-full) or a flex-column parent (flex-1). |
Other props spread onto the root <div>.
AIChat.Header
| Prop | Type | Default | Description |
|---|---|---|---|
title | ReactNode | - | Title text. |
icon | ReactNode | sparkle | Leading graphic. Pass null for none, or a control (e.g. a collapse button) for a docked panel. |
actions | ReactNode | - | Right-aligned slot — compose it from AIChat.Action. |
className | string | - |
AIChat.Conversation
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | required | The transcript. Composed from the attached parts, or AIChat.EmptyState while empty. |
autoScroll | boolean | true | Follow content growth while the reader is pinned to the bottom. |
className | string | - |
Other props spread onto the region's outer <div>.
While the root's status is "submitted", the conversation automatically appends a Spinner and localized “Thinking…” status at the end. This covers the initial reply wait, tool execution, and the next reply wait after a tool result. The indicator disappears when text starts streaming, or when the request finishes, fails, or is stopped. It participates in the conversation's normal auto-scroll behavior; no separate loader state is needed.
AIChat.ToolCall
A compact label for one model-requested tool call. Each label occupies its own row, so multiple calls stack vertically. It does not imply execution success, render tool arguments/results, or manage history.
| Prop | Type | Default | Description |
|---|---|---|---|
call | { id: string; name: string } | required | A toolCalls element returned by useAIChat(). |
className | string | - | Merged onto the outer row, not the badge. |
AIChat.Composer
| Prop | Type | Default | Description |
|---|---|---|---|
onSubmit | (message: string) => void | required | Called with the trimmed prompt. |
onStop | () => void | - | Called from the Stop button while the chat is busy. Omit for a plain busy state. |
value | string | - | Controlled draft. Cleared via onValueChange("") after a successful submit. |
defaultValue | string | "" | Uncontrolled draft's initial value. |
onValueChange | (value: string) => void | - | Called on every draft change, including the post-submit clear. |
placeholder | string | - | |
disabled | boolean | false | Disables the composer — not the transcript above it. |
submitOnEnter | boolean | true | Enter submits (IME-safe); Shift+Enter always inserts a newline. |
actions | ReactNode | - | Open slot on the action row — a visibility toggle, a model picker, a select. |
className | string | - |
Prop pass-through
Most props stay inside their region. These AIChat.Composer props land on another AppShell component, so they carry that component's contract — and any future change to it — rather than one AIChat defines:
| Prop | Reaches | Note |
|---|---|---|
value | Textarea value | The composer body is a real Textarea. |
placeholder | Textarea placeholder | |
disabled | Textarea and the attach Button | One prop, two components. |
onStop | Button onClick | Becomes the Stop button's handler. |
onValueChange is wrapped rather than forwarded — it is called from the Textarea's onChange, and again with "" after a submit. defaultValue seeds the composer's own state and is never forwarded. Nothing on AIChat, AIChat.Header, or AIChat.Conversation reaches another AppShell component.
Four attached parts wrap an AppShell component. They expose only the props the part's job needs rather than inheriting the wrapped component's surface, so its visual treatment is fixed and not yours to change:
| Part | Wraps | Accepts | Fixed |
|---|---|---|---|
AIChat.Suggestion | Button | suggestion, onSelect, className, disabled, children | variant="secondary", size="sm" |
AIChat.Action | Button inside a Tooltip | label, onClick, className, disabled, children | variant="ghost", size="icon" |
AIChat.ChainOfThoughtSearchResult | Badge | className, children, variant | — |
AIChat.ToolCall | Badge | call, className | variant="neutral" |
variant stays open on ChainOfThoughtSearchResult because conveying status is what a Badge is for. AIChat.Action's label becomes both the accessible name and the tooltip text.
ToolCall applies className to its outer row, not the inner badge. For Suggestion, Action, and ChainOfThoughtSearchResult, className is merged with cn(), which is not configured for AppShell's internal prefix, so it cannot reliably override a base utility from the wrapped component. Add properties the component doesn't set, and reach for the wrapped component's own props or variants to change ones it does — see Styling AppShell components.
Filling the page
AIChat fills whatever height its parent gives it — h-full for a block parent, flex-1 min-h-0 for a flex column — and never grows the page: the transcript scrolls internally while the header and composer stay pinned. Give the surface around it a definite height.
Inside a <Layout fill> column (the column is flex flex-col, so the card takes the leftover space):
tsx
<Layout fill>
<Layout.Header title="Assistant" />
<Layout.Column>
<Card.Root className="flex min-h-0 flex-1 flex-col overflow-hidden">
<AIChat status={status}>
<AIChat.Header title="Assistant" />
<AIChat.Conversation>{/* … */}</AIChat.Conversation>
<AIChat.Composer onSubmit={sendMessage} />
</AIChat>
</Card.Root>
</Layout.Column>
</Layout>min-h-0 is what lets the card shrink below its content's natural height so the transcript scrolls instead of pushing the composer off-screen. In a docked panel or Sheet whose height is already fixed, h-full on the card is enough.
Header
A 48px strip above the transcript: leading graphic, title, and an open action slot on the right, closed by a rule that runs the full width of the surface. Omit it for a bare transcript-and-composer surface, and give the card overflow-hidden so the rule stays inside its rounded corners.
Try the history/back action, clear the local transcript, or collapse and reopen the card. The collapse control occupies icon, while history and clear occupy actions. This changes only the example card, not the surrounding application layout:
tsx
function HeaderActions() {
const [collapsed, setCollapsed] = useState(false);
const [showHistory, setShowHistory] = useState(false);
const [message, setMessage] = useState("Your purchase order is ready for review.");
if (collapsed) return <Button onClick={() => setCollapsed(false)}>Open assistant</Button>;
return (
<Card.Root className="flex h-64 flex-col overflow-hidden">
<AIChat>
<AIChat.Header
title={showHistory ? "Conversation history" : "Assistant"}
icon={
<AIChat.Action label="Collapse assistant" onClick={() => setCollapsed(true)}>
<ChevronsRightIcon aria-hidden />
</AIChat.Action>
}
actions={
<>
<AIChat.Action
label={showHistory ? "Back to conversation" : "Conversation history"}
onClick={() => setShowHistory((value) => !value)}
>
<HistoryIcon aria-hidden />
</AIChat.Action>
<AIChat.Action
label="Clear conversation"
onClick={() => {
setMessage("");
setShowHistory(false);
}}
>
<EraserIcon aria-hidden />
</AIChat.Action>
</>
}
/>
<AIChat.Conversation>
{showHistory ? (
<AIChat.EmptyState
title="No older conversations"
description="Use Back to conversation to return to the current transcript."
/>
) : message ? (
<AIChat.Message from="assistant">
<AIChat.Response>{message}</AIChat.Response>
</AIChat.Message>
) : (
<AIChat.EmptyState
title="Conversation cleared"
description="Only this local example was cleared."
/>
)}
</AIChat.Conversation>
</AIChat>
</Card.Root>
);
}Attached parts
Message
tsx
function Message() {
return (
<AIChat.Message from="assistant">
<AIChat.Response>Your purchase order is ready for review.</AIChat.Response>
</AIChat.Message>
);
}User turns render as a right-aligned primary bubble; assistant turns take the full width with no bubble, so reasoning, tool calls, and citations stack inside the same column above the response text.
Response
Renders the markdown subset a streamed LLM response actually emits — bold, inline code, links, headings, bullet/numbered lists — without a markdown dependency. Only http(s):, mailto:, and same-site relative links render as clickable; any other target renders as plain text, since the text passing through here is untrusted model output. For full CommonMark, swap <AIChat.Response> for react-markdown or the AI SDK's streamdown — call sites keep the same shape.
tsx
function Response() {
return (
<AIChat.Response>
{
"## Order summary\n\nThe order is **ready for review**.\n\n- Check the `quantity` for each line.\n- Confirm the delivery date.\n\n[Read the documentation](/components/ai-chat)."
}
</AIChat.Response>
);
}EmptyState / Suggestions
AIChat.EmptyState stacks icon, then the title/description block, then children — so starter suggestions sit alongside the text rather than replacing it:
Choose a starter prompt to display the user turn and a predefined local reply. Use Reset suggestions to return to the empty state. This example does not call a model or execute a request:
tsx
function EmptyStateSuggestions() {
const [prompt, setPrompt] = useState<string | null>(null);
return (
<Card.Root className="flex h-80 flex-col overflow-hidden">
<AIChat>
<AIChat.Header
title="Local suggestions"
actions={
<AIChat.Action label="Reset suggestions" onClick={() => setPrompt(null)}>
<RotateCcwIcon aria-hidden />
</AIChat.Action>
}
/>
<AIChat.Conversation>
{prompt === null ? (
<AIChat.EmptyState
icon={<SparklesIcon className="size-6 text-primary" aria-hidden />}
title="Ask the assistant"
description="Choose a starter prompt. No request is sent."
>
<AIChat.Suggestions>
<AIChat.Suggestion
suggestion="How do I create a purchase order?"
onSelect={setPrompt}
/>
<AIChat.Suggestion suggestion="Summarize my open orders" onSelect={setPrompt} />
</AIChat.Suggestions>
</AIChat.EmptyState>
) : (
<>
<AIChat.Message from="user">
<AIChat.Response>{prompt}</AIChat.Response>
</AIChat.Message>
<AIChat.Message from="assistant">
<AIChat.Response>
This predefined local reply shows where an application would render the answer.
</AIChat.Response>
</AIChat.Message>
</>
)}
</AIChat.Conversation>
</AIChat>
</Card.Root>
);
}AIChat.Suggestion submits its suggestion text as if the reader had typed and sent it via onSelect.
Actions
Icon-button row under a finished assistant turn — copy, retry, feedback. Render it only once the turn has finished so streaming turns stay uncluttered.
Copy the response, produce another local revision with Retry, or mark it helpful. The status below the message records the action. Copy uses the browser clipboard and reports when access is unavailable; Retry and feedback remain entirely local:
tsx
function MessageActions() {
const [revision, setRevision] = useState(1);
const [feedback, setFeedback] = useState("No action selected.");
const response = `Summary revision ${revision}: three orders are ready for review.`;
async function copyResponse() {
try {
await navigator.clipboard.writeText(response);
setFeedback("Response copied.");
} catch {
setFeedback("Clipboard access is unavailable. Select the response text to copy it manually.");
}
}
return (
<div className="space-y-3">
<AIChat.Message from="assistant">
<AIChat.Response>{response}</AIChat.Response>
<AIChat.Actions>
<AIChat.Action label="Copy response" onClick={() => void copyResponse()}>
<CopyIcon aria-hidden />
</AIChat.Action>
<AIChat.Action
label="Retry response"
onClick={() => {
setRevision((value) => value + 1);
setFeedback("Generated another local revision.");
}}
>
<RotateCcwIcon aria-hidden />
</AIChat.Action>
<AIChat.Action
label="Mark response helpful"
onClick={() => setFeedback("Marked helpful.")}
>
<ThumbsUpIcon aria-hidden />
</AIChat.Action>
</AIChat.Actions>
</AIChat.Message>
<Text.p role="status">{feedback}</Text.p>
</div>
);
}Reasoning
Collapsible "thinking" block for reasoning models. Auto-opens while isStreaming is true and auto-closes when it turns false, unless the reader has manually toggled it.
tsx
function Reasoning() {
return (
<AIChat.Reasoning isStreaming={false} duration={3} defaultOpen>
<AIChat.ReasoningTrigger />
<AIChat.ReasoningContent>
{
"I will check the order totals, then compare the requested delivery date with the supplier's lead time."
}
</AIChat.ReasoningContent>
</AIChat.Reasoning>
);
}ChainOfThought
Structured step timeline for agentic turns — the discrete plan being executed, each step with a status and optional result chips. Use Reasoning for free-form thinking text and this for multi-step tool plans.
tsx
function ChainOfThought() {
return (
<AIChat.ChainOfThought defaultOpen>
<AIChat.ChainOfThoughtHeader />
<AIChat.ChainOfThoughtContent>
<AIChat.ChainOfThoughtStep label="Searching the knowledge base" status="complete">
<AIChat.ChainOfThoughtSearchResults>
<AIChat.ChainOfThoughtSearchResult>12 hits</AIChat.ChainOfThoughtSearchResult>
</AIChat.ChainOfThoughtSearchResults>
</AIChat.ChainOfThoughtStep>
<AIChat.ChainOfThoughtStep label="Drafting the answer" status="active" />
</AIChat.ChainOfThoughtContent>
</AIChat.ChainOfThought>
);
}status is "complete" | "active" | "pending".
Tool calls during the active flow
useAIChat() returns a transient toolCalls list separately from messages. Render it with AIChat.ToolCall after the message history inside AIChat.Conversation.
For an application integration, pass a configured client and registered tools to the component below, and choose a model available through your Gateway. Unlike the local preview, submitting a message here calls that client and may execute the supplied tools:
tsx
import {
AIChat,
Card,
useAIChat,
type AIGatewayClient,
type AILocalTool,
} from "@tailor-platform/app-shell";
function ToolCallAssistant({
client,
model,
tools,
}: {
client: AIGatewayClient;
model: string;
tools: Record<string, AILocalTool>;
}) {
const { messages, status, toolCalls, sendMessage, stop } = useAIChat({ client, model, tools });
return (
<Card.Root className="flex h-96 flex-col overflow-hidden">
<AIChat status={status}>
<AIChat.Conversation>
{messages.map((message) => (
<AIChat.Message key={message.id} from={message.role}>
<AIChat.Response>{message.content}</AIChat.Response>
</AIChat.Message>
))}
{toolCalls.map((call) => (
<AIChat.ToolCall key={call.id} call={call} />
))}
</AIChat.Conversation>
<AIChat.Composer onSubmit={sendMessage} onStop={stop} />
</AIChat>
</Card.Root>
);
}The following fixture shows two requested names. Finish request clears them, and Show requested calls restores them, making the transient presentation observable without executing a tool:
tsx
function ActiveToolCalls() {
const [active, setActive] = useState(true);
const calls = [
{ id: "search", name: "search_help_articles" },
{ id: "orders", name: "list_open_orders" },
];
return (
<div className="space-y-3">
<Button variant="outline" onClick={() => setActive((value) => !value)}>
{active ? "Finish request" : "Show requested calls"}
</Button>
<Card.Root className="flex h-40 flex-col overflow-hidden">
<AIChat>
<AIChat.Conversation>
{active ? (
<AIChat.Message from="assistant">
{calls.map((call) => (
<AIChat.ToolCall key={call.id} call={call} />
))}
</AIChat.Message>
) : (
<Text.p role="status">No active tool requests.</Text.p>
)}
</AIChat.Conversation>
</AIChat>
</Card.Root>
<Text.p>
These fixture names represent requests, not execution results. No tools are executed.
</Text.p>
</div>
);
}Each call renders on its own row, in the order supplied. Labels are localized automatically.
The list clears when the response finishes, is stopped, or fails. It does not create tool messages or persist in the conversation log.
These names record model requests, not execution success. Tool arguments and results stay internal. Do not infer a ToolHeader success or running state from name-only metadata.
Tool
Collapsible tool-call card. Maps 1:1 to the AI SDK's tool-part lifecycle, so a streaming loop can update a call in place as parts arrive.
Select each lifecycle state and expand or collapse the card to inspect its local input, result, and error fixtures. The selector controls presentation only; it does not run a tool:
tsx
function ToolLifecycle() {
const states: ToolState[] = [
"input-streaming",
"input-available",
"output-available",
"output-error",
];
const [state, setState] = useState<ToolState>("output-available");
return (
<div className="space-y-3">
<Select
aria-label="Tool lifecycle state"
items={states}
value={state}
onValueChange={(value) => {
if (value) setState(value);
}}
/>
<AIChat.Tool defaultOpen>
<AIChat.ToolHeader
toolName="search_help_articles"
title="Search help articles"
state={state}
/>
<AIChat.ToolContent>
<AIChat.ToolInput input={{ query: "purchase order" }} />
<AIChat.ToolOutput
output={
state === "output-available"
? { matches: [{ title: "Creating a purchase order" }] }
: undefined
}
errorText={
state === "output-error" ? "The local help index is unavailable." : undefined
}
/>
</AIChat.ToolContent>
</AIChat.Tool>
<Text.p>
Change the state to inspect the presentation. Inputs, results, and errors are local
fixtures.
</Text.p>
</div>
);
}state is "input-streaming" | "input-available" | "output-available" | "output-error".
Sources
Compact "Used N sources" citation trigger under a grounded answer. Supply source data from your application; useAIChat() does not return citation metadata.
Expand the citations and choose a source to read its local excerpt below the list. An application can use the same onClick callback to open its document viewer:
tsx
function CitationSources() {
const sources = [
{
id: "purchase-orders",
title: "Purchase order guide",
excerpt: "Create a draft, add line items, then confirm the purchase order.",
},
{
id: "approvals",
title: "Approval policy",
excerpt: "An authorized reviewer checks quantities and delivery dates before approval.",
},
];
const [selectedId, setSelectedId] = useState<string | null>(null);
const selected = sources.find((source) => source.id === selectedId);
return (
<div className="space-y-3">
<AIChat.Sources>
<AIChat.SourcesTrigger count={sources.length} />
<AIChat.SourcesContent>
{sources.map((source) => (
<AIChat.Source
key={source.id}
title={source.title}
onClick={() => setSelectedId(source.id)}
/>
))}
</AIChat.SourcesContent>
</AIChat.Sources>
<Text.p role="status">
{selected
? `${selected.title}: ${selected.excerpt}`
: "Expand the citations, then choose a source to read its local excerpt."}
</Text.p>
</div>
);
}History
Grouped list of past conversations for reopening an earlier chat. Layout-agnostic — render it in a popover behind a header action, or as a sidebar section of a full chat page. Group titles and date bucketing are yours; AIChat.History has no opinion on date ranges.
Choose a conversation to switch its displayed summary. Delete removes only the local fixture; deleting the active item also clears its displayed summary. Reset history restores the sample conversations. There is no remote history store or request:
tsx
function ConversationHistory() {
const initialConversations = [
{
id: "purchase-orders",
title: "Creating a purchase order",
summary: "Start with a draft and add the required line items.",
},
{
id: "stock",
title: "Checking available stock",
summary: "Review the available quantity at each warehouse.",
},
];
const [conversations, setConversations] = useState(initialConversations);
const [activeId, setActiveId] = useState("purchase-orders");
const selected = conversations.find((conversation) => conversation.id === activeId);
return (
<div className="space-y-3">
<Text.p>
Choose a saved conversation to read it. Delete affects only these local fixtures.
</Text.p>
<AIChat.History
groups={[{ title: "Today", items: conversations }]}
activeId={activeId}
onSelect={setActiveId}
onDelete={(id) => {
setConversations((current) => current.filter((conversation) => conversation.id !== id));
setActiveId((current) => (current === id ? "" : current));
}}
/>
<Text.p role="status">
{selected ? `${selected.title}: ${selected.summary}` : "No conversation selected."}
</Text.p>
<Button
variant="outline"
onClick={() => {
setConversations(initialConversations);
setActiveId("purchase-orders");
}}
>
Reset history
</Button>
</div>
);
}