# State Streaming

> Stream partial agent state updates to the UI while a tool call is still running.

## What is this? [#what-is-this]

By default, agent state only updates *between* backend checkpoints, so a long-running tool call, such as writing a full document or drafting an email, appears to the UI as one big burst at the end. For agent-native apps, that feels broken: users expect to watch the output materialize.

**State streaming** copies the value of one tool argument into an agent state key while the model writes it. The UI, subscribed through `useAgent`, re-renders every token.

## When should I use this? [#when-should-i-use-this]

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

- A collaborative writing agent that emits a document
- A research agent that accumulates a list of findings
- A planning agent that builds up a step-by-step plan

Without streaming, the user stares at a spinner. With streaming, they see the answer grow token-by-token.

## The backend: one streaming state mapping [#the-backend-one-streaming-state-mapping]

<Steps>
  <Step>
    ### 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:

~~~~typescript title="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(""),
});
~~~~

  </Step>
  <Step>
    ### 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:

~~~~typescript title="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.

  </Step>
  <Step>
    ### Embed the agent in the runtime

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

    ```ts title="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.

  </Step>
</Steps>

The backend pattern is always the same: map one streaming tool argument to one shared-state key. Middleware-backed frameworks usually expose this as a declarative mapping. Direct SDK adapters do the same work in their streaming loop by parsing partial tool arguments and emitting `STATE_SNAPSHOT` whenever the mapped value changes. When the LLM streams that argument, CopilotKit writes every partial value into shared state before the tool finishes executing. The sample below is the LangGraph (Python) version.

```typescript title="src/mastra/agents/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 LLM-facing tool call you want to forward.
- When the tool call completes, its final return value is written to the same key, so the streamed partial eventually becomes the authoritative final value.

## The frontend: useAgent + OnStateChanged [#the-frontend-useagent--onstatechanged]

The UI side is identical to any other [shared-state](/vue/shared-state) subscription: `useAgent` with `OnStateChanged` gives you a reactive `agent.value.state`. Add `OnRunStatusChanged` if you want a live/done indicator.

```vue title="src/components/StreamingDocument.vue"
<script setup lang="ts">
import { computed } from "vue";
import { useAgent, UseAgentUpdate } from "@copilotkit/vue/v2";

type DocumentState = { document?: string };

const { agent } = useAgent({
  agentId: "writer",
  updates: [
    UseAgentUpdate.OnStateChanged,
    UseAgentUpdate.OnRunStatusChanged,
  ],
});
const state = computed(
  () => (agent.value?.state ?? {}) as DocumentState,
);
</script>

<template>
  <article aria-live="polite">
    <span v-if="agent?.isRunning">LIVE</span>
    <p>{{ state.document ?? "Waiting for a draft…" }}</p>
  </article>
</template>
```

From there, `state.document` is a string that grows on every token, and `agent.isRunning` tells you whether to show a streaming indicator.

```vue title="src/App.vue"
<script setup lang="ts">
import { CopilotChat, CopilotKitProvider } from "@copilotkit/vue/v2";
import StreamingDocument from "./components/StreamingDocument.vue";
</script>

<template>
  <CopilotKitProvider runtime-url="/api/copilotkit">
    <StreamingDocument />
    <CopilotChat agent-id="writer" />
  </CopilotKitProvider>
</template>
```

Ask the writer agent to draft a short document. The LIVE badge shows, and the text grows while the agent writes.

If the runtime does not emit partial state snapshots, the UI sees only the final state. The Vue frontend cannot invent updates the backend never sends.

<IntegrationGrid path="shared-state/streaming" exclude={["agno", "agent-spec", "spring-ai", "langroid"]} />
