Build stateful components and tool UIs that both the user and the model can read and edit. Render them beside the thread, or inside messages as versioned, editable surfaces like notepads and artifacts.
Interactables allow both agents and users to read and edit tool UIs and components. They can be in-thread tool UIs like an email composer, or app-scoped components, like artifacts, task boards, or settings panels.
Task Assistant
Ask me to add tasks to your board.
No tasks yet.
Ask the assistant to add some!
Overview
Types of Interactables
- App-scoped: a component you mount yourself with
unstable_useInteractable, anywhere in your app (a sidebar, a panel, wherever). The model automatically gets anupdate_{name}tool to read and edit it, and its state can persist across threads. - Thread-scoped: an interactable tool UI the model can call in-thread. You define it with
unstable_interactableToolinsidedefineToolkit, and it renders inline when called.
Features
- Shared, editable state: the user (via React) and the model (via the auto-generated
update_{name}tool) both write to the same state, and each sees the other's edits. - Streaming and partial updates: updates are streamed to the interactable, and the model only needs to update the fields it wants to change.
- Versioning and history: each user edit and model
update_*is recorded as a version you can display, list, andrestore()(Versions) - Persistent: state outlives the tool call and the turn, and can survive a reload (thread-scoped via thread history; app-scoped with a persistence adapter).
- Auto-generated update tools: based on the interactable's state schema, an
update_{name}tool is generated for the model to update and edit it.
Use Cases
- Settings panels or dashboards the agent can edit and interact with
- Collaborative task lists, sticky notes, document editors
- Making artifacts editable and versioned
- Anything else, any React component can be an interactable!
Quick Start
Register the interactables scope
import {
useAui,
unstable_Interactables,
AssistantRuntimeProvider,
Tools,
} from "@assistant-ui/react";
import { useChatRuntime } from "@assistant-ui/react-ai-sdk";
function MyRuntimeProvider({ children }: { children: React.ReactNode }) {
const runtime = useChatRuntime();
const aui = useAui({
unstable_interactables: unstable_Interactables(),
});
return (
<AssistantRuntimeProvider aui={aui} runtime={runtime}>
{children}
</AssistantRuntimeProvider>
);
}The legacy interactables: Interactables() scope and the new
unstable_interactables: unstable_Interactables() scope are mutually
exclusive. Mount only one interactables API in a single useAui provider.
This scope is needed for both kinds of interactable. Thread-scoped interactables also live in a toolkit, which you register with Tools (shown below).
Define an interactable
Pick the path that matches who creates it.
A component you mount yourself. Define it with unstable_useInteractable where you render it (a sidebar, a panel, wherever).
import { unstable_useInteractable } from "@assistant-ui/react";
import { z } from "zod";
const taskBoardSchema = z.object({
tasks: z.array(
z.object({ id: z.string(), title: z.string(), done: z.boolean() }),
),
});
function TaskBoard() {
const [state, { setState }] = unstable_useInteractable("taskBoard", {
description:
"A task board panel that lists tasks. Use update_taskBoard with tasks.add/update/remove/clear to manage tasks. New tasks need a title and done=false.",
stateSchema: taskBoardSchema,
initialState: { tasks: [] },
});
return (
<ul>
{state.tasks.map((task) => (
<li key={task.id}>
<input
type="checkbox"
checked={task.done}
onChange={() =>
setState((prev) => ({
tasks: prev.tasks.map((t) =>
t.id === task.id ? { ...t, done: !t.done } : t,
),
}))
}
/>
{task.title}
</li>
))}
</ul>
);
}That's all you need, update_taskBoard is generated automatically from your stateSchema once the TaskBoard component is mounted in your app.
App-scoped state is shared across every thread and can be persisted by defining a persistence adapter.
An interactable tool UI the model can call in-thread. Define it with unstable_interactableTool inside defineToolkit; it renders inline when the model calls it, and its update_{name} tool is generated automatically from your stateSchema once the tool is called by the model.
"use generative";
import { defineToolkit, unstable_interactableTool } from "@assistant-ui/react";
import { z } from "zod";
const notepadSchema = z.object({
title: z.string(),
content: z.string(),
});
const toolkit = defineToolkit({
notepad: unstable_interactableTool({
description: "A notepad with drafted text the user can read and edit.",
stateSchema: notepadSchema,
render: ({ state, setState, version, streaming }) => (
<Notepad
value={state}
onChange={setState}
busy={streaming}
readOnly={version ? !version.isLatest : false}
/>
),
}),
});Register the toolkit alongside the unstable_Interactables scope:
const aui = useAui({
unstable_interactables: unstable_Interactables(),
tools: Tools({ toolkit }),
});Thread-scoped state rides the thread's history, so it survives reloads with
nothing extra to persist. render is run when the interactable is created,
and whenever it's updated (via update_{name}).
Surface state to the model in your route
Each user message carries its state snapshots in its metadata, but the AI SDK's convertToModelMessages ignores metadata. Use unstable_injectInteractableContext to pass interactable state to the model:
import { openai } from "@ai-sdk/openai";
import { convertToModelMessages, streamText } from "ai";
import { unstable_injectInteractableContext as injectInteractableContext } from "@assistant-ui/react-ai-sdk";
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai("gpt-5.4"),
messages: await convertToModelMessages(injectInteractableContext(messages)),
});
return result.toUIMessageStreamResponse();
}The format of the snapshot sent to the model can be customized, see State snapshots for more details.
Each user message carries its state snapshots at metadata.custom.interactables. For other backends (LangGraph, Mastra, a custom runtime), build the equivalent injection with the two helpers exported from @assistant-ui/react:
import {
unstable_getInteractableSnapshots, // (message) => snapshot entries | undefined
unstable_formatInteractableSnapshot, // (entry) => the model-facing formatting of the snapshot injection
} from "@assistant-ui/react";
for (const message of messages) {
if (message.role !== "user") continue;
const items = unstable_getInteractableSnapshots(message);
if (!items?.length) continue;
const text = items.map(unstable_formatInteractableSnapshot).join("\n");
// prepend `text` to the message content in whatever shape your backend expects
}For more details, and how to customize the snapshot format for other backends, see State snapshots.
State snapshots
Outgoing user messages can carry the interactable's state to the model as a snapshot, stamped when the state has changed since the model last saw it. When only some fields change, a partial snapshot is created containing a shallow diff of only the changed fields and the id.
Default full snapshot formatting:
`[Current state of "note" (id: "n1"): {"title":"Q3 launch","body":"Ship the beta by Friday."}]`;Default partial snapshot formatting:
`[State of "note" (id: "n1") changed — updated fields: {"title":"Q4 launch"}; fields not listed are unchanged]`;Customizing the format
A formatter receives one snapshot entry and returns the line the model sees:
nameandididentify the instance. Keep theidvisible so the model knows what the state belongs to.stateis the snapshot payload.partialistruewhenstatecarries a shallow diff of only the fields that changed since the model's last known state. Handle it.
Write a custom formatter:
import { type Unstable_InteractableSnapshotEntry } from "@assistant-ui/react";
const formatSnapshot = (entry: Unstable_InteractableSnapshotEntry) =>
entry.partial
? `State of "${entry.name}" (id: "${entry.id}") has been updated, the following fields have changed: ${JSON.stringify(entry.state)}`
: `Current state of "${entry.name}" (id: "${entry.id}"): ${JSON.stringify(entry.state)}`;When customizing format, remember to:
- Handle
partial: trueentries, whosestatecarries a shallow diff of only the fields that changed. - Keep each instance's
idvisible so the model knows what the state belongs to.
Then wire it to your backend:
- AI SDK: pass it as the second argument,
unstable_injectInteractableContext(messages, formatSnapshot). - Other backends: use it in place of
unstable_formatInteractableSnapshotin your helper (see Step 3's "Other Backends" tab).
messages: await convertToModelMessages(
unstable_injectInteractableContext(messages, formatSnapshot),
),Artifacts
An artifact combines two pieces that point at the same interactable:
- a thread tool (
unstable_interactableTool) the model calls to create the artifact inline (a button or small preview in the message), and - a panel you mount with
unstable_useInteractablethat opens that same instance at full size.
Both use the same id, so they are one interactable, not two: the model creates it in the conversation, and the panel is just a larger view of the very same state. Because the thread holds the creating call, the artifact is thread-scoped: it persists with the thread's history (no persistence adapter needed), and each message's trigger can open that message's version (see Versions).
in the thread (model-created) your layout (mounted once)
────────────────────────────── ──────────────────────────────
unstable_interactableTool("document") ArtifactPanel()
render: a button / inline preview unstable_useInteractable("document", { id })
onClick → openArtifact(id) ────┐ → live, editable, full height
│ │
└───── same id ────┘
one thread-scoped instanceconst toolkit = defineToolkit({
document: unstable_interactableTool({
description: "A document the user can open and edit.",
stateSchema: documentSchema,
render: ({ state, version, id }) => (
<ArtifactButton
title={(version?.state ?? state).title}
onClick={() => openArtifact(id)} // your own state: which artifact is open
/>
),
}),
});
function ArtifactPanel({ id }: { id: string }) {
const [state, { setState }] = unstable_useInteractable("document", {
id,
description: "A document the user can open and edit.",
stateSchema: documentSchema,
initialState: emptyDocument, // fallback only; existing state comes from the thread
});
const versions = unstable_useInteractableVersions<Document>(id, "document");
return (
<aside>
<VersionMenu>
{versions.map((v, i) => (
<DropdownItem key={i} onSelect={v.restore}>
v{i + 1}: {v.origin === "user-edit" ? "you" : "assistant"}
</DropdownItem>
))}
</VersionMenu>
<Editor value={state} onChange={setState} />
</aside>
);
}You don't mount anything per artifact: the model renders the inline part on its own, and openArtifact(id) is your own state setter for which artifact the panel currently shows. Outside message parts the hook always returns the live state (version is undefined), so the panel is plainly editable. The panel and the inline tool UIs register the same id, so they share one instance; registration is reference-counted, and the instance stays alive until the last one unmounts.
Keep one mount of the artifact on screen (hidden is fine) whenever its instance
should stay available. If the panel is closed and every inline button has
scrolled out of a virtualized thread, the instance and its update_{name} tool
unregister and the tool list churns. The state itself is safe, since it rides
thread history.
Companion tools
The generated update_{name} tool covers everything that lives in the state: editing fields, and adding, updating, removing, or clearing items in a list. Reach for a separate frontend tool only for what state can't express: a side effect like sending, exporting, or saving.
Take an email composer the user and assistant co-edit. update_email keeps the draft in sync from both sides, but actually sending it is a side effect that no amount of state editing can perform. That is what a companion tool is for: send_email acts on the current draft and fires it.
How you wire one depends on what its executor touches.
Closes over React state (here, the live draft): declare the contract with stubTool() in your "use generative" toolkit, and supply the executor with useAuiToolOverrides in the component that owns the state. See Dynamic Tools.
"use generative";
import { defineToolkit, stubTool } from "@assistant-ui/react";
import { z } from "zod";
export default defineToolkit({
send_email: {
description:
"Send the email currently shown in the composer. Call this only once the draft is ready.",
parameters: z.object({}),
execute: stubTool(),
renderText: { running: "Sending...", complete: "Email sent" },
},
});import {
unstable_useInteractable,
useAuiToolOverrides,
} from "@assistant-ui/react";
function EmailComposer() {
const [draft, { setState }] = unstable_useInteractable("email", {
description: "An email draft the user and assistant can read and edit.",
stateSchema: emailSchema,
initialState: { to: "", subject: "", body: "" },
});
return (
<>
<SendEmailTool draft={draft} />
{/* inputs bound to draft + setState */}
</>
);
}
// A null-returning child supplies the executor, closing over the live draft.
function SendEmailTool({ draft }: { draft: Email }) {
useAuiToolOverrides({
send_email: {
execute: async () => {
await fetch("/api/send-email", {
method: "POST",
body: JSON.stringify(draft),
});
return { success: true };
},
},
});
return null;
}The split is the whole point: update_email edits the draft, send_email does the thing the draft can't describe. The executor reads the live draft, so it always sends what is currently on screen.
Self-contained (needs nothing from React, only its args and browser APIs): put a real execute with an inner "use client" directly in the toolkit. A copy_share_link({ id }) that builds a URL and writes it to the clipboard is a good fit. See Defining Tools.
Custom Update Rendering
render draws the create call; updateRender draws each update_{name} call. unstable_interactableTool reuses your one render for both, so edits look like the creation. Supply your own updateRender to render edits differently.
To vary by this message's version, or render older messages differently from
the newest, you don't need updateRender. The render already receives
version; see Versions.
Render edits differently from the create
A thread tool locks the create and edit renders together. Drop to unstable_useInteractable to split them, here showing the full notepad on the create call and a one-line summary on every edit:
// Hoisted so its identity is stable; an inline updateRender re-registers the
// tool UI on every render.
const EditSummaryRender: ToolCallMessagePartComponent = ({ args }) => (
<EditSummary changed={args} />
);
const NotepadToolUI: ToolCallMessagePartComponent<NotepadArgs> = ({
toolCallId,
args,
result,
}) => {
if (!result) return <NotepadDraft args={args} />;
return <Notepad id={toolCallId} initial={args} />;
};
function Notepad({ id, initial }: { id: string; initial: NotepadArgs }) {
const [state, { setState }] = unstable_useInteractable("notepad", {
id,
description: "A notepad the user can read and edit.",
stateSchema: notepadSchema,
initialState: initial,
updateRender: EditSummaryRender,
});
return <NotepadEditor value={state} onChange={setState} />;
}
// NotepadToolUI is the create call's render; updateRender handles the edits.
const toolkit = defineToolkit({
notepad: {
type: "frontend",
description: "A notepad the user can read and edit.",
parameters: notepadSchema,
display: "standalone",
execute: async () => ({ success: true as const }),
render: NotepadToolUI,
},
});Pass the create call's toolCallId as the id: that one convention ties both renders to a single instance and restores its state from thread history after a reload.
Mark edits on an app-scoped surface
An app-scoped interactable lives in your layout (a sidebar, a panel), so it has no inline presence in the thread. Pass updateRender and each update_{name} call gains one: an inline marker of what the model just did, while the live component keeps updating in place.
const EditMarkerRender: ToolCallMessagePartComponent = ({ args }) => (
<EditMarker changed={args} />
);
function DocumentPanel() {
const [state, { setState }] = unstable_useInteractable("document", {
description: "A document the user can read and edit.",
stateSchema: documentSchema,
initialState: emptyDocument,
updateRender: EditMarkerRender,
});
return <Editor value={state} onChange={setState} />;
}Versions
A thread is an append-only log, so an instance accumulates versions: each user edit, each update_* call, and (thread-scoped only) the creating call. For thread-scoped interactables these are computed from the thread record, so history survives reloads with nothing extra to persist. There are two ways to reach them.
This message's version. Inside a thread-scoped render, state / setState are the live instance (there's exactly one, shared by every message), while version is this message's snapshot: { state, isLatest, restore }. version.state is the interactable as it was at that point in the conversation; restore() sets the live state back to it.
Those three fields are all you need, and two independent choices decide how history behaves:
- Editable or read-only? Render the live
state/setStateto let any message edit the shared instance, orversion.stateread-only to freeze it. - Restorable? Offer
version.restore()to roll an old version back to live, or leave it out.
| You want | Render |
|---|---|
| Frozen history | version.state read-only on old |
| Live-editable | state / setState everywhere |
| Read-only + rollback | version.state read-only plus restore |
// Read-only history with rollback:
// old messages are frozen but can roll their version back to live
render: ({ state, setState, version }) =>
version && !version.isLatest ? (
<Notepad value={version.state} readOnly onRestore={version.restore} />
) : (
<Notepad value={state} onChange={setState} />
);// Live-editable:
// every message edits the shared instance; restore reverts to this point
render: ({ state, setState, version }) => (
<Notepad value={state} onChange={setState} onRestore={version?.restore} />
);Every version at once. unstable_useInteractableVersions(id, name) returns them oldest-first, each with the full state and a restore(). Use it for a history dropdown; it works for both app- and thread-scoped interactables:
function VersionDropdown({ id, name }: { id: string; name: string }) {
const versions = unstable_useInteractableVersions(id, name);
if (versions.length < 2) return null;
return (
<select onChange={(e) => versions[+e.target.value]!.restore()}>
{versions.map((v, i) => (
<option key={i} value={i}>
v{i + 1}: {v.origin === "user-edit" ? "you" : "assistant"}
</option>
))}
</select>
);
}Thread-scoped:
const Notepad = ({
id,
state,
setState,
}: Unstable_InteractableToolRenderProps<NotepadArgs>) => (
<div>
<VersionDropdown id={id} name="notepad" />
{/* ...editor... */}
</div>
);App-scoped:
const [state, { id }] = unstable_useInteractable("taskBoard", config);
return <VersionDropdown id={id} name="taskBoard" />;An app-scoped item's history covers the current conversation, not its full cross-thread lifetime.
Persistence
By default, app-scoped interactable state is in-memory and lost on page refresh. You can add persistence by passing an adapter to unstable_Interactables:
import { useAui, unstable_Interactables } from "@assistant-ui/react";
// Module-level (or memoized) so the adapter identity is stable across renders.
const persistenceAdapter = {
load: () => {
const saved = localStorage.getItem("interactables");
return saved ? JSON.parse(saved) : undefined;
},
save: (state) => {
localStorage.setItem("interactables", JSON.stringify(state));
},
};
function MyRuntimeProvider({ children }) {
const aui = useAui({
unstable_interactables: unstable_Interactables({
persistence: persistenceAdapter,
}),
});
return /* ... */;
}load is called when the adapter is attached and may be async. Loaded state seeds interactables as they register; a local edit made while a slow load is still in flight wins over the loaded value. Thread-scoped interactables are not touched by the adapter; they persist via thread history.
For dynamic setups (an adapter that depends on auth), call aui.interactables().setPersistenceAdapter(adapter) imperatively instead.
Sync Status
When a persistence adapter is set, interactable hooks expose sync metadata:
const [state, { setState, isPending, error, flush }] =
unstable_useInteractableState<TState>(id);
// isPending: true while a save is in-flight
// error: the error from the last failed save, if any
// flush(): force an immediate save (useful before navigation)State changes are automatically debounced (500ms) before saving. When the owning component unmounts, any pending save is flushed immediately.
Export / Import
For custom persistence strategies, use exportState and importState directly:
const snapshot = aui.interactables().exportState();
// => { "note-1": { name: "note", state: { title: "Hello" } }, ... }
aui.interactables().importState(snapshot);
// Imported state is picked up when components next registerSchema Evolution
If you change a Zod schema after state has been persisted, the loaded snapshot
may silently mis-match the new shape. The adapter does a shallow merge, so
extra fields are preserved and missing fields keep their initial values, but
type mismatches are not caught at runtime. To avoid silent corruption, version
your schema key (e.g. "taskBoard_v2") or namespace it by schema hash
whenever you make breaking changes. Alternatively, add a migration step in
your load or importState call.
Streaming Updates
The same partial merge runs token by token as the model generates an update_{name} call, so the interactable fills in live: a field the model is writing updates character by character, and only the fields and array items the call touches change. Everything it doesn't mention stays exactly as it was.
That stability is concrete, not just visual. While one array item streams in, the items the model isn't editing keep their exact object identity for the whole stream, so a memoized row for them never re-renders:
import { memo } from "react";
const TaskRow = memo(function TaskRow({ task }: { task: Task }) {
return <li>{task.title}</li>;
});
function TaskBoard() {
const [state] = unstable_useInteractable("taskBoard", config);
return (
<ul>
{state.tasks.map((task) => (
<TaskRow key={task.id} task={task} />
))}
</ul>
);
}As update_taskBoard streams an edit to one task, that row re-renders as its fields arrive while every other TaskRow stays put, no flicker and no work. You get a live-updating list for free; you only reach for the partial state when you want to show something extra during the stream.
One case worth handling: at the very start of a fresh create the model may not have produced any items yet. Use the thread's isRunning to tell "still streaming, nothing yet" apart from "the model returned an empty result", and show a skeleton only for that gap:
import { useAuiState } from "@assistant-ui/react";
const isRunning = useAuiState((s) => s.thread.isRunning);
const isLoading = isRunning && state.tasks.length === 0;Inside a thread-scoped render, streaming: true carries the same live state: at the creating call state is the partial draft (fields may be missing); at an update_{name} call it's the live state filling in as the edit streams. Render a preview; edits made during a create stream are dropped.
Multiple Instances
A name can have many live instances at once. They all share one update_{name} tool: the model addresses an instance with the tool's id parameter, which it reads from the state snapshots in the conversation. The tool's name, schema, and description never change as instances mount and unmount, so the model's tool list (and provider prompt caches) stay stable. While exactly one instance exists, the model may omit id; a call with an unknown id returns an error listing the valid ids, so the model can recover.
How instances come into being differs by scope.
Thread-scoped: instances for free
A thread-scoped interactable gets a fresh instance every time the model calls its tool. The instance id is the creating call's toolCallId, so two calls are two instances with no extra code on your side: the same render and the same update_{name} tool serve all of them. This is how a model spins up several artifacts or notepads in one conversation, each addressed by its own toolCallId.
App-scoped: one instance per mount
For app-scoped interactables you decide how many instances exist by mounting unstable_useInteractable in more than one place, one instance per mount. Give each mount a distinct id:
import { unstable_useInteractable } from "@assistant-ui/react";
import { z } from "zod";
const noteSchema = z.object({
title: z.string(),
content: z.string(),
color: z.enum(["yellow", "blue", "green", "pink"]),
});
const noteInitialState = {
title: "New Note",
content: "",
color: "yellow" as const,
};
function NoteCard({ noteId }: { noteId: string }) {
const [state] = unstable_useInteractable("note", {
id: noteId,
description: "A sticky note",
stateSchema: noteSchema,
initialState: noteInitialState,
});
return <div>{state.title}</div>;
}
function App() {
return (
<>
<NoteCard noteId="note-1" />
<NoteCard noteId="note-2" />
{/* one update_note tool: update_note({ id: "note-2", color: "blue" }) */}
</>
);
}Pass an explicit id whenever you need to reach a specific instance: to read or write it from another component with unstable_useInteractableState(id), to share it between an artifact panel and its inline trigger, or to keep persisted state attached across reloads. Omitting id also works, and each mount then gets its own auto-generated id, but those ids are positional and shift as a dynamic list adds and removes items, so persisted state keyed by an old id would not reattach. Leave id off only when the component is the sole reader and its state is not persisted.
A top-level id field in your stateSchema is reserved: the update tool uses
it for instance addressing, so the model cannot write a state field named
id. Nest it or name it differently (e.g. noteId).
update_note edits a note that is already mounted: its title, content, color, and any other schema fields. It cannot mount a new NoteCard or unmount one; which components exist is your app's state. If you want the model to add and remove notes, model them as a single interactable holding an array (one notes field), and update_notes then adds, updates, removes, and clears entries directly, the way the Quick Start task board does. Use separate mounted instances only when each note is genuinely its own component; mounting and unmounting those is app work you can expose as a companion tool.
Partial Updates
Auto-generated tools use a partial schema in which all fields are optional. The AI only sends the fields it wants to change; omitted fields keep their current values.
// If the state is { title: "My Note", content: "Hello", color: "yellow" }
// The AI can call: update_note({ color: "blue" })
// Result: { title: "My Note", content: "Hello", color: "blue" }This is especially useful for large state objects where regenerating the entire state would be expensive and error-prone.
For array fields whose items carry an id, the AI doesn't send a replacement array, it sends operations (add, update, remove, clear) and the framework applies them to the current list. Added items get their id from the framework; existing items are addressed by the id you gave them.
Merge is shallow (one level deep). If the AI sends a nested object, it replaces that entire field rather than deep-merging into it.
How It Works
- Register: the interactable joins the
interactablesscope with its name, description, schema, and initial state. - Generate the tool: one
update_{name}tool per name, with a partial schema (every field optional) plus a requiredid. The tool list stays stable as instances mount and unmount, so provider prompt caches stay warm. - Snapshot: each sent user message carries the current state in
metadata.custom, but only when the model doesn't already know it. A user edit stamps a snapshot; the model's ownupdate_*calls and an in-message instance's create args don't. When the change fits a shallow merge it stamps only the changed fields (partial: true). Your route turns snapshots into model-visible text (see State snapshots). - Stream: state updates field-by-field as the model generates the tool arguments, so the UI fills in live.
- Merge: only the fields the model sends are applied; the rest stay. Array fields keyed by
idtake operations (add/update/remove/clear) instead of a replacement array, and the framework mints ids for added items. - Both directions: a model
update_*updates state and re-renders; a usersetStaterides the next message as a fresh snapshot.
Unmount Behavior
When a component that called unstable_useInteractable unmounts, the interactable is unregistered, but its state is preserved in the unstable_Interactables scope. When the component mounts again with the same name and id, the scope restores the preserved state rather than resetting to initialState. This means transient unmounts (such as React Strict Mode double-mounts or tab switches) do not lose state.
An instance registered from several places (its creating tool call, update_* calls, an artifact panel) stays registered until the last one unmounts, so scrolling one out of a virtualized thread doesn't tear the instance down while another is visible.
API Reference
unstable_useInteractable
Registers an interactable with the AI assistant and returns its state. It behaves like useState, except the model can also read and update the value. Call it once per instance.
const [state, { id, setState, isPending, error, flush }] =
unstable_useInteractable(name, config);Parameters:
Prop
Type
Returns: [state, methods]
Prop
Type
Selection is not a built-in field. To tell the AI which interactable is
focused, add a selection field such as selectedId to your own state; see
Selection.
unstable_useInteractableState
Reads and writes the state of an interactable registered elsewhere, by id. Use this from secondary readers (children, siblings of the owning component).
const [state, { setState, isPending, error, flush }] =
unstable_useInteractableState<TState>(id);Parameters:
Prop
Type
Returns: [state, methods], the same shape as unstable_useInteractable without id. state is TState | undefined until the owning unstable_useInteractable has registered.
unstable_interactableTool
notepad: unstable_interactableTool({ description, stateSchema, render }),Returns a complete toolkit tool entry (a frontend tool with standalone display); the entry key is the interactable name, and the tool's arguments are its initial state. The same render then appears at every message that creates or updates the instance. render receives:
Prop
Type
unstable_useInteractableVersions
const versions = unstable_useInteractableVersions<TState>(id, name);
// → [{ state, origin: "create" | "update" | "user-edit", toolCallId?, restore }, ...]Every version of an interactable recorded in the current thread, oldest first. Each entry carries the full state and a restore() that sets the live instance back to it. Works for both scopes; see Versions for usage. The non-React equivalent for backends is unstable_getInteractableVersions(messages, id, name), exported from @assistant-ui/react.
unstable_Interactables
The scope resource that manages all interactables. Register it via useAui, optionally with a persistence adapter:
const aui = useAui({
unstable_interactables: unstable_Interactables({ persistence: myAdapter }),
});Migrating from the Previous API
If you used an earlier version of the interactables API:
useAssistantInteractableanduseInteractableStatehave been merged into a singleunstable_useInteractablehook that registers and returns state.unstable_useInteractableStateremains for secondary readers.- Per-instance tools (
update_note_note-1) are gone. Each name has one stableupdate_{name}tool with a requiredidparameter. - The top-level
selectedprop andsetSelectedmethod have been removed. Represent selection as ordinary state; see Selection.
Full Example
See the complete with-interactables example for a working implementation featuring:
- Task Board: one interactable whose
tasksarray the AI edits withupdate_taskBoard(add/update/remove/clear) - Sticky Notes: one
notesinteractable with aselectedIdfield, where the AI adds, edits, removes, and selects notes throughupdate_notes - localStorage persistence: state survives page refresh via a
load/savepersistence adapter - Sync indicator: spinning icon while a save is in-flight (
isPending)
Related
- Dynamic Tools: Frontend tools whose executors close over React state
- Tool UI: Inline tool call UIs rendered inside messages
- LangGraph Generative UI: Structured UI components emitted by a LangGraph graph alongside messages