> ## Documentation Index
> Fetch the complete documentation index at: https://docs.paddock.build/llms.txt
> Use this file to discover all available pages before exploring further.

# Streaming to the browser

> Hand a session to your frontend with a session token, and show its live state with the client SDK or React.

Your frontend shows a session with the client SDK: give it a session ID and a session token, and it loads the session's history, follows its live stream, reconnects on its own, and folds everything into one state object. Your frontend writes no streaming, reconnection, or state code, and a user who closes the tab mid-turn and comes back hours later sees everything the agent did in the meantime.

```mermaid theme={null}
sequenceDiagram
  participant Browser
  participant Backend as Your backend
  participant paddock
  Browser->>Backend: open conversation
  Backend->>paddock: session.createToken({ ttl })
  paddock-->>Backend: { token, expiresAt }
  Backend-->>Browser: sessionId, token
  Browser->>paddock: useSession(sessionId, { token }): events, then stream
  paddock-->>Browser: every event, live
```

## 1. Mint a session token on your backend

Your API key never leaves your backend. For the browser, create a session token: it works on one session only, for a lifetime you choose between 60 seconds and 24 hours.

```go Go theme={null}
func sessionToken(ctx context.Context, client *paddock.Client, sessionID string) (*paddock.SessionToken, error) {
	session, err := client.Sessions.Get(ctx, sessionID)
	if err != nil {
		return nil, err
	}
	return session.CreateToken(ctx, paddock.TokenCreate{TTL: time.Hour})
}
```

```python Python theme={null}
def session_token(client: Paddock, session_id: str) -> str:
    session = client.sessions.get(session_id)
    return session.create_token(ttl=3600).token
```

```ts TypeScript theme={null}
async function sessionToken(sessionId: string): Promise<string> {
  const session = await paddock.sessions.get(sessionId);
  const { token } = await session.createToken({ ttl: 3600 });
  return token;
}
```

Check in your own backend that the signed-in user may see that session before you mint its token; paddock does not know your users. The token grants on its session everything the server SDK can do there: read, send, stop, stream, and delete. See [Authentication](https://docs.paddock.build/platform/authentication.md).

## 2. Show the session with React

```bash theme={null}
npm install @paddock/react @paddock/client
```

```tsx theme={null}
import { useSession } from "@paddock/react";

export function Conversation({ sessionId, token }: { sessionId: string; token: string }) {
  const { messages, status, turn, error, connection, send, stop } = useSession(sessionId, { token });

  return (
    <div>
      <p>
        {status} {turn ? `(turn ${turn.id})` : ""} {connection !== "open" ? `· ${connection}` : ""}
      </p>
      {error && <p>The last turn failed: {error.code}</p>}
      {messages.map((m) => {
        switch (m.kind) {
          case "user":
            return <p key={m.id}>{m.text}</p>;
          case "assistant":
          case "streaming":
            return <p key={m.id}>{m.text}</p>;
          case "tool_call":
            return <code key={m.id}>{m.toolCall.tool}</code>;
          default:
            return null;
        }
      })}
      <button onClick={() => void send("Continue")}>Continue</button>
      <button onClick={() => void stop()}>Stop</button>
    </div>
  );
}
```

`useSession(sessionId, { token, baseUrl? })` returns the session's state with `send` and `stop`. Components that call it with the same base URL, token, and session ID share one connection; it opens with the first and closes with the last. During server rendering it returns the empty state and makes no request.

To point every hook at another base URL, such as a local stack, wrap your app in `PaddockProvider`:

```tsx theme={null}
import type { ReactNode } from "react";
import { PaddockProvider } from "@paddock/react";

export function App({ children }: { children: ReactNode }) {
  return <PaddockProvider baseUrl="https://api.paddock.build/v1">{children}</PaddockProvider>;
}
```

## The session state

| Field | Meaning |
| - | - |
| `messages` | The timeline: stored messages in `seq` order, then the messages being generated. One entry per message ID |
| `status` | `idle`, `running`, `retrying`, `failed`, or `blocked` |
| `turn` | The running turn, or `null` |
| `error` | The session's last turn error, while it is `retrying`, `failed`, or `blocked` |
| `processedSeq` | User messages above it are waiting for a turn |
| `heldSeq` | Waiting messages at or below it are held until the next message |
| `session` | The latest session snapshot, or `null` before the first |
| `connection` | `connecting`, `open`, `reconnecting`, or `closed` |
| `connectionError` | The error that closed the connection, if one did |
| `events` | Every stored event received, once each, in `seq` order |
| `harnessStatus` | The latest status of the session's harness, or `null`; see [Harness status](https://docs.paddock.build/guides/harness-status.md) |

Each entry of `messages` is a [message](https://docs.paddock.build/concepts.md#message) with its `seq` (`null` while it is streaming), `turnId`, and `createdAt`. A few rules make rendering simple:

* **Streaming text.** While the agent writes a reply, an entry of kind `streaming` holds the whole text so far, under the ID of the `assistant` message that will complete it. When that message arrives it replaces the entry in place, so a key of `m.id` keeps your list stable. A streaming entry its turn did not complete is removed when the turn ends.
* **Your own messages.** `send` resolves with the stored user message's event, and the message is already in `messages`. It is waiting while its `seq` is above `processedSeq`, and held while it is also at or below `heldSeq`.
* **Tool calls.** A `tool_call` and its `tool_result` share `toolCall.callId` and `toolResult.callId`; pair them to show a call with its result.
* **Unknown kinds.** A message of a kind your SDK version does not know is kept in order with its raw fields; skip it or render it generically.

## Reconnection and expiry

The client reconnects on its own with capped backoff after a dropped connection, a server error, or 45 seconds without a byte, and resumes after the newest `seq` the load or the stream delivered, so it never loses or repeats an event. An event that `send` or `stop` added to the state early does not count, so an earlier event another writer stored is still fetched. `connection` is `reconnecting` meanwhile.

The client does not refresh tokens. When the token expires, the stream ends with `connection: "closed"` and `connectionError` set to a `PaddockError` with code `unauthorized`: mint a new token on your backend and pass it to `useSession`, and the hook opens a new connection with it. When the session is deleted, the stream ends the same way with code `not_found`, or, for a connection opened after the deletion, `unauthorized` with `details.reason` `session_deleted`: the session is gone, so do not mint a new token for it.

```tsx theme={null}
import { PaddockError } from "@paddock/client";

const state = useSession(sessionId, { token });
const closed = state.connection === "closed" ? state.connectionError : null;
const expired = PaddockError.is(closed) && closed.code === "unauthorized" && closed.details?.reason === "expired";
// When expired, fetch a new token from your backend and re-render with it.
// Any other error, such as not_found for a deleted session, is final.
```

## Without React

`@paddock/client` is the framework-independent client the hook is built on:

```ts theme={null}
import { PaddockClient } from "@paddock/client";

const client = new PaddockClient({ token });
const handle = client.session(sessionId);

const unsubscribe = handle.subscribe((state) => {
  render(state.messages, state.status);
});

await handle.send("What changed since yesterday?");
// Later: stop listening. The state stays, and a new subscriber resumes the stream.
unsubscribe();
```

The first subscriber loads the session and opens the stream; the last one to leave closes it. `handle.state` is the current state, replaced on every change, never mutated. See [Browser client](https://docs.paddock.build/sdks/client.md).

## From your backend

The server SDKs stream a session too, for example to log a turn or to wait for its reply. A stream first yields the session's snapshot, then every event after `after` in `seq` order, then live events. It reconnects on its own and never yields an event twice.

```go Go theme={null}
for ev, err := range session.Stream(ctx, paddock.StreamOptions{After: 0}) {
	if err != nil {
		return err // *paddock.Error, or an event that did not decode
	}
	if ev.Session != nil {
		fmt.Println("status:", ev.Session.Status)
		continue
	}
	e := ev.Event
	switch {
	case e.Message != nil && e.Message.Assistant != nil:
		fmt.Println(e.Message.Assistant.Text)
	case e.TurnEnded != nil:
		fmt.Println("turn", e.TurnEnded.Outcome)
		return nil
	}
}
```

```python Python theme={null}
from paddock import types

with session.stream(after=0) as events:
    for event in events:
        if isinstance(event, types.SessionStreamEvent):
            print("status:", event.data.status)
        elif isinstance(event, types.EventStreamEvent):
            data = event.data
            if isinstance(data, types.MessageEvent) and isinstance(data.message, types.AssistantMessage):
                print(data.message.text)
            elif isinstance(data, types.TurnEndedEvent):
                print("turn", data.turn.outcome)
                break
```

```ts TypeScript theme={null}
const stream = session.stream({ after: 0 });
for await (const ev of stream) {
  if (ev.event === "session") {
    console.log("status:", ev.data.status);
  } else if (ev.event === "message" && ev.data.type === "message" && ev.data.message.kind === "assistant") {
    console.log(ev.data.message.text);
  } else if (ev.event === "turn.ended") {
    console.log("turn", ev.data.turn.outcome);
    stream.close();
  }
}
```

A stream ends with an error on the stream's `error` event, such as `not_found` when the session is deleted, and on any non-2xx answer other than a `5xx` when it connects: Go yields a `*paddock.Error`, and Python and TypeScript raise `PaddockError`. An event that does not decode ends it with an error too. Network errors and `5xx` answers are never surfaced; the stream reconnects instead.

Omit `after` to receive every event of the session from the start. To resume a stream you closed, pass the highest `seq` you processed.

## What the stream sends

The stream is Server-Sent Events at `GET /sessions/{id}/stream?after=<seq>`. The SDKs parse it for you; this is the wire format if you read it yourself.

| SSE `event` | `data` | `id` | When |
| - | - | - | - |
| `session` | The session | none | First on every connect, then whenever the session's fields change |
| `message` | An event holding a message | its `seq` | A stored message |
| `message` | An event without `seq`, holding a `streaming` message | none | Text being generated, live only |
| Any other event type, such as `turn.started` | The event | its `seq` | A stored event |
| `status.update` | An event without `seq`, holding a status update | none | A live change of the harness's status |
| `error` | An error body | none | The stream is ending: the session was deleted or the credential expired |

A `: keepalive` comment is sent after 15 seconds of silence. Only events with an `id` are stored and replayed; snapshots, streaming messages, and status updates are live only, and the next one carries the whole current value. Requests carry the token in the `Authorization` header, never in the URL, and any origin may call the API.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.