13A.2 AI UX I: Streaming, Latency and Perceived Speed

Ship & get hiredLesson 2 of 812,861 words7 parts
Module 13A · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Modules 02 and 03 taught you how to call an LLM: the request, the stream of tokens, the events, the reconnects. This lesson teaches what a person experiences while that happens — because the same model call can feel instant or frozen depending entirely on what your interface does with the wait. You will learn the vocabulary of latency as a product property (time to first token, time to useful, perceived latency), why streaming helps and when it actively hurts, how to smooth bursty provider chunks into a readable pace, how to show progress for multi-step agent work without lying, when to abandon streaming for a background job, how to design the typed event contract between your server and every client, and the accessibility rules that keep a moving screen usable. By the end you will have built the first three files of the module's ai_product package: a typed event contract with an SSE encoder, a chunk smoother you can run on a fake clock, and a step-status tracker — plus a FastAPI endpoint and a terminal client that show the whole path working.

What you'll learn

  • Latency as an experience: the three clocks (time to first token, time to useful, total), the classic 0.1 s / 1 s / 10 s response-time limits and what they mean for LLM features, perceived versus measured latency, and per-feature latency budgets, and how to measure the wait on the client where the user feels it
  • Streaming UX: why streaming helps and when it hurts, chunk smoothing and pacing algorithms, rendering partial Markdown safely, scroll behaviour, and the Stop / Regenerate / Continue / Edit-and-resend controls
  • Progress for multi-step work: status events, step lists, what to reveal of reasoning and tool calls, cancellation, partial results, and why fake ETAs are worse than none
  • Long-running work: when a stream is the wrong shape, job IDs, polling, webhooks and notifications, reconnecting, and idempotent submission
  • Voice latency UX at preview depth: turn-taking, barge-in, fillers and silence thresholds (the depth lives in 09.7 and 13B.5)
  • The event contract: typed events, versioning, ordering and idempotency, SSE versus WebSocket versus fetch-streaming, proxy buffering, heartbeats and backpressure, and how it relates to published agent-UI protocols (AI SDK UI stream, AG-UI)
  • Accessibility of streaming: aria-live politeness, announcing completion rather than every token, prefers-reduced-motion, and pause/stop controls (the full treatment is 13A.4)
  • The ai_product package's first files: events.py, smoother.py, progress.py, and a demo endpoint plus terminal client that stream the contract end to end with no API key

What you don't need

  • API keys, or any running model. Every sample runs against a scripted fake; the one FastAPI demo serves canned chunks, so the whole lesson works offline.
  • JavaScript or TypeScript. Where the browser matters you get the event contract, wireframes and a curl-style client; one short browser sketch is labelled "awareness: not required" and reuses the minimal page pattern from 03.3, Part 11.
  • Prior UX research. Every product term (TTFT, skeleton screen, live region, ETA) is defined where it first appears.

Setup

The package code needs Python 3.11+ and Pydantic; the demo server and client add FastAPI, uvicorn and httpx. First time? Create the project once:

bash
uv init ai-product --bare --python 3.13 && cd ai-product
uv add pydantic fastapi uvicorn httpx
# or: pip install pydantic fastapi uvicorn httpx

The samples were written and checked against pydantic 2.14.3, fastapi 0.162.0, uvicorn 0.54.0 and httpx 0.28.1 as of November 2026. A plain install gives you the newest release of each. The demo server uses FastAPI's built-in SSE support, which needs FastAPI 0.135.0 or newer (the same fastapi.sse import 11C.1 uses); on an older FastAPI the import fails, so upgrade it.

Layout: the package is a folder ai_product/ inside the project (files are printed as # ai_product/events.py and so on), and the two demo programs (demo_app.py, demo_client.py) sit next to it. No .env file is needed — nothing in this lesson calls a provider. If you later point the demo at a real model, the key handling is exactly 03.1's.


What you must be able to do after this lesson#

  • Measure time to first token and time to useful output and explain why both matter
  • Smooth streamed chunks with a max_buffer flush
  • Show progress for multi-step work with a step list and a working Stop
  • Choose job IDs and polling when streaming is the wrong shape
  • Define a typed event contract with versioning and idempotency
  • Make streamed text accessible with aria-live and reduced motion

Why this matters for an AI engineer#

The model's latency is fixed by physics and pricing; everything the user feels is yours to design. Two engineers can call the same endpoint and ship products that feel completely different:

You'll hear... You'll understand it after...
"The model is fast, why does the app feel slow?" 1.2 The classic thresholds and 1.4 Latency budgets
"TTFT is fine but users complain." 1.1 Three clocks
"Users say the answer 'types itself' — is that good?" 2.1 Why streaming helps and 2.2 Chunk smoothing
"Gemini sends huge chunks, Claude sends tiny ones." 2.2 Chunk smoothing
"The page jumps around while it types." 2.3 Rendering streams safely and 2.4 Scroll behaviour
"What does Stop actually do?" 2.5 Controls
"The agent just shows a spinner for 40 seconds." Part 3: Progress for multi-step work
"Should we show the model's reasoning?" 3.3 Showing reasoning and tool activity
"How long will this take?" 3.4 ETAs
"This takes five minutes — streaming won't help." Part 4: Long-running and background tasks
"What messages does the server send the UI?" Part 6: The event contract
"A screen reader user can't use our chat." Part 7: Accessibility of streaming

Part 1: Latency as an experience#

1.1 Three clocks: TTFT, time-to-useful, total#

Lesson 02.5, 1.5 defined the engineering metrics — time to first token (TTFT), output tokens per second, end-to-end latency — and 03.3, Part 12 refined them for streams, adding time to first visible token (TTFVT) because reasoning models can think for seconds before any answer text arrives. This lesson adds the product clock that matters most and is measured least:

Clock Definition What it captures
TTFT Request sent → first token of any kind with content (reasoning or text; an empty thinking delta is a placeholder, not content — 03.3, 12.1) Provider queueing, prompt processing (prefill), network — the "is the service alive" signal
TTFVT Request sent → first answer text the user can read What a chat user actually experiences; on reasoning models it includes all thinking time
Time to useful Request sent → the user can act on the result (answer complete enough, or a usable partial, or a job accepted) The product question: when does the wait pay off? A half-written table isn't useful; a complete status update is
Total time Request sent → terminal state (done, error, job finished) Cost of holding the connection, and patience budget

A support copilot that streams a 400-word draft has TTFVT ≈ 1–3 s and total ≈ 10–20 s. A document-extraction job has TTFVT = never (nothing streams) and "time to useful" = however long the job takes — which is why its UX is a progress display, not a stream. Voice turns have a different clock entirely: caller stops speaking → first audio out (see Part 5).

1.2 The classic thresholds and what they mean for LLM features#

In 1993 Jakob Nielsen condensed decades of human-factors research into three response-time limits, and they still frame every latency conversation:

Limit What the user experiences Design consequence
0.1 s Feels instantaneous — the result seems caused by the user (direct manipulation) Button presses, toggles, keystroke echoes. No LLM feature can hit this; it's the bar for interface chrome, not model output
1.0 s Flow of thought stays unbroken; the user notices the delay but stays in control The ceiling for "the app responded". A spinner that appears within 1 s feels like acknowledgement; past it, users start wondering if anything happened
10 s The limit of attention. Past it users mentally context-switch, and many abandon Hard ceiling for an interactive wait without meaningful progress display. Beyond ~10 s you owe the user a reason to stay: progress, partial results, or an honest "this takes a few minutes" with a way to be notified

The source is Nielsen's Usability Engineering (1993), summarised in his NN/g article "Response Times: The 3 Important Limits" — the thresholds are quoted verbatim there and remain NN/g's stated position.

Two honest caveats before you apply this:

  • These are rules of thumb about human perception, not laws. They describe when attention and sense of control degrade, measured on tasks from the 1970s–80s. LLM waits are different in kind: the user knows a model is thinking, and research (below) shows moderate waits can even raise perceived quality for some tasks.
  • The thresholds apply to unfilled waits. Nielsen's own 10-second rule says users should get "feedback indicating when the computer expects to be done". A 60-second agent run with a live step list is a different experience from 60 seconds of spinner — the limit is about silence, not duration.

1.3 Perceived versus measured latency#

Measured latency is what your traces record (11A.1, 11B.1). Perceived latency is what the person experiences, and the two diverge in both directions:

  • Streaming makes a 15-second answer feel like a 2-second wait — the user starts reading at TTFVT and the rest arrives while they read. This is the single biggest free win in LLM UX, and it's why 11B.1, 2.5 calls streaming, progress display and prefetch "the three techniques that shrink the felt wait without changing the physics".
  • Bursty delivery makes a fast answer feel broken. Providers emit chunks at wildly different rates — 03.3, 12.1 notes Gemini's chunks are often far larger than Claude's deltas, and reasoning models produce long silences followed by floods. A user watching text arrive in clumps experiences stutter, not speed.
  • A visible "it's thinking" state can make a wait feel shorter — if the user sees evidence of work, the same seconds feel productive rather than dead.

What the research actually says (the papers exist and are findable as of November 2026. The QoMEX 2025, IUI 2025 and CHI 2026 EA rows are checked against the published abstracts on OpenAlex, Crossref or Semantic Scholar, read on 12 November 2026; the ACM Digital Library itself blocks automated readers. The abstracts give the headline results only, so open the paper before you quote anything finer):

Study What it found What it means for you
QoMEX 2025 — "Assessing the Influence of End-to-End Request Latency and Response Length on Waiting Time Satisfaction of LLM Users" (DOI) 178 crowdsourced workers, 2,189 ratings (as stated in the paper's abstract): end-to-end latency and response length have significant non-linear effects on waiting-time satisfaction Satisfaction isn't a straight line in milliseconds — there's a knee, and response length matters as much as speed. Don't optimise TTFT at the cost of making answers longer
IUI 2025 — "How Dynamic vs. Static Presentation Shapes User Perception…" (ACM DL) The abstract reports N=103, within-subjects, ANOVA: a typing-simulation (dynamic) display beat instant display on perceived competence, warmth, trustworthiness, engagement and connection — no significant difference on perceived effectiveness Animated text helps people like and trust the product more; it does not make answers seem better. Use it for feel, not as a quality signal
CHI 2026 EA — "Just-in-Time Tokens: Adaptive Token Pacing" (ACM DL) Expert interviews (N=4), a pilot (N=12) and an N=24 controlled study on programming tasks: the abstract reports that pacing matched to the reader's rhythm and the task's complexity reduced frustration and improved cognitive alignment compared with standard streaming. The abstract does not give effect sizes Smoothness is a measurable UX variable, not polish. A steady cadence matched to the reader's rhythm beat standard streaming in that study (small sample, programming tasks), so treat it as suggestive
arXiv 2504.20365 — "Thoughtful, Confused, or Untrustworthy" (Zhou, Gallagher, Sterman; 297 participants) Of five conditions (160, 600 and 6,000 wpm, plus backwards and random), the medium 600 wpm speed was rated most comfortable and produced the highest perceived text quality (the paper also correlates speed with perceived humanness and trustworthiness) There is an optimal reveal rate — faster isn't better. This is evidence for pacing, not for a magic number (see 2.2)
CHI 2026 (arXiv 2604.06183) — "The Impact of Response Latency and Task Type on Human-LLM Interaction and Perception" N=240 analysed, between-subjects: a 2 s time-to-first-token produced lower thoughtfulness ratings than 9 s or 20 s, and lower usefulness than 9 s; behaviour (how many prompts people sent) was robust to latency Counterintuitive and single-study: a very short, unexplained wait can read as "the AI didn't think". Treat as suggestive, not settled. The safe lesson is not "add delay" (never slow a feature on purpose) but that perceived quality depends on how delay is framed, so an honest status ("thinking…") matters

1.4 Latency budgets by feature type#

A latency budget is the maximum time each stage of your feature may take before the experience degrades. Budgets are per feature type, because the physics differ:

Feature type Dominated by Typical TTFVT / first feedback Total budget What fills the wait
Autocomplete / inline suggestion TTFT only; must feel instant < 300–500 ms to first suggestion < 1 s Nothing — if you can't make it, don't show it (debounce input, cache aggressively: 11B.3)
Chat / Q&A TTFT + streaming decode 0.5–3 s to first text (longer with reasoning models) 5–30 s Streamed tokens + status text for the pre-TTFT gap (11B.1, 2.5)
Agent task (multi-step tools) Sum of model calls + tool calls First status update in < 2 s; first real progress < 10 s 30 s–several minutes Step list, tool status, partial results, honest ETA or "we'll notify you" (Part 3, 08A.14, 6.5)
Document / batch job Queue + per-item processing N/A — accept instantly Minutes to hours Job status, progress counts ("12 of 40 processed"), notification on completion (Part 4, 11C.1, 2.9)
Voice turn Endpointing + STT + LLM + TTS < 800 ms caller-stops → agent-speaks is the industry aspiration Per turn, continuously Filler/earcons, barge-in handling, semantic VAD (Part 5, 09.7, 13.2)

The numbers in the "typical" column are orders of magnitude, not targets — measure your own per 03.3, Part 12 and set budgets from your p50/p95, not from a blog post. The structure is what transfers: interactive features owe the user sub-second acknowledgement and visible progress; background features owe them honest state and a way back.

1.5 What to show while you wait#

Four patterns cover almost every "user is waiting" moment. Choose per situation — and note that two of them can lie, which is why the decision table matters:

Pattern What the user sees Best when Lies / fails when
Skeleton screen Grey placeholder blocks shaped like the coming content Content layout is predictable (a chat bubble, a result card) and load is short The wait is long (skeletons imply "almost there"), or the content shape varies wildly — a skeleton for a 3-line answer looks absurd for a 3-page report
Status text / spinner "Thinking…", "Searching the handbook…" Pre-TTFT gap, multi-step work, anything where you can name the current stage Left alone too long (a bare spinner for 40 s is the anti-pattern 08A.14, 6.5 warns about); or it claims a stage you can't actually observe
Progressive disclosure Show what's known so far: partial results, retrieved sources, the plan Multi-step work where early outputs are real (citations found, fields extracted) Partial results are presented as final — a half-extracted invoice total shown without a "draft" marker is a correctness bug, not a UX nicety
Optimistic UI Show the expected result immediately, reconcile when the real one lands Low-stakes, high-confidence actions (posting a message, toggling a setting) The action can fail or be wrong — an LLM answer can't be "optimistically correct". Use for the user's own action ("message sent"), never for the model's output

Offer depth as a choice, not a surprise. Reasoning models trade seconds for quality (02.8), so a product can serve the same question on a fast path or a deeper one. Make that choice legible rather than hidden: label the expected wait in plain words ("usually a few seconds" versus "may think for a minute"), default routine requests to the fast path, escalate automatically only when your router has a measurable reason (11B.5) and say so in the status line, and let the user stop a fast answer and ask for a deeper one. The router decides; the interface only has to make the trade-off visible so that a long wait never looks like a hang.

What this means for you as an engineer: the wait is a designed surface, not a gap. For every feature, write down (a) the acknowledgement that appears within ~1 s, (b) what progress information exists between first acknowledgement and result, and (c) what the user can do if they get bored (stop, background it, come back later). If any of the three has no answer, the feature isn't designed yet — it's just slow.

1.6 Measure the wait where the user feels it#

Server-side TTFT (from your traces) stops at your server's edge. The user's clock runs from the click to the first readable character on their screen, and the gap between the two is your network, your smoother, the browser's rendering and, on phones, the radio waking up. Instrument the client as well:

  1. Record performance.now() at the moment the user submits (the click or Enter handler).
  2. Record it again at the first rendered answer text (TTFVT) and at the terminal done/error event (total).
  3. Send those marks (not the content) to your own telemetry, tagged with the meta event's request_id so they join the server trace (11A.1).
  4. Read percentiles (p50, p95), segmented by device class, network type and feature. A p50 that looks healthy beside a p95 of 12 s describes two different products.

The difference between the client's TTFVT and the server's TTFT is the "UX tax" you can still reduce (smoother start delay, rendering cost, connection setup). A second client-side signal is abandonment during the wait: the share of requests where the user pressed Stop, navigated away or re-sent before the first token. It is a better health signal for latency than the average, because people vote with the back button. 13A.6 turns both into product metrics; this lesson's contract only needs to carry the correlation ID.


Part 2: Streaming UX#

2.1 Why streaming helps — and when it hurts#

02.5, Part 8 and 03.3, Part 1 cover the mechanics and the engineering decision. The UX layer adds three things they don't:

Why it helps. Streaming moves the first readable text from "after the whole answer" to "after TTFT". For a 400-token answer at typical decode speeds, that's the difference between ~0.5–3 s of staring at a spinner and ~15–25 s of it — the user reads while the model writes. It also makes long answers interruptible: a user who sees the answer going wrong can stop it early, which also stops paying for the rest (03.3, 8.5). And the research in 1.3 shows dynamic presentation improves perceived warmth, trust and engagement — real effects, if modest ones.

When it hurts. Streaming is a liability when:

Situation Why streaming hurts What to do instead
Reading speed < delivery speed, sustained The user falls behind; the unread tail scrolls away or forces them to chase it Pace the reveal (2.2); offer "skip to end"
Highly formatted output (tables, code, nested lists) Partial Markdown renders wrong: half a table, an unclosed code fence, a link mid-URL Buffer structural blocks; render only settled regions (2.3)
Output must be checked before display You've already shown text you later must retract (moderation, PII, policy) Don't stream to the user; stream internally and release after checks pass (03.3, 1.3)
Very short answers The whole answer arrives in the TTFT window anyway; animation adds annoyance Return it whole; the "typing" is theatre
Jittery networks Deltas arrive in clumps after buffering; the "stream" is secretly batch Measure inter-delta gaps (03.3, 12); smooth at your edge (2.2)

The governing rule: stream to humans, batch to machines. If a person is reading, stream — but smooth it. If code is consuming, wait for the complete object (03.4).

2.2 Chunk smoothing: turning bursts into a steady cadence#

Providers do not emit text at a steady rate. 03.3, 12.1 observed that "providers batch tokens into events differently (Gemini's chunks are often much larger than Claude's deltas)", and reasoning models produce long silences then floods. Render each chunk the moment it arrives and the user sees stutter: text hangs, jumps, hangs. The CHI 2026 "Just-in-Time Tokens" study (1.3) studied exactly this problem — uneven, bursty delivery breaks a reader's flow — and reports that pacing matched to the reader's rhythm reduced frustration (a small controlled study, abstract only checked).

A chunk smoother (or pacer) sits between the provider stream and the renderer. It buffers incoming text and releases it on a steady cadence. Three design decisions define it:

  1. Release rate. Characters (or grapheme clusters — see the caveat below) per second, tuned near comfortable reading speed. The arXiv 2504.20365 study found ~600 wpm most comfortable for appearing text — for English prose that's roughly 50–60 characters per second (an average word plus its space is ~5–6 characters), which is why chars_per_second defaults to 60 below. For scale, average silent reading is ~238 wpm for English non-fiction (Brysbaert 2019, a meta-analysis of 190 studies) — so the study's "slightly faster than average" framing checks out. Faster isn't better — the eye catches up and waits anyway — but 80+ cps is a reasonable brisk setting for short answers, not a mistake: tune against your own readability tests and your readers' actual speed.
  2. First-release latency. Hold the very first piece for a few tens of milliseconds to coalesce a burst, but never so long the user notices a second delay. TTFT-to-first-visible-text should stay close to TTFVT.
  3. Never fall behind. If the backlog exceeds a cap, flush everything. A smoother that strictly enforces its rate will, on a fast model, lag further and further behind — the user then reads stale text while the answer is already done. The cap converts "perfectly smooth but late" into "briefly fast, then smooth".
flowchart LR
    subgraph prov ["Provider stream (bursty)"]
        C1["chunk: 180 chars"] --> B
        C2["chunk: 4 chars"] --> B
        C3["... 2 s silence ..."] --> B
        C4["chunk: 320 chars"] --> B
    end
    B["ChunkSmoother<br/>buffer + release clock"] --> D["Display events<br/>steady cadence"]
    D --> U["User's screen"]

Here is ai_product/smoother.py — the complete file. It is pure standard library and runs on an injected clock, so you can replay recorded traces deterministically:

python
# ai_product/smoother.py — turn bursty provider chunks into a steady, readable cadence.
"""smoother.py — turn bursty provider chunks into a steady, readable cadence.

A provider stream is bursty: reasoning models go silent then flood, Gemini
sends a few large chunks, Claude sends many tiny deltas, and networks add
their own jitter. Rendered naively, the user sees stutter — text that hangs,
then jumps. A smoother sits between the provider stream and the screen and
releases text on a steady cadence.

Three strategies, one interface:

  passthrough — show every chunk the moment it arrives (the naive baseline)
  batch      — hold chunks for a fixed interval, then flush them together
  pace       — release characters at a target rate, flushing early if the
               backlog grows past max_buffer (never fall behind)

Feed every provider chunk to .feed(); call .release(now) on a timer and show
whatever non-empty string it returns. .next_due(now) says when the next
non-empty release is due, which is what a real UI's animation loop waits for.

Everything runs on an injected clock, so the whole thing is testable with a
FakeClock and no sleeping.
"""
from __future__ import annotations

import time
from collections import deque
from dataclasses import dataclass
from typing import Protocol


class Clock(Protocol):
    def now(self) -> float: ...


class RealClock:
    """Wall-clock source for production use."""

    def now(self) -> float:
        return time.perf_counter()


class FakeClock:
    """Manual clock for tests and replays: time only moves when you say so."""

    def __init__(self, start: float = 0.0) -> None:
        self.t = start

    def now(self) -> float:
        return self.t

    def advance(self, dt: float) -> None:
        self.t += dt


# A recorded provider stream: (arrival_seconds, text) pairs, like the traces
# you capture with 03.3's StreamTimer or your own logging.
Trace = list[tuple[float, str]]


@dataclass
class DisplayEvent:
    """One thing the user's screen showed, and when."""

    t: float
    text: str


def _break_at_word(text: str, limit: int) -> int:
    """How many leading chars of `text` to release, preferring a word boundary."""
    if len(text) <= limit:
        return len(text)
    cut = text.rfind(" ", 0, limit)
    return cut + 1 if cut > 0 else limit


class ChunkSmoother:
    """Coalesce bursty provider chunks into a steady display cadence.

    mode="passthrough": release() returns the whole buffer immediately.
    mode="batch":      release() returns the whole buffer once `interval`
                       seconds have passed since the last flush.
    mode="pace":       release() returns at most `chars_per_second * dt`
                       characters per call, cut at a word boundary when
                       possible; if the backlog exceeds `max_buffer`
                       characters it flushes everything (never fall behind).
    """

    def __init__(
        self,
        mode: str = "pace",
        interval: float = 0.05,
        chars_per_second: float = 60.0,
        max_buffer: int = 400,
    ) -> None:
        if mode not in ("passthrough", "batch", "pace"):
            raise ValueError(f"unknown mode {mode!r}")
        self.mode = mode
        self.interval = interval
        self.chars_per_second = chars_per_second
        self.max_buffer = max_buffer
        self._buf = deque()
        self._buffered = 0
        self._last_release: float | None = None
        self._last_flush: float | None = None
        self._credit = 0.0

    def feed(self, text: str) -> None:
        if text:
            self._buf.append(text)
            self._buffered += len(text)

    def _take(self, n: int) -> str:
        out: list[str] = []
        while n > 0 and self._buf:
            head = self._buf[0]
            if len(head) <= n:
                out.append(head)
                n -= len(head)
                self._buffered -= len(head)
                self._buf.popleft()
            else:
                out.append(head[:n])
                self._buf[0] = head[n:]
                self._buffered -= n
                n = 0
        return "".join(out)

    def release(self, now: float) -> str:
        """Text to display at `now`, or "" if nothing is due yet."""
        if self.mode == "passthrough":
            text = self._take(self._buffered)
            self._last_release = now
            return text

        if self._buffered == 0:
            # Quiet period: clear the release clock (and any stale credit) so
            # the next burst's first release() hits the "first piece
            # immediately" branch below — that branch is dead code if we keep
            # _last_release fresh on every empty tick.
            self._last_release = None
            self._credit = 0.0
            return ""

        if self.mode == "batch":
            if self._last_flush is None or now - self._last_flush >= self.interval:
                self._last_flush = now
                self._last_release = now
                return self._take(self._buffered)
            self._last_release = now
            return ""

        # pace: accumulate character-credit over elapsed time, then spend it.
        # (Computing allowance per call and resetting the clock each call
        # would starve the release rate on fine-grained ticks.)
        if self._last_release is None:
            # First release after a quiet period: show a small first piece
            # immediately so the user sees motion, then settle into cadence.
            self._last_release = now
            self._credit = 0.0
            text = "".join(self._buf)
            n = min(len(text), max(1, int(self.chars_per_second * 0.05)))
            cut = _break_at_word(text, n)
            return self._take(cut)

        self._credit += self.chars_per_second * (now - self._last_release)
        self._last_release = now
        allowed = int(self._credit)
        if self._buffered > self.max_buffer or allowed >= self._buffered:
            self._credit = 0.0
            return self._take(self._buffered)
        if allowed <= 0:
            return ""
        head = "".join(self._buf)
        cut = _break_at_word(head, allowed)
        taken = self._take(cut)
        self._credit -= len(taken)
        return taken

    def next_due(self, now: float) -> float | None:
        """Seconds from `now` until release() returns non-empty, or None if
        the buffer is empty and nothing is known to be coming."""
        if self._buffered == 0:
            return None
        if self.mode == "passthrough":
            return 0.0
        if self.mode == "batch":
            if self._last_flush is None:
                return 0.0
            return max(0.0, self.interval - (now - self._last_flush))
        # pace: roughly one character-slot of waiting
        if self._last_release is None:
            return 0.0
        return max(0.0, 1.0 / self.chars_per_second)


def replay(
    trace: Trace,
    smoother: ChunkSmoother,
    tick: float = 0.005,
    start: float = 0.0,
    max_seconds: float = 60.0,
) -> list[DisplayEvent]:
    """Drive a smoother over a recorded trace on a FakeClock.

    Every `tick` seconds: feed any chunks that arrived, then release whatever
    is due. Returns the display events the user would have seen. Stops as soon
    as everything has been shown; `max_seconds` (counted from the last arrival)
    is only a safety cap, so a slow pacer still gets time to drain its backlog.
    """
    clock = FakeClock(start)
    pending = deque(sorted(trace))
    shown: list[DisplayEvent] = []
    last_arrival = max((t for t, _ in trace), default=0.0)
    end = last_arrival + max_seconds

    while clock.t <= end:
        while pending and pending[0][0] <= clock.t:
            _, text = pending.popleft()
            smoother.feed(text)
        text = smoother.release(clock.now())
        if text:
            shown.append(DisplayEvent(t=clock.t, text=text))
        if not pending and smoother._buffered == 0 and clock.t > last_arrival:
            break
        clock.advance(tick)
    return shown


def metrics(events: list[DisplayEvent]) -> dict:
    """The two numbers the exercise compares: time to first visible text and
    the longest stall (gap) between display events."""
    if not events:
        return {"ttfvt": None, "events": 0, "max_gap": None}
    times = [e.t for e in events]
    gaps = [b - a for a, b in zip(times, times[1:])]
    return {
        "ttfvt": times[0],
        "events": len(events),
        "max_gap": max(gaps) if gaps else 0.0,
    }

Now replay one recorded trace — a bursty, reasoning-model-style arrival pattern — through all three strategies. This runs for real, no key and no network:

python
# replay_demo.py — sits next to ai_product/; run from the project root: uv run python replay_demo.py
from ai_product.smoother import ChunkSmoother, replay, metrics

# A recorded trace: (arrival_seconds, text) — like a StreamTimer capture.
# Six chunks arrive in a 0.13 s burst after a 0.42 s thinking gap.
TRACE = [
    (0.42, "The refund policy allows returns within 30 days of delivery. "),
    (0.45, "Orders placed through the mobile app are eligible for a full refund to the original payment method, "),
    (0.47, "while web orders receive store credit unless the item arrived damaged. "),
    (0.49, "Gift-card purchases are non-refundable. "),
    (0.52, "To start a return, open the order in your account and choose Return item; "),
    (0.55, "you will get a prepaid label by email within one business day."),
]

for name, sm in {
    "passthrough": ChunkSmoother(mode="passthrough"),
    "batch(50ms)": ChunkSmoother(mode="batch", interval=0.05),
    # max_buffer=800: the trace is 408 chars, so the cap never trips and you
    # see true pacing — try max_buffer=300 to watch the flush fallback instead.
    "pace(60cps)": ChunkSmoother(mode="pace", chars_per_second=60.0, max_buffer=800),
}.items():
    m = metrics(replay(TRACE, sm))
    print(f"{name:<14} events={m['events']:<4} "
          f"ttfvt={m['ttfvt']:.3f}s  max_gap={m['max_gap']:.3f}s")

print()
sm = ChunkSmoother(mode="pace", chars_per_second=60.0, max_buffer=800)
for e in replay(TRACE, sm)[:8]:
    print(f"{e.t:6.3f}  {e.text!r}")
Output12 lines
passthrough    events=6    ttfvt=0.420s  max_gap=0.030s
batch(50ms)    events=4    ttfvt=0.420s  max_gap=0.050s
pace(60cps)    events=406  ttfvt=0.420s  max_gap=0.020s

 0.420  'The'
 0.440  ' '
 0.455  'r'
 0.470  'e'
 0.490  'f'
 0.505  'u'
 0.520  'n'
 0.540  'd'

Reading it: passthrough shows everything instantly but in six clumps; batch halves the event count but creates a 50 ms stall per flush; pace trades 406 tiny releases for a maximum stall of 20 ms — imperceptible — at the price of lag. The whole 408-character trace has arrived by 0.55 s, but at 60 characters per second the last character is not shown until about 7.2 s (you can check by printing replay(TRACE, sm)[-1].t). That is the honest cost of strict pacing, and exactly why the smoother has a max_buffer cap and why 60 cps suits a reader's comfortable speed rather than a fast model's output rate. Note pace's ttfvt is the first chunk's arrival time (0.420 s): after a quiet period the first release() shows a small first piece immediately — the is None branch — then settles into cadence, which is exactly the "user sees motion" behaviour the comment promises. Your UI doesn't need 400 DOM updates per answer, though: batch the display events further downstream (one update per animation frame, ~16 ms, per 03.3, 11.7's batching note) while the smoother decides what text is due.

What this means for you as an engineer: put a smoother at the server edge (in the SSE generator) rather than in every client — one implementation, consistent cadence for web, mobile and CLI, and your event contract stays "text due now", not "provider chunk arrived". Tune chars_per_second against your own readability tests, and log the backlog (_buffered) so you can see when the model outpaces your display rate.

2.3 Rendering streams safely#

Text that arrives incrementally is text that arrives broken: half a Markdown table, an unclosed code fence, a URL still being typed, **bold** markers mid-word. Rendering each delta naively produces flicker — formatting appears and disappears as markers complete. The rules:

Hazard What the user sees Mitigation
Partial Markdown **bol renders literally, then snaps to bold Render through an incremental Markdown parser that tolerates truncation (parse the prefix, re-render on each batch); or buffer structural blocks (tables, code fences, lists) until they close
Half-rendered code blocks Unclosed fence swallows the rest of the page Track fence state; render code only inside a closed fence, or style the open fence explicitly as "still writing"
Half-rendered tables A table with a missing last column jumps layout Same rule: tables are structural — buffer until the closing row or a timeout, then render
Link/image preview mid-URL Browser fetches https://exa then https://example.com/... — broken requests, privacy leak Never render links/images until the destination is complete (a ) or whitespace after the URL); 13A.4 owns the sanitisation depth, 12.2/12.5 the security
Layout shift (re-flow) Content above the viewport grows, user's scroll position jumps Reserve space or render into a stable container; CSS overflow-anchor/scroll anchoring (2.4) compensates automatically in supporting browsers
Flickering formatting Bold/italic toggling as ** pairs complete Same incremental-parser fix; alternatively render a "plain text until settled" mode for sensitive layouts
Structured output as partial JSON Half an object isn't valid Show settled fields only (fields followed by a later key), never act on partials — 03.4, Part 8 owns the technique

The pattern that covers most of these: two-zone rendering. Zone 1 is the live tail — plain-text-safe rendering of the newest, unsettled text. Zone 2 is settled history — fully parsed Markdown re-rendered only when a block closes. Most chat UIs do a simpler version: re-render the whole accumulated text through a tolerant Markdown parser on each animation frame; the parser's job is to never crash and never show raw syntax for completed constructs.

2.4 Scroll behaviour#

The canonical chat scroll rule: stick to the bottom only while the user is at the bottom. The moment they scroll up to re-read, streaming must not yank them back. Implementation:

  • Track "is at bottom" (scroll position within a few px of scrollHeight) on scroll events.
  • On each display update: if at-bottom flag is set, scroll to bottom; if the user scrolled up, leave them — and show a "New messages ↓" pill so they can jump back.
  • When they send a message or the stream ends, re-pin to bottom.

Browsers help automatically: scroll anchoring (CSS overflow-anchor, part of the CSS Scroll Anchoring spec) keeps the visible content stable when content is inserted above the viewport — it became Baseline Newly Available across browsers in September 2026 (MDN, as of November 2026). It solves the "image loaded above and pushed my reading position" problem, which is the same problem a growing chat log creates in reverse. You still own the stick-to-bottom policy; the browser owns not-moving-content-the-user-isn't-looking-at.

2.5 Controls: Stop, Regenerate, Continue, Edit and resend#

Every streaming UI needs an escape hatch and a retry path. What each control means is a product decision with real consequences:

Control What it should do The trap
Stop Cancel generation and close the upstream stream so the provider stops billing for ungenerated tokens Hiding the stream client-side while the server keeps generating — you pay for tokens nobody sees (03.3, 8.5: you still pay for input + generated tokens; only OpenRouter documents which providers stop billing immediately). Stop must propagate: browser abort → your server cancels the provider stream (async with + re-raise CancelledError, 03.3, 11.4)
Regenerate Discard this answer, request a new one (new sample, possibly different) Resending the identical request expecting different output — sampling makes it likely different but not guaranteed; say "try again" honestly
Continue Extend a truncated/max_tokens answer from where it stopped Anthropic's documented continuation pattern puts the partial response inside a user message (03.3, 7.5); expect rough joins (missing space, repeated word) — it's for long text, not tool calls
Edit and resend Let the user modify their prompt (or the draft) and resubmit Losing the original — keep both in history; the edit is a new turn, not a rewrite of history
Resume/reconnect Re-attach to an in-flight stream after a network drop Only possible where the provider supports it: OpenAI background responses (starting_after cursor) and Gemini Interactions (last_event_id) — 03.3, Part 9. Elsewhere your options are restart-silently (nothing shown yet), restart-and-reset (send a reset event so the client clears everything shown), or continue (above) — pick by "has anything been shown?"

The reset event exists precisely because "shown" includes reasoning panels and tool badges, not just answer text: a stream that showed a thinking panel then failed must clear that too, or the UI shows it twice (03.3, 7.5).

Put together, a streaming answer pane has a fixed anatomy — status line, live token area, controls, composer:

text
┌──────────────────────────────────────────────────┐
│ Chat — "What is the refund policy?"         [⋯]  │
├──────────────────────────────────────────────────┤
│ ┌─ assistant ─────────────────────────────────┐ │
│ │ ▸ Thinking… (collapsed reasoning summary)   │ │
│ │                                            │ │
│ │ The refund policy allows returns within    │ │
│ │ 30 days of delivery. Orders placed through │ │
│ │ the mobile app are eligible…               │ │
│ │ ▓▓▓▓▓▓▓▓░░  streaming                     │ │
│ └────────────────────────────────────────────┘ │
│ [ ⏹ Stop ]   [ ↻ Regenerate ]   [ Continue ]     │
│ ┌────────────────────────────────────────────┐ │
│ │ Ask a follow-up…                   [Send]  │ │
│ └────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────┘
   ↑ status events      ↑ smoothed token area
                        ↑ controls appear only while
                          a stream is live

Wireframe, not a design system — the anatomy is the lesson: the status line sits above the answer (it explains the pre-TTFT gap), the token area is the smoother's output, the controls are part of the stream's lifecycle (hidden or disabled when nothing is running), and the composer stays usable so the user can queue a follow-up. Every later lesson's UI work renders this same skeleton with different content.

What this means for you as an engineer: your event contract needs done (with status), error (with retryable), reset, and a way to express "cancelled by user" distinctly from "failed". The Stop button is a billing feature as much as a UX one — wire it through to the provider or don't ship it.


Part 3: Progress for multi-step work#

3.1 Why agents need more than a spinner#

A chat answer is one wait. An agent run is many waits summed: plan → retrieve → read sources → call tools → draft → verify, each a full-price model call or tool execution (08A.2). 08A.14, 6.5 states the rule plainly: "agents take seconds-to-minutes, not milliseconds; show progress rather than a frozen spinner." A spinner says "something is happening"; a step list says what is happening, which is the difference between a user who waits and a user who abandons.

The UX requirements for multi-step progress:

  • Name the stages in user language. "Searching the handbook", "Reading 3 sources", "Drafting the reply" — not "step 4", "tool_call", "LLM invocation". The user cares what the system is doing for them.
  • Show position. "Step 3 of 6" or a determinate bar gives the user a reason to wait — the end is visible. (Only show a percentage you can defend; 3.4 covers fake ETAs.)
  • Update on real events. Progress must come from actual tool/model events in your loop, not a timer pretending to be work.
  • Keep finished steps visible. Collapsed or checkmarked — the user should see what was already done, both for trust and so a failure at step 5 doesn't erase the record of steps 1–4.
  • Stream the answer when it starts. The status display hands off to the token stream at the drafting stage; the user experience is continuous, not two UIs.

3.2 Status events and step lists#

The contract event for this is status: a short message plus optional step position. Here is ai_product/progress.py, the complete file — pure standard library, emitting contract-shaped dicts:

python
# ai_product/progress.py — track multi-step task progress and emit status events.
"""progress.py — track multi-step task progress and emit status events.

An agent run is a sequence of named steps ("searching the handbook", "reading
3 sources", "drafting the reply"). This tracker holds the step list, moves
each step through pending -> running -> done/failed/skipped, and emits one
contract-shaped status event per transition, in the shape ai_product.events
uses: {"type": "status", "message": ..., "step": i, "total": n, "state": ...}.

Pure standard library: it emits plain dicts so it works with or without the
Pydantic event models.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class StepState(str, Enum):
    PENDING = "pending"
    RUNNING = "running"
    DONE = "done"
    FAILED = "failed"
    SKIPPED = "skipped"


@dataclass
class Step:
    id: str
    label: str                       # what the user reads: "Searching the handbook"
    detail: str | None = None        # optional live detail: "3 of 12 chunks"
    state: StepState = StepState.PENDING


class ProgressTracker:
    """Owns the step list for one task and the events a UI renders from it."""

    def __init__(self, steps: list[tuple[str, str]]) -> None:
        """steps: [(id, user-facing label), ...] in the order they will run."""
        if not steps:
            raise ValueError("a tracker needs at least one step")
        self.steps = [Step(id=sid, label=label) for sid, label in steps]
        self._by_id = {s.id: s for s in self.steps}
        self._events: list[dict] = []
        self._started = False

    # -- transitions ---------------------------------------------------------
    def _emit(self, step: Step) -> dict:
        index = self.steps.index(step) + 1
        event = {
            "type": "status",
            "message": step.detail or step.label,
            "step": index,
            "total": len(self.steps),
            "state": step.state.value,
            "id": step.id,
        }
        self._events.append(event)
        return event

    def begin(self) -> dict:
        """Emit the opening status: 'Step 1 of N — ...'. Call once."""
        if self._started:
            raise ValueError("begin() already called")
        self._started = True
        first = self.steps[0]
        first.state = StepState.RUNNING
        return self._emit(first)

    def start(self, step_id: str) -> dict:
        step = self._by_id[step_id]
        if step.state is not StepState.PENDING:
            raise ValueError(f"step {step_id!r} already {step.state.value}")
        step.state = StepState.RUNNING
        return self._emit(step)

    def update(self, step_id: str, detail: str) -> dict:
        """Refresh the live detail line without changing state."""
        step = self._by_id[step_id]
        if step.state is not StepState.RUNNING:
            raise ValueError(f"step {step_id!r} is not running")
        step.detail = detail
        return self._emit(step)

    def complete(self, step_id: str, detail: str | None = None) -> dict:
        step = self._by_id[step_id]
        if step.state is not StepState.RUNNING:
            raise ValueError(f"step {step_id!r} is {step.state.value}, not running")
        if detail is not None:
            step.detail = detail
        step.state = StepState.DONE
        return self._emit(step)

    def fail(self, step_id: str, error: str) -> dict:
        step = self._by_id[step_id]
        if step.state is not StepState.RUNNING:
            raise ValueError(f"step {step_id!r} is {step.state.value}, not running")
        step.detail = error
        step.state = StepState.FAILED
        return self._emit(step)

    def skip(self, step_id: str, reason: str = "not needed") -> dict:
        """Skip a step that hasn't run yet or is running — 'not needed'."""
        step = self._by_id[step_id]
        if step.state not in (StepState.PENDING, StepState.RUNNING):
            raise ValueError(f"step {step_id!r} is already {step.state.value}")
        step.detail = reason
        step.state = StepState.SKIPPED
        return self._emit(step)

    # -- queries ------------------------------------------------------------
    @property
    def events(self) -> list[dict]:
        return list(self._events)

    def current(self) -> Step | None:
        for s in self.steps:
            if s.state is StepState.RUNNING:
                return s
        return None

    def fraction(self) -> float:
        """Finished steps (done, skipped or failed) over total — for a
        determinate progress bar. A failed step still counts as finished
        *work*; use summary() to distinguish outcomes."""
        finished = sum(s.state in (StepState.DONE, StepState.SKIPPED, StepState.FAILED)
                       for s in self.steps)
        return finished / len(self.steps) if self.steps else 1.0

    def is_finished(self) -> bool:
        return all(s.state in (StepState.DONE, StepState.SKIPPED, StepState.FAILED)
                   for s in self.steps)

    def summary(self) -> str:
        done = sum(s.state is StepState.DONE for s in self.steps)
        failed = sum(s.state is StepState.FAILED for s in self.steps)
        return f"{done}/{len(self.steps)} steps done" + (f", {failed} failed" if failed else "")

Run it against a six-step support-copilot run — real output, no key:

python
# progress_demo.py — run from the project root: uv run python progress_demo.py
from ai_product.progress import ProgressTracker
import json

t = ProgressTracker([
    ("plan", "Planning the answer"),
    ("search", "Searching the handbook"),
    ("read", "Reading sources"),
    ("check", "Checking the refund policy"),
    ("draft", "Drafting the reply"),
    ("review", "Final review"),
])
t.begin()
t.complete("plan", "route: refund question")
t.start("search"); t.complete("search", "12 handbook pages matched")
t.start("read"); t.update("read", "Reading source 2 of 3"); t.complete("read", "3 sources read")
t.start("check"); t.complete("check", "30-day window applies")
t.start("draft"); t.complete("draft", "reply drafted")
t.start("review"); t.complete("review", "citations verified")
for e in t.events:
    print(json.dumps(e))
print(t.summary(), f"| fraction={t.fraction():.2f} | finished={t.is_finished()}")
Output14 lines
{"type": "status", "message": "Planning the answer", "step": 1, "total": 6, "state": "running", "id": "plan"}
{"type": "status", "message": "route: refund question", "step": 1, "total": 6, "state": "done", "id": "plan"}
{"type": "status", "message": "Searching the handbook", "step": 2, "total": 6, "state": "running", "id": "search"}
{"type": "status", "message": "12 handbook pages matched", "step": 2, "total": 6, "state": "done", "id": "search"}
{"type": "status", "message": "Reading sources", "step": 3, "total": 6, "state": "running", "id": "read"}
{"type": "status", "message": "Reading source 2 of 3", "step": 3, "total": 6, "state": "running", "id": "read"}
{"type": "status", "message": "3 sources read", "step": 3, "total": 6, "state": "done", "id": "read"}
{"type": "status", "message": "Checking the refund policy", "step": 4, "total": 6, "state": "running", "id": "check"}
{"type": "status", "message": "30-day window applies", "step": 4, "total": 6, "state": "done", "id": "check"}
{"type": "status", "message": "Drafting the reply", "step": 5, "total": 6, "state": "running", "id": "draft"}
{"type": "status", "message": "reply drafted", "step": 5, "total": 6, "state": "done", "id": "draft"}
{"type": "status", "message": "Final review", "step": 6, "total": 6, "state": "running", "id": "review"}
{"type": "status", "message": "citations verified", "step": 6, "total": 6, "state": "done", "id": "review"}
6/6 steps done | fraction=1.00 | finished=True

Note the shape is already the contract: every transition is one status event a client can render as a step-list row update. update() exists for live detail ("Reading source 2 of 3") without changing state — that detail line is where denominators live when you have them (09.10, 1.4: "a determinate bar that lies is worse than an honest stage label; chunked work … gives you real denominators").

The step list renders as its own pane — same contract, different layout:

text
┌─ Processing 40 invoices ─────────────────────────┐
│ ✓ Upload & scan          40 files received       │
│ ● Extracting fields      23 of 40 done           │
│ ○ Flagging anomalies                           │
│ ○ Writing summary CSV                          │
│ elapsed 1:42                        [ Cancel ]    │
└──────────────────────────────────────────────────┘
   ✓ done   ● running (with live detail)   ○ pending

Wireframe, not a design system — the anatomy again: finished steps stay visible (checkmarked, collapsed detail), the running step carries the live update() detail with its real denominator, pending steps show the user the shape of the remaining work, and elapsed time replaces the invented ETA. The same component renders a six-step agent run and a 40-item batch — only the labels and denominators change.

3.3 Showing reasoning and tool activity safely#

Two kinds of "show your work" exist, and they have different rules:

  • Reasoning / thinking summaries. Current models think before answering (02.8); providers can stream a summary of it (OpenAI reasoning summaries, Claude display: "summarized", Gemini thought summaries — 02.8, Part 3, 03.3, 6.1). Show it collapsed by default in a "Thinking…" disclosure: it explains the pre-answer silence (1.1) and builds calibrated trust — but it is generated text about the answer, not the answer, and 02.8, 4.3 warns it is not a faithful account of the computation. Never present it as an audit trail; the real trace is your own logging (11A.1).
  • Tool activity. "Calling lookup_order" / "Searching the handbook" badges are safe if you show the tool's name and a human label, and never raw arguments. Tool arguments are model output aimed at your backend — they can contain prompt-injection payloads copied from retrieved content, PII, or exfiltration attempts (12.6, 2.4). A UI that renders args verbatim is an injection surface. Show tool_start/tool_end with name + status + a curated summary ("found 3 orders"), never the JSON.

The citation event deserves a mention here because it arrives mid-stream: emit it when a source is confirmed used (your code decides, not the model's markdown), and render citations as they arrive — they're proof-of-work the user can inspect while the answer types. 13A.3 owns citation UX depth; 07.5 the retrieval side.

3.4 Cancellation, partial results and ETAs#

  • Cancellation must reach every layer: UI stop → your endpoint → provider stream close, plus any queued tool calls. A cancelled run should emit a terminal event (done with status: "cancelled", or error with a cancelled code) so clients don't hang waiting for done.
  • Partial results are legitimate: "found 3 of 5 sources before timing out" is a real, honest outcome — emit what you have with a warning, mark what's missing, and let the user decide (retry, accept partial, escalate). The failure is silent partial results that look complete.
  • ETAs: don't fake them. You cannot predict LLM latency — it varies with load, reasoning depth, output length, and provider queues. What you can show: elapsed time ("working for 12 s"), stage position ("step 3 of 6"), and coarse expectations set before the wait ("this usually takes 30–60 s" — from your own p50/p95, 03.3, Part 12). A countdown that resets or a percentage invented from nothing destroys trust faster than no estimate at all. If you must show a bar, make it indeterminate (animated, no percentage) unless fraction()-style real progress exists.

What this means for you as an engineer: your orchestrator should emit status events at every stage boundary and tool_start/tool_end per call — the UI is a renderer of your event stream, so design the events first and the progress UI falls out for free on every client.


Part 4: Long-running and background tasks#

Deep-dive

4.1 When streaming is not enough#

Streaming solves "the user is watching a spinner for 15 seconds." It does nothing for "the job takes six minutes" — you can't hold an HTTP stream open that long through proxies, users close tabs, and a phone loses signal. Past roughly 30–60 seconds of interactive wait, or whenever the work is batch-shaped (N documents, scheduled reports, exports), the honest shape is a job: accept the request instantly, do the work in the background, and let the user check on it.

Decision rule: stream while the user is present and the answer is one object; job when the work outlives attention. The boundary is your latency budget (1.4) — if total time exceeds what a user will plausibly watch, the stream is the wrong transport even if technically possible.

stateDiagram-v2
    [*] --> queued: POST /jobs → 202 + job_id
    queued --> running: worker picks up
    running --> running: progress events (status)
    running --> succeeded: result stored
    running --> failed: error stored
    running --> cancelled: user cancel
    queued --> cancelled: user cancel
    succeeded --> [*]
    failed --> [*]
    cancelled --> [*]

4.2 The job UX: submit, track, return#

The mechanics are 11C.1, 2.9–2.10's accept-and-poll with idempotency, and 03.9, Part 11's job semantics; 09.10, 1.4 covers the same pattern for media. The UX layer:

  • Accept instantly and say so. 202 Accepted + job ID + a human confirmation ("Queued — we'll email you when it's done" or "Track progress"). The user should leave knowing the work is safe.
  • Give them a way back. A jobs list ("your recent tasks"), a status page per job, and/or a notification. Polling GET /jobs/{id} every few seconds is the simple baseline; web push/email is the "come back later" answer. The job record — status, progress counts, result pointer, timestamps — is the same shape everywhere (09.10, 1.4's job-record fields are a good template).
  • Progress where you have it. "12 of 40 documents processed" beats "running". If the provider or your pipeline exposes per-item counts, surface them via status events or the job record's progress field; if it doesn't, honest stage labels ("extracting → summarising → writing") — never an invented percentage.
  • Idempotent submission. Double-clicking "Process" or retrying a timed-out POST must not start two billed runs. Send an Idempotency-Key header (11C.1, 2.10) and make the server return the existing job — the UX symptom of getting this wrong is "I submitted it twice and now I have two results," which users experience as a bug even when the backend deduped correctly.
  • Reconnect-safe results. The result must be retrievable after the fact: stored, addressable by job ID, and rendered the same whether the user watched live or returned tomorrow. Jobs are the "come back later" surface — design the result page first, the live progress second.

The completion notification is the return path. For async work the notification is the answer to "how do I know it's done" — treat it as a feature surface, not a mailer afterthought:

Decision Options Rule of thumb
Channel In-app inbox/bell, email, web push, SMS In-app for users already inside the product; email for "come back tomorrow" jobs and anyone without push permission; push for time-sensitive completions on installed apps; SMS only for opted-in users and short content
Timing Instant on completion, batched digest, business-hours only Instant for jobs the user is plausibly waiting on; one digest ("3 jobs finished") for high-frequency or overnight batches; respect quiet hours — a 3 a.m. "done" ping is a defect, not diligence
Content Status + counts + deep link Enough to triage without opening: "38 processed, 2 need review". Link-only is fine for routine completions; a failure needs a one-line reason
Controls Unsubscribe, frequency caps, per-job mute Every notification type needs a working opt-out and a repeat cap — notification fatigue is how users learn to ignore the channel your failures also use

Three rules keep it honest:

  • Deep-link to the result, not the app. The notification's job is to land the user on the finished artefact — the job page, the document, the report — in one click. A notification that opens a generic dashboard makes the user hunt for what they asked for.
  • The notification is a pointer, not the payload. Never trust its contents as state: it may be stale, duplicated, or sent just before a retry changed the outcome. On tap, re-fetch the job's real status — the same discipline as reconnecting a stream.
  • Failure notifications are copy too. "Job failed — invoice batch" deserves the same treatment as a UI error state (13A.4): what happened in plain words, whether retry is safe, and a link to the per-item detail. A bare "failed" notification teaches users the channel is noise.

No new event type is needed: the notification is derived server-side from the job's terminal done/error event — it is a delivery concern, not part of the stream contract.

4.3 Batch-style UX for documents#

The capstone's document-intelligence app (13B.3) is the canonical case: upload N files, extract fields, ask questions. The UX lessons that transfer:

  • Per-item status, not one global bar. A 40-file batch where file 7 failed and 39 succeeded needs per-file rows — a single progress bar hides exactly the failure the user needs to see. Model each item as a mini-job with its own status events.
  • Partial success is the normal case. Some files will fail (unsupported format, scan quality, timeout). Show them in a separate "needs attention" state with the reason and a retry — silently dropping failures is how users discover missing documents a week later.
  • Results are reviewable, not just downloadable. Extracted fields should be editable/correctable with the source region highlighted — "show your work" (09.10) is also the cheapest eval data you'll collect.
  • The notification is part of the feature. "Done — 38 processed, 2 need review" in an inbox or bell is the moment the job pays off; design it as carefully as the progress display.

What this means for you as an engineer: jobs reuse your event contract — status for progress, done/error for terminal state — but the transport changes from a held-open stream to poll/webhook delivery. Keep the event shapes identical so the same UI components render live streams and job history.


Part 5: Voice latency UX (a preview)#

Reference

Voice is the extreme case of perceived latency: the budget is sub-second and the "content" is audio, not text. 09.7 owns the architectures (speech-to-speech, cascaded STT→LLM→TTS, full-duplex) and 13B.5 the capstone product; this preview covers only the UX patterns you'll meet there:

Pattern What it solves Where it's covered
Turn-taking / endpointing Deciding when the user has finished speaking — too eager cuts them off, too patient feels dead 09.7, 3.4: server VAD vs semantic VAD vs manual; the silence-duration trade-off
Barge-in / interruption User talks over the agent — the agent must stop, truncate, and listen 09.7, 3.6: speech_started → stop playback → conversation.item.truncate
Fillers and earcons Short acknowledgements ("mm-hm", a click) while the agent thinks, so silence doesn't read as a dropped call 09.7 covers the mechanism; designing when to use them is UX
Latency budget Time-to-first-audio ≈ 500–900 ms for realtime models, 1–3 s cascade 09.7, 13.2 has the stage-by-stage table — the same "budget each stage" method as 1.4
Transcripts as the text equivalent Live captions give deaf/hard-of-hearing users and noisy environments the same "watch it type" benefit as token streaming A UX requirement, not optional decoration

The one idea to carry forward: in voice, the perceived-latency tricks of text UX (streaming, smoothing) have audio analogues — incremental TTS (speak sentence one while generating sentence two), filler sounds during long tool calls, and immediate barge-in response. The event contract generalises too: a voice session is a stream of typed events (user_speech, agent_text, agent_audio, tool_call, interruption) over WebSocket rather than SSE.

What this means for you as an engineer: voice turns reuse the same perceived-latency method as text — decompose the turn into stages (endpointing, STT, LLM, TTS), budget each one, and fill every gap with honest feedback. When you build 13B.5, the Part 6 contract is the same shape; only the transport changes.


Part 6: Designing the event contract#

6.1 Your own protocol, not the provider's#

03.3, 11.2 established the three-layer architecture: provider SDK → your application → your clients. The event contract is the middle layer's output — and it must be yours, not the provider's, for three reasons:

  1. Providers differ. OpenAI emits response.output_text.delta, Claude emits content_block_delta, Gemini emits candidates[].content.parts[] (03.3, Part 3). A client written against one provider's wire format breaks on the next.
  2. The provider doesn't know your UX. It has no concept of your six-step progress, your citation scheme, your "draft vs final" distinction, or your error-recovery semantics.
  3. You need events the provider never sends. status for progress, warning for partial results, reset for restarts, heartbeat for dead-connection detection — these are your product's vocabulary.

6.2 ai_product/events.py: typed events and an SSE encoder#

Here is the complete file. It defines one Pydantic model per event type, unions them into a discriminated StreamEvent, and provides SSEEncoder — a transport-agnostic encoder that produces spec-correct Server-Sent Events frames (the same wire format FastAPI's EventSourceResponse emits, so you can use either):

python
# ai_product/events.py — typed event contract + SSE encoder for AI product UIs.
"""events.py — the typed event contract between your server and every client.

One Pydantic model per event type, discriminated on `type`, so a client can
parse every message into a known shape. `SSEEncoder` turns events into
Server-Sent Events frames; `iter_sse` wraps an event iterable for any ASGI
framework. Pure product code: no provider imports, no I/O.
"""
from __future__ import annotations

from typing import Annotated, Iterable, Literal, Union

from pydantic import BaseModel, Field


# --- the event types ---------------------------------------------------------

class StatusEvent(BaseModel):
    """Progress for multi-step work: 'Searching the handbook', 'Step 3 of 6'."""
    type: Literal["status"] = "status"
    message: str
    step: int | None = None
    total: int | None = None
    state: Literal["pending", "running", "done", "failed", "skipped"] | None = None
    id: str | None = None


class TokenEvent(BaseModel):
    """A piece of answer text, already smoothed for display."""
    type: Literal["token"] = "token"
    text: str


class ReasoningEvent(BaseModel):
    """A piece of the model's thinking summary — collapsed UI by default."""
    type: Literal["reasoning"] = "reasoning"
    text: str


class ToolStartEvent(BaseModel):
    """A tool call began. `label` is the human line; `name` is the tool id."""
    type: Literal["tool_start"] = "tool_start"
    name: str
    label: str | None = None
    args_preview: str | None = None      # truncated, curated — never raw args


class ToolEndEvent(BaseModel):
    """A tool call finished. `summary` is curated ('found 3 orders')."""
    type: Literal["tool_end"] = "tool_end"
    name: str
    ok: bool
    summary: str | None = None


class CitationEvent(BaseModel):
    """A source confirmed as used by the answer."""
    type: Literal["citation"] = "citation"
    index: int
    title: str | None = None
    url: str | None = None


class SuggestionEvent(BaseModel):
    """Follow-up prompts offered after (or during) an answer."""
    type: Literal["suggestion"] = "suggestion"
    items: list[str]


class WarningEvent(BaseModel):
    """Something partial or degraded the user should know about."""
    type: Literal["warning"] = "warning"
    message: str


class ErrorEvent(BaseModel):
    """A failure. `retryable` tells the client whether resubmitting helps."""
    type: Literal["error"] = "error"
    message: str
    retryable: bool = False
    code: str | None = None


class UsageEvent(BaseModel):
    """Token/cost accounting, emitted once near the end."""
    type: Literal["usage"] = "usage"
    input_tokens: int | None = None
    output_tokens: int | None = None
    model: str | None = None


class ResetEvent(BaseModel):
    """'Clear everything shown so far' — for restart-and-reset recovery."""
    type: Literal["reset"] = "reset"
    reason: str | None = None


class HeartbeatEvent(BaseModel):
    """Keep-alive for transports without SSE comment lines (WebSocket etc.)."""
    type: Literal["heartbeat"] = "heartbeat"


class MetaEvent(BaseModel):
    """Stream-open metadata, emitted once and first: the IDs that join every
    later event back to the request, trace and eval records (11A.1), plus the
    model and prompt version that produced the answer."""
    type: Literal["meta"] = "meta"
    request_id: str | None = None
    trace_id: str | None = None
    model: str | None = None
    prompt_version: str | None = None


class DoneEvent(BaseModel):
    """Terminal event. Every stream ends with exactly one of these."""
    type: Literal["done"] = "done"
    status: Literal["completed", "incomplete", "failed", "cancelled"] = "completed"
    reason: str | None = None


# Discriminated union: parse any incoming dict into the right model.
StreamEvent = Annotated[
    Union[
        StatusEvent, TokenEvent, ReasoningEvent,
        ToolStartEvent, ToolEndEvent, CitationEvent,
        SuggestionEvent, WarningEvent, ErrorEvent,
        UsageEvent, ResetEvent, HeartbeatEvent, MetaEvent, DoneEvent,
    ],
    Field(discriminator="type"),
]


def parse_event(data: dict) -> "StreamEvent":
    """Validate one decoded event dict against the contract."""
    # TypeAdapter handles the discriminated union in pydantic v2.
    from pydantic import TypeAdapter
    return TypeAdapter(StreamEvent).validate_python(data)


# --- SSE encoding ------------------------------------------------------------

class SSEEncoder:
    """Turns contract events into Server-Sent Events frames.

    Frame format (WHATWG spec): `event:` names the type, `id:` is a
    monotonically increasing sequence number (clients echo it back as
    Last-Event-ID on reconnect), `data:` carries the JSON payload, and a
    blank line terminates the frame.
    """

    def __init__(self) -> None:
        self._seq = 0

    def encode(self, event: "StreamEvent") -> str:
        self._seq += 1
        data = event.model_dump_json(exclude_none=True)
        return f"event: {event.type}\nid: {self._seq}\ndata: {data}\n\n"

    def encode_many(self, events: Iterable["StreamEvent"]) -> list[str]:
        return [self.encode(e) for e in events]


def iter_sse(events: Iterable["StreamEvent"]) -> Iterable[str]:
    """Convenience: encode an event iterable with one shared sequence."""
    enc = SSEEncoder()
    for e in events:
        yield enc.encode(e)

The event vocabulary maps to everything this lesson taught: meta first, for request/trace correlation; status/tool_start/tool_end for Part 3's step lists, token/reasoning for Part 2's smoothed answer and collapsed thinking, warning for 3.4's honest partials, reset/error/done for 2.5's recovery paths, heartbeat for transports without SSE comments, and usage/citation/suggestion for the extras the product needs.

6.3 Versioning, ordering and idempotency#

  • Versioning. Add new event types freely (old clients ignore unknown event: names — SSE spec behaviour). Never rename or remove a field clients may depend on; add optional fields instead. If a breaking change is unavoidable, version the endpoint (/v2/stream) rather than the event.
  • Ordering. Events are ordered within one stream. id: is the sequence number — clients use it for dedup and for Last-Event-ID resume (03.3, 9). done is always last; a client that sees the connection close without done knows the stream died mid-flight.
  • Idempotency. status/token/reasoning are idempotent-by-accumulation (replaying them rebuilds state). citation, suggestion, usage, done are once-only — a client that reconnects and replays history must not double-count them. Either mark them with a stable id the client dedupes on, or make resume replay only the delta since Last-Event-ID.
  • Product extensions. A product contract extends this vocabulary rather than forking it: add event types to the union (or define product models that keep the same type discriminator and optional-field rules), emit meta first for correlation, and keep every addition additive. When a product needs something this vocabulary can't express — an approval gate, a draft-review payload — the new event type carries it; the renderer switches on type and ignores what it doesn't know. If a change genuinely can't be additive, version the endpoint (/v2/stream), not the event.

6.4 Transports: SSE, WebSocket, fetch-streaming#

Transport Bidirectional? Auto-reconnect? Best for Caveats
SSE (EventSource / fetch + reader) Server→client only (client sends via separate POST) EventSource auto-reconnects + sends Last-Event-ID; fetch streaming does not One-directional event streams: chat answers, job progress, notifications Through proxies that buffer, heartbeats or flush headers matter (03.3, 11.7); no binary. Native EventSource can only issue GET requests without custom headers, so an authenticated chat that POSTs a prompt uses fetch streaming (as this lesson's demo does). Over HTTP/1.1 browsers cap open SSE connections at 6 per browser and domain (across all tabs), so serve over HTTP/2, where the limit defaults to 100 streams (MDN, as of November 2026)
WebSocket Full duplex Manual Voice/realtime sessions (Part 5), interactive agents needing client→server mid-stream messages You own reconnect, ping/pong, backpressure; more complex
Fetch streaming (response.body.getReader()) Server→client, POST body allowed Manual When you need request-body streaming or custom parsing Most control, most code; the terminal client below uses this shape
Polling / webhook N/A N/A Background jobs (Part 4) Latency = poll interval; fine for minutes-scale work

Production concerns that apply regardless of transport — all owned in depth by 03.3, 11.7, listed here because they are UX: heartbeats so proxies don't kill idle connections during long thinking pauses; backpressure so a slow client doesn't make your server buffer unboundedly; timeouts generous enough for reasoning models' long TTFT; and gzip where it helps (SSE compresses poorly on tiny deltas — sometimes better left off).

What this means for you as an engineer: design events first, transports second — the contract is what makes every client consistent, and versioning it additively is what lets web, mobile and CLI ship on their own schedules. The demo below is deliberately small; the discipline it teaches (typed events, done always last, correlation IDs up front) is what scales to the capstone builds.

6.5 Putting it together: the demo endpoint and terminal client#

demo_app.py serves the contract over SSE from a scripted fake — no provider, no key, deterministic chunks. It reuses 03.3, Part 11's fastapi.sse.EventSourceResponse pattern but emits contract events instead of provider-shaped ones:

python
# demo_app.py — FastAPI endpoint streaming ai_product contract events.
# Run from the project root: uv run uvicorn demo_app:app --port 8000   (then: uv run python demo_client.py)
import asyncio
import uuid
from collections.abc import AsyncIterator

from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel

from ai_product.events import DoneEvent, MetaEvent, StatusEvent, TokenEvent
from ai_product.smoother import ChunkSmoother

app = FastAPI(title="ai-product demo")

ANSWER = (
    "The refund policy allows returns within 30 days of delivery. "
    "Orders placed through the mobile app are eligible for a full refund "
    "to the original payment method, while web orders receive store "
    "credit unless the item arrived damaged. Gift-card purchases are "
    "non-refundable. To start a return, open the order in your account "
    "and choose Return item; you will get a prepaid label by email "
    "within one business day."
)


class ScriptedStream:
    """A canned provider stream with realistic timing — a thinking gap, then
    a burst — no API, no key. (Not 08A.2's `ScriptedModel`, which scripts
    tool-loop *turns*; this one only scripts *timing*, so it has its own
    name.) Swap in a real provider stream when you have one."""

    def __init__(self, text: str, chunk_size: int = 80) -> None:
        self._chunks = [text[i:i + chunk_size] for i in range(0, len(text), chunk_size)]

    async def stream(self):
        """Yield (arrival_seconds, text) like a provider stream would."""
        for i, chunk in enumerate(self._chunks):
            # first chunk after a 0.4 s "thinking" gap; the rest arrive fast
            yield (0.4 if i == 0 else 0.4 + 0.05 * i, chunk)


class AskRequest(BaseModel):
    question: str = "What is the refund policy?"


@app.post("/v1/answer/stream", response_class=EventSourceResponse)
async def answer_stream(body: AskRequest) -> AsyncIterator[ServerSentEvent]:
    """The path operation *is* the async generator: FastAPI's routing layer
    sees `response_class=EventSourceResponse` + a generator and encodes each
    yielded ServerSentEvent (03.3, Part 11). Never `return` a response object
    from a coroutine — the SSE encoder only runs for yielded items."""
    yield ServerSentEvent(
        event="meta",
        data=MetaEvent(request_id=uuid.uuid4().hex[:12], model="scripted-fake"),
    )
    yield ServerSentEvent(event="status", data=StatusEvent(message="Thinking…"))

    # Drive the smoother on a fixed 20 ms tick: feed chunks as their scripted
    # arrival times pass, release whatever display text is due.
    smoother = ChunkSmoother(mode="pace", chars_per_second=120.0, max_buffer=600)
    chunks = [pair async for pair in ScriptedStream(ANSWER).stream()]
    loop = asyncio.get_running_loop()
    started = loop.time()
    idx = 0
    while idx < len(chunks) or smoother.next_due(loop.time()) is not None:
        elapsed = loop.time() - started
        while idx < len(chunks) and chunks[idx][0] <= elapsed:
            smoother.feed(chunks[idx][1])
            idx += 1
        out = smoother.release(loop.time())
        if out:
            yield ServerSentEvent(event="token", data=TokenEvent(text=out))
        await asyncio.sleep(0.02)

    yield ServerSentEvent(event="done", data=DoneEvent(status="completed"))


@app.get("/v1/health")
async def health():
    return {"ok": True}

Two details worth noticing. data= takes the Pydantic model itself — FastAPI JSON-serializes it once. Passing .model_dump_json() instead would produce data: "{\"type\":\"status\",…}" on the wire (a quoted string, not an object) because ServerSentEvent.data is always JSON-encoded; raw_data= is the escape hatch for pre-serialised payloads. And max_buffer=600 is deliberate headroom: the canned answer is 408 characters and the backlog stays below 400 at 120 characters per second, so the flush never trips and you see true pacing. With a longer answer or a slower rate the cap would trip and the screen would jump, which is the safety valve working, not a bug.

demo_client.py consumes it with httpx and renders events to the terminal — the same parsing a browser client does:

python
# demo_client.py — terminal client for the contract stream.
# Run: uv run python demo_client.py   (server must be up on :8000)
import asyncio
import json
import time

import httpx


async def main() -> None:
    url = "http://localhost:8000/v1/answer/stream"
    start = time.perf_counter()
    first_token_at = None
    answer = []
    async with httpx.AsyncClient(timeout=None) as client:
        async with client.stream("POST", url, json={"question": "refund?"}) as r:
            r.raise_for_status()
            event_name, data_lines, event_id = "message", [], None
            async for line in r.aiter_lines():
                if line == "":                       # blank line: dispatch frame
                    if data_lines:
                        data = json.loads("\n".join(data_lines))
                        if event_name == "token" and first_token_at is None:
                            first_token_at = time.perf_counter() - start
                        await handle(event_name, data, start)
                        if event_name == "token":
                            answer.append(data["text"])
                    event_name, data_lines = "message", []
                elif line.startswith("event:"):
                    event_name = line[6:].strip()
                elif line.startswith("data:"):
                    data_lines.append(line[5:].strip())
                elif line.startswith("id:"):
                    event_id = line[3:].strip()
    print(f"\n---\n{''.join(answer)}")
    if first_token_at is not None:
        print(f"\nTTFVT: {first_token_at:.2f}s | total: {time.perf_counter()-start:.2f}s")


async def handle(kind: str, data: dict, start: float) -> None:
    t = time.perf_counter() - start
    if kind == "meta":
        print(f"[{t:5.2f}s] meta: request={data.get('request_id')} model={data.get('model')}")
    elif kind == "status":
        print(f"[{t:5.2f}s] status: {data.get('message')}")
    elif kind == "token":
        print(data["text"], end="", flush=True)
    elif kind == "tool_start":
        print(f"\n[{t:5.2f}s] tool: {data.get('label') or data['name']}")
    elif kind == "tool_end":
        print(f"[{t:5.2f}s]   -> {'ok' if data.get('ok') else 'FAILED'}: {data.get('summary') or ''}")
    elif kind == "warning":
        print(f"\n[{t:5.2f}s] WARNING: {data['message']}")
    elif kind == "error":
        print(f"\n[{t:5.2f}s] ERROR ({'retryable' if data.get('retryable') else 'fatal'}): {data['message']}")
    elif kind == "done":
        print(f"\n[{t:5.2f}s] done: {data.get('status')} {data.get('reason') or ''}")


if __name__ == "__main__":
    asyncio.run(main())
Example output · illustrative8 lines
[ 0.00s] meta: request=3f9a2c71b0d4 model=scripted-fake
[ 0.00s] status: Thinking…
The refund policy allows returns within 30 days of delivery. Orders placed through the mobile app are eligible
[ 3.81s] done: completed

---
The refund policy allows returns within 30 days of delivery. ...
TTFVT: 0.42s | total: 3.84s

The browser version is the same parse loop in JavaScript — awareness only, not required: fetch() the endpoint, read response.body with a TextDecoder, split on blank lines, dispatch on event:, render token into the message div. 03.3, Part 11 builds that minimal page; this lesson's contract is what it would consume.


Part 7: Accessibility of streaming (preview of 13A.4)#

Deep-dive

A streaming UI is a moving UI, and moving UIs have accessibility rules that static pages don't. 13A.4 owns the full treatment; the streaming-specific rules:

  • Announce completion, not every token. A live region that speaks each token is unusable — screen readers would stutter through the answer. Put aria-live="polite" (or role="status", which implies polite + aria-atomic) on a summary element that announces "Answer complete" or "3 sources found" once — the status event's terminal state is the announcement trigger, not the token stream. MDN's aria-live reference (verified November 2026) defines the three politeness levels: off, polite (next graceful opportunity), assertive (interrupt immediately — reserve for errors).
  • Never lose the text. Screen-reader users must be able to read the full answer after it streams — the rendered DOM must contain the complete text, not just the visual animation. Token streaming that only "types" visually without accumulating real text is an accessibility failure.
  • prefers-reduced-motion. The typing animation itself is non-essential motion; honour the media query (Baseline Widely Available since January 2020, MDN) by rendering text instantly for users who request reduced motion — the content is identical, only the reveal differs.
  • Pause/stop must be keyboard-operable. The Stop control is a real button with a label ("Stop generating"), reachable by Tab, activatable by Enter/Space — not a click-only div.
  • Don't auto-scroll under the user. The stick-to-bottom rule (2.4) is also an accessibility rule: yanking focus/scroll position while a screen-reader user is reading earlier content is disorienting. Respect the same "user scrolled up = hands off" flag.

WCAG context: WCAG 2.2 is the current W3C Recommendation (last updated 12 December 2024); the Accessibility Guidelines WG is not planning a 2.3 — WCAG 3.0 is a Working Draft published September 2026 (W3C, verified November 2026). For streaming specifically, 2.2's status-message criterion (4.1.3) and the general perceivable/operable principles are what apply; 13A.4 maps them fully.

What this means for you as an engineer: accessibility rules are contract rules — encode them in the events and components (announce-on-terminal-state, a reduced-motion flag your renderer honours, keyboard-operable controls) rather than retrofitting them onto a finished UI. If the contract can't express "the stream ended" or "motion is reduced", the UI can't be accessible — which is why done, status and the meta fields exist.


What goes wrong What the user experiences Root cause Prevention
Text arrives in clumps Stutter, jumps, unreadable Provider burstiness rendered raw ChunkSmoother pace mode (2.2)
Half-rendered Markdown Literal **, broken tables, flicker Naive per-delta render Incremental parser / settled-block buffering (2.3)
Page jumps while reading Lost scroll position Content growth above viewport Stick-to-bottom policy + overflow-anchor (2.4)
Stop button hides the stream Keeps paying, thinks it stopped Client-side cancel only Propagate cancel to provider (2.5, 03.3, 8.5)
Stream dies mid-answer, UI hangs Spinner forever, no error No terminal event on disconnect done/error always emitted; client timeout + reconnect (6.3)
Agent shows a bare spinner for 40 s Abandons the task No progress events status/tool_* events per stage (Part 3)
Fake progress bar / invented ETA Trust destroyed when it stalls Timer pretending to be work Real fraction() or indeterminate bar (3.4)
Tool args rendered in UI Injection payloads visible/executable Raw model output to DOM Curated labels only (3.3, 12.6, 2.4)
Double-submitted job Two billed runs, confusing UX No idempotency key Idempotency-Key header (4.2)
Live region reads every token Screen reader unusable aria-live on token stream Announce terminal state only (Part 7)
Long job holds an HTTP stream Proxy timeout, lost work Wrong transport for the duration Job + poll/webhook (Part 4)

Where you'll use this#


Common misconceptions#

Misconception Why it's wrong
"Streaming makes the model faster." Total generation time is identical — streaming improves perceived speed by starting the user's reading at TTFT, not by finishing sooner. 02.5, Part 8
"TTFT is the only latency that matters." TTFT is the first signal; TTFVT (first visible answer text) and total time determine whether the user stays. Reasoning models decouple them by seconds. 1.1
"A spinner is fine for anything under a minute." A spinner says nothing; past ~10 s of unfilled wait users context-switch. Progress must be informative, not just animated. 1.2, 3.1
"Show the raw stream — it's the most honest." Raw provider chunks are bursty, unformatted, and provider-specific. The honest thing is a curated contract; honesty is in the content, not the wire format. 6.1
"Typing effects are just decoration." Research shows dynamic presentation measurably improves perceived trust and engagement — but it's a feel enhancement, not a quality signal, and it must never fake progress. 1.3, 2.2
"The provider's event format is fine for our UI." Provider events are model plumbing; your UI needs product events (status, warning, reset, done) that providers never send. 6.1
"Stop just hides the answer." Client-side hide still bills the full generation. Real Stop cancels upstream. 2.5
"We can estimate completion time." LLM latency is too variable; show elapsed time and stage position, or an honest coarse range — never a fake countdown. 3.4
"Long jobs can just stream forever." Proxies time out, users leave, phones sleep. Past ~30–60 s, use a job. Part 4
"Accessibility is a 13A.4 problem, not mine." The streaming rules (live regions, reduced motion, keyboard stop) apply to every lesson's code — 13A.4 deepens them, it doesn't own them alone. Part 7

Key takeaways#

  • Latency is a product property. The same model call feels instant or frozen depending on what your UI does with the wait. Budget per feature type; measure TTFT, TTFVT and total separately.
  • Streaming helps humans, hurts machines. Stream to people (smoothed), batch to code. The smoother's job is steady cadence; its hard rule is never fall behind.
  • Progress must be real. Status events come from actual stages; fake ETAs and invented percentages destroy trust faster than honest indeterminacy.
  • Pick the transport by duration. Stream for seconds, job for minutes. Jobs need idempotent submission, a way back, and results that outlive the session.
  • Your event contract is the product's vocabulary. Typed events (status, token, tool_*, warning, error, reset, done) decouple every client from every provider — version additively, order always, end always with done.
  • Accessibility is part of the contract. Announce completion not tokens, honour reduced motion, keep Stop keyboard-operable, never scroll-yank.

Terms introduced in this lesson#

Term One-line definition
Latency budget Per-stage maximum times for a feature's wait
Client-side TTFVT / abandonment during the wait Time from submit to first readable text measured in the browser; share of requests the user stops or leaves before the first token
TTFT Time to first token of any kind with content (empty placeholder deltas don't count)
TTFVT Time to first visible token / first readable answer text
Time to useful When the user can act on the result
Perceived latency Felt wait, as distinct from measured latency
Chunk smoother / pacer Buffer + steady-cadence release of bursty provider chunks
Max stall Longest gap between display events in a smoothed stream
Skeleton screen Placeholder blocks shown while content loads
Optimistic UI Show the expected result before confirmation (wrong for LLM output)
Progressive disclosure Show what's known so far during multi-step work
Live region / aria-live Accessibility announcement channel (off / polite / assertive)
prefers-reduced-motion User setting requesting minimal animation
Scroll anchoring / overflow-anchor Browser compensation that keeps visible content stable on insertion
Event contract The typed message vocabulary between server and clients
meta event Stream-open correlation fields: request/trace IDs, model, prompt version
SSE / Server-Sent Events One-directional HTTP event stream (text/event-stream)
Last-Event-ID SSE resume cursor a client echoes back on reconnect
Accept-and-poll / job Submit-instantly, track-later pattern for long-running work
Idempotency key Dedup token making resubmission safe
Barge-in User interruption of agent speech (voice)
Filler / earcon Acknowledgement sound during agent thinking (voice)

Project checklist#

Copy this into your project's README or tracking issue and check items off as you ship:

  • Latency budget written down per feature (TTFT / TTFVT / total targets from your own p50/p95)
  • Acknowledgement appears within ~1 s of submit (status text or skeleton)
  • Pre-TTFT gap has an honest status ("Thinking…", stage name) — no bare spinner past ~10 s
  • Token stream passes through a smoother (pace mode) before display
  • Partial Markdown/HTML renders safely (no raw syntax, no broken tables)
  • Scroll sticks to bottom only while user is at bottom; "new messages" pill offered
  • Stop button cancels upstream (provider stream closes, billing stops)
  • Regenerate / Continue / Edit-and-resend behave as 2.5 describes
  • Multi-step work emits status/tool_* events per real stage; finished steps stay visible
  • No fake ETA or invented percentage — indeterminate bar or real fraction() only
  • Tool args never rendered raw; reasoning shown collapsed, labelled as summary
  • Partial results carry a warning; silent partials impossible
  • Terminal event (done/error) always emitted; client handles stream-death-without-done
  • Event contract versioned additively; id: sequence + Last-Event-ID resume path exists
  • Long-running work (> ~60 s) is a job with idempotent submission and a way back
  • aria-live announces completion, not tokens; prefers-reduced-motion honoured; Stop keyboard-operable

Exercises#

  1. Smooth a real trace. Capture a real provider stream's chunk timings (03.3's StreamTimer or your own logging), save as a Trace, and replay it through passthrough, batch(50ms) and pace(60cps). Report TTFVT and max stall for each. Then try pace(30cps) and pace(200cps) — at what rate does the smoother start to fall behind (watch max_buffer flush)? What does that tell you about tuning per model/provider?

  2. Design status messages for a six-step agent task. Take a real agent flow (e.g., "research → outline → draft → cite → review → format"). Write the user-facing label for each step, the update() detail lines you'd emit mid-step, and the complete() summaries. Check each against 3.1's rules: user language, real denominators where they exist, no invented progress. Then wire ProgressTracker to emit them and render the JSONL.

  3. Write the event contract for a document-processing job. Design the event types and job-record fields for "upload 40 PDFs → extract invoice fields → flag anomalies → produce a summary CSV". Specify: the submit response, the progress events per item, the terminal states, the idempotency key, the notification payload, and which events are once-only vs accumulative (6.3). Compare your contract to ai_product/events.py — what's missing?

Hints for the exercises
  1. Expect passthrough and batch to keep the burst structure (clumps, with batch's fixed stall per flush) and pace to show the smallest max stall. On the lesson's 408-character TRACE with max_buffer=800 (the cap never trips), the last character appears at about 14 s at 30 cps, 7.2 s at 60 cps and 2.4 s at 200 cps, although every character has arrived by 0.55 s: a lower rate means more lag, a higher rate looks more like passthrough. Set max_buffer=300 and the backlog exceeds the cap at about 0.52 s, so the smoother flushes about 330 characters in one jump (visible, but the lag vanishes) at every rate. With a real trace, the rate at which flushes begin depends on the model's decode speed, so tune chars_per_second and max_buffer per provider from recorded traces, not from a default.
  2. A good label is in user language ("Reading the policy"), a good update() line carries a real denominator ("Reading source 2 of 3") only where your code knows it, and a good complete() summary states a result ("30-day window applies"). Anything like "Step 4: tool_call" or a percentage you cannot compute fails the check.
  3. Minimum contract: a 202 submit response with job_id; an Idempotency-Key request header; per-item status events carrying an item id, the item index and total; terminal job states succeeded / failed / cancelled plus a per-item "needs attention" state; a notification payload with counts and a deep link; once-only events (citation-like per-item results, usage, the terminal event) versus accumulative ones (status updates). What events.py lacks for this job: an item-level identifier on status beyond id, a partial-success terminal status (it only has completed/incomplete/failed/cancelled), and a job-level record, which is a storage concern (13A.5) rather than a stream event.

Check yourself#

  1. What's the difference between TTFT and TTFVT, and why does it matter on reasoning models?
  2. Why does a chunk smoother need a max_buffer flush instead of strictly enforcing its rate?
  3. Why is token text smoothed before display rather than showing the provider's raw chunks?
  4. Name three things a bare spinner fails to communicate that a step list provides.
  5. When is streaming the wrong transport, and what's the alternative?
  6. Why must Stop propagate to the provider rather than just hiding the stream client-side?
  7. What's wrong with rendering a progress bar that estimates completion from elapsed time?
  8. Why does the event contract need reset, warning and done as distinct types rather than folding them into error?
  9. When would you choose raw_data over data in ServerSentEvent?
  10. What should a client do when the connection closes without a done event?
  11. What does the meta event carry, and why is it emitted first?
  12. What's the accessibility rule for a streaming token display?

Further resources#


The ai_product package so far#

After this lesson the package holds four files — feature_brief.py from 13A.1 and the three added here:

text
ai-product/
├── ai_product/
│   ├── __init__.py
│   ├── feature_brief.py      # 13A.1 — the AI feature brief + use-case scorer
│   ├── events.py             # 13A.2 — typed event contract + SSE encoder
│   ├── smoother.py           # 13A.2 — chunk smoother (passthrough/batch/pace)
│   └── progress.py           # 13A.2 — multi-step status tracker
├── demo_app.py               # 13A.2 — FastAPI endpoint streaming the contract
└── demo_client.py            # 13A.2 — httpx terminal client

events.py is the vocabulary every later lesson's UI work builds on; smoother.py and progress.py are the two render-side helpers. Later lessons add feedback.py, jobs.py, markdown_safety.py and the rest — each lesson's tree shows the cumulative state at that point.


← 13A.1 — Product Thinking for AI Features: What to Build and When Not to Use AI | Module 13A overview | 13A.3 — AI UX II: Trust, Transparency, Feedback and Human-in-the-Loop →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close