> ## 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.

# Chat app with React

> A chat application on one agent: your backend opens a session per conversation and mints its token, and a React page shows it live.

This example builds a small chat application: every conversation is a session on one agent, your backend creates sessions and their tokens, and a React page shows each conversation live, including the agent's tool calls, and refreshes its token when it expires. It extends the [quickstart](https://docs.paddock.build/quickstart.md) into the shape a real application has.

```mermaid theme={null}
flowchart LR
  page["React page<br/>useSession"] -- "POST /api/conversations" --> backend["Your backend<br/>@paddock/server"]
  backend -- "sessions.create, createToken" --> paddock["paddock"]
  page -- "session token: events, stream, send" --> paddock
```

## 1. Set up the agent once

Publish the template and create the application's agent once, and keep its ID in your configuration.

```yaml agent/template.yaml theme={null}
apiVersion: paddock.build/v1
kind: Template
metadata:
  name: chat
spec:
  harness: claude-code
  model: claude-sonnet
  system_prompt: You are a concise assistant. Answer in a few sentences.
```

```go Go theme={null}
tpl, err := client.Templates.Create(ctx, "agent/template.yaml")
if err != nil {
	return err
}
agent, err := client.Agents.Create(ctx, paddock.AgentCreate{
	Template: fmt.Sprintf("%s@%d", tpl.Name, tpl.Version),
	Metadata: map[string]string{"app": "chat"},
})
if err != nil {
	return err
}
fmt.Println("AGENT_ID=" + agent.ID)
```

```python Python theme={null}
template = client.templates.create("agent/template.yaml")
agent = client.agents.create(template=f"{template.name}@{template.version}", metadata={"app": "chat"})
print(f"AGENT_ID={agent.id}")
```

```ts TypeScript theme={null}
const template = await paddock.templates.create("agent/template.yaml");
const agent = await paddock.agents.create({
  template: `${template.name}@${template.version}`,
  metadata: { app: "chat" },
});
console.log(`AGENT_ID=${agent.id}`);
```

All conversations share the agent's sandbox, so they can share files. If your users must not see each other's files, give each user an agent of their own instead, and store its ID with the user.

## 2. The backend

Two routes: one starts a conversation, the other mints a fresh token for a conversation the user already has. They are written as Web-standard handlers, which Next.js route handlers and most frameworks accept. `userIdOf` stands for your own authentication.

```ts app/api/conversations/route.ts theme={null}
import { Paddock } from "@paddock/server";

const paddock = new Paddock(); // PADDOCK_API_KEY
const agentId = process.env.AGENT_ID ?? "";

function userIdOf(request: Request): string {
  return request.headers.get("x-user-id") ?? "anonymous"; // replace with your authentication
}

// POST /api/conversations: start a conversation.
export async function POST(request: Request): Promise<Response> {
  const agent = await paddock.agents.get(agentId);
  const session = await agent.sessions.create({ metadata: { userId: userIdOf(request) } });
  const { token, expiresAt } = await session.createToken({ ttl: 3600 });
  return Response.json({ sessionId: session.id, token, expiresAt });
}

// GET /api/conversations: the user's conversations, newest first.
export async function GET(request: Request): Promise<Response> {
  const page = await paddock.sessions.list({ agentId, metadata: { userId: userIdOf(request) } });
  return Response.json(page.data.map((s) => ({ sessionId: s.id, status: s.status, createdAt: s.createdAt })));
}
```

```ts app/api/conversations/[id]/token/route.ts theme={null}
import { Paddock, PaddockError } from "@paddock/server";

const paddock = new Paddock();

function userIdOf(request: Request): string {
  return request.headers.get("x-user-id") ?? "anonymous"; // replace with your authentication
}

// POST /api/conversations/{id}/token: a new token for one of the user's conversations.
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
  const { id } = await params;
  try {
    const session = await paddock.sessions.get(id);
    if (session.metadata.userId !== userIdOf(request)) return new Response("not found", { status: 404 });
    const { token, expiresAt } = await session.createToken({ ttl: 3600 });
    return Response.json({ sessionId: id, token, expiresAt });
  } catch (e) {
    if (PaddockError.is(e) && e.code === "not_found") return new Response("not found", { status: 404 });
    throw e;
  }
}
```

The user's ID lives in the session's metadata, so `sessions.list` finds their conversations and the token route checks ownership with no table of your own.

## 3. The chat page

```tsx app/chat.tsx theme={null}
"use client";

import { useCallback, useEffect, useState } from "react";
import { useSession, type ClientMessage } from "@paddock/react";

type Conversation = { sessionId: string; token: string };

export function ChatPage() {
  const [conversation, setConversation] = useState<Conversation | null>(null);

  useEffect(() => {
    void fetch("/api/conversations", { method: "POST" })
      .then((r) => r.json() as Promise<Conversation>)
      .then(setConversation);
  }, []);

  if (!conversation) return <p>Starting…</p>;
  return <Chat conversation={conversation} onToken={setConversation} />;
}

function Chat({ conversation, onToken }: { conversation: Conversation; onToken: (c: Conversation) => void }) {
  const { sessionId, token } = conversation;
  const { messages, status, error, processedSeq, heldSeq, connection, connectionError, send, stop } = useSession(
    sessionId,
    { token },
  );
  const [text, setText] = useState("");

  // The client does not refresh tokens: when the stream closes on an expired token, get a new one.
  const refresh = useCallback(async () => {
    const r = await fetch(`/api/conversations/${sessionId}/token`, { method: "POST" });
    if (r.ok) onToken((await r.json()) as Conversation);
  }, [sessionId, onToken]);
  useEffect(() => {
    if (connection === "closed" && connectionError) void refresh();
  }, [connection, connectionError, refresh]);

  // Pair each tool call with its result by callId.
  const results = new Map<string, ClientMessage>();
  for (const m of messages) if (m.kind === "tool_result") results.set(m.toolResult.callId, m);

  return (
    <main>
      <p>
        {status}
        {connection === "reconnecting" && " · reconnecting"}
      </p>
      {messages.map((m) => {
        switch (m.kind) {
          case "user": {
            const waiting = m.seq !== null && m.seq > processedSeq;
            const held = waiting && m.seq !== null && m.seq <= heldSeq;
            return (
              <p key={m.id}>
                <b>You:</b> {m.text} {held ? "(held)" : waiting ? "(waiting)" : ""}
              </p>
            );
          }
          case "assistant":
          case "streaming":
            return (
              <p key={m.id}>
                <b>Agent:</b> {m.text}
              </p>
            );
          case "tool_call": {
            const result = results.get(m.toolCall.callId);
            const failed = result?.kind === "tool_result" && result.toolResult.isError;
            return (
              <p key={m.id}>
                <code>{m.toolCall.tool}</code> {result ? (failed ? "failed" : "done") : "running"}
              </p>
            );
          }
          default:
            return null;
        }
      })}
      {error && <p role="alert">The last turn failed: {error.code}</p>}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!text.trim()) return;
          void send(text);
          setText("");
        }}
      >
        <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Message…" />
        <button type="submit">Send</button>
        {(status === "running" || status === "retrying") && (
          <button type="button" onClick={() => void stop()}>
            Stop
          </button>
        )}
      </form>
    </main>
  );
}
```

## What you get without writing it

* **Send at any time.** The message box stays enabled during a turn: messages sent meanwhile wait, marked `waiting`, and the next turn takes them all.
* **Stop and hold.** After **Stop**, waiting messages are held; the next message sends them along.
* **Live text.** The reply grows as the agent writes it, as `streaming` entries that the finished message replaces in place.
* **Away and back.** Close the tab mid-turn and open the conversation later: `useSession` loads every event, including everything the agent did meanwhile, then follows it live.
* **Reconnection.** A dropped connection shows `reconnecting` and resumes after the last event the page holds, with nothing lost or repeated.
* **Backend messages.** Your backend can send into the same conversation at any time with `session.send(text)`, and the page shows it like any other message.


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