# Streaming to the browser

> How tokens reach the page over SSE, what happens on reload, stop() and failures, and the limits of temporary streams.

Source: https://cairnflow.dev/docs/agents/streaming

An agent turn writes UI chunks to a stream of its invocation while it runs. The browser reads that
stream over Server-Sent Events. `cairnMiddleware` and `cairnTools` do the writing and
`cairnChatTransport` does the reading, so with `chatObject` and `useChat` you write no streaming
code. This page explains what happens underneath, so you can reason about reloads, stops and
failures.

## The path of a message

1. `sendMessage` posts the last message to `POST /invoke/Chat/send/send?key=<chatId>`. The answer
   comes as soon as the invocation is durable and carries its ID. The transport attaches an
   `Idempotency-Key`, so a resend after a network error points at the same invocation instead of
   starting a second turn.
2. The transport opens `GET /invocations/{id}/streams/ui` with `accept: text/event-stream`.
3. In the handler, the middleware runs the model call inside `ctx.run`. Each part of the model
   stream is translated into a UI chunk (`start-step`, `text-delta`, `tool-input-available`, …)
   and appended to the `ui` stream as it arrives. In streaming mode the page sees tokens while the
   step is still running; in request-response mode it sees them when the step finishes (see
   below).
4. Tool calls append their input, approval request, output or error the same way.
5. When the turn ends, the stream is sealed; the SSE connection receives `end`, and the transport
   emits `finish`.

Chunks are appended only inside the step that produces them. When a handler replays, the model
and tool results come from the journal and nothing is sent to the stream a second time.

:::note[Live tokens need the streaming transport]
Chunks reach the page as they are generated only when your environment calls the service in
streaming mode (`BIDI_STREAM`). On Cairnflow Cloud an `https://` endpoint is called in
request-response mode unless you register it with `"transport": "declared"`, which works only when
HTTP/2 reaches your app. In request-response mode the chunks of a step travel with the step's
result and reach the page together when the step finishes; the chat still works, without the
typing effect. See [Deployments](/docs/cloud/deployments#transport) and the comparison in
[Vercel AI SDK](/docs/agents/vercel-ai-sdk#streaming-versus-request-response).
:::

## Reload and reconnect

With `resume: true`, `useChat` calls the transport's `reconnectToStream` when the page loads. The
transport asks the object's `active` handler whether a turn is running; if so, it reads that
invocation's stream from the beginning, and the first chunk resets the message being shown.

```tsx
// `initial` comes from `await transport.messages(chatId)` when the page is rendered.
const { messages } = useChat({
  id: chatId,
  transport,
  messages: initial,
  resume: true,
});
```

`messages` already includes the user message of the running turn, so the page shows the question
and the answer streams in under it. The same works in a second tab or on another device.

The reader also reconnects by itself when an SSE connection ends: a connection lives at most ten
minutes, and the node serving the stream can change. If the stream turns out to be a new one
(the step is being generated again), the transport sends a `reset-step` chunk first: the UI drops
the partial step and shows it again from the start.

:::note
In request-response mode the running turn becomes visible to `active` only after its first durable
step. A reload during the very first model call finds nothing to reconnect to; the answer appears
in `messages` when the turn ends.
:::

## Stop

`stop()` in `useChat` stops reading and sends `POST /invocations/{id}/cancel?mode=signal`, a
**cooperative** cancel. An Invoke only key may send it.

- In streaming mode (`BIDI_STREAM`) the cancel reaches the running turn at once. The model or tool
  call in progress receives an `AbortSignal`, so the provider request is cut and stops spending
  tokens. No later model or tool step runs.
- The model call that was cut returns **the text generated so far** as its result. The turn ends
  `completed`, and the saved history holds exactly what the user saw, like a "Stop" button in a
  hosted chat app.
- In request-response mode there is no channel into a running step: the step finishes, and the
  cancel takes effect from the next step.

A tool that should stop mid-way reads the signal from the AI SDK's `execute` options:

```ts
const tools = {
  research: tool({
    description: "Search the web",
    inputSchema: z.object({ query: z.string() }),
    execute: async ({ query }, { abortSignal }) => search(query, { signal: abortSignal }),
  }),
};
```

See [Cancellation](/docs/develop/cancellation) for the hard cancel used from the console.

## When something dies mid-step

| What dies | What the page sees |
|---|---|
| Your service process (deploy, crash, out of memory) | Cairnflow retries the turn. The old attempt is marked superseded on the stream, the UI receives `reset-step`, and the step streams again from the start. The model call of that step **is** made again: it had no journaled result yet |
| The node leading the chat's range | The temporary stream is lost with it. The UI receives `reset-step` and the new leader runs the unfinished step again. Completed steps do not run again |
| A step completed just before the failure | The new run has nothing left to stream for it. The transport closes cleanly, the UI keeps what it received, and the full history is in `messages` |

## Temporary streams: what to expect

The `ui` stream is a **temporary** stream: it lives in the memory of the node that leads the
chat's range, and writing to it costs no storage requests. That is what makes token streaming
cheap, and it comes with limits:

- **It holds the running step, not the whole history.** Each stream keeps up to 1 MiB; older
  records are overwritten, and a reader that falls that far behind sees a gap.
- **It disappears after the turn.** A sealed stream can be read for about 60 seconds, then it is
  gone. Read finished turns from `messages`.
- **A long wait releases it.** A turn suspended on an approval that streams nothing for about a
  minute releases its records. See [Human approval](/docs/agents/approvals) for how pending
  requests are recovered from `messages`.
- **Only the leader serves it.** Another node answers `503` and names the leader; the transport
  follows it once.
- **Each invocation has at most 16 streams.** An invocation never fails because of a stream:
  records over a limit are dropped.
- **The console does not show temporary streams.** Its **Streams** tab lists durable streams
  only. The model and tool results are in the **Journal** tab.
- **Open connections are capped** per environment and node; see [Limits](/docs/cloud/limits). A
  reader over the cap receives `429` and retries.

If you need records that survive a node failure, write them to a durable stream
(`ctx.stream(name, { durable: true })`) in your own code; see
[Streams and logs](/docs/develop/streams-logs).

## SSE events

You only need these if you read streams without the transport, for example with `readStream`
from the SDK client.

| Event | Data |
|---|---|
| `record` | `{offset, durable, step, attempt, k, data}`; the SSE `id` is the offset, `data` is the JSON the handler appended |
| `gap` | `{offset, dropped}`: records dropped over a cap, or overwritten because the reader fell too far behind |
| `superseded` | `{offset, step, attempt}`: that attempt of that step was replaced; its earlier records belong to an abandoned branch |
| `end` | `{next}`: the stream is sealed and fully read; the server closes the connection |
| `moved` | `{leader}`: the node stopped leading the range; ask the new leader |
| `reset` | `{}`: follows `moved` for a temporary stream; what was shown is gone, and a new attempt will stream again from the start |

Resume after a dropped connection with `?from=<offset>` or the `Last-Event-ID` header. The server
sends a keep-alive comment every 15 seconds.

## Proxies

If a proxy sits between the browser and cairnflow, it must not buffer or compress
`text/event-stream` responses, and it must pass `Last-Event-ID` through. See the proxy sketch in
[Vercel AI SDK](/docs/agents/vercel-ai-sdk#keep-the-api-key-on-the-server).
