Skip to main content
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 into the shape a real application has.

1. Set up the agent once

Publish the template and create the application’s agent once, and keep its ID in your configuration.
agent/template.yaml
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.
app/api/conversations/route.ts
app/api/conversations/[id]/token/route.ts
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

app/chat.tsx

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.