Skip to main content

Assistant

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 assistant. The composer is a Prompt Input with Attachment chips, a Dropdown Menu 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.

The assistant has two homes. On its own route it is the page. On every other route it sits beside the page in AppLayout.SidePanel. One conversation feeds both, and a navigation between them morphs the page into the panel with the answer still streaming, the draft in the composer, and the same text at the top of the transcript.

Pick a starter prompt, or type a question and press Enter. The first message opens the side panel, so the conversation comes along when you leave. Click Endpoints while the answer streams, then Assistant to bring the page back. 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. Ask three questions, and Conversation outline shows in the header to jump back to any of them. 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. Switch the demo to its mobile width to see the assistant on a phone.

Desktop viewport
Tablet viewport
Mobile viewport

note

The demo fakes its router, because a preview is a document inside this site's own router and React Router permits one router per tree. It keeps a pathname in state and sets it inside startTransition, which is what React Router does with every navigation. The pieces below are the real ones; only the shell's links differ.

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 model picker follows Amp's. A quiet button names the model and its effort. Its menu lists each model on one line, with a provider icon, an optional Badge, a muted description, and a check on the pick. Effort and the other models sit in submenus under a separator. The menu takes the width of its widest row, capped at 24rem and the screen, so a name never wraps and truncates only as a last resort. In a chat narrower than 24rem, as in the side panel or on a phone, the button drops the effort from view, and a screen reader still hears it. send and retry hand the model and the effort to respond. A menu holds no form value, so hidden inputs carry both for a form that posts.
  • One panel look at every size. The page and the side panel render the same Chat, built on Panel's parts: Panel.Body for the transcript and Panel.Footer for the composer. The page's header is AppLayout.Header; the panel's is AppLayout.SidePanelHeader, which renders Panel.Header and adds the swipe that closes it. Neither body scrolls: Conversation.Viewport scrolls, so it can follow the answer as it streams.
  • 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.
  • The transcript lines up with the composer. The transcript and the composer share one centered column, at every width. The transcript sits one corner radius inside the composer, so the edge of a code block or a table meets the composer where its rounded corner ends, as in Amp. The bottom fade ends at the composer. The column and the composer reserve the scrollbar's space alike, so they line up with a classic scrollbar too. The button that goes back to the newest message sits just inside the composer's right edge, as in Amp, not at the window's edge.
  • The outline waits for a long chat. From the third message the person sends, a Conversation Outline button shows in the header, at every width. It lists their messages, and a press jumps to one. With fewer messages a scroll is faster, so the button stays hidden, and it renders before the header's other actions so they do not move. Each person's Message.Root takes its message id and scroll-mt-4, so a jump leaves room above it.
  • 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.

Two homes, one conversation

The tempting shape is one panel that grows to fill the row on the assistant's route. Avoid it. An <aside> is the complementary landmark, and ARIA in HTML does not let it take role="main". A screen reader user on the assistant's route would find the page in the complementary landmark and nothing in main. The landmark follows the route instead:

  • On /assistant, AssistantPage renders Chat inside AppLayout.Body, which is main.
  • On every other route, AssistantPanel renders the same Chat inside AppLayout.SidePanel, after the content card.
  • On the assistant's route, AppLayout.SidePanel renders nothing, so one chat is on screen at a time.

What persists is the conversation, not the DOM. ChatSessionProvider sits above the shell and holds everything a navigation must keep:

  • The messages and the answer in flight. useChat streams on, whichever home is mounted.
  • The draft, its files, and the model picks. A half-typed message is still there in the new home.
  • The reader's place. The transcript passes the session's scrollAnchorRef to useScrollAnchor. The old home writes down which text is at its top edge as it unmounts, and the new one scrolls that text back to its top edge before its first paint, at its own width. A new message drops the place.
  • Focus and the caret. A navigation from the keyboard, such as a shortcut, swaps the field while it has focus. The old field writes its selection as it unmounts, and the new field takes focus back with the same caret.

Put the provider above every shell the conversation must survive. A dashboard whose settings zone renders a shell of its own loses an in-memory conversation at that crossing unless the provider sits above both.

The morph

Mantle runs the morph. The app wires three things:

  • homeActive on AppLayout.SidePanelRoot. Pass true on the route where the chat is the page, and false everywhere else. Compute it from the URL: mantle reads no router.
  • AppLayout.SharedPart on the parts both homes have. The demo names the title, the new conversation button, and the composer. Each one glides from where it sits in one home to where it sits in the other, at its own size, so text never stretches or blurs.
  • Navigation in a transition. React runs the morph only for a navigation it commits in startTransition. React Router 7 and later do this for every link, sidebar row, and Back and Forward. A command palette that navigates through the router does too.

Mantle does the rest. AppLayout.Content and AppLayout.SidePanel render React's <ViewTransition> with a name that each AppLayout.SidePanelRoot generates, so two shells on one page never collide. mantle.css styles the morph:

  • The panel is a layer over the page. Going from the page to the panel, the card shrinks toward the end edge and lands flush where the panel sits. Going back, it grows from the end edge over the page. The page beneath holds still. The moving card is opaque at every frame and carries the floating panel's shadow. In a right-to-left document the end edge is on the left.
  • One clock. The card, the shared parts, and the panel's close button move for 200ms on mantle's ease-out-strong curve, the curve the panel's own slide uses. The old content fades out in the first 60ms, so two layouts of the same text never show through each other. A new navigation mid-morph interrupts it.
  • The sidebar glides. When the open panel needs the sidebar's lane, the morph collapses or expands the sidebar on the same clock, above the page and flush with the card.
  • The close button slides. It has no twin on the page, so it slides out past the end edge, and back in.
  • A closed panel fades. With the panel closed there is nothing to pair with, so the page fades out on its own, or fades in when the reader comes back.
  • Nothing else animates. A navigation between two product pages, a streaming answer, a first load, a reload, and hydration run no morph. Neither does a navigation out of the shell, such as to a sign-in page.
  • Reduced motion is a cut. Under prefers-reduced-motion: reduce the crossing swaps in one frame, and the browser's own crossfade of the page stops too, so clicks land at once.
  • The phone's navigation sheet closes first. Sidebar.Root closes its mobile sheet on any navigation, before the router commits: a link, a command palette, Back and Forward. The sheet never covers the morph, and the shell needs no close-on-navigate effect.

The morph needs a React with <ViewTransition>. On an earlier React the parts render as before, and the crossing swaps in one frame. Leave out React Router's viewTransition prop and useViewTransitionState: the prop starts a transition of the whole document around every navigation it is on, and mantle's boundaries already decide what animates.

The route decides

The shell reads the pathname once. Here is a React Router 8 layout route, complete as written:

// app/routes/layouts/app.tsx
import {
	AppLayout,
	extractSidePanelStateCookie,
	serializeSidePanelStateCookie,
} from "@ngrok/mantle/app-layout";
import {
	extractSidebarStateCookie,
	serializeSidebarStateCookie,
	Sidebar,
} from "@ngrok/mantle/sidebar";
import { SkipToMainLink } from "@ngrok/mantle/skip-to-main-link";
import { GraphIcon } from "@phosphor-icons/react/Graph";
import { SparkleIcon } from "@phosphor-icons/react/Sparkle";
import { NavLink, Outlet, useLocation } from "react-router";
import { AssistantPanel, isAssistantPath } from "~/features/assistant";
import { ChatSessionProvider } from "~/features/chat-view";
import type { Route } from "./+types/app";
 
const navItems = [
	{ label: "Assistant", icon: <SparkleIcon />, path: "/assistant" },
	{ label: "Endpoints", icon: <GraphIcon />, path: "/endpoints" },
];
 
export const loader = ({ request }: Route.LoaderArgs) => {
	const cookie = request.headers.get("Cookie");
	return {
		sidebarOpen: extractSidebarStateCookie(cookie) ?? true,
		sidePanelOpen: extractSidePanelStateCookie(cookie) ?? false,
	};
};
 
export default function Layout({ loaderData }: Route.ComponentProps) {
	const { pathname } = useLocation();
 
	return (
		<ChatSessionProvider>
			<AppLayout.SidePanelRoot
				defaultOpen={loaderData.sidePanelOpen}
				homeActive={isAssistantPath(pathname)}
				onOpenChange={(open) => {
					document.cookie = serializeSidePanelStateCookie(open);
				}}
			>
				<Sidebar.Root
					defaultOpen={loaderData.sidebarOpen}
					onOpenChange={(open) => {
						document.cookie = serializeSidebarStateCookie(open);
					}}
				>
					<AppLayout.Root className="fixed inset-0">
						<SkipToMainLink />
						<AppLayout.Workspace>
							<Sidebar.Nav aria-label="Main">
								<Sidebar.Body>
									<Sidebar.Group>
										<Sidebar.List>
											{navItems.map((item) => (
												<Sidebar.Item key={item.path}>
													<Sidebar.Tooltip label={item.label}>
														{/* Why `NavLink`: it marks a row current on its child routes too, such as a conversation's URL. */}
														<Sidebar.ItemButton asChild>
															<NavLink to={item.path}>
																{item.icon}
																{item.label}
															</NavLink>
														</Sidebar.ItemButton>
													</Sidebar.Tooltip>
												</Sidebar.Item>
											))}
										</Sidebar.List>
									</Sidebar.Group>
								</Sidebar.Body>
							</Sidebar.Nav>
							<AppLayout.Content>
								<Outlet />
							</AppLayout.Content>
							<AssistantPanel />
						</AppLayout.Workspace>
					</AppLayout.Root>
				</Sidebar.Root>
			</AppLayout.SidePanelRoot>
		</ChatSessionProvider>
	);
}

~/features/assistant stands for the demo's isAssistantPath, AssistantPage, AssistantPanel, and NewConversationButton, without its fake router and product pages. The assistant's route module renders AssistantPage and nothing else. A product page renders AppLayout.SidePanelTrigger in its AppLayout.HeaderActions, the way the side panel demo does.

Two rules keep the morph correct:

  • Read the pathname the way the router matches it. isAssistantPath decodes it and ignores case and a trailing slash, so /Assistant is the assistant's route too, and the page and the panel never show together.
  • Render AssistantPanel on every route. homeActive hides it on the assistant's route, so the shell needs no condition of its own.

Server rendering

Both halves of the state are available on the server, so the first paint is right and nothing corrects it:

  • Which home. The URL. isAssistantPath(pathname) is the same on the server and the client.
  • Whether the panel is open. The side panel cookie. Read it in the loader with extractSidePanelStateCookie, pass it to defaultOpen, and write it back from onOpenChange with serializeSidePanelStateCookie, as Persisting the side panel to a cookie shows.

A document load runs no morph; the browser only snapshots a same-document navigation. The conversation itself is data, and the demo's session is in memory. A real assistant keeps the active conversation on the server and puts its id in the URL or a cookie, so a reload hydrates the same transcript.

Tablet and phone

The panel keeps one <aside> at every width, and the crossing morphs into whichever shape it takes:

  • Beside the page, with the sidebar yielding. Where the row is too narrow for an expanded sidebar and the panel, Sidebar.Root collapses the sidebar while the panel is open, and expands it again when the panel closes. A sidebar the reader toggled keeps their choice.
  • Floating, below mobileBreakpoint. The panel is an overlay the reader can dismiss with Escape while focus is inside. A drag on its header toward the end edge swipes it away at every width.
  • Covering, one breakpoint lower. The panel spans the row and turns modal: the card and the sidebar go inert, a focus trap wraps Tab inside it, and Escape closes it.

Match mobileBreakpoint to Sidebar.Root's, so the sidebar and the panel change presentation at one width. The demo narrows both to md; most apps keep the lg default.

The chat

chat-view.tsx holds the session and the chat both homes render. Nothing in it knows where it renders.

import { Alert } from "@ngrok/mantle/alert";
import { AppLayout } from "@ngrok/mantle/app-layout";
import { Attachment } from "@ngrok/mantle/attachment";
import { Badge } from "@ngrok/mantle/badge";
import { Button, IconButton } from "@ngrok/mantle/button";
import { CodeBlock, jsonCodeBlockValue } from "@ngrok/mantle/code-block";
import { Conversation } from "@ngrok/mantle/conversation";
import { ConversationOutline } from "@ngrok/mantle/conversation-outline";
import { DropdownMenu } from "@ngrok/mantle/dropdown-menu";
import { Empty } from "@ngrok/mantle/empty";
import { Markdown } from "@ngrok/mantle/markdown";
import { Message } from "@ngrok/mantle/message";
import { Panel } from "@ngrok/mantle/panel";
import { PromptInput } from "@ngrok/mantle/prompt-input";
import { Reasoning } from "@ngrok/mantle/reasoning";
import { type ScrollAnchor, useCopyToClipboard, useScrollAnchor } from "@ngrok/mantle/hooks";
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 { GoogleLogoIcon } from "@phosphor-icons/react/GoogleLogo";
import { OpenAiLogoIcon } from "@phosphor-icons/react/OpenAiLogo";
import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from "react";
import {
	type ChatAnswer,
	type ChatFile,
	type ChatToolCall,
	type ChatUserMessage,
	useChat,
} from "~/features/chat";
import { mockRespond } from "~/features/chat-mock";
 
/** Anthropic's mark. Phosphor has the OpenAI and Google marks, but not this one. */
const anthropicIcon = (
	<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
		<path d="M17.304 3.541h-3.672l6.696 16.918H24Zm-10.608 0L0 20.459h3.744l1.37-3.553h7.005l1.369 3.553h3.744L10.536 3.541Zm-.371 10.223 2.291-5.946 2.292 5.946Z" />
	</svg>
);
 
/** The models the menu lists first, each with a line that says what it is for. */
const models = [
	{
		value: "claude-sonnet-5-5",
		label: "Claude Sonnet 5.5",
		icon: anthropicIcon,
		badge: "Staff pick",
		description: "Feature work, best at front-end",
	},
	{
		value: "gpt-6-sol",
		label: "GPT-6 Sol",
		icon: <OpenAiLogoIcon />,
		description: "Code review and root-causing bugs",
	},
	{
		value: "gemini-4-hydrogen",
		label: "Gemini 4 Hydrogen",
		icon: <GoogleLogoIcon />,
		description: "Simple scoped changes, cheapest",
	},
];
 
/** The models under "Other models". */
const otherModels = [
	{ value: "claude-opus-5-5", label: "Claude Opus 5.5", icon: anthropicIcon },
	{ value: "gpt-6-astra", label: "GPT-6 Astra", icon: <OpenAiLogoIcon /> },
	{ value: "gemini-4-carbon", label: "Gemini 4 Carbon", icon: <GoogleLogoIcon /> },
];
 
const efforts = ["Low", "Medium", "High"];
 
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 };
 
/**
 * The chat state that outlives each place the chat shows. The assistant's page
 * and its side panel each mount their own `Chat`, so the messages, the draft,
 * the picks, the reader's place, and the caret live here, above both, and a
 * navigation between them keeps all of it.
 */
function useChatSessionState() {
	const chat = useChat({ respond: mockRespond });
	const [draft, setDraft] = useState("");
	const [files, setFiles] = useState<DraftFile[]>([]);
	const [model, setModel] = useState(models[0]?.value ?? "");
	const [effort, setEffort] = useState("Medium");
	// Why refs: each `Chat` writes them as it unmounts and reads them as it mounts.
	const scrollAnchorRef = useRef<ScrollAnchor | null>(null);
	const caretRef = useRef<{ start: number; end: number } | null>(null);
 
	return {
		...chat,
		// Why: a new conversation starts with an empty composer, too.
		reset: () => {
			chat.reset();
			setDraft("");
			setFiles([]);
		},
		draft,
		setDraft,
		files,
		setFiles,
		model,
		setModel,
		effort,
		setEffort,
		scrollAnchorRef,
		caretRef,
	};
}
 
type ChatSession = ReturnType<typeof useChatSessionState>;
 
const ChatSessionContext = createContext<ChatSession | null>(null);
 
/**
 * Holds one chat for the app. Render it above the routes, so every `Chat` and
 * `ChatOutline` below it shows the same conversation.
 *
 * @example
 * ```tsx
 * <ChatSessionProvider>
 *   <AppShell />
 * </ChatSessionProvider>
 * ```
 */
export function ChatSessionProvider({ children }: { children: ReactNode }) {
	const session = useChatSessionState();
	return <ChatSessionContext value={session}>{children}</ChatSessionContext>;
}
 
/** The chat that the nearest `ChatSessionProvider` holds. */
export function useChatSession(): ChatSession {
	const session = useContext(ChatSessionContext);
	if (session == null) {
		throw new Error("useChatSession must be used inside ChatSessionProvider.");
	}
	return session;
}
 
/**
 * The outline of the person's messages, for the chat's header at every width.
 * It shows from the third message: with fewer, a scroll is faster. It renders
 * before the header's other actions, so they do not move when it appears.
 */
export function ChatOutline() {
	const { messages } = useChatSession();
	const questions = messages.filter(
		(message): message is ChatUserMessage => message.from === "user",
	);
	if (questions.length < 3) {
		return null;
	}
 
	return (
		<ConversationOutline.Root>
			<ConversationOutline.Trigger />
			<ConversationOutline.Content align="end">
				{questions.map((message) => (
					<ConversationOutline.Item key={message.id} target={message.id}>
						{message.text.trim() || message.files.map((file) => file.name).join(", ")}
					</ConversationOutline.Item>
				))}
			</ConversationOutline.Content>
		</ConversationOutline.Root>
	);
}
 
/**
 * 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. It fills its container: a page, a
 * side panel, or a phone. The answer comes from a mock, so the demo runs with
 * no network. Ask anything with "fail" in it to see a failed answer.
 *
 * One gutter sets the layout at each width, as Amp does. The composer sits one
 * gutter in from the edge. The transcript sits 1rem further in, the composer's
 * corner radius, so the edge of a code block or a table meets the composer
 * where its corner ends. The gutter is 0.75rem, and 1rem when the chat is
 * wider than 32rem.
 */
export function Chat({
	onSend,
}: {
	/** Runs after a message sends. The assistant's page opens the side panel here. */
	onSend?: () => void;
}) {
	const chat = useChatSession();
	const { draft, setDraft, files, setFiles, model, setModel, effort, setEffort, caretRef } = chat;
	const fieldRef = useRef<HTMLTextAreaElement | null>(null);
	// Why: each place the chat shows mounts its own transcript at its own width.
	// The transcript writes the reader's place as it unmounts, and the next one
	// scrolls back to it before its first paint. A new message drops the place.
	const anchorContent = useScrollAnchor({
		anchorRef: chat.scrollAnchorRef,
		key: chat.messages.at(-1)?.id,
	});
	// Why: a navigation from the keyboard swaps this field for the other place's
	// while it has focus. The new field takes focus back with the same caret.
	const keepCaret = useCallback(
		(field: HTMLTextAreaElement) => {
			fieldRef.current = field;
			const caret = caretRef.current;
			caretRef.current = null;
			if (caret != null) {
				field.focus({ preventScroll: true });
				field.setSelectionRange(caret.start, caret.end);
			}
			return () => {
				fieldRef.current = null;
				if (document.activeElement === field) {
					caretRef.current = { start: field.selectionStart, end: field.selectionEnd };
				}
			};
		},
		[caretRef],
	);
 
	function send(text: string) {
		if (text.trim() === "" && files.length === 0) {
			return;
		}
		chat.send({
			text,
			files: files.map(({ id, name, size }) => ({ id, name, size })),
			model,
			effort,
		});
		setDraft("");
		setFiles([]);
		// Why: a starter button leaves with the empty state, so focus must not fall to the page.
		fieldRef.current?.focus();
		onSend?.();
	}
 
	const lastAnswer = chat.messages.findLast((message) => message.from === "assistant");
 
	return (
		<div className="@container flex min-h-0 flex-1 flex-col">
			{/* Why a second element: a container query reads an ancestor, so the gutter sits inside the container. */}
			<div className="flex min-h-0 flex-1 flex-col [--gutter:--spacing(3)] @lg:[--gutter:--spacing(4)]">
				{/* Why no scroll here: `Conversation.Viewport` scrolls, so it can follow the answer as it streams. */}
				<Panel.Body className="flex flex-col overflow-visible">
					<Conversation.Root
						streaming={chat.streaming}
						stopped={lastAnswer?.status === "stopped"}
						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>
								<Conversation.Content
									ref={anchorContent}
									aria-label="Conversation with the assistant"
									className="mx-auto w-full max-w-3xl px-[calc(var(--gutter)+(--spacing(4)))] py-6"
								>
									{chat.messages.map((message) =>
										message.from === "user" ? (
											<Message.Root
												key={message.id}
												id={message.id}
												from="user"
												className="scroll-mt-4"
											>
												<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, effort });
																// Why: Retry leaves while the new answer streams, so focus moves to the field.
																fieldRef.current?.focus();
															}
														: undefined
												}
											/>
										),
									)}
								</Conversation.Content>
							</Conversation.Viewport>
						)}
						{/* Why the column: the button's right edge sits just inside the composer's, as in Amp, not at the window's. */}
						{/* Why the gutters: the band reserves the scrollbar's space as the viewport does, so the column matches. */}
						<div className="scrollbar-gutter-both pointer-events-none absolute inset-x-0 bottom-0 h-14 overflow-y-hidden">
							<div className="relative mx-auto h-full max-w-3xl">
								<Conversation.ScrollButton className="pointer-events-auto right-[calc(var(--gutter)+(--spacing(1)))] bottom-3" />
							</div>
						</div>
					</Conversation.Root>
				</Panel.Body>
				{/* Why the gutters: the footer reserves the scrollbar's space as the viewport does, so the composer's edges line up with the transcript's. */}
				{/* Why the negative margin: a hidden overflow would clip the composer's focus ring. */}
				<Panel.Footer className="scrollbar-gutter-both -mt-1 overflow-y-hidden px-(--gutter) pt-1 pb-(--gutter)">
					{/* Why a shared part: on a navigation between the page and the side panel, the composer glides to its new place. */}
					<AppLayout.SharedPart name="composer">
						<PromptInput.Root
							className="mx-auto w-full max-w-[calc(var(--container-3xl)-2*var(--gutter))]"
							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={keepCaret}
								aria-label="Message the assistant"
								name="message"
								placeholder="Ask about your endpoints…"
								value={draft}
								onChange={(event) => setDraft(event.target.value)}
							/>
							<PromptInput.Footer>
								<PromptInput.AttachButton />
								<ModelPicker
									model={model}
									onModelChange={setModel}
									effort={effort}
									onEffortChange={setEffort}
								/>
								<PromptInput.Dictate />
								<PromptInput.Submit />
							</PromptInput.Footer>
						</PromptInput.Root>
					</AppLayout.SharedPart>
				</Panel.Footer>
			</div>
		</div>
	);
}
 
/**
 * The model picker, after Amp's: a quiet button that names the model and its
 * effort, and a menu with one row for each model. The menu takes the width of
 * its widest row, up to 24rem, so a name never wraps. A row truncates only when
 * the screen is narrower than its text. Hidden inputs submit both choices with
 * the message.
 *
 * The button reads the chat's container width: below 24rem, as in a side panel
 * or on a phone, it shows the model's name and drops the effort, which the menu
 * still shows and a screen reader still hears.
 */
function ModelPicker({
	model,
	onModelChange,
	effort,
	onEffortChange,
}: {
	model: string;
	onModelChange: (model: string) => void;
	effort: string;
	onEffortChange: (effort: string) => void;
}) {
	const selected = [...models, ...otherModels].find((option) => option.value === model);
 
	return (
		<>
			<input type="hidden" name="model" value={model} />
			<input type="hidden" name="effort" value={effort} />
			<DropdownMenu.Root>
				<DropdownMenu.Trigger asChild>
					<Button
						type="button"
						appearance="ghost"
						intent="neutral"
						size="sm"
						icon={selected?.icon}
						className="min-w-0"
					>
						<span className="sr-only">Model: </span>
						<span className="truncate">{selected?.label}</span>
						<span className="text-muted flex gap-1.5 @max-sm:sr-only">
							<span aria-hidden>·</span>
							<span>{effort}</span>
							<span className="sr-only"> effort</span>
						</span>
					</Button>
				</DropdownMenu.Trigger>
				<DropdownMenu.Content
					side="top"
					align="start"
					className="max-w-[min(24rem,var(--available-width))]"
				>
					<DropdownMenu.RadioGroup value={model} onValueChange={onModelChange}>
						{models.map((option) => (
							<DropdownMenu.RadioItem
								key={option.value}
								value={option.value}
								textValue={option.label}
								className="gap-3"
							>
								{option.icon}
								<span className="flex min-w-0 flex-1 flex-col">
									<span className="flex items-center gap-2 overflow-hidden">
										<span className="max-w-full shrink-0 truncate font-medium">{option.label}</span>
										{option.badge != null && (
											<Badge
												appearance="muted"
												color="neutral"
												className="min-w-0 shrink overflow-hidden whitespace-nowrap"
											>
												{option.badge}
											</Badge>
										)}
									</span>
									<span className="text-muted truncate text-xs">{option.description}</span>
								</span>
							</DropdownMenu.RadioItem>
						))}
					</DropdownMenu.RadioGroup>
					<DropdownMenu.Separator />
					<DropdownMenu.Sub>
						<DropdownMenu.SubTrigger>
							<span className="flex-1">Effort</span>
							<span className="text-muted ps-6">{effort}</span>
						</DropdownMenu.SubTrigger>
						<DropdownMenu.SubContent>
							<DropdownMenu.RadioGroup value={effort} onValueChange={onEffortChange}>
								{efforts.map((level) => (
									<DropdownMenu.RadioItem key={level} value={level}>
										{level}
									</DropdownMenu.RadioItem>
								))}
							</DropdownMenu.RadioGroup>
						</DropdownMenu.SubContent>
					</DropdownMenu.Sub>
					<DropdownMenu.Sub>
						<DropdownMenu.SubTrigger>Other models</DropdownMenu.SubTrigger>
						<DropdownMenu.SubContent className="max-w-[min(24rem,var(--available-width))]">
							<DropdownMenu.RadioGroup value={model} onValueChange={onModelChange}>
								{otherModels.map((option) => (
									<DropdownMenu.RadioItem key={option.value} value={option.value}>
										{option.icon}
										<span className="min-w-0 truncate">{option.label}</span>
									</DropdownMenu.RadioItem>
								))}
							</DropdownMenu.RadioGroup>
						</DropdownMenu.SubContent>
					</DropdownMenu.Sub>
				</DropdownMenu.Content>
			</DropdownMenu.Root>
		</>
	);
}
 
/** 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}
						truncated={answer.status === "stopped" || answer.status === "failed"}
					>
						{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 shell

assistant-demo.tsx is the two homes, the path helper, and the demo's shell. Swap its fake router for your router's Link and useLocation.

import { AppLayout, useSidePanel } from "@ngrok/mantle/app-layout";
import { Badge } from "@ngrok/mantle/badge";
import { Breadcrumb } from "@ngrok/mantle/breadcrumb";
import { Button, IconButton } from "@ngrok/mantle/button";
import { Sidebar } from "@ngrok/mantle/sidebar";
import { SkipToMainLink } from "@ngrok/mantle/skip-to-main-link";
import { Table } from "@ngrok/mantle/table";
import { Tooltip } from "@ngrok/mantle/tooltip";
import { GlobeHemisphereWestIcon } from "@phosphor-icons/react/GlobeHemisphereWest";
import { GraphIcon } from "@phosphor-icons/react/Graph";
import { PencilSimpleLineIcon } from "@phosphor-icons/react/PencilSimpleLine";
import { PlusIcon } from "@phosphor-icons/react/Plus";
import { SparkleIcon } from "@phosphor-icons/react/Sparkle";
import { XIcon } from "@phosphor-icons/react/X";
import { startTransition, useState, type ReactNode } from "react";
import { Chat, ChatOutline, ChatSessionProvider, useChatSession } from "~/features/chat-view";
 
/*
 * Navigation in this demo is a FAKE ROUTER, because a preview renders inside
 * the docs app's router and React Router permits one router per tree. A real
 * app renders react-router's `Link` through `Sidebar.ItemButton`'s `asChild`
 * and reads `useLocation()`. React Router commits every navigation inside
 * `startTransition`, and this demo does the same, so mantle's morph between
 * the page and the side panel runs in both.
 */
 
/** The assistant's own route, where the conversation is the page. */
const assistantPath = "/assistant";
 
/**
 * Reads a pathname the way React Router matches one: decoded, lowercase, and
 * with no trailing slash. A malformed escape keeps the raw pathname, which is
 * what the router does too.
 */
function normalizePathname(pathname: string): string {
	let decoded = pathname;
	try {
		decoded = decodeURIComponent(pathname);
	} catch {
		// a malformed escape: the raw pathname stands
	}
	return decoded.toLowerCase().replace(/\/+$/, "") || "/";
}
 
/**
 * Returns true on the assistant's route and on its children, such as a
 * conversation's own URL. A sibling route that shares the prefix is a
 * different page. The comparison matches the router's: `/Assistant` and
 * `/assi%73tant` are the assistant's route, so the shell never renders the
 * page and the panel together.
 *
 * @example
 * ```ts
 * isAssistantPath("/assistant"); // true
 * isAssistantPath("/assistant/c_123"); // true
 * isAssistantPath("/Assistant/"); // true
 * isAssistantPath("/assistants"); // false
 * ```
 */
export function isAssistantPath(pathname: string): boolean {
	const normalized = normalizePathname(pathname);
	return normalized === assistantPath || normalized.startsWith(`${assistantPath}/`);
}
 
type DemoNavItem = {
	label: string;
	icon: ReactNode;
	path: string;
};
 
const demoNavItems: ReadonlyArray<DemoNavItem> = [
	{ label: "Assistant", icon: <SparkleIcon />, path: assistantPath },
	{ label: "Endpoints", icon: <GraphIcon />, path: "/endpoints" },
	{ label: "Domains", icon: <GlobeHemisphereWestIcon />, path: "/domains" },
];
 
type DemoEndpoint = {
	url: string;
	type: "Cloud" | "Agent";
	policy: "Traffic Policy" | "No Traffic Policy";
};
 
const demoEndpoints: ReadonlyArray<DemoEndpoint> = [
	{ url: "https://api.acme-demo.ngrok.app", type: "Cloud", policy: "Traffic Policy" },
	{ url: "https://checkout.acme-demo.com", type: "Cloud", policy: "Traffic Policy" },
	{ url: "https://billing.acme-demo.com", type: "Cloud", policy: "No Traffic Policy" },
	{ url: "https://nimble-otter-1423.ngrok.app", type: "Agent", policy: "No Traffic Policy" },
	{ url: "https://orders.internal", type: "Agent", policy: "No Traffic Policy" },
];
 
type DemoDomain = {
	name: string;
	certificate: "Managed" | "Pending";
};
 
const demoDomains: ReadonlyArray<DemoDomain> = [
	{ name: "api.acme-demo.ngrok.app", certificate: "Managed" },
	{ name: "checkout.acme-demo.com", certificate: "Managed" },
	{ name: "billing.acme-demo.com", certificate: "Pending" },
];
 
/**
 * A product page's chrome: the route-owned header with the assistant's trigger
 * in its actions slot, and the `main` body with the page heading at
 * production's scale.
 */
function DemoProductPage({
	title,
	description,
	action,
	children,
}: {
	title: string;
	description: string;
	action: ReactNode;
	children: ReactNode;
}) {
	return (
		<>
			<AppLayout.Header>
				<AppLayout.HeaderStart>
					<Sidebar.Trigger />
				</AppLayout.HeaderStart>
				<AppLayout.HeaderContent>
					<Breadcrumb.Root>
						<Breadcrumb.List>
							<Breadcrumb.Item>
								<Breadcrumb.Page>{title}</Breadcrumb.Page>
							</Breadcrumb.Item>
						</Breadcrumb.List>
					</Breadcrumb.Root>
				</AppLayout.HeaderContent>
				<AppLayout.HeaderActions>
					<AppLayout.SidePanelTrigger icon={<SparkleIcon />} label="Toggle the assistant" />
				</AppLayout.HeaderActions>
			</AppLayout.Header>
			<AppLayout.Body>
				<div className="mx-auto max-w-7xl p-6">
					<header className="mb-6">
						<h1 className="text-strong mb-2 text-3xl font-medium">{title}</h1>
						<p className="text-body max-w-prose text-sm">{description}</p>
					</header>
					<div className="mb-4 flex justify-end">{action}</div>
					{children}
				</div>
			</AppLayout.Body>
		</>
	);
}
 
function DemoEndpointsPage() {
	return (
		<DemoProductPage
			title="Endpoints"
			description="Endpoints are the starting point for all connections in ngrok: the gateway for your HTTP/S, TLS, or TCP applications, configurable with the Traffic Policy you control."
			action={
				<Button type="button" appearance="filled" intent="neutral">
					<PlusIcon />
					New endpoint
				</Button>
			}
		>
			<Table.Root>
				<Table.Element>
					<Table.Head>
						<Table.Row>
							<Table.Header>URL</Table.Header>
							<Table.Header className="w-24">Type</Table.Header>
							<Table.Header className="w-40">Policy</Table.Header>
						</Table.Row>
					</Table.Head>
					<Table.Body>
						{demoEndpoints.map((endpoint) => (
							<Table.Row key={endpoint.url}>
								<Table.Cell className="text-strong font-medium" translate="no">
									{endpoint.url}
								</Table.Cell>
								<Table.Cell>{endpoint.type}</Table.Cell>
								<Table.Cell>
									<Badge
										appearance="muted"
										color={endpoint.policy === "Traffic Policy" ? "amber" : "neutral"}
									>
										{endpoint.policy}
									</Badge>
								</Table.Cell>
							</Table.Row>
						))}
					</Table.Body>
				</Table.Element>
			</Table.Root>
		</DemoProductPage>
	);
}
 
function DemoDomainsPage() {
	return (
		<DemoProductPage
			title="Domains"
			description="Reserve a domain and ngrok serves your endpoints on it, with a managed certificate and nothing to renew."
			action={
				<Button type="button" appearance="filled" intent="neutral">
					<PlusIcon />
					New domain
				</Button>
			}
		>
			<Table.Root>
				<Table.Element>
					<Table.Head>
						<Table.Row>
							<Table.Header>Domain</Table.Header>
							<Table.Header className="w-36">Certificate</Table.Header>
						</Table.Row>
					</Table.Head>
					<Table.Body>
						{demoDomains.map((domain) => (
							<Table.Row key={domain.name}>
								<Table.Cell className="text-strong font-medium" translate="no">
									{domain.name}
								</Table.Cell>
								<Table.Cell>
									<Badge
										appearance="muted"
										color={domain.certificate === "Managed" ? "success" : "neutral"}
									>
										{domain.certificate}
									</Badge>
								</Table.Cell>
							</Table.Row>
						))}
					</Table.Body>
				</Table.Element>
			</Table.Root>
		</DemoProductPage>
	);
}
 
/**
 * The sidebar, the same shape a real app uses with its router. `Sidebar.Root`
 * closes the mobile sheet when a row navigates, so the rows need no close.
 */
function DemoNav({
	pathname,
	onNavigate,
}: {
	pathname: string;
	onNavigate: (path: string) => void;
}) {
	return (
		<Sidebar.Nav aria-label="Main">
			<Sidebar.Body>
				<Sidebar.Group>
					<Sidebar.GroupLabel>Workspace</Sidebar.GroupLabel>
					<Sidebar.List>
						{demoNavItems.map((item) => (
							<Sidebar.Item key={item.path}>
								<Sidebar.Tooltip label={item.label}>
									<Sidebar.ItemButton asChild current={pathname === item.path}>
										<a
											href={item.path}
											onClick={(event) => {
												event.preventDefault();
												onNavigate(item.path);
											}}
										>
											{item.icon}
											{item.label}
										</a>
									</Sidebar.ItemButton>
								</Sidebar.Tooltip>
							</Sidebar.Item>
						))}
					</Sidebar.List>
				</Sidebar.Group>
			</Sidebar.Body>
		</Sidebar.Nav>
	);
}
 
/** The control that starts a new conversation, in both headers. */
function NewConversationButton() {
	const { reset } = useChatSession();
 
	return (
		<AppLayout.SharedPart name="new-conversation">
			<Tooltip.Root>
				<Tooltip.Trigger asChild>
					<IconButton
						type="button"
						appearance="ghost"
						intent="neutral"
						size="sm"
						icon={<PencilSimpleLineIcon />}
						label="New conversation"
						onClick={reset}
					/>
				</Tooltip.Trigger>
				<Tooltip.Content>New conversation</Tooltip.Content>
			</Tooltip.Root>
		</AppLayout.SharedPart>
	);
}
 
/**
 * The assistant's route: the chat as the page, inside the shell's
 * `AppLayout.Content`. The first message opens the side panel, so the
 * conversation comes along when the reader leaves.
 *
 * @example
 * ```tsx
 * // app/routes/assistant.tsx
 * export default function AssistantRoute() {
 *   return <AssistantPage />;
 * }
 * ```
 */
function AssistantPage() {
	const { setOpen } = useSidePanel();
 
	return (
		<>
			<AppLayout.Header>
				<AppLayout.HeaderStart>
					<Sidebar.Trigger />
				</AppLayout.HeaderStart>
				<AppLayout.HeaderContent>
					<AppLayout.SharedPart name="title">
						<h1 className="text-strong text-sm font-medium">Assistant</h1>
					</AppLayout.SharedPart>
				</AppLayout.HeaderContent>
				<AppLayout.HeaderActions>
					<ChatOutline />
					<NewConversationButton />
				</AppLayout.HeaderActions>
			</AppLayout.Header>
			{/* Why no scroll here: `Conversation.Viewport` scrolls, so it can follow the answer as it streams. */}
			<AppLayout.Body className="flex flex-col overflow-y-hidden">
				<Chat onSend={() => setOpen(true)} />
			</AppLayout.Body>
		</>
	);
}
 
/**
 * The assistant's side panel: the same chat beside a page. Render it as the
 * last child of `AppLayout.Workspace`. On the assistant's route,
 * `AppLayout.SidePanelRoot`'s `homeActive` makes it render nothing, because
 * the page is the chat's home there.
 *
 * @example
 * ```tsx
 * <AppLayout.SidePanelRoot homeActive={isAssistantPath(pathname)}>
 *   <AppLayout.Workspace>
 *     <Sidebar.Nav aria-label="Main">…</Sidebar.Nav>
 *     <AppLayout.Content>
 *       <Outlet />
 *     </AppLayout.Content>
 *     <AssistantPanel />
 *   </AppLayout.Workspace>
 * </AppLayout.SidePanelRoot>
 * ```
 */
function AssistantPanel() {
	return (
		<AppLayout.SidePanel aria-label="Assistant" mobileBreakpoint="md">
			<AppLayout.SidePanelHeader>
				<AppLayout.SharedPart name="title">
					<h2 className="text-strong min-w-0 flex-1 truncate text-sm font-medium">Assistant</h2>
				</AppLayout.SharedPart>
				<ChatOutline />
				<NewConversationButton />
				<AppLayout.SidePanelTrigger icon={<XIcon />} label="Close the assistant" />
			</AppLayout.SidePanelHeader>
			<Chat />
		</AppLayout.SidePanel>
	);
}
 
/**
 * The assistant on its own route and beside every other one. The chat is
 * `main` on the assistant's route and the `complementary` side panel on the
 * others. One `ChatSessionProvider` above the shell feeds both, and
 * `homeActive` tells mantle which route is the chat's home, so a navigation
 * between the two morphs the page into the panel. Renders as an entire
 * framed-preview document (see preview-registry.ts). Ask a question, then
 * click Endpoints while the answer streams.
 */
export function AssistantDemo() {
	const [pathname, setPathname] = useState(assistantPath);
	const onAssistantPage = isAssistantPath(pathname);
 
	const navigate = (to: string) => {
		// What React Router does with every navigation: a transition, so the
		// morph that mantle owns runs on the crossing.
		startTransition(() => {
			setPathname(to);
		});
	};
 
	return (
		<ChatSessionProvider>
			{/* Open by default so the first crossing shows the morph. An app reads
					the preference from the side panel cookie in its loader instead. */}
			<AppLayout.SidePanelRoot defaultOpen homeActive={onAssistantPage}>
				{/* the framed demo narrows the mobile breakpoints; most apps keep the "lg" default */}
				<Sidebar.Root mobileBreakpoint="md">
					<AppLayout.Root className="fixed inset-0">
						<SkipToMainLink />
						<AppLayout.Workspace>
							<DemoNav pathname={pathname} onNavigate={navigate} />
							<AppLayout.Content>
								{onAssistantPage && <AssistantPage />}
								{pathname === "/endpoints" && <DemoEndpointsPage />}
								{pathname === "/domains" && <DemoDomainsPage />}
							</AppLayout.Content>
							<AssistantPanel />
						</AppLayout.Workspace>
					</AppLayout.Root>
				</Sidebar.Root>
			</AppLayout.SidePanelRoot>
		</ChatSessionProvider>
	);
}

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;
	effort: string;
	signal: AbortSignal;
}) => AsyncIterable<ChatEvent>;
 
/** The model and the effort a person picks for the next answer. */
export type ChatModelChoice = { model: string; effort: string };
 
/**
 * 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[], choice: ChatModelChoice) {
		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: choice.model,
					effort: choice.effort,
					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, ...choice }: { text: string; files: ChatFile[] } & ChatModelChoice) => {
			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], choice);
		},
		/** 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: (choice: ChatModelChoice) => {
			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, choice);
			}
		},
		/** Drops the answer in flight and every message, for a new conversation. */
		reset: () => {
			abortRef.current?.abort();
			abortRef.current = null;
			commit([]);
		},
	};
}

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:
 
\`\`\`yaml
on_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.