# State Rendering

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

<!-- interactive demo: shared-state-streaming -->

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

<Steps>
  <Step>
    ### Make the state your agent's working memory

    On Mastra, the shared state is the agent's
    [working memory](https://mastra.ai/en/docs/memory/working-memory). Give
    the agent a `Memory` with working memory enabled and a Zod schema. The
    schema is the shape of `agent.state` in the UI.

~~~~typescript title="src/mastra/agents/index.ts — state schema"
/**
 * Shared-state schema for the Shared State (Read + Write) demo.
 *
 * - `preferences` is WRITTEN by the UI via `agent.setState({ preferences })`.
 *   The AG-UI Mastra adapter merges `input.state` into the thread's
 *   `workingMemory` metadata before each run, so the LLM sees the latest UI
 *   preferences as part of working memory on every turn.
 * - `notes` is WRITTEN by the agent (via the `set_notes` tool) and READ by
 *   the UI via `useAgent({ updates: [OnStateChanged] })`. Mastra emits a
 *   `STATE_SNAPSHOT` after each run with the working-memory contents.
 */
export const SharedStateRWAgentState = z.object({
  preferences: z
    .object({
      name: z.string().default(""),
      tone: z.enum(["formal", "casual", "playful"]).default("casual"),
      language: z.string().default("English"),
      interests: z.array(z.string()).default([]),
    })
    .default({
      name: "",
      tone: "casual",
      language: "English",
      interests: [],
    }),
  notes: z.array(z.string()).default([]),
});
~~~~

    The AG-UI Mastra adapter merges the state that the UI writes with
    `agent.setState` into working memory before each run. After a run that
    changed working memory, it sends the new contents to the UI as a
    `STATE_SNAPSHOT`.

~~~~typescript title="src/mastra/agents/index.ts — agent with working memory"
/**
 * Mastra agent backing the Shared State (Read + Write) demo.
 *
 * Bidirectional shared-state pattern:
 *   - UI -> agent: the UI writes `preferences` via `agent.setState(...)`.
 *     The AG-UI Mastra adapter merges that into working memory before each
 *     run, so the LLM reads it as part of its system context.
 *   - agent -> UI: the LLM calls `set_notes` to update the `notes` array.
 *     Mastra includes the `notes` field in its working-memory schema, so
 *     after each run the AG-UI adapter emits a `STATE_SNAPSHOT` and the UI
 *     re-renders.
 *
 * Note on the system prompt: rather than a static string, this is a
 * function so we can reaffirm — every turn — that the LLM should respect
 * whatever `preferences` are sitting in working memory. Mastra exposes
 * working memory to the LLM automatically; the prompt just nudges it to
 * actually USE those preferences instead of ignoring them.
 */
export const sharedStateReadWriteAgent = new Agent({
  id: "shared-state-read-write",
  name: "Shared State Read+Write Agent",
  tools: { setNotesTool },
  model: openai("gpt-6-luna"),
  instructions: `You are a helpful, concise assistant wired to a UI that owns the user's preferences and an agent-authored notes panel.

PREFERENCES (READ from working memory every turn):
The UI writes a \`preferences\` object into shared state. It contains:
  - name: how to address the user
  - tone: "formal" | "casual" | "playful"
  - language: the language to reply in
  - interests: a list of topics the user cares about
Always tailor your reply to these preferences. Address the user by name when one is set. Reply in their preferred language and tone. Lean on their interests when suggesting examples or topics.

NOTES (WRITE via the \`set_notes\` tool):
The UI also renders an "Agent notes" panel sourced from the \`notes\` array in shared state. Whenever the user asks you to remember something, OR when you make a useful observation about the user worth surfacing, call the \`set_notes\` tool with the FULL updated list of short note strings (existing notes + new ones). Always pass the entire list — never a diff. Keep each note short (< 120 chars).

The \`set_notes\` tool persists the notes to working memory itself — you do NOT need to also call \`updateWorkingMemory\`. Just call \`set_notes\` and the UI will update.`,
  memory: new Memory({
    storage: new LibSQLStore({
      id: "shared-state-rw-agent-memory",
      url: WORKING_MEMORY_DB_URL,
    }),
    options: {
      workingMemory: {
        enabled: true,
        schema: SharedStateRWAgentState,
      },
    },
  }),
});
~~~~

  </Step>
  <Step>
    ### Tell the agent to use the state

    Mastra shared state is prompt-driven. The model only acts on a value the
    UI wrote, or writes a value back, when its `instructions` tell it to.
    Name the state fields in `instructions` and say what to do with them, as
    the agent above does for `preferences` and `notes`.

    The agent can write state with Mastra's built-in `updateWorkingMemory`
    tool. The demo's `set_notes` tool writes working memory itself, so the
    UI updates even when the model does not call `updateWorkingMemory`:

~~~~typescript title="src/mastra/tools/shared-state-read-write.ts"
/**
 * Backend-side tool the LLM calls to update the `notes` slot in shared state.
 *
 * Mirrors the LangGraph-Python `set_notes` reference: the tool always receives
 * the FULL updated notes list (existing notes + any new ones).
 *
 * Determinism: this tool writes the new notes array to the agent's working
 * memory DIRECTLY (`writeNotesToWorkingMemory`), instead of relying on the
 * LLM to remember to call Mastra's `updateWorkingMemory` in addition to this
 * tool. The AG-UI Mastra adapter emits a `STATE_SNAPSHOT` event whenever
 * working memory changes, which drives the live re-render of the notes card —
 * so as long as the write here lands, the UI updates regardless of whether
 * the LLM remembers anything.
 *
 * The returned JSON is what the LLM sees: notes echoed back plus an
 * `updated: true` flag confirming the write attempt completed (best-effort —
 * see `working-memory.ts` for the failure semantics).
 */
export const setNotesTool = createTool({
  id: "set_notes",
  description:
    "Replace the notes array in shared state with the FULL updated list of short note strings (existing notes + any new ones). Each note should be < 120 chars. Call this whenever the user asks you to remember something, or when you have an observation worth surfacing in the UI's notes panel. The tool persists the notes to working memory directly — you do not need to also call updateWorkingMemory.",
  inputSchema: z.object({
    notes: z
      .array(z.string())
      .describe(
        "Full updated notes list (existing notes plus any new ones). NOT a diff.",
      ),
  }),
  execute: async (inputData, executionContext) => {
    const notes = inputData.notes ?? [];
    await writeNotesToWorkingMemory(executionContext, notes);
    return JSON.stringify({ notes, updated: true as const });
  },
});
~~~~

    `writeNotesToWorkingMemory` is the demo's helper in
    `src/mastra/tools/working-memory.ts`.

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

    Shared state works when the Mastra agent runs inside Copilot Runtime
    through `getLocalAgents` (or `getLocalAgent`):

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

    It does **not** work through a remote Mastra agent from
    `MastraAgent.getRemoteAgents`. That bridge does not carry working memory,
    so the UI never receives the state and nothing reports an error.

  </Step>
  <Step>
    ### Use the agent's registered key

    The `agentId` you pass to `useAgent` must exactly match the key the
    runtime registers the agent under. With `getLocalAgents`, that is the key
    in your Mastra `agents` map, for example `searchAgent` in
    `agents: { searchAgent }`.

    Working memory starts empty. To show a default before the agent writes
    anything, set the missing value with `agent.setState` once `isReady` is
    true:

    ```tsx title="app/page.tsx"
    import { useEffect } from "react";
    import { useAgent } from "@copilotkit/react-core/v2";
    import type { AgentState } from "@/mastra/agents/language-agent";

    // inside your component
    const { agent, isReady } = useAgent({ agentId: "languageAgent" });
    const state = (agent.state ?? {}) as Partial<AgentState>;

    useEffect(() => {
      if (!isReady || state.language !== undefined) return;
      agent.setState({ ...(agent.state ?? {}), language: "english" });
    }, [agent, isReady, state.language]);
    ```

  </Step>
</Steps>

1. On the backend, write the value to a key in the
   [agent state](/mastra/shared-state). To stream a tool argument into a state key
   token by token, see [State Streaming](/mastra/shared-state/streaming).
2. On the frontend, import `useAgent` from `@copilotkit/react-core/v2`:

   ```tsx
   import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
   ```

3. Subscribe to the agent state. Each time the state changes, your component
   renders again with the latest value:

   ```typescript title="src/app/demos/shared-state-streaming/page.tsx"
     // Subscribe to BOTH state changes and run-status changes. The former
     // drives the per-token document rerender; the latter toggles the
     // "LIVE" badge when the agent starts / stops.
     const { agent } = useAgent({
       agentId: "shared-state-streaming",
       updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
     });
   ```

4. Read the key from `agent.state` and render it:

   ```tsx
   const document = (agent.state as { document?: string }).document ?? "";
   ```

To check it, ask the agent to write a short poem. Your component renders the
poem each time the agent updates `document` in its state.

To render the state inside the chat instead, pass a `children` function to
the chat's `messageView` slot and add your UI next to the messages. For
example, to list the searches an agent keeps in a `searches` key:

```tsx
<CopilotChat
  agentId="sample_agent"
  messageView={{
    children: ({ messageElements, interruptElement }) => (
      <div>
        {messageElements}
        {state.searches?.map((search, index) => (
          <div key={index}>{search.done ? "✅" : "❌"} {search.query}</div>
        ))}
        {interruptElement}
      </div>
    ),
  }}
/>
```

Here `state` is `agent.state` from `useAgent`.

<Callout type="info">
  **Free course:** See this pattern built end-to-end in [Build Interactive Agents with Generative UI](https://www.deeplearning.ai/short-courses/build-interactive-agents-with-generative-ui/). This free DeepLearning.AI short course is taught by CopilotKit's CEO. It covers the full Generative UI spectrum (Controlled, Declarative, and Open-Ended).
</Callout>

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