Troubleshooting and Extending a Streaming LLM Chat UI
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
In a 60-minute practical coding interview, you are handed a runnable local web application for an AI assistant chat interface. The frontend uses a component framework (such as React or Vue) backed by a client-side state store and talks to an LLM endpoint (either directly or via a thin server route) that streams tokens incrementally.
Walk through how you would diagnose two broken behaviors and build two interactive controls:
- Authentication failure on send: Submitting any prompt fails right away with an unauthorized / invalid-credential error in DevTools. Explain how you isolate the misconfiguration and make outbound requests authenticate properly.
- Blank assistant bubble despite network traffic: After authentication works, sending a prompt returns a
200stream in the Network inspector, yet the assistant's reply box shows no text. Explain how you inspect the wire format and repair stream decoding, payload extraction, and UI updates. - Conversation reset control (
Clear): Add a toolbar action that wipes rendered turns, purges accumulated prompt context, and returns the UI to its starting state by calling the store's built-in reset method rather than manually clearing individual fields. - Mid-generation cancel control (
Stop): Display a stop control whenever a reply is actively streaming so clicking it aborts the active HTTP stream (AbortController), retains the text generated so far, updates tracking fields such asisStreamingandcurrentRequestId, and leaves the input ready for the next turn.
Scope & Expectations
- Methodical fault isolation: Reproduce each defect first and use browser network/console evidence to pinpoint the failing boundary before editing code.
- Wire-contract accuracy: Handle streamed chunk framing, partial line buffering, and provider JSON schemas cleanly without mutating store state in place.
- Race-free lifecycle control: Coordinate
Stop,Clear, and subsequent prompts so aborted or stale streams never leak tokens or lock the composer.
Step-by-step walkthrough
Map the request path and set up a debugging loop
Before changing code in a live debugging interview, spend two minutes tracing every hop a chat message takes from the input box to the rendered reply, and narrate your workflow out loud:
ChatInput (Enter / Send button) -> Store action: sendMessage(text) manages messages[], isStreaming, currentRequestId -> API client: streamChat(...) calls fetch(), decodes bytes, parses SSE lines -> Backend proxy (/api/chat, optional) attaches secret API key, forwards to LLM provider -> LLM API streams back Server-Sent Event (SSE) chunksUse the same four-step loop on both bugs so you never stack blind guesses:
- Reproduce the failure and note the exact HTTP status, console message, and UI state.
- Isolate the boundary in the browser DevTools Network tab: inspect outgoing request headers/body versus incoming raw response payload to see whether the bug happens before or after the network boundary.
- Test one hypothesis with the smallest possible code or config change, then re-run the exact reproduction.
- Add a startup check or unit test so the bug fails loudly if reintroduced.
Start by checking
README.md,package.jsonscripts, and.env.example—configuration mismatches almost always leave clues there.Fix Bug 1: trace 401 credential errors through configuration and headers
An unauthorized (
401/"invalid_api_key") response means the upstream LLM endpoint received an authentication header it rejected—most commonly literal"Bearer undefined", an empty string, or the wrong header format. Inspect the outgoing request headers in the Network tab (check key length and prefix only; never print raw secrets into shared logs) and verify four failure points in order:- Unexposed browser environment variable: Frontend bundlers strip environment variables unless they start with a public prefix (
VITE_in Vite,REACT_APP_in Create React App,NEXT_PUBLIC_in Next.js) so server secrets are not leaked by accident. Readingimport.meta.env.LLM_API_KEYin Vite evaluates toundefinedand sendsAuthorization: Bearer undefined. - Unloaded
.envfile:.env.examplewas never copied to.env,.envis in the wrong directory, or the dev server was not restarted after editing.env. - Header contract mismatch: OpenAI-compatible APIs expect
Authorization: Bearer <key>, whereas Anthropic's API expectsx-api-key: <key>. - Malformed key value: Accidental surrounding quotes, trailing newline/spaces, or pointing at the wrong base URL/environment. A one-line
curltest from the terminal immediately separates a revoked key from app misconfiguration.
// Broken: missing VITE_ prefix evaluates to undefined in browser code const apiKey = import.meta.env.LLM_API_KEY; // Fixed for a local prototype: matching public prefix + fail-fast startup guard const apiKey = import.meta.env.VITE_LLM_API_KEY?.trim(); if (!apiKey) { throw new Error( "Missing VITE_LLM_API_KEY: copy .env.example to .env and restart the dev server." ); }Immediately point out the production security rule: any key shipped to browser JavaScript is visible to every user. In production, move the key to a server-side
.envvariable read by a/api/chatbackend proxy route so the browser only sends user session credentials.- Unexposed browser environment variable: Frontend bundlers strip environment variables unless they start with a public prefix (
Fix Bug 2: align the stream parser with the actual payload shape
When the Network tab shows
200 OKwith response text arriving, yet the assistant chat bubble stays blank, data is being dropped between network parsing and UI rendering. Compare the raw Network response (ResponseorEventStreamtab) against what the code reads:- Streaming vs non-streaming JSON path: Non-streaming OpenAI-style responses store text at
choices[0].message.content, whereas Server-Sent Events (SSE)—an HTTP text stream ofdata: ...lines—place each token increment insidechoices[0].delta.content(ordelta.texton Anthropiccontent_block_deltaevents). Reading.message.contenton a streamed chunk returnsundefined. - Metadata-only chunks and
[DONE]: The opening chunk often contains only{"role": "assistant"}and the closing chunk only{"finish_reason": "stop"}, followed bydata: [DONE]. Missing text fields must default to"", never"undefined". - TCP chunk boundaries split lines mid-JSON: Network chunks arrive as arbitrary byte slices (
Uint8Array), not neat lines. - Field mismatch or in-place mutation: Writing
msg.textwhen the component rendersmsg.content, or mutatinglastMsg.content += tokenin place instead of creating a new object reference so React/Vue skips re-rendering.
Trace how a line buffer handles a 3-chunk network stream split mid-JSON:
Chunk 1 (39 chars): 'data: {"choices":[{"delta":{"content":"Hel' -> no '\n' yet; buffer keeps all 39 chars, 0 tokens emitted Chunk 2 (57 chars): 'lo"}}]}\ndata: {"choices":[{"delta":{"content":"!"}}]}\n' -> joins onto buffer -> splits on '\n' into 2 complete lines + trailing "" -> emits "Hello", then emits "!"; buffer is now "" Chunk 3 (14 chars): 'data: [DONE]\n\n' -> sees "[DONE]" and exits cleanlyIsolate the provider format in one small helper and buffer unfinished lines safely:
// Single adapter that knows the provider's streaming JSON contract function extractDelta(chunk: unknown): string { const c = chunk as { choices?: Array<{ delta?: { content?: string } }> }; return c?.choices?.[0]?.delta?.content ?? ""; } function handleSseLine(line: string, onToken: (text: string) => void): boolean { if (!line.startsWith("data:")) return false; const payload = line.slice(5).trim(); if (!payload) return false; if (payload === "[DONE]") return true; // signals end of stream const text = extractDelta(JSON.parse(payload)); if (text) onToken(text); return false; } async function streamChat( body: unknown, signal: AbortSignal, onToken: (text: string) => void ): Promise<void> { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal, }); if (!res.ok || !res.body) { throw new Error(`HTTP ${res.status}: ${await res.text()}`); } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; try { while (true) { const { done, value } = await reader.read(); if (done) { // Flush any remaining multi-byte UTF-8 state and final un-terminated line buffer += decoder.decode(); if (buffer.trim()) handleSseLine(buffer.trim(), onToken); break; } buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; // hold back the incomplete tail for the next read for (const line of lines) { if (handleSseLine(line.trim(), onToken)) return; } } } finally { reader.releaseLock(); } }- Streaming vs non-streaming JSON path: Non-streaming OpenAI-style responses store text at
Build Feature 1: wire the Clear button to abort first and reuse reset
The prompt notes that the store already provides a state-reset action. Always call that existing helper instead of manually zeroing fields (
messages = []), which risks forgetting auxiliary state such as error banners, draft inputs, orconversationId. Two rules keep Clear bug-free:- Cancel any active stream before resetting: If a response is mid-stream when the user clicks Clear, abort it first; otherwise buffered network tokens arriving a few milliseconds later will append phantom words into the freshly cleared chat.
- Clear persisted or server-linked context: Ensure whatever builds the next API payload reads from the reset store (and clear any
localStoragemirror orconversationIdif the app uses one).
type Message = { id: string; role: "user" | "assistant"; content: string; stopped?: boolean; error?: string; }; type ChatState = { messages: Message[]; isStreaming: boolean; currentRequestId: string | null; controller: AbortController | null; }; // Reuse the store's existing reset() action after cancelling any active stream function handleClearChat() { stopStreaming(); // aborts in-flight controller if one exists useChatStore.getState().reset(); // restores clean initial ChatState }Disable the Clear button when
messages.length === 0 && !isStreamingso users have clear visual feedback.Build Feature 2: cancel in-flight streams cleanly with AbortController
Clean stream cancellation relies on three coordinated pieces of state:
isStreaming(toggles the Send button into a Stop button),controller(anAbortController, the standard browser object whoseabort()method cancels a linkedfetchand stream reader), andcurrentRequestId(a unique ID per turn so callbacks from an aborted or cleared request can never corrupt a newer turn).Idle (isStreaming=false) -- sendMessage() --> Streaming (requestId="r1", controller=c1, Stop visible) -- click Stop -----> c1.abort() -> fetch throws AbortError -> keep partial text, mark stopped=true (no error banner!) -> finally: reset isStreaming=false, controller=nullWrite every store update immutably (returning new array/object references so the UI re-renders on every token) and guard every callback with
currentRequestId === requestId:async function sendMessage(userText: string): Promise<void> { const trimmed = userText.trim(); if (!trimmed || useChatStore.getState().isStreaming) return; const requestId = crypto.randomUUID(); const controller = new AbortController(); // Build API history up through the new user message (exclude empty assistant placeholder) const priorMessages = useChatStore.getState().messages.map(({ role, content }) => ({ role, content, })); const apiPayload = { messages: [...priorMessages, { role: "user", content: trimmed }] }; // Appends user message + empty assistant message (id = requestId), sets isStreaming = true useChatStore.getState().startTurn(requestId, trimmed, controller); try { await streamChat(apiPayload, controller.signal, (token) => { if (controller.signal.aborted) return; if (useChatStore.getState().currentRequestId !== requestId) return; useChatStore.getState().appendToken(requestId, token); }); } catch (err) { // Only update UI if this turn was not wiped by Clear if (useChatStore.getState().currentRequestId === requestId) { if ((err as Error).name === "AbortError") { useChatStore.getState().markStopped(requestId); // normal user stop, keep partial reply } else { useChatStore.getState().markError(requestId, (err as Error).message); } } } finally { // Always restore input usability if this turn is still the active one useChatStore.getState().finishTurn(requestId); } } function stopStreaming(): void { useChatStore.getState().controller?.abort(); } // Store reducer helpers (immutable updates, guarded by requestId): // appendToken: (id, token) => set((s) => // s.currentRequestId !== id ? s : { // messages: s.messages.map((m) => (m.id === id ? { ...m, content: m.content + token } : m)), // }), // finishTurn: (id) => set((s) => // s.currentRequestId === id ? { isStreaming: false, currentRequestId: null, controller: null } : s),If
/api/chatis a backend proxy, propagate cancellation upstream too: listen for client disconnect (req.on("close", ...)in Node) and abort the server-to-LLM request so you stop paying for discarded tokens.Verify normal flows and timing edge cases
Use DevTools network throttling ("Slow 3G" or a throttled custom profile) to stretch streams over several seconds and test each transition systematically:
Scenario Expected behavior ------------------------------------ -------------------------------------------------------- Normal prompt Tokens stream smoothly; Stop button switches back to Send Click Stop mid-sentence Text freezes immediately; partial reply kept; no error UI Send a follow-up after Stop New turn streams normally; input is not stuck disabled Click Clear mid-stream Stream aborts; chat stays empty; zero late tokens appear Send a prompt after Clear Network payload contains only the new message Double-press Enter rapidly Guard on isStreaming prevents duplicate parallel streams 401 / 500 response from server Error banner shown on that turn; user can retry cleanlyFinish by adding two focused unit tests: one asserting that
streamChatreassembles tokens across mid-line chunk splits and ignores[DONE], and one asserting thatStopandClearmid-stream leaveisStreaming === false.
Intuition & how it works
Think of a streaming chat app like a live telegraph ticker connected to a remote operator: a badge check at the door lets your request connect (authentication), paper tape arrives in uneven strips that must be taped together into whole lines before reading each word (buffered stream parsing), a Stop lever cuts the wire while leaving the half-printed sentence on the page (request cancellation), and a Clear lever cuts the wire first and then sweeps the desk clean so no stray letters land on the fresh sheet (ordered state reset).
Jumping straight into guessing at UI components fails because identical screen symptoms can come from completely different layers. Fixing an empty chat bubble with content || "" in JSX hides undefined without ever reading the field where streamed tokens actually live, and splitting raw network chunks on "\n" without a buffer works on fast localhost tests yet crashes with SyntaxError on real networks whenever TCP splits a JSON line across two packets. Worse, resetting messages = [] without aborting an active stream lets late-arriving tokens ghost-write into the cleared conversation.
Walk through one concrete 3-chunk reply after sending "Hi" with requestId = "req-1": Chunk 1 arrives with 39 characters 'data: {"choices":[{"delta":{"content":"Hel' (no newline yet, so the line buffer holds all 39 characters and renders nothing), Chunk 2 arrives with 'lo"}}]}\ndata: {"choices":[{"delta":{"content":" there"}}]}\n' (completing two lines so the store immutably updates the assistant bubble to "Hello" and then "Hello there"), and if the user clicks Stop right then, controller.abort() cancels the stream before Chunk 3 arrives, catches AbortError as an expected user action, marks "req-1" as stopped: true with "Hello there" intact, and resets isStreaming = false so the next prompt works immediately.
Key points
- Isolate at the network boundary first: Reproduce the bug and open the browser DevTools Network tab before touching code—outgoing headers/payload vs incoming raw response immediately tells you whether the bug is in request setup or response handling.
- Fix authentication config safely: Frontend build tools require a bundler public env prefix (
VITE_,REACT_APP_,NEXT_PUBLIC_)—a naming rule that prevents server secrets from leaking into client bundles by accident—so unprefixed variables evaluate toundefined(Bearer undefined). Verify.envloading, dev-server restarts, and provider header names (Authorization: Bearervsx-api-key), and move real API keys behind a backend proxy in production. - Parse Server-Sent Events (SSE) with an adapter and a line buffer: SSE (Server-Sent Events) is an HTTP streaming format that pushes newline-separated
data: ...text events over one open connection. Read streamed tokens fromchoices[0].delta.content(not non-streamingmessage.content), hold incomplete trailing text acrossreader.read()calls, flushTextDecoderat end-of-stream, ignore metadata-only chunks, and stop atdata: [DONE]. - Update UI state immutably: Perform immutable state updates—creating a new
messagesarray and updated message object on each token rather than mutatingmsg.content += tokenin place—so reference-comparing UI stores (React, Zustand, Redux) re-render reliably. - Reuse the store's reset helper for Clear, after aborting: Calling
stopStreaming()beforestore.reset()prevents in-flight callbacks from repopulating a cleared chat, while reusingreset()clears every piece of conversation context consistently. - Coordinate Stop with
AbortControllerandcurrentRequestId:AbortControlleris a built-in browser/Node object whoseabort()method signals linkedfetchcalls and stream readers to cancel immediately withAbortError. CatchAbortErrorwithout showing an error banner, clean upisStreaminginsidefinally, and guard every callback withcurrentRequestId === requestIdso stale or cleared turns become harmless no-ops.
Common mistakes
- Stacking unverified code edits before checking the Network tab, masking which layer was actually broken.
- Hard-coding the secret API key in frontend source files or committing
.env, exposing billing credentials to every browser visitor and git clone. - Reading
choices[0].message.contenton a streamed payload or papering overundefinedin the UI instead of inspecting the real JSON chunk contract. - Calling
JSON.parseon each rawUint8Arraychunk without buffering unfinished lines, causing intermittent crashes whenever a JSON object spans two network reads. - Clearing only the rendered array while leaving old history in a separate request buffer or
conversationId, so the LLM still answers using "cleared" context. - Treating
AbortErroras a network failure (flashing a red error alert when the user intentionally clicked Stop) or forgettingfinallycleanup soisStreamingstays stuck attrue. - Cancelling only in the browser while a backend proxy keeps streaming and paying for upstream LLM tokens after the client disconnected.
Follow-up questions
- Why should production web apps route LLM requests through a backend proxy rather than calling the model provider directly from browser code? Anything bundled into browser JavaScript—including
VITE_orNEXT_PUBLIC_variables—can be inspected in DevTools and stolen within seconds. A backend proxy keeps the provider API key strictly on the server, avoids browser CORS (Cross-Origin Resource Sharing) restrictions (headers that block unauthorized cross-domain browser reads), and gives you a trusted place to enforce user login, per-user rate limits, prompt logging, and upstream abort on client disconnect. - When a user aborts a reply mid-stream, should that partial assistant turn be sent in the context window of subsequent prompts? Either keeping or discarding it can work, as long as what stays visible on screen matches what gets sent to the model. Most chat interfaces keep the partial assistant message in both the UI (badged as
"Stopped") and themessagesarray sent on the next turn, because users naturally write follow-ups like"Continue from where you stopped"or"Rewrite that first paragraph". If product prefers discarding stopped drafts, remove or visually gray out the bubble so the user knows the assistant cannot see it. - How can you write fast, deterministic unit or integration tests for chunked streaming, Stop, and Clear without calling a live model endpoint? Stub
fetchto return aResponsebacked by a customReadableStreamwhere the test controls exactUint8Arraypushes and timing via promises. Push recorded SSE lines deliberately sliced mid-JSON across chunks, assert that tokens render progressively, triggerStopmid-stream to verify partial text stays andisStreamingresets tofalse, and triggerClearmid-stream to verify late chunks are ignored and the nextfetchbody starts with a clean history.
Follow-up questions
- Why should production web apps route LLM requests through a backend proxy rather than calling the model provider directly from browser code?
- When a user aborts a reply mid-stream, should that partial assistant turn be sent in the context window of subsequent prompts?
- How can you write fast, deterministic unit or integration tests for chunked streaming, Stop, and Clear without calling a live model endpoint?
Similar questions
- Intercepting Descending Aircraft and Counting User Sessions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager