Streaming answers without lying about state

A chat client has to show progress, stay cancellable and never present a half-finished answer as complete. What that takes over server-sent events, and why the on-device path uses the same contract.

Streaming answers without lying about state

Streaming a model's answer looks like a solved problem until you put it on a phone. The connection drops in a lift. The user rotates the screen mid-answer. They hit back, and the socket keeps reading in the background. The quota runs out between the request and the first token. Each of those is a state the interface has to represent honestly, and none of them is visible in a demo.

This is the shape we settled on in the DigitMind AI Android client.

Parse the protocol, don't guess at it

Server-sent events are a line protocol: event: names the event, data: lines accumulate, and a blank line dispatches what has been collected. Reading it as a stream of lines rather than waiting for a complete body is the whole point.

while (true) {
    currentCoroutineContext().ensureActive()
    val line = source.readUtf8Line() ?: break
    when {
        line.isEmpty() -> {
            parseEvent(eventName, data.toString())?.let { emit(it) }
            eventName = null
            data.clear()
        }
        line.startsWith("event:") -> eventName = line.substringAfter("event:").trim()
        line.startsWith("data:") -> {
            if (data.isNotEmpty()) data.append('\n')
            data.append(line.substringAfter("data:").trimStart())
        }
    }
}

The ensureActive() call at the top of the loop is the part that matters most and is easiest to leave out. Without it, cancelling the coroutine that collects the flow does not stop the read: the socket stays open, bytes keep arriving, and the user who navigated away is still paying for tokens. With it, leaving the screen stops the work.

The parse runs on the IO dispatcher and the result is a Flow, so backpressure, cancellation and threading are handled by machinery the rest of the app already uses, rather than by a bespoke callback interface.

Types at the boundary

The stream does not emit strings. It emits a sealed hierarchy, and every event carries what the UI needs to make a decision:

  • Started — the request id plus both messages, so the conversation can render the user's turn and an empty answer immediately.
  • Delta — the request id and the text fragment.
  • Completed — the final answer, whether another message can be sent (quota, in the same event rather than a second round trip), and the ids of any messages this answer supersedes, which is what makes regeneration coherent.
  • Failure — a code, a message and, crucially, whether the failure is retryable.

That last flag is the difference between a UI that offers "try again" on a transient network error and one that offers it on a content policy rejection, where retrying will fail identically and only annoy the person.

Carrying requestId on every event sounds redundant until two answers overlap — a regeneration started before the previous stream finished — and the client has to attribute deltas correctly rather than appending them to whatever is on screen.

One contract for the cloud and the device

The same client also runs answers through an on-device model. Those two routes could not be more different underneath: one is an HTTP stream from a provider, the other is a local inference engine emitting decode steps.

They share an event contract anyway, and they share measurement:

  • time to first token, from accepted request to first visible chunk,
  • time to last token,
  • tokens per second over the decode window.

For the local engine, one chunk is one decoded step, so the token count is exact. For cloud providers, chunk size is provider-defined, so tokens are estimated from characters with a documented heuristic. The estimate is labelled as an estimate in the code rather than presented as a measurement.

Keeping one contract means the chat screen does not branch on where an answer came from, and it means a slow local model and a slow provider show up in the same numbers, comparably.

What the UI owes the user

The rules that fell out of this, which are mostly about not overstating what has happened:

  • A streaming answer is visibly in progress until Completed arrives. A dropped connection ends it as interrupted, not as finished.
  • Partial text is kept, because losing a half-written answer to a lift is worse than showing an incomplete one.
  • Quota changes travel with the completion event, so the composer disables itself at the right moment instead of after the next failed attempt.
  • Cancellation is real cancellation, all the way into the socket or the native engine.

None of this is exotic. It is the difference between a chat interface that feels trustworthy and one that occasionally lies about whether it is still thinking.

View
case