Week 19 • Day 2Week 19

Day 2:Streaming Chat UI — Smart Auto-Scroll & Client Cancellation

Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz

Day 2: Streaming Chat UI — Smart Auto-Scroll & Client Cancellation

1. First-Principles: The "Forced Scroll" UX Disaster

In naive streaming chat implementations, developers attach an unconditional scroll trigger on every received token:

javascript
// NAIVE ANTI-PATTERN - ANNOYS USERS! function onToken(delta) { messageDiv.innerText += delta; chatContainer.scrollTop = chatContainer.scrollHeight; // FORCED JUMP! }

If the assistant is generating a 600-word response and the user scrolls up to review a previous terminal command, the next token arriving violently rips the scroll position back to the bottom, making it impossible to read or copy earlier messages.


2. The Smart Auto-Scroll Algorithm

A production chat client records whether the user was already at the bottom before appending the new token:

Architecture Flow Diagram
Incoming Token Delta->Check{Was User at Bottom? (Within 50px)}
|Yes| Append1[Append Token Delta
Scroll[Auto-Scroll to Bottom (Smooth)
|No (User Scrolled Up)| Append2[Append Token Delta
Keep[Preserve Current Scroll Position (Do Not Jump)

Formula:

isAtBottom=(scrollHeight−scrollTop−clientHeight)≤50px\text{isAtBottom} = (\text{scrollHeight} - \text{scrollTop} - \text{clientHeight}) \le 50\text{px}


3. Client Cancellation with AbortController

When a user clicks "Stop Generating", the client must not simply hide the UI; it must terminate the underlying network connection:

javascript
const abortController = new AbortController(); fetch('/v1/chat/stream', { method: 'POST', body: JSON.stringify(payload), signal: abortController.signal }); // When user clicks "Stop Generating": stopButton.onclick = () => { abortController.abort(); // Disconnects TCP socket immediately };

This triggers ASGI http.disconnect on the FastAPI server, halting upstream token generation and saving money.


In Simple English: Smart Auto-Scroll & Hit-Stop Cancellation (AbortController)

Look at the scroll formula (scrollHeight - scrollTop - clientHeight) <= 40:

  • scrollHeight = full height of the chat conversation.
  • scrollTop + clientHeight = bottom edge of what is visible on screen right now!
  • Why Smart Auto-Scroll Matters: If the user scrolls UP to copy a line of code while the AI is still typing below, don't force-snap them back down! Auto-scroll ONLY when they are already within 40px of the bottom!
  • AbortController Stop Button: Calls controller.abort() to slam shut the network socket immediately, triggering backend generator cancellation and saving tokens!