Chapter 6
The chat widget
The React side, in my-portfolio/src/assistant/: how it stays off your Lighthouse score,
reads a streaming answer, keeps chat state, and renders model output without trusting it.
Costing (almost) nothing until clicked
Your site is built for fast first paint, so the assistant is split in two:
| Piece | When it loads | Size (gzip) |
|---|---|---|
AssistantLauncher.tsx: the ✦ button | With the page | ~2 KB |
AssistantPanel.tsx + markdown + voice mode + orb | First click only | 12.6 KB, separate file |
React.lazy(() => import('./AssistantPanel')) tells the bundler (Vite) to put that module and
everything only it imports into its own file, downloaded the first time it renders. Suspense shows
"loading…" for that moment. Once opened, the panel stays mounted (just hidden) so closing and reopening keeps the
conversation.
A build-time feature flag
import.meta.env.VITE_* variables are replaced with their values at build time. With
VITE_ASSISTANT_URL unset, the launcher renders nothing, so the production site is unchanged until the
backend is deployed and you set it. .env.development points the dev server at
localhost:8000.
Reading the stream
The browser's built-in EventSource reads SSE, but only for GET requests, and our question goes in a
POST body. So we read the response body ourselves. fetch returns a ReadableStream of bytes;
we pipe it through a TextDecoderStream to get text, and split on blank lines:
The key detail is buffer. The network delivers bytes in chunks that don't respect event boundaries:
one chunk can end in the middle of data: {"text": "sched. So we only parse up to the last complete
\n\n and keep the unfinished tail for the next chunk. This is the general pattern for parsing any
streamed protocol. The function is an async generator (async function*), so callers simply
write for await (const event of streamChat(…)).
The signal comes from an AbortController. The ■ stop button calls
controller.abort(), which cancels the fetch; the server notices the closed connection and cancels the
generation (its finally still saves the partial answer).
Chat state: useChat
One hook owns the conversation, shared by text and voice mode. When you send, it immediately adds two messages,
your question and an empty assistant message marked streaming, then patches the assistant message as
events arrive:
metaremembers the conversation id (so the next question continues the same chat) and the 5 retrieved sources.deltaappends text; React re-renders and the answer grows. It also callsonDelta, which voice mode uses to feed sentences to the speaker (chapter 7).donereplaces the 5 retrieved sources with only the cited ones, in citation order, and stores the answer's server id (needed to rate it).
send is a stable function created once (useCallback(…, [])). If it read the
conversationId state, it would forever see the value from when it was created (a stale
closure). A ref is a mutable box that always holds the latest value. The state copy exists only to re-render
the UI.
Rendering untrusted text
The model writes markdown (**bold**, lists, links, [1]). Rendering it with
innerHTML would be dangerous: model output is untrusted input. A prompt injection could
make it emit <img src=x onerror=…>, and you'd be running attacker JavaScript on your site (that's
XSS). Markdown.tsx parses a small subset of markdown into React elements, and React escapes all text. Links
are allowed only to your own pages (rendered as router Links, so they navigate without reloading) or
https://; anything else renders as plain text.
Citation markers like [2][3] become small numbered badges linking to the cited page: the visible proof
that an answer came from your content.
The interface: simple on purpose
The first version had a model name in the header, three header buttons, a mic next to the send button and a disclaimer under the input. It worked, but it felt busy. The redesign copied what the products people already know do (ChatGPT's composer; the "Ask AI" panels of Mintlify and Netlify docs, tested hands-on) and removed everything else:
| Element | Behaviour | Borrowed from |
|---|---|---|
| Opening | Always a fresh chat: a greeting and three suggestions. On a project or job page the first one is "Summarize this page". | ChatGPT, Mintlify |
| Header | History icon · title · new chat (only once there are messages) · close. | Most chat apps |
| History | Its own screen with a ← back arrow, "New chat", and past conversations. Open one and keep typing: the next question continues it. | ChatGPT sidebar, in a small panel |
| Composer | One round button that changes role: voice (a waveform, not a mic) while the box is empty, send (↑) as soon as you type, stop (■) while answering. | ChatGPT |
| Under each answer | Copy · 👍 · 👎 (ratings feed the eval loop, chapter 4). | Mintlify, kapa.ai |
| Shortcut | Ctrl+K (⌘K on Mac) opens and closes it from anywhere. | Docs sites (Mintlify uses Ctrl+I) |
Why a waveform and not a microphone? A mic icon next to a text box means "dictate" in every OS keyboard: people expect their speech to be typed into the box. The waveform says "talk with it", and the screen that opens proves it: the sphere appears and immediately says "Start talking" (chapter 7).
The horizontal-scroll bug, and the CSS rule behind it
The old panel sometimes grew a horizontal scrollbar. The culprit was a source chip with a long title. In flexbox
(and grid), an item's minimum width defaults to min-width: auto, meaning "as wide as my content".
truncate (text-overflow: ellipsis) can't shrink anything if its flex parent refuses to get
narrower than the text. Three small rules fix it, and they are worth memorizing:
min-w-0on the flex child that holds the text: now it may shrink, so the ellipsis kicks in.[overflow-wrap:anywhere]on messages: a long URL or code token can break mid-word instead of pushing the bubble wider.overflow-x-hiddenon the scroll areas, as a last line of defense.
Sending the current page
Page awareness (chapter 3) needs one thing from the frontend: the path the visitor is
on. useChat reads it from the router and keeps it in a ref (same stale-closure reason as
conversationRef above), then sends it with every question:
Links that land on the right section
Answers often link to a section of the homepage, like /#contact. React Router changes the URL but,
unlike a plain HTML page, it doesn't scroll to #contact; and the site's scroll manager only reacted to
path changes, so it either did nothing (already on /) or jumped to the top (from a project
page). The fix: also watch the hash and the navigation key (new on every click, so clicking the same
link twice works), and scroll to the element once the page has laid out:
On phones the panel covers the whole screen, so following a link inside an answer also closes the panel: otherwise you'd navigate to Contact and see… the chat.
Accessibility and storage
- The panel is a
role="dialog"; when closed it'sinert(unfocusable, hidden from screen readers); the message list isaria-live="polite"so screen readers announce answers; Esc closes it. Icon-only buttons all carry anaria-label, and the 👍/👎 usearia-pressed. - Delete in history needs a second click to confirm (no browser
confirm()dialogs). - The only thing kept in localStorage is the anonymous client id, wrapped in
try/catch: private browsing can make localStorage throw, and the chat should still work for that session.
How the content reaches the backend
The site's build script now ends with the knowledge export:
"build": "tsc -b && vite build && node scripts/prerender.mjs && node scripts/export-knowledge.mjs"
Deploying the site publishes /knowledge.json; the production backend reads it from that URL on startup,
or when you call POST /api/admin/reindex. Add a project to projects.ts, deploy, reindex:
the assistant knows it.
A network chunk ends with event: delta\ndata: {"text": "Amine bu. What does streamChat do with it?
Only text up to the last "\n\n" is complete. Everything after waits for more bytes.
Why not render the model's markdown with a quick dangerouslySetInnerHTML?
Treat LLM output like user input: it's text someone else can influence.
A flex row holds an icon and a <span class="truncate"> with a long title, inside a 300px panel. The text overflows instead of ending in "…". What's missing?
truncate already includes nowrap and overflow: hidden. The trap is the flexbox default. It's one of the most common CSS layout bugs, and the reason the panel used to scroll sideways.
Go further
- docsMDN: Using readable streams
- docsReact: lazy and useRef
- docsMDN: AbortController
- docsVite: env variables and modes
- securityOWASP LLM05: Improper Output Handling