# State Rendering

> Render your agent's state with custom UI components in real-time.

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

State rendering lets you build UI that reflects your agent's state in real-time. As your agent progresses through nodes and emits state updates, your frontend renders those changes, showing progress, drafts, or intermediate results.

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

Use state rendering when you want to:

- Show real-time progress (e.g. "Researching... 2/5 complete")
- Display drafts that update as the agent works
- Build dashboards that reflect agent state
- Render structured output outside of the chat

## How it works in code [#how-it-works-in-code]

On the frontend, subscribe to the agent's state. Each time the backend forwards a fresh value, your component re-renders with the latest partial output. `useAgent` returns an `agent` ref; read `agent.value?.state` in script or let templates unwrap the ref. Keep the provider in an ancestor SFC.

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

type ResearchState = { status?: string; draft?: string; completed?: number; total?: number };

const { agent } = useAgent({
  agentId: "researcher",
  updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
});

const state = computed(() => (agent.value?.state ?? {}) as ResearchState);
</script>

<template>
  <section aria-live="polite">
    <p>{{ state.status ?? "Idle" }}</p>
    <progress :value="state.completed ?? 0" :max="state.total ?? 1" />
    <article v-if="state.draft">{{ state.draft }}</article>
  </section>
</template>
```

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

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

On the backend, a state-streaming mapping forwards a tool argument into a state key while the model writes it. Some frameworks provide that as middleware. Direct SDK adapters can emit `STATE_SNAPSHOT` events from their streaming loop. Either way, the UI can watch the answer assemble token-by-token rather than appearing in one burst between checkpoints.

<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>

```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,
      },
    },
  }),
});
```

Ask the researcher agent to write a report. The status line and the progress bar change while the agent runs, and the draft text grows as the tokens arrive.

Treat agent state as untrusted external data. Validate it before using it for privileged actions, and avoid putting secrets in state that is streamed to the browser.

<IntegrationGrid
  path="generative-ui/state-rendering"
  exclude={["agno", "agent-spec"]}
/>
