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.
important
How it works
- The parts own the behavior, the app owns the state.
useChatholds the messages and streams each answer.Conversation.RootandPromptInput.Rootboth take itsstreamingflag: 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.Pendingsits afterMessage.Contentand pulses until the answer ends. - The work folds away when the answer ends.
Work.Roottakes the answer'sstreamingflag, 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.
stopaborts the stream and ends the answer as stopped, so the reader keeps what arrived. A new message sent mid-answer does the same.retryreplaces 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.
Markdownlexes only the unfinished block, renders at most once per frame, and renders a fence as aCodeBlockthat highlights as the code arrives.
The demo
1import { Alert } from "@ngrok/mantle/alert";2import { Attachment } from "@ngrok/mantle/attachment";3import { Button, IconButton } from "@ngrok/mantle/button";4import { CodeBlock, jsonCodeBlockValue } from "@ngrok/mantle/code-block";5import { Conversation } from "@ngrok/mantle/conversation";6import { Empty } from "@ngrok/mantle/empty";7import { Main } from "@ngrok/mantle/main";8import { Markdown } from "@ngrok/mantle/markdown";9import { Message } from "@ngrok/mantle/message";10import { PromptInput } from "@ngrok/mantle/prompt-input";11import { Reasoning } from "@ngrok/mantle/reasoning";12import { useCopyToClipboard } from "@ngrok/mantle/hooks";13import { Select } from "@ngrok/mantle/select";14import { Toast, makeToast } from "@ngrok/mantle/toast";15import { ToolCall } from "@ngrok/mantle/tool-call";16import { Work } from "@ngrok/mantle/work";17import { ArrowClockwiseIcon } from "@phosphor-icons/react/ArrowClockwise";18import { ChatsCircleIcon } from "@phosphor-icons/react/ChatsCircle";19import { CopyIcon } from "@phosphor-icons/react/Copy";20import { useRef, useState } from "react";21import { type ChatAnswer, type ChatFile, type ChatToolCall, useChat } from "~/features/chat";22import { mockRespond } from "~/features/chat-mock";23 24const models = [⋯25 { value: "claude-sonnet-5-5", label: "Claude Sonnet 5.5" },26 { value: "gpt-6-sol", label: "GPT-6 Sol" },27 { value: "gemini-4-hydrogen", label: "Gemini 4 Hydrogen" },28];29 30const starters = ["Which endpoints have no traffic policy?", "Why did my last request fail?"];31 32/** A file in the composer, kept until the message sends. */33type DraftFile = ChatFile & { file: File };34 35/**36 * A full chat: an empty state with starter prompts, a transcript that follows37 * the answer as it streams, and a composer with attachments, a model picker,38 * dictation, and one send-or-stop button. The answer comes from a mock, so the39 * demo runs with no network. Ask anything with "fail" in it to see a failed40 * answer.41 */42export function ChatDemo() {⋯43 const chat = useChat({ respond: mockRespond });44 const [draft, setDraft] = useState("");45 const [files, setFiles] = useState<DraftFile[]>([]);46 const [model, setModel] = useState(models[0]?.value ?? "");47 const fieldRef = useRef<HTMLTextAreaElement>(null);48 49 function send(text: string) {⋯50 if (text.trim() === "" && files.length === 0) {⋯51 return;52 }53 chat.send({ text, files: files.map(({ id, name, size }) => ({ id, name, size })), model });54 setDraft("");55 setFiles([]);56 // Why: a starter button leaves with the empty state, so focus must not fall to the page.57 fieldRef.current?.focus();58 }59 60 const lastAnswer = chat.messages.findLast((message) => message.from === "assistant");61 62 return (63 <Main className="fixed inset-0 flex flex-col">⋯64 <Conversation.Root streaming={chat.streaming} className="min-h-0 flex-1">⋯65 {chat.messages.length === 0 ? (66 <Empty.Root className="m-auto">⋯67 <Empty.Icon svg={<ChatsCircleIcon />} />68 <Empty.Title>Ask about your endpoints</Empty.Title>69 <Empty.Description>⋯70 <p>The assistant reads your account. It never changes anything without asking.</p>71 </Empty.Description>72 <Empty.Actions className="flex-wrap justify-center">⋯73 {starters.map((starter) => (74 <Button⋯75 key={starter}76 type="button"77 appearance="outlined"78 intent="neutral"79 onClick={() => send(starter)}80 >81 {starter}82 </Button>83 ))}84 </Empty.Actions>85 </Empty.Root>86 ) : (87 <Conversation.Viewport aria-label="Conversation with the assistant">⋯88 <Conversation.Content className="mx-auto w-full max-w-3xl px-4 py-6">⋯89 {chat.messages.map((message) =>90 message.from === "user" ? (91 <Message.Root key={message.id} from="user">⋯92 <Message.Content className="flex flex-col gap-2">⋯93 {message.files.length > 0 && (94 <Attachment.List aria-label="Attached files">⋯95 {message.files.map((file) => (96 <Attachment.Root key={file.id}>⋯97 <Attachment.Preview />98 <Attachment.Name title={file.name}>{file.name}</Attachment.Name>99 <Attachment.Size bytes={file.size} />100 </Attachment.Root>101 ))}102 </Attachment.List>103 )}104 <p className="whitespace-pre-wrap">{message.text}</p>105 </Message.Content>106 </Message.Root>107 ) : (108 <Answer⋯109 key={message.id}110 answer={message}111 onRetry={112 message === lastAnswer113 ? () => {⋯114 chat.retry(model);115 // Why: Retry leaves while the new answer streams, so focus moves to the field.116 fieldRef.current?.focus();117 }118 : undefined119 }120 />121 ),122 )}123 </Conversation.Content>124 </Conversation.Viewport>125 )}126 <Conversation.ScrollButton />127 </Conversation.Root>128 <div className="mx-auto w-full max-w-3xl px-4 pb-4">⋯129 <PromptInput.Root⋯130 streaming={chat.streaming}131 onStop={chat.stop}132 onFilesAdd={(added) => {⋯133 const entries = added.map((file) => ({⋯134 id: crypto.randomUUID(),135 name: file.name,136 size: file.size,137 file,138 }));139 setFiles((current) => [...current, ...entries]);140 }}141 onSubmit={(event) => {⋯142 event.preventDefault();143 send(draft);144 }}145 >146 {files.length > 0 && (147 <Attachment.List aria-label="Files to send" className="px-3 pt-3">⋯148 {files.map((file) => (149 <Attachment.Root key={file.id}>⋯150 <Attachment.Preview />151 <Attachment.Name title={file.name}>{file.name}</Attachment.Name>152 <Attachment.Size bytes={file.size} />153 <Attachment.Remove⋯154 label={`Remove ${file.name}`}155 onClick={() =>156 setFiles((current) => current.filter((entry) => entry.id !== file.id))157 }158 />159 </Attachment.Root>160 ))}161 </Attachment.List>162 )}163 <PromptInput.TextArea⋯164 ref={fieldRef}165 aria-label="Message the assistant"166 name="message"167 placeholder="Ask about your endpoints…"168 value={draft}169 onChange={(event) => setDraft(event.target.value)}170 />171 <PromptInput.Footer>⋯172 <PromptInput.AttachButton />173 <Select.Root name="model" value={model} onValueChange={setModel}>⋯174 <Select.Trigger⋯175 aria-label="Model"176 className="h-8 w-auto rounded-full border-transparent bg-transparent shadow-none hover:border-transparent"177 >178 <Select.Value />179 </Select.Trigger>180 <Select.Content>⋯181 {models.map((option) => (182 <Select.Item key={option.value} value={option.value}>⋯183 {option.label}184 </Select.Item>185 ))}186 </Select.Content>187 </Select.Root>188 <PromptInput.Dictate />189 <PromptInput.Submit />190 </PromptInput.Footer>191 </PromptInput.Root>192 </div>193 </Main>194 );195}196 197/** One answer: its reasoning, its tool calls, its text, and how it ended. */198function Answer({ answer, onRetry }: { answer: ChatAnswer; onRetry: (() => void) | undefined }) {⋯199 const streaming = answer.status === "streaming";200 const reasoningStreams = streaming && answer.reasoningSeconds == null;201 const copy = useCopyToClipboard();202 203 return (204 <Message.Root from="assistant">⋯205 <Message.Content className="flex flex-col gap-3">⋯206 {(answer.reasoning !== "" || answer.tools.length > 0) && (207 <Work.Root streaming={streaming}>⋯208 <Work.Trigger />209 <Work.Content>⋯210 {answer.reasoning !== "" && (211 <Reasoning.Root streaming={reasoningStreams}>⋯212 <Reasoning.Trigger>⋯213 {answer.reasoningSeconds == null214 ? "Reasoning"215 : `Thought for ${answer.reasoningSeconds} ${answer.reasoningSeconds === 1 ? "second" : "seconds"}`}216 </Reasoning.Trigger>217 <Reasoning.Content>{answer.reasoning}</Reasoning.Content>218 </Reasoning.Root>219 )}220 {answer.tools.map((tool) => (221 <Tool key={tool.id} tool={tool} />222 ))}223 </Work.Content>224 </Work.Root>225 )}226 {answer.text !== "" && <Markdown streaming={streaming}>{answer.text}</Markdown>}227 {answer.status === "failed" && (228 <Alert.Root intent="danger" role="alert">⋯229 <Alert.Icon />230 <Alert.Content>⋯231 <Alert.Title>The answer stopped partway</Alert.Title>232 <Alert.Description>⋯233 The connection to the model dropped. Retry to ask again.234 </Alert.Description>235 </Alert.Content>236 </Alert.Root>237 )}238 {answer.status === "stopped" && (239 <p className="text-muted text-sm">You stopped this answer.</p>240 )}241 </Message.Content>242 {/* Why the reasoning check: Reasoning already reads "Thinking…" while it streams. */}243 {streaming && !(reasoningStreams && answer.reasoning !== "") && (244 <Message.Pending>Thinking…</Message.Pending>245 )}246 {!streaming && (247 <Message.Actions>⋯248 <IconButton⋯249 type="button"250 appearance="ghost"251 intent="neutral"252 size="sm"253 label="Copy the answer"254 icon={<CopyIcon />}255 onClick={() => {⋯256 copy(answer.text).catch(() => {⋯257 makeToast(258 <Toast.Root intent="danger">⋯259 <Toast.Icon />260 <Toast.Message>Could not copy the answer.</Toast.Message>261 </Toast.Root>,262 );263 });264 }}265 />266 {onRetry != null && (267 <IconButton⋯268 type="button"269 appearance="ghost"270 intent="neutral"271 size="sm"272 label="Retry"273 icon={<ArrowClockwiseIcon />}274 onClick={onRetry}275 />276 )}277 </Message.Actions>278 )}279 </Message.Root>280 );281}282 283/** One tool call, with its arguments and, once it ends, its result. */284function Tool({ tool }: { tool: ChatToolCall }) {⋯285 return (286 <ToolCall.Root status={tool.status}>⋯287 <ToolCall.Trigger>⋯288 <ToolCall.Name>{tool.name}</ToolCall.Name>289 </ToolCall.Trigger>290 <ToolCall.Content>⋯291 <CodeBlock.Root>⋯292 <CodeBlock.Header>⋯293 <CodeBlock.Title>Arguments</CodeBlock.Title>294 </CodeBlock.Header>295 <CodeBlock.Body>⋯296 <CodeBlock.CopyButton />297 <CodeBlock.Code value={jsonCodeBlockValue(tool.args)} />298 </CodeBlock.Body>299 </CodeBlock.Root>300 {tool.result != null && (301 <CodeBlock.Root>⋯302 <CodeBlock.Header>⋯303 <CodeBlock.Title>Result</CodeBlock.Title>304 </CodeBlock.Header>305 <CodeBlock.Body>⋯306 <CodeBlock.CopyButton />307 <CodeBlock.Code value={jsonCodeBlockValue(tool.result)} />308 </CodeBlock.Body>309 </CodeBlock.Root>310 )}311 </ToolCall.Content>312 </ToolCall.Root>313 );314}The hook
useChat owns the messages and one stream at a time. Swap respond for your server, and keep the rest.
1import { useEffect, useRef, useState } from "react";2 3/** One piece of an answer as it streams. Text arrives as deltas. */4export type ChatEvent =5 | { type: "reasoning"; text: string }6 | { type: "tool-start"; id: string; name: string; args: unknown }7 | { type: "tool-end"; id: string; result: unknown; failed?: boolean }8 | { type: "text"; text: string };9 10/** A file the person attached to a message. */11export type ChatFile = { id: string; name: string; size: number };12 13/** A tool call in an answer, with the status `ToolCall.Root` takes. */14export type ChatToolCall = {⋯15 id: string;16 name: string;17 /** The arguments, as JSON. */18 args: unknown;19 /** The result, as JSON, once the call ends. */20 result: unknown;21 status: "running" | "done" | "failed" | "interrupted";22};23 24/** A message the person sent. */25export type ChatUserMessage = { id: string; from: "user"; text: string; files: ChatFile[] };26 27/** An answer, with where its stream is. */28export type ChatAnswer = {⋯29 id: string;30 from: "assistant";31 reasoning: string;32 /** How long the model reasoned, once its reasoning ends. */33 reasoningSeconds: number | null;34 tools: ChatToolCall[];35 text: string;36 status: "streaming" | "done" | "stopped" | "failed";37};38 39export type ChatMessage = ChatUserMessage | ChatAnswer;40 41/** Streams the answer to the last message. The demo mocks it; an app calls its server. */42export type Respond = (request: {⋯43 messages: ChatMessage[];44 model: string;45 signal: AbortSignal;46}) => AsyncIterable<ChatEvent>;47 48/**49 * Applies one event to the answer it belongs to. Pure, so a test can drive an50 * answer with no stream.51 */52export function applyChatEvent(53 answer: ChatAnswer,54 event: ChatEvent,55 elapsedMs: number,56): ChatAnswer {⋯57 const endReasoning =58 event.type !== "reasoning" && answer.reasoning !== "" && answer.reasoningSeconds == null59 ? { reasoningSeconds: Math.max(1, Math.round(elapsedMs / 1000)) }60 : null;61 switch (event.type) {⋯62 case "reasoning":63 return { ...answer, reasoning: answer.reasoning + event.text };64 case "tool-start":65 return {⋯66 ...answer,67 ...endReasoning,68 tools: [⋯69 ...answer.tools,70 { id: event.id, name: event.name, args: event.args, result: null, status: "running" },71 ],72 };73 case "tool-end":74 return {⋯75 ...answer,76 ...endReasoning,77 tools: answer.tools.map((tool) =>78 tool.id === event.id79 ? { ...tool, result: event.result, status: event.failed ? "failed" : "done" }80 : tool,81 ),82 };83 case "text":84 return { ...answer, ...endReasoning, text: answer.text + event.text };85 }86}87 88/** Reads one answer's events. A module function, because React Compiler cannot compile `for await`. */89async function readAnswer(90 events: AsyncIterable<ChatEvent>,91 onEvent: (event: ChatEvent) => void,92 signal: AbortSignal,93): Promise<void> {⋯94 for await (const event of events) {⋯95 if (signal.aborted) {⋯96 return;97 }98 onEvent(event);99 }100}101 102/** Ends an answer: running tools are interrupted unless the answer finished. */103function endAnswer(answer: ChatAnswer, status: ChatAnswer["status"]): ChatAnswer {⋯104 return {⋯105 ...answer,106 status,107 tools: answer.tools.map((tool) =>108 tool.status === "running" ? { ...tool, status: "interrupted" } : tool,109 ),110 };111}112 113function newAnswer(): ChatAnswer {⋯114 return {⋯115 id: crypto.randomUUID(),116 from: "assistant",117 reasoning: "",118 reasoningSeconds: null,119 tools: [],120 text: "",121 status: "streaming",122 };123}124 125/**126 * Holds a chat's messages and streams each answer from `respond`.127 *128 * One answer streams at a time. `stop` keeps the text so far, `retry`129 * replaces the last answer with a new one, and a new message, a stop, a130 * retry, or an unmount aborts the stream in flight. An answer whose stream131 * throws ends as `"failed"` with its text so far.132 *133 * @example134 * ```tsx135 * const chat = useChat({ respond });136 * <PromptInput.Root streaming={chat.streaming} onStop={chat.stop} onSubmit={…}>…</PromptInput.Root>137 * ```138 */139export function useChat({ respond }: { respond: Respond }) {⋯140 const [messages, setMessages] = useState<ChatMessage[]>([]);141 // Why a ref too: two sends before a render must each build on the other, not on the rendered array.142 const messagesRef = useRef<ChatMessage[]>([]);143 const abortRef = useRef<AbortController | null>(null);144 145 useEffect(() => () => abortRef.current?.abort(), []);146 147 function commit(next: ChatMessage[]) {⋯148 messagesRef.current = next;149 setMessages(next);150 }151 152 /** Updates the last message, which is the answer that streams. */153 function updateAnswer(update: (answer: ChatAnswer) => ChatAnswer) {⋯154 const current = messagesRef.current;155 const last = current.at(-1);156 if (last?.from === "assistant") {⋯157 commit([...current.slice(0, -1), update(last)]);158 }159 }160 161 async function stream(history: ChatMessage[], model: string) {⋯162 abortRef.current?.abort();163 const controller = new AbortController();164 abortRef.current = controller;165 commit([...history, newAnswer()]);166 167 const startedAt = Date.now();168 let status: ChatAnswer["status"] = "done";169 try {⋯170 await readAnswer(171 respond({ messages: history, model, signal: controller.signal }),172 (event) => updateAnswer((answer) => applyChatEvent(answer, event, Date.now() - startedAt)),173 controller.signal,174 );175 } catch {⋯176 status = "failed";177 }178 // Why: a stop or a newer message already ended this answer.179 if (controller.signal.aborted) {⋯180 return;181 }182 abortRef.current = null;183 updateAnswer((answer) => endAnswer(answer, status));184 }185 186 const last = messages.at(-1);187 const streaming = last?.from === "assistant" && last.status === "streaming";188 189 return {⋯190 messages,191 /** True while an answer streams. Hand it to `Conversation.Root` and `PromptInput.Root`. */192 streaming,193 /** Sends a message and streams its answer. */194 send: ({ text, files, model }: { text: string; files: ChatFile[]; model: string }) => {⋯195 const message: ChatUserMessage = { id: crypto.randomUUID(), from: "user", text, files };196 const current = messagesRef.current;197 const previous = current.at(-1);198 // Why: a message sent mid-answer keeps that answer as stopped, as the stop button would.199 const history =200 previous?.from === "assistant" && previous.status === "streaming"201 ? [...current.slice(0, -1), endAnswer(previous, "stopped")]202 : current;203 void stream([...history, message], model);204 },205 /** Stops the answer and keeps its text so far. */206 stop: () => {⋯207 abortRef.current?.abort();208 abortRef.current = null;209 updateAnswer((answer) =>210 answer.status === "streaming" ? endAnswer(answer, "stopped") : answer,211 );212 },213 /** Streams a new answer in place of the last one. */214 retry: (model: string) => {⋯215 const current = messagesRef.current;216 const history = current.at(-1)?.from === "assistant" ? current.slice(0, -1) : current;217 if (history.at(-1)?.from === "user") {⋯218 void stream(history, model);219 }220 },221 };222}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.
1import type { ChatEvent, Respond } from "~/features/chat";2 3const reasoning =4 "The user wants endpoints with no traffic policy. List the endpoints, check each one for a policy, then suggest a rule for each gap.";5 6const endpoints = [⋯7 { url: "https://api.example.com", policy: null },8 { url: "https://app.example.com", policy: "rate-limit" },9 { url: "tcp://1.tcp.ngrok.io:20012", policy: null },10];11 12const answer = `Two of your three endpoints have **no traffic policy**:⋯13 14| Endpoint | Policy | Risk |15| --- | --- | --- |16| \`https://api.example.com\` | none | One client can use up its capacity. |17| \`tcp://1.tcp.ngrok.io:20012\` | none | Anyone on the internet can reach it. |18 19Add a rate limit by client IP to the API endpoint:20 21\`\`\`yaml22on_http_request:23 - actions:24 - type: rate-limit25 config:26 name: per-client27 algorithm: sliding_window28 capacity: 10029 rate: 60s30 bucket_key:31 - conn.client_ip32\`\`\`33 34Then 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.`;35 36/** Waits like a network chunk, and rejects when the request aborts. */37function wait(ms: number, signal: AbortSignal): Promise<void> {⋯38 return new Promise((resolve, reject) => {⋯39 const onAbort = () => {⋯40 clearTimeout(timer);41 reject(signal.reason);42 };43 const timer = setTimeout(() => {⋯44 signal.removeEventListener("abort", onAbort);45 resolve();46 }, ms);47 signal.addEventListener("abort", onAbort, { once: true });48 });49}50 51/** Splits text into word-sized deltas that keep their spaces and line breaks. */52function deltas(text: string): string[] {⋯53 return text.match(/\S+\s*|\s+/g) ?? [];54}55 56/**57 * A stand-in for the chat endpoint. It streams reasoning, one tool call, and a58 * Markdown answer with a table and a code block, and honors the abort signal.59 * A message that contains "fail" drops the stream partway, as a lost60 * connection would. The real endpoint sends the messages to a model through61 * the ngrok.ai gateway, which routes the inference.62 */63export const mockRespond: Respond = async function* ({⋯64 messages,65 signal,66}): AsyncGenerator<ChatEvent> {⋯67 const question = messages.findLast((message) => message.from === "user");68 const fails = question?.text.toLowerCase().includes("fail") === true;69 70 for (const text of deltas(reasoning)) {⋯71 await wait(25, signal);72 yield { type: "reasoning", text };73 }74 75 yield { type: "tool-start", id: "call-1", name: "list_endpoints", args: { online: true } };76 await wait(700, signal);77 yield { type: "tool-end", id: "call-1", result: endpoints };78 79 const files = question?.files ?? [];80 // Why a count, not the names: a file name is input, and in Markdown it could close a code span and add a link.81 const intro =82 files.length > 083 ? `I read the ${files.length === 1 ? "file" : `${files.length} files`} you attached.\n\n`84 : "";85 const words = deltas(intro + answer);86 for (const [index, text] of words.entries()) {⋯87 if (fails && index === Math.floor(words.length / 3)) {⋯88 throw new Error("The connection to the model dropped.");89 }90 await wait(30, signal);91 yield { type: "text", text };92 }93};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.