State Streaming

Stream partial agent state to your React Native UI while a tool call is still running.

What is this?

By default, agent state only updates between backend checkpoints, so a long tool call (writing a full document, drafting an email) reaches the UI as one burst at the end. In an agent-native app, that feels broken: users expect to watch the output appear.

State streaming copies one tool argument into an agent state key while the model writes the argument. Your screen, subscribed with useAgent, re-renders on every token.

When should I use this?

Use state streaming when a tool's output is long-form text or a growing structured value, and you want the user to see it build up in real time. Common shapes:

  • A writing agent that produces a document
  • A research agent that collects a list of findings
  • A planning agent that builds a step-by-step plan

The backend: one streaming state mapping

Stream working memory through updateWorkingMemory

Mastra has no streaming middleware to configure. When working memory is enabled, Mastra gives the agent a built-in updateWorkingMemory tool. During a run:

  1. The agent calls updateWorkingMemory.
  2. The AG-UI Mastra adapter reads the tool call's arguments while they stream.
  3. It sends one STATE_SNAPSHOT, then a STATE_DELTA for each new part, against the working-memory schema.
  4. useAgent renders again on each delta.

The field you stream is a key in the working-memory schema:

src/mastra/agents/index.ts — streamed state
/**
 * Shared-state schema for the Shared State (Streaming) demo.
 *
 * `document` is streamed token-by-token into shared state as the agent
 * writes. Mastra parity for the LangGraph `StateStreamingMiddleware` /
 * predictive-state pattern: instead of a `write_document` tool whose arg is
 * forwarded per-token, this agent calls Mastra's built-in
 * `updateWorkingMemory` tool with the growing document. The AG-UI Mastra
 * adapter intercepts that tool call's STREAMING args (OSS-414) and emits a
 * leading `STATE_SNAPSHOT` followed by incremental `STATE_DELTA`s on the
 * `document` key, so `useAgent({ updates:[OnStateChanged] })` sees
 * `state.document` grow live.
 */
export const SharedStateStreamingAgentState = z.object({
  document: z.string().default(""),
});

Tell the model to write into working memory

Only updateWorkingMemory streams. A custom tool that writes working memory sends a single STATE_SNAPSHOT when the run ends. So the prompt must make the model put the whole value in one updateWorkingMemory call, and keep it out of the chat message:

src/mastra/agents/index.ts — streaming agent
/**
 * Mastra agent backing the Shared State (Streaming) demo.
 *
 * Per-token state streaming. When asked to write, draft, or revise text the
 * agent calls the built-in `updateWorkingMemory` tool with the FULL document
 * text under the `document` key. Because working memory is enabled with the
 * `SharedStateStreamingAgentState` schema, Mastra streams that tool call's
 * args as `tool-call-delta` frames; the AG-UI Mastra adapter accumulates
 * them, re-parses the growing prefix, and emits a leading `STATE_SNAPSHOT`
 * plus incremental `STATE_DELTA`s on `/document` (OSS-414). The frontend
 * renders `state.document` live as it fills in.
 *
 * NOTE: unlike `sharedStateReadWriteAgent`/`genUiAgent` (which use a custom
 * `set_*` tool that yields a single end-of-run `STATE_SNAPSHOT`), this demo
 * deliberately drives the built-in `updateWorkingMemory` tool — that is the
 * only path that streams progressive per-token deltas rather than one blob
 * at run end. So the prompt tells the model to write the document straight
 * into working memory instead of via a bespoke tool.
 */
export const sharedStateStreamingAgent = new Agent({
  id: "shared-state-streaming",
  name: "Shared State Streaming Agent",
  tools: {},
  model: openai("gpt-6-luna"),
  instructions: `You are a collaborative writing assistant wired to a live Document panel.

Whenever the user asks you to write, draft, revise, or explain anything of any length (a poem, an email, an essay, a summary, an explanation, etc.), you MUST call the \`updateWorkingMemory\` tool with the FULL content as a single string under the \`document\` field, e.g. { "document": "<the full text>" }.

Rules:
  - NEVER paste the document body into a chat message. The document belongs in shared state — the UI renders it live from working memory as you stream it.
  - Always send the ENTIRE document in one \`updateWorkingMemory\` call (not a diff, not chunks across multiple calls).
  - After the document is written, reply with ONE short chat sentence confirming what you wrote (e.g. "Done — I've drafted your poem in the document panel."). Keep the document text itself out of that message.`,
  memory: new Memory({
    storage: new LibSQLStore({
      id: "shared-state-streaming-agent-memory",
      url: WORKING_MEMORY_DB_URL,
    }),
    options: {
      workingMemory: {
        enabled: true,
        schema: SharedStateStreamingAgentState,
      },
    },
  }),
});

Register the agent in your Mastra instance. Its key in the agents map is the agentId the frontend uses.

Embed the agent in the runtime

State streaming works only when the agent runs inside Copilot Runtime through getLocalAgents:

app/api/copilotkit/[[...slug]]/route.ts
const runtime = new CopilotRuntime({
  agents: MastraAgent.getLocalAgents({ mastra, resourceId: "user-1" }),
});

The working-memory snapshot at the end of the run replaces the streamed value, so any drift is corrected.

The backend pattern is always the same: map one streaming tool argument to one shared-state key. Each framework does this in its own way:

  • LangGraph Python: StateStreamingMiddleware with StateItem(...) entries.
  • LangGraph TypeScript: copilotkitCustomizeConfig with an emitIntermediateState mapping.
  • Direct SDK adapters: parse partial tool arguments in the streaming loop, and emit STATE_SNAPSHOT whenever the mapped value changes.
  • LlamaIndex and Pydantic AI: there is no per-token mapping. A backend tool sends a state snapshot after each step or tool call instead (see the setup above).

When the model streams that argument, CopilotKit writes every partial value into shared state before the tool finishes.

index.ts
/**
 * Mastra agent backing the Shared State (Streaming) demo.
 *
 * Per-token state streaming. When asked to write, draft, or revise text the
 * agent calls the built-in `updateWorkingMemory` tool with the FULL document
 * text under the `document` key. Because working memory is enabled with the
 * `SharedStateStreamingAgentState` schema, Mastra streams that tool call's
 * args as `tool-call-delta` frames; the AG-UI Mastra adapter accumulates
 * them, re-parses the growing prefix, and emits a leading `STATE_SNAPSHOT`
 * plus incremental `STATE_DELTA`s on `/document` (OSS-414). The frontend
 * renders `state.document` live as it fills in.
 *
 * NOTE: unlike `sharedStateReadWriteAgent`/`genUiAgent` (which use a custom
 * `set_*` tool that yields a single end-of-run `STATE_SNAPSHOT`), this demo
 * deliberately drives the built-in `updateWorkingMemory` tool — that is the
 * only path that streams progressive per-token deltas rather than one blob
 * at run end. So the prompt tells the model to write the document straight
 * into working memory instead of via a bespoke tool.
 */
export const sharedStateStreamingAgent = new Agent({
  id: "shared-state-streaming",
  name: "Shared State Streaming Agent",
  tools: {},
  model: openai("gpt-6-luna"),
  instructions: `You are a collaborative writing assistant wired to a live Document panel.

Whenever the user asks you to write, draft, revise, or explain anything of any length (a poem, an email, an essay, a summary, an explanation, etc.), you MUST call the \`updateWorkingMemory\` tool with the FULL content as a single string under the \`document\` field, e.g. { "document": "<the full text>" }.

Rules:
  - NEVER paste the document body into a chat message. The document belongs in shared state — the UI renders it live from working memory as you stream it.
  - Always send the ENTIRE document in one \`updateWorkingMemory\` call (not a diff, not chunks across multiple calls).
  - After the document is written, reply with ONE short chat sentence confirming what you wrote (e.g. "Done — I've drafted your poem in the document panel."). Keep the document text itself out of that message.`,
  memory: new Memory({
    storage: new LibSQLStore({
      id: "shared-state-streaming-agent-memory",
      url: WORKING_MEMORY_DB_URL,
    }),
    options: {
      workingMemory: {
        enabled: true,
        schema: SharedStateStreamingAgentState,
      },
    },
  }),
});

A few things to note:

  • The state key must exist in your agent state (document in this example).
  • The tool and argument names must match the exact tool call the model makes (write_document.document here).
  • Streamed values are previews. When the step ends, the state the agent saves replaces them, so save the final value when the tool finishes. On CrewAI, LlamaIndex, and Pydantic AI, write the final value to the agent state yourself, or it is overwritten when the step returns.

The frontend: useAgent and OnStateChanged

The app side is the same as any other shared-state subscription: useAgent with OnStateChanged gives you a live agent.state. Add OnRunStatusChanged for a "writing" indicator.

src/DocumentView.tsx
import { ActivityIndicator, ScrollView, Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";

export function DocumentView() {
  const { agent } = useAgent({
    agentId: "default",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const document = (agent.state as { document?: string } | undefined)?.document ?? "";

  return (
    <View style={{ padding: 16, gap: 8 }}>
      {agent.isRunning ? <ActivityIndicator /> : null}
      <ScrollView style={{ maxHeight: 320 }}>
        <Text>{document}</Text>
      </ScrollView>
    </View>
  );
}

agent.state.document is a string that grows on every token, and agent.isRunning tells you whether to show the indicator. The ScrollView with a maxHeight keeps a long document from pushing the rest of the screen away.

If a fast stream re-renders a heavy screen too often, pass throttleMs to useAgent to batch the updates.

Try it

Ask the agent to write a short poem. The document text grows on your screen while the agent writes. When the run ends, agent.isRunning is false, so the indicator goes away.

How is this guide?