Skip to main content

Chat

Every assistant at ngrok is built from the same parts: the dashboard assistant, the corp assistant, and the AI Gateway playground. This recipe puts them together into one chat. The composer is a Prompt Input with Attachment chips, a Select model picker, and dictation. The transcript is a Conversation of Messages, and each answer folds its Reasoning and its Tool Calls under one Work toggle above streaming Markdown.

Pick a starter prompt, or type a question and press Enter. Scroll up while the answer streams, and the transcript stays where you put it until you press the button that goes back to the newest message. Press Stop answer to keep the answer so far, and press Retry to ask again. Ask anything with "fail" in it to see a failed answer. A mock writes the answers, so the demo runs with no network and answers the same way every time.

Desktop viewport
Tablet viewport
Mobile viewport

important

Don't copy the copy. The recipe teaches the composition and the state: one hook owns the messages and the stream, and the parts only render it. The endpoint questions, the starter prompts, and the mock answer are stand-ins.

How it works

  • The parts own the behavior, the app owns the state. useChat holds the messages and streams each answer. Conversation.Root and PromptInput.Root both take its streaming flag: the transcript follows the end and announces "Answering…" once, and the send button turns into stop. There is no chat root component, because each app stores its messages in its own place (a route loader, a query cache, a store above the shell).
  • One answer, one shape. An answer is reasoning, tool calls, and text, each built from stream events by the pure applyChatEvent. Reasoning reads "Thinking…" until the first other event, then "Thought for N seconds". A tool call runs until its result arrives, and a stop or a failure marks it interrupted. Message.Pending sits after Message.Content and pulses until the answer ends.
  • The work folds away when the answer ends. Work.Root takes the answer's streaming flag, so the reasoning and the tool calls show while they arrive and fold under "Show work" once the text is done. A step the reader opened mid-answer stays open. Each step's caret shows on hover, focus, or open, and always on a touch screen.
  • Stop keeps the text. stop aborts the stream and ends the answer as stopped, so the reader keeps what arrived. A new message sent mid-answer does the same. retry replaces the last answer with a new one from the same messages.
  • A failure is a notice, not a dead end. When the stream throws, the answer keeps its text so far and shows an Alert with role="alert" under it, so a screen reader hears it, and the retry action asks again.
  • The empty state is the first screen. Before the first message, Empty offers starter prompts in place of the transcript. The composer stays put, so the draft never moves, and a pressed starter or Retry hands focus to the field.
  • Markdown streams as it arrives. Markdown lexes only the unfinished block, renders at most once per frame, and renders a fence as a CodeBlock that highlights as the code arrives.

The demo

import { Alert } from "@ngrok/mantle/alert";import { Attachment } from "@ngrok/mantle/attachment";import { Button, IconButton } from "@ngrok/mantle/button";import { CodeBlock, jsonCodeBlockValue } from "@ngrok/mantle/code-block";import { Conversation } from "@ngrok/mantle/conversation";import { Empty } from "@ngrok/mantle/empty";import { Main } from "@ngrok/mantle/main";import { Markdown } from "@ngrok/mantle/markdown";import { Message } from "@ngrok/mantle/message";import { PromptInput } from "@ngrok/mantle/prompt-input";import { Reasoning } from "@ngrok/mantle/reasoning";import { useCopyToClipboard } from "@ngrok/mantle/hooks";import { Select } from "@ngrok/mantle/select";import { Toast, makeToast } from "@ngrok/mantle/toast";import { ToolCall } from "@ngrok/mantle/tool-call";import { Work } from "@ngrok/mantle/work";import { ArrowClockwiseIcon } from "@phosphor-icons/react/ArrowClockwise";import { ChatsCircleIcon } from "@phosphor-icons/react/ChatsCircle";import { CopyIcon } from "@phosphor-icons/react/Copy";import { useRef, useState } from "react";import { type ChatAnswer, type ChatFile, type ChatToolCall, useChat } from "~/features/chat";import { mockRespond } from "~/features/chat-mock"; const models = [	{ value: "claude-sonnet-5-5", label: "Claude Sonnet 5.5" },	{ value: "gpt-6-sol", label: "GPT-6 Sol" },	{ value: "gemini-4-hydrogen", label: "Gemini 4 Hydrogen" },]; const starters = ["Which endpoints have no traffic policy?", "Why did my last request fail?"]; /** A file in the composer, kept until the message sends. */type DraftFile = ChatFile & { file: File }; /** * A full chat: an empty state with starter prompts, a transcript that follows * the answer as it streams, and a composer with attachments, a model picker, * dictation, and one send-or-stop button. The answer comes from a mock, so the * demo runs with no network. Ask anything with "fail" in it to see a failed * answer. */export function ChatDemo() {	const chat = useChat({ respond: mockRespond });	const [draft, setDraft] = useState("");	const [files, setFiles] = useState<DraftFile[]>([]);	const [model, setModel] = useState(models[0]?.value ?? "");	const fieldRef = useRef<HTMLTextAreaElement>(null); 	function send(text: string) {		if (text.trim() === "" && files.length === 0) {			return;		}		chat.send({ text, files: files.map(({ id, name, size }) => ({ id, name, size })), model });		setDraft("");		setFiles([]);		// Why: a starter button leaves with the empty state, so focus must not fall to the page.		fieldRef.current?.focus();	} 	const lastAnswer = chat.messages.findLast((message) => message.from === "assistant"); 	return (		<Main className="fixed inset-0 flex flex-col">			<Conversation.Root streaming={chat.streaming} className="min-h-0 flex-1">				{chat.messages.length === 0 ? (					<Empty.Root className="m-auto">						<Empty.Icon svg={<ChatsCircleIcon />} />						<Empty.Title>Ask about your endpoints</Empty.Title>						<Empty.Description>							<p>The assistant reads your account. It never changes anything without asking.</p>						</Empty.Description>						<Empty.Actions className="flex-wrap justify-center">							{starters.map((starter) => (								<Button									key={starter}									type="button"									appearance="outlined"									intent="neutral"									onClick={() => send(starter)}								>									{starter}								</Button>							))}						</Empty.Actions>					</Empty.Root>				) : (					<Conversation.Viewport aria-label="Conversation with the assistant">						<Conversation.Content className="mx-auto w-full max-w-3xl px-4 py-6">							{chat.messages.map((message) =>								message.from === "user" ? (									<Message.Root key={message.id} from="user">										<Message.Content className="flex flex-col gap-2">											{message.files.length > 0 && (												<Attachment.List aria-label="Attached files">													{message.files.map((file) => (														<Attachment.Root key={file.id}>															<Attachment.Preview />															<Attachment.Name title={file.name}>{file.name}</Attachment.Name>															<Attachment.Size bytes={file.size} />														</Attachment.Root>													))}												</Attachment.List>											)}											<p className="whitespace-pre-wrap">{message.text}</p>										</Message.Content>									</Message.Root>								) : (									<Answer										key={message.id}										answer={message}										onRetry={											message === lastAnswer												? () => {														chat.retry(model);														// Why: Retry leaves while the new answer streams, so focus moves to the field.														fieldRef.current?.focus();													}												: undefined										}									/>								),							)}						</Conversation.Content>					</Conversation.Viewport>				)}				<Conversation.ScrollButton />			</Conversation.Root>			<div className="mx-auto w-full max-w-3xl px-4 pb-4">				<PromptInput.Root					streaming={chat.streaming}					onStop={chat.stop}					onFilesAdd={(added) => {						const entries = added.map((file) => ({							id: crypto.randomUUID(),							name: file.name,							size: file.size,							file,						}));						setFiles((current) => [...current, ...entries]);					}}					onSubmit={(event) => {						event.preventDefault();						send(draft);					}}				>					{files.length > 0 && (						<Attachment.List aria-label="Files to send" className="px-3 pt-3">							{files.map((file) => (								<Attachment.Root key={file.id}>									<Attachment.Preview />									<Attachment.Name title={file.name}>{file.name}</Attachment.Name>									<Attachment.Size bytes={file.size} />									<Attachment.Remove										label={`Remove ${file.name}`}										onClick={() =>											setFiles((current) => current.filter((entry) => entry.id !== file.id))										}									/>								</Attachment.Root>							))}						</Attachment.List>					)}					<PromptInput.TextArea						ref={fieldRef}						aria-label="Message the assistant"						name="message"						placeholder="Ask about your endpoints…"						value={draft}						onChange={(event) => setDraft(event.target.value)}					/>					<PromptInput.Footer>						<PromptInput.AttachButton />						<Select.Root name="model" value={model} onValueChange={setModel}>							<Select.Trigger								aria-label="Model"								className="h-8 w-auto rounded-full border-transparent bg-transparent shadow-none hover:border-transparent"							>								<Select.Value />							</Select.Trigger>							<Select.Content>								{models.map((option) => (									<Select.Item key={option.value} value={option.value}>										{option.label}									</Select.Item>								))}							</Select.Content>						</Select.Root>						<PromptInput.Dictate />						<PromptInput.Submit />					</PromptInput.Footer>				</PromptInput.Root>			</div>		</Main>	);} /** One answer: its reasoning, its tool calls, its text, and how it ended. */function Answer({ answer, onRetry }: { answer: ChatAnswer; onRetry: (() => void) | undefined }) {	const streaming = answer.status === "streaming";	const reasoningStreams = streaming && answer.reasoningSeconds == null;	const copy = useCopyToClipboard(); 	return (		<Message.Root from="assistant">			<Message.Content className="flex flex-col gap-3">				{(answer.reasoning !== "" || answer.tools.length > 0) && (					<Work.Root streaming={streaming}>						<Work.Trigger />						<Work.Content>							{answer.reasoning !== "" && (								<Reasoning.Root streaming={reasoningStreams}>									<Reasoning.Trigger>										{answer.reasoningSeconds == null											? "Reasoning"											: `Thought for ${answer.reasoningSeconds} ${answer.reasoningSeconds === 1 ? "second" : "seconds"}`}									</Reasoning.Trigger>									<Reasoning.Content>{answer.reasoning}</Reasoning.Content>								</Reasoning.Root>							)}							{answer.tools.map((tool) => (								<Tool key={tool.id} tool={tool} />							))}						</Work.Content>					</Work.Root>				)}				{answer.text !== "" && <Markdown streaming={streaming}>{answer.text}</Markdown>}				{answer.status === "failed" && (					<Alert.Root intent="danger" role="alert">						<Alert.Icon />						<Alert.Content>							<Alert.Title>The answer stopped partway</Alert.Title>							<Alert.Description>								The connection to the model dropped. Retry to ask again.							</Alert.Description>						</Alert.Content>					</Alert.Root>				)}				{answer.status === "stopped" && (					<p className="text-muted text-sm">You stopped this answer.</p>				)}			</Message.Content>			{/* Why the reasoning check: Reasoning already reads "Thinking…" while it streams. */}			{streaming && !(reasoningStreams && answer.reasoning !== "") && (				<Message.Pending>Thinking…</Message.Pending>			)}			{!streaming && (				<Message.Actions>					<IconButton						type="button"						appearance="ghost"						intent="neutral"						size="sm"						label="Copy the answer"						icon={<CopyIcon />}						onClick={() => {							copy(answer.text).catch(() => {								makeToast(									<Toast.Root intent="danger">										<Toast.Icon />										<Toast.Message>Could not copy the answer.</Toast.Message>									</Toast.Root>,								);							});						}}					/>					{onRetry != null && (						<IconButton							type="button"							appearance="ghost"							intent="neutral"							size="sm"							label="Retry"							icon={<ArrowClockwiseIcon />}							onClick={onRetry}						/>					)}				</Message.Actions>			)}		</Message.Root>	);} /** One tool call, with its arguments and, once it ends, its result. */function Tool({ tool }: { tool: ChatToolCall }) {	return (		<ToolCall.Root status={tool.status}>			<ToolCall.Trigger>				<ToolCall.Name>{tool.name}</ToolCall.Name>			</ToolCall.Trigger>			<ToolCall.Content>				<CodeBlock.Root>					<CodeBlock.Header>						<CodeBlock.Title>Arguments</CodeBlock.Title>					</CodeBlock.Header>					<CodeBlock.Body>						<CodeBlock.CopyButton />						<CodeBlock.Code value={jsonCodeBlockValue(tool.args)} />					</CodeBlock.Body>				</CodeBlock.Root>				{tool.result != null && (					<CodeBlock.Root>						<CodeBlock.Header>							<CodeBlock.Title>Result</CodeBlock.Title>						</CodeBlock.Header>						<CodeBlock.Body>							<CodeBlock.CopyButton />							<CodeBlock.Code value={jsonCodeBlockValue(tool.result)} />						</CodeBlock.Body>					</CodeBlock.Root>				)}			</ToolCall.Content>		</ToolCall.Root>	);}

The hook

useChat owns the messages and one stream at a time. Swap respond for your server, and keep the rest.

import { useEffect, useRef, useState } from "react"; /** One piece of an answer as it streams. Text arrives as deltas. */export type ChatEvent =	| { type: "reasoning"; text: string }	| { type: "tool-start"; id: string; name: string; args: unknown }	| { type: "tool-end"; id: string; result: unknown; failed?: boolean }	| { type: "text"; text: string }; /** A file the person attached to a message. */export type ChatFile = { id: string; name: string; size: number }; /** A tool call in an answer, with the status `ToolCall.Root` takes. */export type ChatToolCall = {	id: string;	name: string;	/** The arguments, as JSON. */	args: unknown;	/** The result, as JSON, once the call ends. */	result: unknown;	status: "running" | "done" | "failed" | "interrupted";}; /** A message the person sent. */export type ChatUserMessage = { id: string; from: "user"; text: string; files: ChatFile[] }; /** An answer, with where its stream is. */export type ChatAnswer = {	id: string;	from: "assistant";	reasoning: string;	/** How long the model reasoned, once its reasoning ends. */	reasoningSeconds: number | null;	tools: ChatToolCall[];	text: string;	status: "streaming" | "done" | "stopped" | "failed";}; export type ChatMessage = ChatUserMessage | ChatAnswer; /** Streams the answer to the last message. The demo mocks it; an app calls its server. */export type Respond = (request: {	messages: ChatMessage[];	model: string;	signal: AbortSignal;}) => AsyncIterable<ChatEvent>; /** * Applies one event to the answer it belongs to. Pure, so a test can drive an * answer with no stream. */export function applyChatEvent(	answer: ChatAnswer,	event: ChatEvent,	elapsedMs: number,): ChatAnswer {	const endReasoning =		event.type !== "reasoning" && answer.reasoning !== "" && answer.reasoningSeconds == null			? { reasoningSeconds: Math.max(1, Math.round(elapsedMs / 1000)) }			: null;	switch (event.type) {		case "reasoning":			return { ...answer, reasoning: answer.reasoning + event.text };		case "tool-start":			return {				...answer,				...endReasoning,				tools: [					...answer.tools,					{ id: event.id, name: event.name, args: event.args, result: null, status: "running" },				],			};		case "tool-end":			return {				...answer,				...endReasoning,				tools: answer.tools.map((tool) =>					tool.id === event.id						? { ...tool, result: event.result, status: event.failed ? "failed" : "done" }						: tool,				),			};		case "text":			return { ...answer, ...endReasoning, text: answer.text + event.text };	}} /** Reads one answer's events. A module function, because React Compiler cannot compile `for await`. */async function readAnswer(	events: AsyncIterable<ChatEvent>,	onEvent: (event: ChatEvent) => void,	signal: AbortSignal,): Promise<void> {	for await (const event of events) {		if (signal.aborted) {			return;		}		onEvent(event);	}} /** Ends an answer: running tools are interrupted unless the answer finished. */function endAnswer(answer: ChatAnswer, status: ChatAnswer["status"]): ChatAnswer {	return {		...answer,		status,		tools: answer.tools.map((tool) =>			tool.status === "running" ? { ...tool, status: "interrupted" } : tool,		),	};} function newAnswer(): ChatAnswer {	return {		id: crypto.randomUUID(),		from: "assistant",		reasoning: "",		reasoningSeconds: null,		tools: [],		text: "",		status: "streaming",	};} /** * Holds a chat's messages and streams each answer from `respond`. * * One answer streams at a time. `stop` keeps the text so far, `retry` * replaces the last answer with a new one, and a new message, a stop, a * retry, or an unmount aborts the stream in flight. An answer whose stream * throws ends as `"failed"` with its text so far. * * @example * ```tsx * const chat = useChat({ respond }); * <PromptInput.Root streaming={chat.streaming} onStop={chat.stop} onSubmit={…}>…</PromptInput.Root> * ``` */export function useChat({ respond }: { respond: Respond }) {	const [messages, setMessages] = useState<ChatMessage[]>([]);	// Why a ref too: two sends before a render must each build on the other, not on the rendered array.	const messagesRef = useRef<ChatMessage[]>([]);	const abortRef = useRef<AbortController | null>(null); 	useEffect(() => () => abortRef.current?.abort(), []); 	function commit(next: ChatMessage[]) {		messagesRef.current = next;		setMessages(next);	} 	/** Updates the last message, which is the answer that streams. */	function updateAnswer(update: (answer: ChatAnswer) => ChatAnswer) {		const current = messagesRef.current;		const last = current.at(-1);		if (last?.from === "assistant") {			commit([...current.slice(0, -1), update(last)]);		}	} 	async function stream(history: ChatMessage[], model: string) {		abortRef.current?.abort();		const controller = new AbortController();		abortRef.current = controller;		commit([...history, newAnswer()]); 		const startedAt = Date.now();		let status: ChatAnswer["status"] = "done";		try {			await readAnswer(				respond({ messages: history, model, signal: controller.signal }),				(event) => updateAnswer((answer) => applyChatEvent(answer, event, Date.now() - startedAt)),				controller.signal,			);		} catch {			status = "failed";		}		// Why: a stop or a newer message already ended this answer.		if (controller.signal.aborted) {			return;		}		abortRef.current = null;		updateAnswer((answer) => endAnswer(answer, status));	} 	const last = messages.at(-1);	const streaming = last?.from === "assistant" && last.status === "streaming"; 	return {		messages,		/** True while an answer streams. Hand it to `Conversation.Root` and `PromptInput.Root`. */		streaming,		/** Sends a message and streams its answer. */		send: ({ text, files, model }: { text: string; files: ChatFile[]; model: string }) => {			const message: ChatUserMessage = { id: crypto.randomUUID(), from: "user", text, files };			const current = messagesRef.current;			const previous = current.at(-1);			// Why: a message sent mid-answer keeps that answer as stopped, as the stop button would.			const history =				previous?.from === "assistant" && previous.status === "streaming"					? [...current.slice(0, -1), endAnswer(previous, "stopped")]					: current;			void stream([...history, message], model);		},		/** Stops the answer and keeps its text so far. */		stop: () => {			abortRef.current?.abort();			abortRef.current = null;			updateAnswer((answer) =>				answer.status === "streaming" ? endAnswer(answer, "stopped") : answer,			);		},		/** Streams a new answer in place of the last one. */		retry: (model: string) => {			const current = messagesRef.current;			const history = current.at(-1)?.from === "assistant" ? current.slice(0, -1) : current;			if (history.at(-1)?.from === "user") {				void stream(history, model);			}		},	};}

The mock

The mock streams the same events an endpoint would: reasoning deltas, a tool call with its result, and Markdown text deltas. It honors the abort signal, so stop and a new message end it at once.

import type { ChatEvent, Respond } from "~/features/chat"; const reasoning =	"The user wants endpoints with no traffic policy. List the endpoints, check each one for a policy, then suggest a rule for each gap."; const endpoints = [	{ url: "https://api.example.com", policy: null },	{ url: "https://app.example.com", policy: "rate-limit" },	{ url: "tcp://1.tcp.ngrok.io:20012", policy: null },]; const answer = `Two of your three endpoints have **no traffic policy**: | Endpoint | Policy | Risk || --- | --- | --- || \`https://api.example.com\` | none | One client can use up its capacity. || \`tcp://1.tcp.ngrok.io:20012\` | none | Anyone on the internet can reach it. | Add a rate limit by client IP to the API endpoint: \`\`\`yamlon_http_request:	- actions:			- type: rate-limit				config:					name: per-client					algorithm: sliding_window					capacity: 100					rate: 60s					bucket_key:						- conn.client_ip\`\`\` Then restrict the TCP endpoint to your office network with a \`restrict-ips\` action. \`https://app.example.com\` already has a policy, so it needs no change.`; /** Waits like a network chunk, and rejects when the request aborts. */function wait(ms: number, signal: AbortSignal): Promise<void> {	return new Promise((resolve, reject) => {		const onAbort = () => {			clearTimeout(timer);			reject(signal.reason);		};		const timer = setTimeout(() => {			signal.removeEventListener("abort", onAbort);			resolve();		}, ms);		signal.addEventListener("abort", onAbort, { once: true });	});} /** Splits text into word-sized deltas that keep their spaces and line breaks. */function deltas(text: string): string[] {	return text.match(/\S+\s*|\s+/g) ?? [];} /** * A stand-in for the chat endpoint. It streams reasoning, one tool call, and a * Markdown answer with a table and a code block, and honors the abort signal. * A message that contains "fail" drops the stream partway, as a lost * connection would. The real endpoint sends the messages to a model through * the ngrok.ai gateway, which routes the inference. */export const mockRespond: Respond = async function* ({	messages,	signal,}): AsyncGenerator<ChatEvent> {	const question = messages.findLast((message) => message.from === "user");	const fails = question?.text.toLowerCase().includes("fail") === true; 	for (const text of deltas(reasoning)) {		await wait(25, signal);		yield { type: "reasoning", text };	} 	yield { type: "tool-start", id: "call-1", name: "list_endpoints", args: { online: true } };	await wait(700, signal);	yield { type: "tool-end", id: "call-1", result: endpoints }; 	const files = question?.files ?? [];	// Why a count, not the names: a file name is input, and in Markdown it could close a code span and add a link.	const intro =		files.length > 0			? `I read the ${files.length === 1 ? "file" : `${files.length} files`} you attached.\n\n`			: "";	const words = deltas(intro + answer);	for (const [index, text] of words.entries()) {		if (fails && index === Math.floor(words.length / 3)) {			throw new Error("The connection to the model dropped.");		}		await wait(30, signal);		yield { type: "text", text };	}};

Wire it to your server

Return an async iterable of ChatEvents from respond. Read your endpoint's server-sent events, and map each one to an event. Pass the signal to fetch, so stop and unmount cancel the request. The model's request goes through the ngrok.ai gateway, which routes the inference.