# State Rendering

> Render your agent's state with your own React Native 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 works and writes to its state, your app renders those changes: 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 (for example, "Researching... 2/5 complete")
- Display drafts that update as the agent works
- Build dashboards that reflect agent state
- Render structured output outside 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](/react-native/mastra/shared-state). To stream a tool argument into a state key token by token, see [State Streaming](/react-native/mastra/shared-state/streaming).
2. On the frontend, subscribe to the agent's state with `useAgent`. Each time the state changes, your component renders again with the latest value.
3. Read the keys from `agent.state` and render them.

```tsx title="src/ResearchProgress.tsx"
import { Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";

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

export function ResearchProgress() {
  const { agent } = useAgent({ // [!code highlight:4]
    agentId: "researcher",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const state = (agent.state ?? {}) as ResearchState;

  return (
    <View style={{ padding: 16, gap: 8 }} accessibilityLiveRegion="polite">
      <Text style={{ fontWeight: "600" }}>
        {state.status ?? (agent.isRunning ? "Working..." : "Idle")}
      </Text>
      <Text>
        {state.completed ?? 0} of {state.total ?? "?"} complete
      </Text>
      {state.draft ? <Text>{state.draft}</Text> : null}
    </View>
  );
}
```

`updates` picks which changes re-render the component. `OnStateChanged` fires on state changes, and `OnRunStatusChanged` fires when a run starts or ends, so `agent.isRunning` stays current. Leave `updates` out to re-render on messages too.

Render it next to your chat, under the same provider. The chat and `ResearchProgress` share one agent:

```tsx title="App.tsx"
import { View } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { CopilotChat } from "@copilotkit/react-native/components";
import { ResearchProgress } from "./src/ResearchProgress";

const runtimeUrl = "http://localhost:8200/api/copilotkit";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl={runtimeUrl}>
      <View style={{ flex: 1 }}>
        <ResearchProgress />
        <CopilotChat agentName="researcher" />
      </View>
    </CopilotKitProvider>
  );
}
```

To check it, ask the researcher agent to write a report. The status line and the counter change while the agent runs, and the draft grows as the agent updates `draft` in its state.

## Inside the chat [#inside-the-chat]

The rendered `CopilotChat` has no slot for extra content between messages. To show state inside the conversation, build your own chat and add a row for it to your `FlatList` data. See [Headless UI](/react-native/mastra/custom-look-and-feel/headless-ui).

## Treat state as untrusted [#treat-state-as-untrusted]

Treat agent state as external data. Validate it before you use it for a privileged action, and don't put secrets in state that is streamed to the device.

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