# Shared State

> Create a two-way connection between your UI and agent state.

## What is shared state? [#what-is-shared-state]

Shared state connects your UI with the agent's run. With shared state you can:

- Display the agent's current progress and intermediate results
- Update the agent's state through UI interactions
- React to state changes in real-time across your application

<ImageZoom
  src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif"
  alt="Shared State Demo"
  width={1000}
  height={1000}
  className="rounded-lg shadow-lg border mt-0"
/>

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

Use shared state when you want the agent and the user to collaborate through the same application state. The agent's outputs are reflected in the UI, and user updates in the UI are reflected in the agent's execution.

<OpsPlatformCTA
  variant="inline"
  title="Building stateful agents?"
  body="Persistent threads ship with CopilotKit Intelligence on the free Developer tier."
  surface="docs_shared_state"
/>

## Reading agent state [#reading-agent-state]

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

Subscribe a component to the agent's state with `useAgent`. Any time the agent mutates its state, for example via a tool call, the composable updates its reactive `agent` ref and your UI re-renders with the new values.

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

type WorkspaceState = {
  notes?: string[];
  preferences?: { tone?: string };
};

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

<template>
  <ul>
    <li v-for="note in state.notes ?? []" :key="note">{{ note }}</li>
  </ul>
</template>
```

The returned `agent.value.state` is a plain object. Read it like any other reactive application data and render the parts you care about: agent-written notes, structured outputs, progress indicators, or anything else the agent has put there.

## Writing agent state [#writing-agent-state]

The same agent object exposes `setState`. Calling it from a UI event handler pushes the new value into shared state, and the agent reads it back on its next turn. The UI's writes visibly steer the model.

```vue title="src/components/SharedWorkspace.vue"
<script setup lang="ts">
function setTone(tone: string) {
  const current = agent.value;
  if (!current) return;

  const previous = (current.state ?? {}) as WorkspaceState;
  current.setState({
    ...previous,
    preferences: { ...previous.preferences, tone },
  });
}
</script>

<template>
  <button @click="setTone('concise')">Prefer concise answers</button>
</template>
```

The UI can also send the agent new inputs, such as preferences, selections, or partial work, without the chat.

## Rendering shared state in the UI [#rendering-shared-state-in-the-ui]

Because `agent.state` is plain data exposed through a Vue ref, the UI layer is ordinary Vue. The example above wires the agent's outputs into a list and feeds user edits back through `setState`.

Nothing about this is chat-specific: `useAgent` works in any component under `CopilotKitProvider`, so you can render shared state in your main view or canvas, not just inside the chat panel. See **[Render agent state in your app](/vue/shared-state/rendering-in-app)** for the full main-view pattern.

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

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

## Streaming partial state updates [#streaming-partial-state-updates]

By default, shared state only updates *between* backend checkpoints, so a long-running tool call appears as one big burst at the end. State streaming copies a tool argument into a state key while the model writes it, so the UI can watch the answer assemble token-by-token. 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,
      },
    },
  }),
});
```

See **[State streaming](/vue/shared-state/streaming)** for the full walkthrough, including the corresponding `useAgent` subscription on the frontend.

## Read-only context [#read-only-context]

When a value is **UI-owned** and the agent should read it but never write it back, such as current user, selected record, or scroll position, reach for `useAgentContext` instead of full shared state. It publishes values as a one-way UI-to-agent channel that auto-unregisters on unmount.

`useAgentContext` is a separate read-only capability; it does not replace the bidirectional `agent.state` / `agent.setState(...)` contract above.

See **[Agent read-only context](/vue/shared-state/agent-readonly)** for the full pattern.

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