The chat: what streams and what reloads
<AgentChat> draws a conversation with one of a workspace's agents: it streams each reply through your route and picks a reply back up after a reload. This page is what it reads, for when something on screen looks wrong, or when you draw your own UI with useAgentChat.
The smallest version
app/agent/page.tsx, which npx openlegion init wrote, reads the thread's history on your server and hands it to the chat. Without its loading and error states:
import { toAgentChatMessages } from "@openlegion/platform";
import { AgentChat } from "@openlegion/platform/react";
async function Conversation() {
const session = await currentSession();
if (!session) return null; // your sign-in
const workspace = await workspaceFor(session.customer);
const ws = openlegion().workspace(workspace, { subject: session.user });
let [thread] = (await ws.threads.list({ limit: 1 })).data;
if (!thread) {
const [agent] = (await ws.agents.list({ limit: 1 })).data;
thread = await ws.threads.create({ agent: agent!.id });
}
const history = await ws.messages.list(thread.id, { limit: 100 });
const messages = toAgentChatMessages(history.data);
return <AgentChat threadId={thread.id} initialMessages={messages} />;
}
toAgentChatMessages turns the API's history (newest first) into what the chat takes: oldest first, with each message's tainted, run and stopped. Pass history through it rather than mapping it yourself: without run, a reload can't say how a message with no answer ended, and without stopped, a reply its person stopped reads as a finished one.
What a reply streams
Your route forwards the run's stream from OpenLegion: Server-Sent Events carrying the AI SDK's UI message stream. These are the parts your UI can receive:
| Part | What it says | What <AgentChat> shows |
|---|---|---|
text-delta (with text-start, text-end) | The reply's words, as they are written. The model writes Markdown. | The words, with their Markdown drawn: bold, lists, links, code, tables. Never HTML, never an image loaded; links only to http, https and mailto. renderText replaces it with yours. |
tool-input-available | A tool call and its input, whole and once: no input deltas. Your workspace's secrets and anything shaped like a credential read as a marker such as [redacted:github_pat]. | The tool's name, never its input. |
tool-output-available | Where the call's action stands: output is {action, status, outcome}, plus approval: "apr_…" while it waits for a person. It is never the tool's output: that is on GET /actions/{id}, behind the actions scope. | The tool's name and state; while it waits for a person, a card to approve or reject it. |
tool-output-error | The call failed, was refused, or its outcome isn't known. errorText is a sentence written for your user. | That sentence. |
data-vault-request | The agent asks your user to save a login or a key. | A secure form, <VaultSecretForm>. |
data-artifact | A file the agent delivered: {object: "artifact", id: "art_…", name, mime, size_bytes, tainted}, with no link (GET /artifacts/{id} signs one). It follows the tool part of the call that delivered it. A file the run wrote and did not deliver itself arrives at the very end, unnumbered, just before message-metadata. | A card in the reply, where the file was delivered: a download link, and a preview for an image, a PDF, Markdown and plain text. That is its one place; showFiles also lists the conversation's files under the chat. |
data-computer | The agent's browser: {object: "computer_session", id: "cps_…", agent, site, status, reason?, waiting_for?}. status is live, owner_control (a person holds it), parked (the run ended and the browser waits, at most 15 minutes, for a decision or for a person) or ended (with reason). waiting_for is challenge or sign_in while the page needs a person, and, on a parked session only, person when a person held it as the run ended. The next message in the same conversation takes the parked browser back where the person left it. A later part with the same id replaces the earlier one; after the last chunk, one per session says how the run left it. | One line where the session first appeared: what the agent is doing, the site, and Watch (computer={{ fetchViewer }}). Your route calls POST /computer_sessions/{id}/viewer for the person whose conversation it is. |
data-queued | The run waits to start: {position, reason} (below). | "Waiting for the agent to finish its current task". |
data-refusal | The run stopped, or never started: {code, message}, message written for your user. | Your words for the code (labels.refusals), else message. |
message-metadata | {tainted}, just before the end: did the run read untrusted content? Until it arrives, treat the reply as tainted. | Nothing; the message carries data-ol-tainted. |
error | Follows a data-refusal of a run that never started, with the same sentence, for a client that reads no data parts. | Nothing (it already showed the refusal). |
abort | The run was cancelled: before it started, or stopped while it was running (see "Stop a reply" below). | The end of the reply, and "Stopped." |
[DONE] | The end of the stream. |
agent.finish, which ends every run, arrives as a tool part of type tool-agent_finish. <AgentChat> never shows it; skip it in your own UI.
What history holds
GET /threads/{id}/messages builds each message from the same records the stream did, so a reload shows what the stream showed:
- An assistant message has one tool part per action of its run, before its text. Its
toolCallIdis the action'sact_…id, and itsinputis{}. - A call that repeats one already waiting for approval in the same conversation opens no second approval. Each reply that asked has the tool part, with the same
act_…and the sameapproval, live and after a reload. The same call asked in another conversation is its own action with its own approval. - A run stopped by its budget or its workspace ends its message with the same
data-refusalpart. - A reply its person stopped has
stopped: trueon its message, the fact its stream gave withabort. Every other message hasstopped: false. - Each message says what started the run that wrote it:
trigger(messagefor a reply to your user,schedulefor a schedule's report, asGET /runsnames a run's trigger) andschedule(thesch_…id, ornull). A message from your user hastrigger: null. Use it to show a report as the schedule's ("From your Monday schedule") rather than as one more reply. - A delivered file's
data-artifactpart follows its tool part, as on the stream. A file the run wrote and did not deliver itself has its part last in the message. A file rejected in review has none. - The agent's browser has one
data-computerpart per session, after the call that first used it, as the session is now: a session that was waiting and ran out readsended. Only the person who started the conversation can watch it. In a conversation nobody started, such as the agent's home conversation, the workspace's owners and admins can, and a member can't. Create the conversation for your user (POST /threadswith theirOpenLegion-Subject) and that user can watch. - A message erased for its person (
DELETE /subjects/{subject}) is onedata-redactedpart. - A run refused before it started has no assistant message at all. The person's message keeps its
run, andGET /runs/{id}saysfailed, witherror.messagefor your user.
When the chat doesn't show what you expect
Nothing comes back at all
Auth middleware (middleware.ts or proxy.ts) over /api blocks the kit's route: OpenLegion's tool calls and webhooks, and npx openlegion dev's checks. Exclude /api/openlegion from it. The route checks OpenLegion's signature itself, and your resolve decides who a browser caller is.
A message has nothing under it after a reload
History has no reply for a run that was refused before it started, or that ended with tool calls and no words. For those, <AgentChat> asks your route once (GET {basePath}/runs/{run}) and draws the refusal's sentence, or one line per tool call, as the live stream did. It needs each message's run, which toAgentChatMessages keeps. In your own UI, useAgentChat returns what it found as runOutcomes, by the person's message id.
A reply waits
A run waits rather than failing when something ahead of it holds what it needs. data-queued's reason says what:
agent_busy: the agent is answering something else. Runs on one agent take turns.agent_paused: the agent was paused while this run was already waiting. The run starts when the agent is resumed. A message sent to an agent that is already paused doesn't wait: it is refused (409 agent_paused), the chat marks it "Not sent.", and it has to be sent again once the agent is resumed. The sentence your user reads for it is general on purpose, because they may not be the one who paused the agent. If your app lets people pause their own agents, say so in your words:labels.refusals.agent_pausedon<AgentChat>. An approval is different: one decided while the agent is paused is kept, and the agent acts on it once it is resumed. After Approve the card says "Approved." and, under it, "This agent is paused. It will act on this when you resume it." Your words for that go inlabels.decisionRefusals.agent_paused;labels.refusals.agent_pausedis for a refused message and isn't shown there.workspace_busy: the workspace is at its limit, either on runs at once or on credits that runs in flight still hold. A run waiting for credits holds none itself, and starts when they are given back.
Treat a reason you don't know as a plain wait. A run that still can't start after its wait ends with a data-refusal, such as cap_reached when the workspace's cap can't fit it even with nothing in flight.
A message sent while the agent is still answering
<AgentChat> never locks the message box. A message sent during a reply goes to your route at once, and OpenLegion answers it after the current reply; messages that waited behind the same reply are answered together. A message sent in a reply's first moment can be read by that same reply: the chat then puts the message before it, so a reply is drawn once, after the last message it answered, as history has it. Until then the chat shows it after the transcript with "Your message will be answered after the current reply." When the reply ends, the chat follows the thread's next answer (GET /chat/{thread}/stream). In your own UI, useAgentChat().send does the same, and waiting holds the ids of the messages that wait.
A list of conversations
ws.threads.list() has what a conversation list shows, with no second call per thread:
title: the first line of the thread's first message (at most 80 characters), until someone renames it.nullbefore the first message.last_message_at: when the newest message was written, by your user or by the agent.- The order. Newest conversation first. For a list people come back to,
ws.threads.list({ order: "last_message_at" })puts the conversation with the newest message first, so an old one your user picks up again comes back to the top. One with no message yet sorts by when it was made. seen_throughandunseen: how far the person you name has seen the conversation, and how many messages there they haven't.unseencounts exactly, up to 100; to ask whether anything is new, testunseen > 0.seen_throughis the time of the newest message they've seen, to the second, for display. Both arenullwhen your key names no person, and each person gets their own.- Only what's new.
ws.threads.list({ unseen: "true" })lists only the conversations where that person has something unseen, however old, in the same order and pages. It's for an inbox: an unread reply in an old conversation shows on the first page. It needs a person, so your key alone gets400 subject_required. archived: the list leaves archived threads out;ws.threads.list({ archived: "true" })is the archive.home:trueon the agent's home conversation, where its work in the background reports (a schedule's run, a hand-off, a decision made outside any conversation). Make it your user's first conversation withws.threads.create({ agent, home: true }): the same thread every time, so the reports land where your user already talks to the agent.- Who can use it. The home conversation belongs to the workspace, not to one person, so only an owner or admin opens it (and your key with no person named). It fits a product where each person has their own workspace and you give them the admin role (
POST /sessions {role: "admin"}). - A product whose users are members (the scaffold's default,
default_subject_role: member): a member who asks for home gets403 insufficient_role. Start each person's conversation withws.threads.create({ agent })instead. A schedule's run, a hand-off and a decision made outside any conversation still report to the home conversation, which a member doesn't see. To show those reports, your server reads that thread with your key (noOpenLegion-Subject) and shows what you choose.
- Who can use it. The home conversation belongs to the workspace, not to one person, so only an owner or admin opens it (and your key with no person named). It fits a product where each person has their own workspace and you give them the admin role (
await ws.threads.update(thread.id, { title: "Trip to Lisbon" }); // rename; title: null clears it
await ws.threads.update(thread.id, { archived: true }); // nothing is deleted
A new message to an archived thread brings it back. A member renames and archives only the threads they started.
A list of agents, with what your user hasn't seen
For a sidebar of agents, one call answers everything it shows, for the person you name:
const { data } = await ws.agents.summary();
// [{ agent, name, status, ongoing_thread, unseen, waiting, working, last_message_at }, …]
ongoing_thread: the conversation to open when your user picks the agent. Open it withws.threads.create({ agent, ongoing: true }), which answers that same thread, or makes one when there isn't one yet. For an owner or admin it's the agent's home conversation, so its reports land there. For a member it's their newest conversation with the agent that isn't archived.unseen: the messages there your user hasn't seen.100means 100 or more: show "99+". Their own messages are never counted, and anything before what they last said counts as seen.waiting: the approvals of this agent your user may decide.working: the agent is answering, or has a reply queued, where your user can see it.
Tell OpenLegion what your user has seen with ws.threads.seen(thread, { message }), naming the newest message on their screen. <AgentChat> does this for you when it fires onSeen. The mark is that message's own time, so a reply that arrived after the screen was drawn still counts as unseen. A mark only moves forward, and it's your user's alone: nobody else sees it.
Both calls need a person: an OpenLegion-Subject, or a session. The summary also needs the approvals scope, besides messages. Call it again every few seconds while the page is open and when the page regains focus; there's no push for badges.
A member can't see a thread
A person whose workspace role is member sees only the threads they started: another person's thread, and its runs, answer exactly as if they didn't exist (404 resource_missing). An owner or admin sees every thread, and so does your key with no person named. A thread your key created without naming a person, or one a schedule or an inbound event started, belongs to nobody, so a member never sees it.
The reply stopped mid-sentence
A stream cut short (a deploy, a function's time limit, the network) is not the end of the run. The kit re-attaches after the last part it saw, so the reply continues in place; after three tries that bring nothing it shows "The reply was interrupted." with a Reconnect button. Closing the stream never cancels the run: only POST /runs/{id}/cancel does.
Stop a reply
In <AgentChat>, Stop takes Send's place while the agent works and the message box is empty. A tap in the first moment, before your route has answered the message, is remembered: the stop is sent as soon as the run has an id. It calls your route (POST /runs/{run}/cancel), which stops the run as the signed-in person. Once the stream ends with abort, the chat says "Stopped." under the words the reply already had. A reply that finished before the stop reached it is shown whole. If the run can't be stopped, the chat says so in one line and the reply carries on. After a reload the reply still says "Stopped.", from its message's stopped. In your own UI, useAgentChat() gives stop() and stopState, and isMessageStopped(message) reads a past reply.
POST /runs/{id}/cancel stops a run, with your key, acting as the person who asked (OpenLegion-Subject).
- A run that is waiting is cancelled at once:
200, and the run readscancelled. - A run that is working answers
202and still readsrunning. The answer the model is writing is cut within about 2 seconds, keeping the words so far. A tool call that is already running completes; nothing further starts. Then the stream ends withabort, the run readscancelled, andrun.cancelledfires. This holds for the last step too: a stopped run never readscompleted. - A long tool call finishes first. A slow tool call runs to its end before the stop takes effect. So does the model call of a run nobody streams (a schedule's run,
POST /agents/{id}/runs, a resume); a chat message's run always streams. - What the agent wrote stays. The words it wrote before the stop are in the thread, and a reload shows them. If it had only called tools and written nothing yet, the reply is still there after a reload, with its tool parts and its files and no text.
- The next message is not held up. Send it right away; it starts when the stopped run has ended.
- An approval the run asked for is still there, and can still be answered.
A member can stop only a run in a thread they started; another person's run answers 404. A run that has already ended answers 409 run_not_cancellable.
A refusal names the wrong person
Every refusal and every run error has two sentences. message is for your user, and never names OpenLegion or your plumbing. partner_message is for you: show the first, log the second. A session token's responses leave partner_message out.
The events an assistant app handles
The chat shows what happens while your user is looking at it. For the rest (they closed the tab, a schedule ran overnight), your route's webhooks map hears the events. An app with an assistant in it usually handles these:
| Event | When it fires | What an app does with it |
|---|---|---|
run.completed, run.failed, run.cancelled | A run ended. Every run fires exactly one of the three. | Mark the conversation as answered, tell a user who is away, log a failure (error.partner_message says what to do). |
action.requires_approval | A tool call waits for a person. data.approval is the approval to decide. | Tell the person something needs them. The card itself is in the chat. |
approval.decided, approval.expired | A person approved or rejected it, or nobody did in time. | Clear your own "needs you" marker. |
action.completed, action.failed | An action ran, or ran and did not work. | Show what was done, for an action approved earlier. |
approval.requested | The agent asked a person a question. | Tell the person there is a question for them. |
workspace.cap_reached | A customer's workspace reached its credit cap. | Offer a higher limit, or say when the period renews. |
connection.needs_reauth | A connected account's sign-in stopped working. | Ask the person to reconnect it. |
A type with no handler is acknowledged and dropped, and npx openlegion dev says so once per type. Every type and its object: Webhooks.
The kit's routes
createNextHandler serves these under /api/openlegion (your basePath). The chat routes, the vault routes and the editors' routes exist only when you pass resolve, and answer only a request from your own origin (or one you list in allowedOrigins).
| Route | What it does |
|---|---|
POST /chat | Sends your user's message and streams the reply. |
GET /chat/{thread}/stream, GET /runs/{run}/stream | Re-attach to a reply in progress. |
GET /threads, POST /threads | Your user's conversations, newest message first, and a new one with an agent: what useThreads() reads and starts. |
POST /runs/{run}/cancel | Stops a run, for the chat's Stop button. Answers the run's id and status. |
GET /runs/{run} | How a run that left no answer ended, for a reload: its status, the sentence for your user, and its tool calls' names and states. Also when it started and ended, which is how the chat knows one reply answered two messages. |
GET /vault, POST /vault | Whether the item an agent asked for is saved, and the secure form's save. |
/template_agents, /agents, /agents/{id}, /schedules, /schedules/{id} and its pause and resume | What useAgents, useSchedules, <AgentEditor> and <ScheduleEditor> read and change. |
POST /webhooks | Your webhook endpoint. |
POST /mcp, POST /template | Your tools and your template, called by OpenLegion, signed. |
A route that refuses answers {error: {code, message}}. Every code is on Errors.