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:

  1. 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.
  2. Blank assistant bubble despite network traffic: After authentication works, sending a prompt returns a 200 stream 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.
  3. 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.
  4. 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 as isStreaming and currentRequestId, 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

  1. 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) chunks
    

    Use the same four-step loop on both bugs so you never stack blind guesses:

    1. Reproduce the failure and note the exact HTTP status, console message, and UI state.
    2. 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.
    3. Test one hypothesis with the smallest possible code or config change, then re-run the exact reproduction.
    4. Add a startup check or unit test so the bug fails loudly if reintroduced.

    Start by checking README.md, package.json scripts, and .env.example—configuration mismatches almost always leave clues there.

  2. 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. Reading import.meta.env.LLM_API_KEY in Vite evaluates to undefined and sends Authorization: Bearer undefined.
    • Unloaded .env file: .env.example was never copied to .env, .env is 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 expects x-api-key: <key>.
    • Malformed key value: Accidental surrounding quotes, trailing newline/spaces, or pointing at the wrong base URL/environment. A one-line curl test 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 .env variable read by a /api/chat backend proxy route so the browser only sends user session credentials.

  3. Fix Bug 2: align the stream parser with the actual payload shape

    When the Network tab shows 200 OK with 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 (Response or EventStream tab) 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 of data: ... lines—place each token increment inside choices[0].delta.content (or delta.text on Anthropic content_block_delta events). Reading .message.content on a streamed chunk returns undefined.
    • Metadata-only chunks and [DONE]: The opening chunk often contains only {"role": "assistant"} and the closing chunk only {"finish_reason": "stop"}, followed by data: [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.text when the component renders msg.content, or mutating lastMsg.content += token in 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 cleanly
    

    Isolate 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();
      }
    }
    
  4. 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, or conversationId. 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 localStorage mirror or conversationId if 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 && !isStreaming so users have clear visual feedback.

  5. 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 (an AbortController, the standard browser object whose abort() method cancels a linked fetch and stream reader), and currentRequestId (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=null
    

    Write 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/chat is 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.

  6. 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 cleanly
    

    Finish by adding two focused unit tests: one asserting that streamChat reassembles tokens across mid-line chunk splits and ignores [DONE], and one asserting that Stop and Clear mid-stream leave isStreaming === 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 to undefined (Bearer undefined). Verify .env loading, dev-server restarts, and provider header names (Authorization: Bearer vs x-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 from choices[0].delta.content (not non-streaming message.content), hold incomplete trailing text across reader.read() calls, flush TextDecoder at end-of-stream, ignore metadata-only chunks, and stop at data: [DONE].
  • Update UI state immutably: Perform immutable state updates—creating a new messages array and updated message object on each token rather than mutating msg.content += token in place—so reference-comparing UI stores (React, Zustand, Redux) re-render reliably.
  • Reuse the store's reset helper for Clear, after aborting: Calling stopStreaming() before store.reset() prevents in-flight callbacks from repopulating a cleared chat, while reusing reset() clears every piece of conversation context consistently.
  • Coordinate Stop with AbortController and currentRequestId: AbortController is a built-in browser/Node object whose abort() method signals linked fetch calls and stream readers to cancel immediately with AbortError. Catch AbortError without showing an error banner, clean up isStreaming inside finally, and guard every callback with currentRequestId === requestId so 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.content on a streamed payload or papering over undefined in the UI instead of inspecting the real JSON chunk contract.
  • Calling JSON.parse on each raw Uint8Array chunk 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 AbortError as a network failure (flashing a red error alert when the user intentionally clicked Stop) or forgetting finally cleanup so isStreaming stays stuck at true.
  • 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_ or NEXT_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 the messages array 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 fetch to return a Response backed by a custom ReadableStream where the test controls exact Uint8Array pushes and timing via promises. Push recorded SSE lines deliberately sliced mid-JSON across chunks, assert that tokens render progressively, trigger Stop mid-stream to verify partial text stays and isStreaming resets to false, and trigger Clear mid-stream to verify late chunks are ignored and the next fetch body starts with a clean history.

Follow-up questions

Similar questions

More Supio interview questions

All 2 Supio questions →