Skip to main content
Back to all articles
AI Engineering 9 min readUpdated August 31, 2026

Streaming an Agent Is a State-Management Problem, Not a Typing Effect

Token streaming improves perceived latency, but tool-using agents need a stronger event contract. This article designs resumable progress events, text deltas, tool states, approvals, cancellation, and reconnect behavior for reliable AI UX.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#streaming#agent-ux#ai-agents#server-sent-events#durable-execution#cancellation#typescript#python
On this page

The first version of streaming AI usually looks like this:

Text
model emits tokenserver forwards tokenbrowser appends token

That is enough for a one-shot text generator.

It becomes incomplete as soon as an agent does anything between model calls.

A user asks for a deployment investigation. The agent searches logs, reads a runbook, checks the latest release, waits on a slow monitoring API, asks for approval before a risky action, then writes the final explanation. During most of that time there are no answer tokens to stream.

If the UI only knows about text deltas, the application appears frozen exactly when the workflow is busiest.

I prefer to stream agent events, not just model tokens.

The event stream becomes a public application contract describing what the run is doing without exposing hidden reasoning. Text output is one event type among several.

Start with an event protocol

I want every browser-visible event to have identity, ordering, and a small stable payload.

type AgentStreamEvent =  | {      id: number;      type: "run.started";      runId: string;    }  | {      id: number;      type: "text.delta";      text: string;    }  | {      id: number;      type: "step.started";      stepId: string;      label: string;    }  | {      id: number;      type: "step.completed";      stepId: string;    }  | {      id: number;      type: "approval.required";      approvalId: string;      summary: string;    }  | {      id: number;      type: "run.completed";    }  | {      id: number;      type: "run.failed";      message: string;      retryable: boolean;    };

The exact events depend on the product. The important part is that the frontend does not have to infer workflow state from prose such as “Let me check that for you.”

Progress should describe observable work

I do not stream private chain-of-thought.

A user does not need the model's hidden internal reasoning to understand that a request is moving.

Useful progress events are application facts:

Text
Searching deployment logsChecking release metadataComparing current configurationWaiting for approvalGenerating final response

Those labels come from workflow steps or tool metadata, not from asking the model to narrate every thought.

That makes the UI more predictable and reduces the temptation to expose internal reasoning as a loading indicator.

Separate durable events from ephemeral deltas

Not every event has the same recovery value.

A text.delta can be tiny and frequent. A tool completion or approval request is a meaningful state transition that I may need after reconnect.

I usually keep a durable run-event log for important transitions and treat fine-grained token deltas as optionally transient.

type DurableRunEvent = {  runId: string;  sequence: number;  type: string;  payload: unknown;  createdAt: string;};

For products where reconnect must reproduce the exact partially generated answer, I can persist assembled text checkpoints or all deltas. For many applications it is enough to persist the latest rendered answer plus durable workflow events.

The retention choice should be deliberate rather than an accidental consequence of whichever SSE library was easiest to install.

Give events monotonically increasing sequence numbers

Network delivery can duplicate or reconnect.

The frontend needs a way to know whether an event is new.

type StreamCursor = {  runId: string;  lastEventId: number;};​function shouldApplyEvent(  event: AgentStreamEvent,  cursor: StreamCursor,): boolean {  return event.id > cursor.lastEventId;}

Sequence numbers do not need to be globally ordered across every run. Per-run ordering is enough for this UI contract.

If events are emitted from several distributed workers, one component should assign the canonical run sequence or the transport should carry ordering semantics the renderer understands.

Do not assume wall-clock timestamps create a reliable total order across processes.

Server-Sent Events fit many text-first agent UIs

For one-way server-to-browser progress, SSE is often a simple fit:

Text
HTTP request  -> server keeps response open  -> events arrive as text/event-stream  -> browser/client consumes until completion

It works naturally with incremental text and status events.

WebSockets or a realtime transport can make more sense when the session is strongly bidirectional, especially voice, shared collaboration, or frequent client control messages.

The transport is less important than the event contract. I do not want business state encoded in assumptions specific to one socket library.

Encode one application event per SSE message

A simple TypeScript encoder:

function encodeSse(event: AgentStreamEvent): string {  return [    `id: ${event.id}`,    `event: ${event.type}`,    `data: ${JSON.stringify(event)}`,    "",    "",  ].join("\n");}

Production code also needs correct response headers, heartbeat behavior, proxy/load-balancer configuration, disconnect detection, and output flushing.

The protocol itself should stay boring.

Do not make every provider event part of your public API

Model providers expose their own streaming event vocabularies.

Those can change independently from your product.

I put an adapter between provider events and application events:

TypeScript
type ProviderEvent = unknown;​interface StreamAdapter {  consume(event: ProviderEvent): AgentStreamEvent[];}

A text token becomes text.delta. A provider tool-call fragment may remain internal until arguments are complete and validated. A reasoning-specific provider event may not belong in the user stream at all.

This gives the frontend one stable protocol even if the backend changes model provider or SDK.

It also prevents the browser from becoming tightly coupled to an upstream API's low-level streaming implementation.

Buffer structured data until it is valid

Streaming JSON field-by-field is awkward.

Suppose the model is producing a tool call:

JSON
{  "tool": "refund_payment",  "arguments": {    "paymentId": "pay_...",    "amount": 12500  }}

Halfway through the stream, the arguments are not valid JSON and have not passed authorization or domain validation.

I do not show “Refunding payment...” merely because the model has started spelling the tool name.

The tool layer waits until the proposal is complete, validates it, authorizes it, then emits a safe progress event such as:

Text
step.started: Checking refund eligibility

For side effects, the UI should distinguish proposed, approved, executing, and completed. Streaming partial model intent should never imply that a real action has happened.

Treat the visible answer as a projection

The frontend can reduce events into UI state.

type AgentUiState = {  status: "running" | "waiting-approval" | "completed" | "failed";  text: string;  steps: Record<string, "running" | "completed">;  approvalId?: string;  error?: string;  lastEventId: number;};​function reduceEvent(  state: AgentUiState,  event: AgentStreamEvent,): AgentUiState {  if (event.id <= state.lastEventId) return state;​  const next = { ...state, lastEventId: event.id };​  switch (event.type) {    case "text.delta":      return { ...next, text: next.text + event.text };    case "step.started":      return {        ...next,        steps: { ...next.steps, [event.stepId]: "running" },      };    case "step.completed":      return {        ...next,        steps: { ...next.steps, [event.stepId]: "completed" },      };    case "approval.required":      return {        ...next,        status: "waiting-approval",        approvalId: event.approvalId,      };    case "run.completed":      return { ...next, status: "completed" };    case "run.failed":      return { ...next, status: "failed", error: event.message };    default:      return next;  }}

This reducer is useful beyond the browser. Replay tests can feed the same events into it and assert that a reconnect reconstructs the expected state.

Reconnect from a cursor, not from hope

Mobile networks disappear. Laptop lids close. Reverse proxies reset connections.

A run should not fail because the browser's streaming connection failed.

I separate run execution from stream attachment:

Text
POST /agent-runs  -> create durable run  -> return run ID​GET /agent-runs/:id/events?after=42  -> replay durable events after cursor  -> continue streaming live events

For a short synchronous assistant, creating a separate run resource may be unnecessary. For long tool-using work, it is a much cleaner lifecycle.

The worker owns the run. The socket does not.

That is the same distinction used in durable execution earlier in the series.

Reconnection must not repeat side effects

The browser reconnecting should only replay observations.

It should not re-submit tool calls or re-run the agent.

A dangerous design is:

Text
stream disconnectedfrontend POSTs the original request again

If the first run already sent an email or created a ticket, that can duplicate work.

Reconnect using the run ID. If the product offers “retry run,” create that as an explicit new operation with idempotency policy rather than making network recovery indistinguishable from business retry.

Stream heartbeats separately from progress

A workflow can legitimately spend 30 seconds inside one slow tool.

The connection still needs evidence that it is alive.

An SSE heartbeat/comment can keep intermediaries and clients from assuming the stream is dead without telling the user fake progress.

Text
: heartbeat​

Do not emit “Almost done...” every five seconds unless the system actually knows that.

Connection liveness and workflow progress are different signals.

That small distinction avoids a surprisingly common AI UX problem: fabricated confidence in how long an operation will take.

Progress should be coarse enough to stay true

I avoid percentage bars such as 73% complete for open-ended agent tasks unless the workflow has a known number of deterministic units.

For a four-stage document pipeline, percentage progress can be honest.

For a research agent that may discover another necessary search, it is usually not.

Step labels work better:

Text
Searching sourcesReading 4 relevant documentsChecking conflicting evidenceDrafting answer

The UI communicates movement without pretending the planner already knows the future.

Streaming can make bad output visible sooner

If output policy runs only after generation, the browser may already have seen a sensitive token before the final egress check rejects the answer.

That changes the security boundary.

For destinations with strict output controls, I have several options:

Text
buffer the full answer and validate before releasestream only after a safe structured layerrun incremental deterministic filters where feasiblestream internally but not to external/public destinations

There is no universal answer.

The important point is that “we added streaming” can invalidate an existing assumption that the whole answer is checked before any of it leaves the trust zone.

Security review needs to include the streaming path.

Citations should not arrive before they are valid

RAG answers often produce text before source mapping is complete.

If a sentence is streamed with [3] and the final grounding step later removes source 3, the UI has a dangling citation.

I prefer structured citation events or stable source IDs:

TypeScript
type CitationEvent = {  id: number;  type: "citation.added";  citationId: string;  sourceId: string;  startOffset: number;  endOffset: number;};

For strict claim verification, I may buffer at claim or paragraph boundaries and release only after grounding passes.

That adds latency but preserves the meaning of a citation.

Perceived speed should not turn evidence markers into decoration.

Cancellation is part of streaming UX

A Stop button that only closes the browser stream is misleading.

The run may continue calling tools and spending tokens in the background.

The client should issue an explicit cancellation request:

Text
POST /agent-runs/:id/cancel

The server records the cancellation state and propagates it through model calls, tools, subprocesses, and workers where possible.

Then the stream can emit:

Text
run.cancelled

A cancellation event means the workflow observed the cancellation policy—not merely that the UI stopped listening.

For writes with unknown outcomes, the run may need a reconciliation state rather than claiming everything stopped cleanly.

Approval turns the stream into a pause/resume workflow

When a run reaches a human gate, I do not hold one HTTP request open indefinitely and hope the reviewer responds.

The event says:

Text
approval.required

The durable run moves to waiting-for-approval. The stream can remain open for a short period or close cleanly.

The reviewer later approves through a normal application request, the run resumes, and the browser can attach to events again.

This makes a two-hour approval pause look like what it is: workflow state, not a very slow network response.

Stream errors at the right level

There are at least three failure classes:

Text
transport error  stream connection failed, run may still be healthy​step/tool error  workflow may recover or choose another path​run error  workflow cannot continue

The UI should not turn every dropped connection into “Agent failed.”

Likewise, an internal tool retry does not need a large red error banner if the runtime is handling it normally.

Events should represent the user-visible consequence of failures, while detailed retry/error information remains in traces.

Backpressure applies to the browser too

A model can emit deltas faster than a slow client renders them.

Appending React state for every tiny token can create unnecessary rerenders and memory pressure.

I often batch text deltas on the client or server into small time/size windows:

class TextDeltaBuffer {  private value = "";​  push(delta: string): void {    this.value += delta;  }​  flush(): string {    const current = this.value;    this.value = "";    return current;  }}

The model can still stream continuously while the UI renders every 30–50 ms, for example. The exact interval should come from UX testing, not from this article.

Streaming more network frames is not the same as feeling faster.

Measure time to useful feedback

Total latency is still important, but streaming adds intermediate UX metrics:

Text
time to run acknowledgementtime to first meaningful progress eventtime to first visible answer texttime waiting on toolstime waiting on approvaltime to final answerreconnect ratecancel-before-completion rate

“Time to first token” is too narrow for agents.

If the first token appears in 400 ms and the system then shows nothing for 18 seconds while a tool executes, the user experience is still poor.

A useful progress event during that tool phase can make the same backend latency much easier to understand.

Test the event stream as a protocol

I write tests for sequences, not only screenshots.

Cases include:

Text
normal text responsetext + tool + textapproval pause and resumeduplicate event after reconnectconnection drops after side effectcancel during tool executionrun fails before any textpartial answer followed by policy block

The reducer should reach the same final state whether events arrive live or are replayed from durable storage.

That is a strong sign the UI protocol is decoupled from connection timing.

When token streaming is enough

A short answer endpoint with no tools, approvals, or durable state probably does not need an event architecture.

Use the provider's streaming API, forward text deltas, and keep the implementation small.

The richer protocol becomes worth it when the application has real workflow state between model calls.

At that point, the key UX question changes from:

How fast can I display the first word?

To:

Can the user understand what state the job is in, stop it safely, leave and come back, approve what needs approval, and trust that the final UI corresponds to one durable run?

That is why streaming an agent is mostly a state-management problem.

The typing animation is the easy part.

KEEP READING

Related engineering notes