Skip to main content

Sessions, items and streaming

A session is where a flow keeps many requests together as one record. For a chat it is the conversation; for a workflow it is the log of everything the work did. Everything that happens in it is an item: a message, a tool call, a progress card, an error. Items reach the browser while the work is running, so a reply appears as it is written. The session keeps them, so a reload brings them back.

The example on this page is a support desk. A customer asks where order A-1001 is, the model looks it up, and then it writes the reply.

One reply, as it arrives​

Each message the user sends starts a request: one run of one action, which is a call a client can make. The figure is one request, left to right, and the session's list below it.

One request, and the session's list under it
A dashed outline, because a request lasts one action run, holds four boxes joined by arrows that mean then. First the user message, complete at once. Second a tool call, a tool_output item for lookUpOrder that is in progress and then done. Third, highlighted, the reply: a message item that is in progress while its text grows piece by piece, as Your order, shipped, Tuesday. Fourth the end, item.done, when the reply is completed with its full text. Below the request is the session's list, hatched because it outlives the request, holding the same items in the same order.ONE REQUEST · THE REPLY ACTIONUSER MESSAGEmessagerole: usercomplete at onceTOOL CALLtool_outputlookUpOrderin_progress, then doneTHE ENDitem.donereply is completedfull text, one itemTHE REPLYmessagein_progress"Your order"" shipped"" Tuesday."THE SESSION'S LIST · EVERY REQUEST'S ITEMSmessage tool_output messageThe same items, in the same order. The next request adds to the end.01Halfway through the sentence, the browser holds the user message, the tool call and the reply so far.02The reply is one item. It stays in place and its text grows, so there is nothing to stitch together.03The request ends with the action run. The session's list keeps what it produced.THENLASTS ONE ACTION RUNOUTLIVES THE REQUESTTHE TEXT GROWS

The user's message is there because the action asks for it. An action written as { block, userMessage: (input) => input.message } records the input as the user's line when the request starts; an action without userMessage records none. The message is complete the moment it appears. The tool call is one item that gains its result when it finishes. The reply is one message item that grows as the model's words arrive, then is sent again whole when the model finishes. The items reference has the events and statuses.

So when the model is halfway through a sentence, the browser holds the user's message, the finished tool call, and the reply so far. It has not yet received the reply's done event.

Reading it on a page​

src/app/ticket-thread.tsx
"use client";

import { useSession } from "@flow-state-dev/react";

export function TicketThread({ sessionId }: { sessionId: string }) {
const session = useSession(sessionId, { autoResume: true });

return (
<ul>
{session.items.map((item) =>
item.type === "message" ? (
<li key={`${item.requestId}:${item.id}`}>
{item.content.map((part) => (part.type === "output_text" ? part.text : ""))}
</li>
) : null,
)}
</ul>
);
}

session.items is every item in the session, in order, and the hook updates it as pieces arrive, so the reply grows on screen. The key pairs requestId with id because an item's id is unique only within its request. Drawing cards and tool calls too is Rendering items.

The items you will meet​

Each item has a type and a status, and records the block that made it. A block is the framework's unit of work, and Blocks explains it. These four types cover what this page shows.

ItemMade byIn a model's history by default
messageThe user's input, a generator, or ctx.emit.messageYes
tool_outputA tool callYes
datactx.emit.dataNo
statusctx.emit.statusNo

The items reference lists every type, its fields and the visibility rules.

A session keeps them​

A session belongs to the user who created it. Anyone else who asks for it, or for one of its requests, gets a 404, the same answer as for an id nobody has used. A live view and a reloaded page show the same items in the same order. The default store keeps them in memory, so a server restart loses them; a SQLite or Postgres store keeps them. The items reference has what is stored and who can read it.

What the next request's model sees is a separate choice. A generator sees earlier items only when its history option is on, and then only the types marked Yes, unless you change an item's visibility. The options are in the reference.

Emitting your own​

A generator makes its own messages. Any other block emits items through ctx.emit. Here a handler shows a progress card while it looks up the order.

src/flows/support/blocks/check-order.ts
import { handler } from "@flow-state-dev/core";
import { z } from "zod";

// A stand-in for your order system.
const orders: Record<string, string> = { "A-1001": "shipped Tuesday" };

export const checkOrder = handler({
name: "check-order",
inputSchema: z.object({ orderId: z.string() }),
outputSchema: z.object({ orderId: z.string(), detail: z.string() }),
execute: async (input, ctx) => {
const key = `order-${input.orderId}`;
ctx.emit.data("order-lookup", { orderId: input.orderId, state: "looking" }, { key });
const detail = orders[input.orderId] ?? "not found";
ctx.emit.data("order-lookup", { orderId: input.orderId, state: "found", detail }, { key });
return { orderId: input.orderId, detail };
},
});

Each call emits a data item, a structured record on the stream. The first argument is its dataType, the name a client registers a renderer under; Rendering items shows how. The key makes the second call replace the first instead of stacking beside it. The new value replaces the old whole, with no merge, so send every field each time. A reload shows only the latest copy.

ctx.emit.message(text) and ctx.emit.status(text) are the other two emitters. The items reference says what each one stores.

From a terminal​

fsdev run prints each item as a line of JSON. Below is the reply from the hello-chat example, shortened. A generator needs its model provider's key in the environment.

fsdev run hello-chat chat -i '{"message":"Say hi in four words."}' --quiet
{"type":"item_added","item":{"type":"message","role":"assistant","status":"in_progress","content":[{"type":"output_text","text":""}], …}}
{"type":"content_delta","itemId":"item_msg_…","delta":"Hi"}
{"type":"item_done","item":{"type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Hi there, my friend!"}], …}}

The terminal also prints trace rows such as block_trace. A browser's stream leaves them out unless the client asks for them, as the items reference explains.

If the connection drops​

A request keeps running on the server when the browser's connection ends. The stream is a view onto it, so a client that reconnects picks up after the last event it saw.

A dropped connection, resumed at the next number
Three boxes in a row. On the left, the browser live, holding events 1 to 41 and the reply so far, Your order shi. In the middle, the request running on the server, producing events 42 to 57 while nobody listens. A red line with a bar between the first two boxes marks the lost connection. On the right, highlighted, the browser back, asking starting_after=41, so events 42 onward are sent. An arrow runs from the middle box to the right one.THE BROWSER, LIVEevents 1 to 41the reply so far"Your order shi"THE REQUEST, STILL RUNNINGevents 42 to 57nobody is listeningthe reply finishes anywayTHE BROWSER, BACKstarting_after=41events 42 onward are sentthe reply text snaps toits saved copy, then grows01The connection drops after event 41. The request keeps running on the server.02The browser reconnects and asks for everything after 41. A finished request replays the same way.03Pieces of a half-written reply are not replayed. The text snaps to its latest saved copy, then grows again.REPLAYED TO THE BROWSERRESUMES AT THE NEXT NUMBERCONNECTION LOST

When the stream ends before the request does, the browser client reconnects and resumes on its own, with no option to set. The pieces of text sent during the gap are not replayed, so the reply can be missing those words until the message finishes and arrives whole. A reload is different: it reads the saved items. Reload mid-reply and the order A-1001 thread comes back with the reply text saved so far, which can trail what was on screen by a moment. With autoResume: true, as in the example above, the hook then attaches to the running request and carries on.

Detecting a stalled stream, heartbeats and the recovery calls are in the items reference.

What it gets you​

  • The reply shows as it is written. The reply is one item whose text grows, and session.items holds it.
  • A reload brings the thread back. Reload mid-reply and the order A-1001 thread returns, and with autoResume the reply carries on. A dropped stream resumes where it stopped.
  • One list for everything the run does. A message, a tool call and a progress card are all items in one ordered list, drawn by type.
  • Progress cards stay out of the prompt. Each item type has a default visibility, so a card shown to the user is not sent to the next request's model.

How it fits with the others​

Blocks emit items. State and resources are separate. A change to either reaches a browser as a short notice item, not as the state itself; State and scopes covers that.

Next​

  • Rendering items: register the components that draw messages, tool calls and cards.
  • Blocks: the units that emit items.
  • Items reference: every item type, visibility, the wire format, resume and heartbeat.