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.
An interactable is a piece of component state that you and the model both read and write. You render it like any React state. The model edits it through an update_{name} tool that assistant-ui generates from your schema, and your own edits reach the model as a state snapshot on the next message you send.
No tasks yet.
Ask the assistant to add some!
Overview
An interactable is either app-scoped or thread-scoped, depending on who creates it.
| App-scoped | Thread-scoped | |
|---|---|---|
| Created by | You, by mounting unstable_useInteractable | The model, by calling a tool built with unstable_interactableTool |
| Renders | Wherever you mount it: a sidebar, a panel | Inline, at the creating tool call |
| Instance id | Your id option, or an auto-generated one | The creating call's toolCallId |
| Survives a reload | With a persistence adapter | When the thread's history is stored, for example by a cloud thread list |
| Typical use | Task board, settings panel, sticky notes | Notepad, email draft, artifact |
Both kinds share the same state model, update tool, snapshots and versions. The two can point at one instance, which is how an artifact works.
Warning
Every interactables export on this page carries the unstable_ prefix. The API is
experimental and may change in any release.
Quick start
Register the interactables scope
Add unstable_Interactables() to your provider's config. The runtime also has to send the conversation on after the model edits an interactable: the update tool runs in the browser, and useChatRuntime otherwise stops at the tool call. Set sendAutomaticallyWhen; see multi-step tool calls.
import {
AssistantRuntimeProvider,
AuiConfig,
unstable_Interactables,
} from "@assistant-ui/react";
import { useChatRuntime } from "@assistant-ui/ai-sdk";
import { lastAssistantMessageIsCompleteWithToolCalls } from "ai";
function MyRuntimeProvider({ children }: { children: React.ReactNode }) {
const runtime = useChatRuntime({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
});
const config = AuiConfig({
unstable_interactables: unstable_Interactables(),
});
return (
<AssistantRuntimeProvider runtime={runtime} config={config}>
{children}
</AssistantRuntimeProvider>
);
}Both kinds of interactable need this scope.
Define an interactable
Call unstable_useInteractable in the component that renders the state. It returns [state, methods], like useState:
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>
);
}While TaskBoard is mounted, the model has an update_taskBoard tool. App-scoped state is shared across threads and in memory only until you add persistence.
Define a tool with unstable_interactableTool in a toolkit. The model calls it to create an instance, and its render draws that instance inline. The toolkit key is the tool's name and the interactable's name; the tool's arguments are the initial state.
"use generative";
import { defineToolkit, unstable_interactableTool } from "@assistant-ui/react";
import { z } from "zod";
import { Notepad } from "./notepad";
export default defineToolkit({
notepad: unstable_interactableTool({
description: "A notepad with drafted text the user can read and edit.",
stateSchema: z.object({ title: z.string(), content: z.string() }),
render: ({ state, setState, version, streaming }) => (
<Notepad
value={state}
onChange={setState}
busy={streaming}
readOnly={version ? !version.isLatest : false}
/>
),
}),
});Register the toolkit with Tools next to the interactables scope, as in Defining Tools:
AuiConfig({
unstable_interactables: unstable_Interactables(),
tools: Tools({ toolkit }),
});The "use generative" directive needs the build plugin; see Defining Tools. Without the directive, define the toolkit in a plain client module and the same entry works unchanged. Inside a "use generative" file the argument must be an inline object literal, and unstable_interactableTool must be imported from an assistant-ui package, or the compiler rejects the entry.
To name the creating tool apart from the interactable, pass name: create_notepad: unstable_interactableTool({ name: "notepad", ... }) gives the model create_notepad and update_notepad, with versions kept under notepad.
Send the tools and state to the model
The update_{name} tool lives in the model context, so your route has to receive it, and the state snapshots your edits produce have to be turned into text the model reads.
The client uploads the update tool in the request body's tools. Convert it with frontendTools, and add snapshots with unstable_injectInteractableContext, because convertToModelMessages ignores message metadata:
import { openai } from "@ai-sdk/openai";
import { convertToModelMessages, streamText } from "ai";
import {
frontendTools,
unstable_injectInteractableContext as injectInteractableContext,
} from "@assistant-ui/ai-sdk";
export async function POST(req: Request) {
const { messages, tools } = await req.json();
const aiSDKTools = frontendTools(tools ?? {});
const result = streamText({
abortSignal: req.signal,
model: openai("gpt-6-luna"),
messages: await convertToModelMessages(injectInteractableContext(messages), {
tools: aiSDKTools,
}),
tools: aiSDKTools,
});
return result.toUIMessageStreamResponse();
}If the route already imports a toolkit through AISDKToolkit, pass the uploaded tools to it instead: aiToolkit.tools({ frontend: tools }). See Backend tools for what the route does with the body and why to treat it as untrusted.
Each user message carries its snapshots at metadata.custom.interactables. Read them with the two helpers exported from @assistant-ui/react, and prepend the text to the message in whatever shape your backend takes:
import {
unstable_getInteractableSnapshots,
unstable_formatInteractableSnapshot,
} 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
}Your runtime must also upload the model context's tools. LangGraph, Google ADK, LangChain and A2A do not read them, so the update tool never reaches the model there; see Other runtimes.
Concepts
State and schema
stateSchema describes the state. It accepts a schema that converts to JSON Schema (Zod, or another Standard Schema library with a JSON Schema converter) or a plain JSON Schema object. The type of state is inferred from a Standard Schema, and is unknown for plain JSON Schema. Keep these rules in mind:
- Use an object at the root. The update tool's schema is derived from the root object's properties. A non-object root falls back to a tool that accepts arbitrary fields with no validation.
- Keep the state JSON-serializable. Snapshots compare state by value. An
undefined,NaN, function or symbol makes every send look like a change; development builds warn about it. - Do not name a top-level field
id. The update tool usesidto address an instance, so the model cannot write a state field with that name. Nest it or call it something else, such asnoteId. descriptionis model-facing. It is appended to the update tool's description. Say how to use the tool, for example which array operations to use and what a new item needs.
setState takes a value or an updater function, like useState. Updates replace the state you pass, so spread prev when you only change part of it.
Instance ids
Every instance has an id. The model uses it to say which instance it edits, and snapshots show it next to the state. A name can have many live instances that share one update_{name} tool, so the tool's name and schema stay stable as instances mount and unmount and provider prompt caches stay warm.
- Thread-scoped: the id is the creating call's
toolCallId. Two calls are two instances with no extra code. - App-scoped: one instance per mounted
unstable_useInteractable. Pass an explicitidwhenever you need to reach the instance from elsewhere, or keep persisted state attached across reloads. Withoutid, each mount gets an auto-generated one that depends on its position in the tree, so persisted state under an old id no longer reattaches after the layout changes.
function NoteCard({ noteId }: { noteId: string }) {
const [state] = unstable_useInteractable("note", {
id: noteId,
description: "A sticky note",
stateSchema: noteSchema,
initialState: { title: "New note", content: "", color: "yellow" },
});
return <div>{state.title}</div>;
}
// update_note({ id: "note-2", color: "blue" }) edits the second card
<>
<NoteCard noteId="note-1" />
<NoteCard noteId="note-2" />
</>Register each app-scoped instance once. To read or write it from another component, pass its id to unstable_useInteractableState(id); a second unstable_useInteractable with the same id logs a development warning.
The update tool edits an instance that is mounted. It cannot mount or unmount a NoteCard, because which components exist is your app's state. If the model should add and remove notes, model them as one interactable that holds an array, as the Quick start task board does. Use separate instances only when each one is its own component, and expose mounting as a companion tool.
Selection and focus
There is no built-in selection. To tell the model which instance or item is focused, add a field such as selectedId to your state. The user's click is a normal setState, and the model changes focus by editing the same field. The example does this for its sticky notes.
Lifecycle
- An instance registers when its component mounts and unregisters when it unmounts. While none of a name's instances are registered, the model has no
update_{name}tool. - Unregistering keeps the state in the scope. Remounting with the same name and id restores it instead of
initialState, so a Strict Mode double mount or a tab switch loses nothing. A thread-scoped instance is remembered per thread. - A thread-scoped instance restores from the thread record after a reload, so an edit you made but have not sent yet is lost.
- Registration is reference-counted. An instance registered from several places (its creating call, its
update_*calls, an artifact panel) stays alive until the last one unmounts. - Mount an interactable where it stays mounted. A panel the user can close removes the tool from the model; keep a hidden mount if the model should keep access.
- Changing
description,stateSchemaorupdateRenderre-registers the instance. Pass stable references for the last two.
How the model sees an interactable
The update tool
The scope contributes one update_{name} frontend tool per distinct name to the model context. It does not go through Tools(); a thread-scoped creating tool does, because it is a normal toolkit entry. The tool runs in the browser, so it follows the frontend-tool rules in Defining Tools.
- Name.
update_plus the interactable name, with characters outsidea-z,A-Z,0-9,_and-replaced by_. Two names that sanitize to the same tool name collide, and the second is ignored with a development warning. - Arguments.
idis required. Every other top-level field of your schema is optional, and the model sends only the fields it changes. A nested object replaces the existing one, so the schema keeps its required fields and the model sends it complete. Omitted fields keep their current values. - Arrays take operations instead of a replacement array. An array field becomes an object with
add,removeandclear, plusupdatewhen the item schema has anidproperty. For such id-keyed arrays, the framework assigns ids to added items (the model does not send them),removetakes ids, andupdatetakes{ id, ...changedFields }. For other arrays,removetakes item values. Operations apply in the order clear, remove, update, add. - Result.
{ success: true, id }with the resolved instance id, plusaddedItemIdswhen the call added items to an id-keyed array. An unknownidreturns{ success: false, error }listing the valid ids so the model can retry. A call withoutidis accepted only while exactly one instance of the name exists.
// State: { title: "My Note", content: "Hello", color: "yellow" }
// update_note({ id: "note-1", color: "blue" })
// State: { title: "My Note", content: "Hello", color: "blue" }
// State: { tasks: [{ id: "a1", title: "Buy milk", done: false }] }
// update_taskBoard({ id: "board", tasks: { update: [{ id: "a1", done: true }], add: [{ title: "Pay rent", done: false }] } })State snapshots
The model learns about your edits through snapshots. When you send a message, assistant-ui stamps it with the current state of every mounted instance the model does not already know:
- The first send after an instance mounts carries a full snapshot.
- After that, a snapshot appears only when the state differs from what the model last saw: the creating call's arguments, an earlier snapshot, or the model's own
update_*calls. The model's own edits never produce a snapshot. - When the change fits a shallow merge, the snapshot is partial: it carries the instance id and only the top-level fields that changed.
Snapshots live on user messages at metadata.custom.interactables. Your route turns them into text; the AI SDK helper prepends one text part per message. Because only user messages are stamped, an edit you make reaches the model with your next message and not before.
Default formatting for a full and a partial snapshot:
`[Current state of "note" (id: "n1"): {"title":"Q3 launch","body":"Ship the beta by Friday."}]`;
`[State of "note" (id: "n1") changed — updated fields: {"title":"Q4 launch"}; fields not listed are unchanged]`;Customizing the format
A formatter receives one entry and returns the line the model sees. name and id identify the instance, so keep the id visible: the model needs it to address the update tool. state is the snapshot payload, and partial is true when state is only the changed fields, so handle it.
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)}`;On the AI SDK, pass it as the second argument: unstable_injectInteractableContext(messages, formatSnapshot). On other backends, use it in place of unstable_formatInteractableSnapshot in the loop from the Quick start.
Streaming updates
The same merge runs token by token while the model writes an update_{name} call, so the interactable fills in live. Only the fields and array items the call touches change, and a nested object keeps its previous fields until the model closes it. Items the model is not editing keep their object identity for the whole stream, so a memoized row does not re-render:
const TaskRow = memo(function TaskRow({ task }: { task: Task }) {
return <li>{task.title}</li>;
});At the start of a create call the model may not have produced any items yet. Use the thread's isRunning to tell "still streaming" from "the model returned an empty result", and show a skeleton only for that gap:
const isRunning = useAuiState((s) => s.thread.isRunning);
const isLoading = isRunning && (state.tasks?.length ?? 0) === 0;Inside a thread-scoped render, streaming: true carries the same live state. At the creating call, state is the partial draft and fields may be missing; at an update call, it is the live state filling in as the edit streams. Render a preview: setState does nothing during a create stream.
Companion tools
update_{name} covers everything that lives in the state. Add a separate frontend tool only for what state cannot express, such as sending, exporting or saving.
Take an email composer that you and the model co-edit. update_email keeps the draft in sync from both sides, but sending it is a side effect. A send_email tool covers it. Because its executor reads the live draft, declare the contract with stubTool() and supply the executor with useAuiToolOverrides from the component that owns the state; Dynamic Tools walks through the pattern.
"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;
}Register the toolkit with Tools({ toolkit }). A stub is a compiled frontend tool, so the client does not upload its schema, and your route must import the toolkit through AISDKToolkit for the model to see send_email. The update_email tool, by contrast, is uploaded; see Backend tools. For a self-contained companion that needs only its arguments and browser APIs, such as copy_share_link({ id }), put a real execute with an inner "use client" in the toolkit; see frontend tools.
Persistence
App-scoped state is in memory and lost on reload. Pass an adapter to unstable_Interactables to keep it. Thread-scoped instances never use the adapter; they persist through the thread's history, so they survive a reload only when that history is stored.
// Module-level (or memoized): a new adapter object is a new persistence scope.
const persistenceAdapter = {
load: () => {
const saved = localStorage.getItem("interactables");
return saved ? JSON.parse(saved) : undefined;
},
save: (state) => {
localStorage.setItem("interactables", JSON.stringify(state));
},
};
AuiConfig({
unstable_interactables: unstable_Interactables({
persistence: persistenceAdapter,
}),
});save(state)receives the whole app-scoped snapshot, keyed by instance id as{ [id]: { name, state } }. It includes mounted instances, instances that were loaded but never mounted, and ones whose component has since unmounted. It never includes thread-scoped ones.load()is optional and may be async. It runs when the adapter attaches, and loaded state seeds instances as they register. A local edit made while a slowloadis in flight wins over the loaded value.- An instance still on its
initialStateis left out of the snapshot until it is edited, imported or loaded. A changedinitialStatetherefore reaches users who never edited it. A default that an earlier snapshot already stored stays in storage, because a stored default cannot be told apart from an edit. - Persisted state is keyed by instance id, so give a persisted instance an explicit
id.
For an adapter that depends on auth, call aui.unstable_interactables.setPersistenceAdapter(adapter) instead. Replacing an adapter resets app-scoped instances to initialState before loading from the new one, including when the change passes through undefined. Removing an adapter flushes queued changes and keeps local state, and reattaching the same adapter continues that scope. Keep the adapter memoized unless an account or workspace change should deliberately reset the scope; a changed identity logs a development warning.
Sync status
With an adapter set, unstable_useInteractable and unstable_useInteractableState return sync metadata:
const [state, { setState, isPending, error, flush }] =
unstable_useInteractableState<TState>(id);isPending is true while a save is queued or in flight, and error holds the last failed load or save. flush() saves immediately, skipping the 500 ms debounce, and retries a failed load or save. It flushes every instance, not only this one, so call it before navigation.
- Unmounting the owning component flushes a pending save once the scope has loaded. If the load is still pending or has failed, the state stays in memory and joins the next snapshot after a successful load.
- A failed load keeps queued changes. The next edit retries the load after the debounce, and
flush()retries it immediately. If a load is pending,flush()waits up to 5 seconds for it, then resolves without saving. - A failed save stays queued and is not retried in the background. It is sent again with the next save, which an edit to any instance or
flush()triggers. Every save sends the full snapshot, soerrorclears once a later save succeeds without a newer edit to that instance. A newer edit supersedes the failed value, and replacing the adapter drops it.
Export and import
For custom persistence, use exportState and importState directly:
const snapshot = aui.unstable_interactables.exportState();
// => { "note-1": { name: "note", state: { title: "Hello" } }, ... }
aui.unstable_interactables.importState(snapshot);exportState returns the edited, imported or loaded instances that are mounted right now, so it is a subset of what save receives. importState applies to mounted instances immediately and seeds ones that register later.
Changing the schema
Warning
Loaded state replaces initialState as a whole and is not validated. After
you change a schema, old snapshots can lack new fields or carry the wrong
types, and nothing fails at runtime. Because state is keyed by instance id,
give the instance a new id (for example "taskBoard-v2") when the change is
breaking, or migrate inside load or before importState.
Advanced
Versions
A thread is an append-only log, so an instance accumulates versions: its creating call (thread-scoped only), each of your edits that was sent as a snapshot, and each update_* call. They are computed from the thread record, so history needs no persistence of its own and survives a reload whenever the thread does. Your edits enter history when the next message is sent, not as you make them.
This message's version. Inside a thread-scoped render, state and setState are the live instance, shared by every message. version is this message's snapshot, { state, isLatest, restore }: version.state is the interactable as it was at that point in the conversation, and restore() sets the live state back to it. version is undefined while streaming, and outside tool-call parts.
Two independent choices decide how history behaves. Render version.state read-only to freeze an old message, or the live state and setState to let any message edit. Offer version.restore() to roll back, or leave it out.
| You want | Render |
|---|---|
| Frozen history | version.state, read-only, on old messages |
| Live-editable everywhere | state and setState |
| Read-only with rollback | version.state, read-only, plus version.restore |
// Read-only history with rollback: old messages are frozen but can restore
render: ({ state, setState, version }) =>
version && !version.isLatest ? (
<Notepad value={version.state} readOnly onRestore={version.restore} />
) : (
<Notepad value={state} onChange={setState} />
);Every version at once. unstable_useInteractableVersions(id, name) returns them oldest first, each with the full state, an origin of "create", "update" or "user-edit", and restore(). It works for both scopes and fits a history dropdown. An app-scoped instance's history covers the current conversation, not its lifetime across threads.
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>
);
}Get id from the render props in a thread-scoped render, or from unstable_useInteractable's methods for an app-scoped one, and pass the interactable's name. Backends can compute the same list with unstable_getInteractableVersions(messages, id, name).
Artifacts
An artifact is one interactable shown twice: a thread tool the model calls to create it inline (a button or preview in the message), and a panel you mount that opens the same instance at full size. Both use the same id, so they are one thread-scoped instance. The creating call lives in the thread, so the artifact persists with the thread, needs no persistence adapter, and each message's trigger can open that message's version.
const 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 <Editor value={state} onChange={setState} history={versions} />;
}You mount nothing per artifact. The model renders the inline part, and openArtifact(id) is your own state for which artifact the panel shows. Outside message parts version is undefined, so the panel edits the live state. The with-artifacts example is a complete version with a version menu and preview.
Warning
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.
Custom update rendering
unstable_interactableTool draws the create call and every update_{name} call with your one render, so edits look like the creation. To vary by message or version, use the version prop that render already receives; see Versions. Use updateRender when the edit should look different.
updateRender is a tool UI component for the update_{name} calls. It is installed once per name and requires a tools scope, which the runtime adds by default. Pass a stable reference, because a new identity re-registers the tool UI.
On an app-scoped surface. The interactable lives in your layout, so it has no inline presence in the thread. An updateRender gives each model edit an inline marker 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} />;
}On a thread-scoped tool. unstable_interactableTool has no updateRender option, so to render the create and the edits differently, define the creating tool by hand in a plain client module (not a "use generative" file, where an execute without "use client" would be a backend tool) and call unstable_useInteractable from its render. Pass the create call's toolCallId as id; that convention ties the create and edit renders to one instance and restores its state from thread history after a reload.
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, // hoisted, stable component
});
return <NotepadEditor value={state} onChange={setState} />;
}
export 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,
},
});API reference
Signatures and types are generated in the Interactables API reference. This section lists the options.
unstable_useInteractable
const [state, { id, setState, version, isPending, error, flush }] =
unstable_useInteractable(name, config);Registers an instance and returns its live state. Call it once per instance. name determines the update_{name} tool. Inside an update_{name} tool-call part, the instance id is inferred from the call, so one component works at the creating call and at update calls.
config:
| Option | Type | Description |
|---|---|---|
description | string | Required. Shown to the model; see State and schema. |
stateSchema | Standard Schema or JSON Schema | Required. The state's schema, for example a Zod object. |
initialState | inferred from stateSchema | Required. Used until saved, loaded or model-written state replaces it. |
id | string | Instance id. Auto-generated if omitted; see Instance ids. |
updateRender | ToolCallMessagePartComponent | Renders the update_{name} calls; see Custom update rendering. |
Returned methods:
| Field | Type | Description |
|---|---|---|
id | string | The instance id. Pass it to unstable_useInteractableState elsewhere. |
setState | (updater) => void | Like useState: takes a value or (prev) => next. |
version | { state, isLatest, restore } or undefined | This message's version inside a thread-scoped tool-call part. Otherwise undefined. See Versions. |
isPending | boolean | A persistence save is queued or in flight. |
error | unknown | Error from the last failed load or save. |
flush | () => Promise<void> | Save now, retrying a failed load or save. |
unstable_useInteractableState
const [state, { setState, isPending, error, flush }] =
unstable_useInteractableState<TState>(id);Reads and writes an instance registered elsewhere, by id. Use it in children and siblings of the owning component. It returns the same methods as unstable_useInteractable without id and version. state is undefined until the owner registers.
unstable_interactableTool
notepad: unstable_interactableTool({ description, stateSchema, render, name }),Returns a complete toolkit entry: a frontend tool with standalone display, whose arguments are the initial state. name sets the interactable's name apart from the creating tool's. render runs at the creating call and at every update call, with:
| Prop | Type | Description |
|---|---|---|
state | inferred from stateSchema | The live state. While streaming, fields the model has not finished may be missing. |
setState | (updater) => void | Updates the live state. |
version | { state, isLatest, restore } or undefined | This message's version. undefined while streaming. |
id | string | The instance id, which is the creating call's toolCallId. |
streaming | boolean | true while the call's arguments are still streaming. |
unstable_useInteractableVersions
const versions = unstable_useInteractableVersions<TState>(id, name);
// [{ state, origin: "create" | "update" | "user-edit", toolCallId?, restore }, ...]Every version recorded in the current thread, oldest first. See Versions.
unstable_Interactables
The scope resource that manages all interactables. Register it as unstable_interactables in your provider's config, optionally with a persistence adapter:
AuiConfig({
unstable_interactables: unstable_Interactables({ persistence: myAdapter }),
});Troubleshooting
| Symptom | Cause and fix |
|---|---|
The model never calls update_{name} | Your route does not forward the uploaded tools. Convert tools with frontendTools (or pass frontend: tools to AISDKToolkit.tools()). On LangGraph, Google ADK, LangChain and A2A the tool is never uploaded; see Other runtimes. Also check that a component with that name is mounted |
| The model edits the state and the chat then stops | Set sendAutomaticallyWhen on useChatRuntime |
| The model ignores or overwrites your edits | The route does not inject snapshots. Wrap messages in unstable_injectInteractableContext. A custom formatter must keep the id and handle partial entries |
Unknown id "x" for interactable "note". Valid ids: ... | The model addressed an instance that is not mounted or never existed. Keep the id in snapshots, and keep the instance mounted |
| The tool disappears when a panel closes | The last instance of that name unmounted. Keep a hidden mount; see Lifecycle |
"note" (n1) is already registered (development) | Two unstable_useInteractable calls share an id. Register once and read elsewhere with unstable_useInteractableState |
a top-level "id" field in an interactable's stateSchema is reserved (development) | Rename the state field |
Failed to convert the state schema of "x" to JSON Schema | The schema cannot be converted, so the update tool accepts arbitrary fields with no validation. Use a schema library that exposes a JSON Schema converter, or pass a JSON Schema object |
state for "note" (n1) is not JSON-equatable (development) | The state holds undefined, NaN, functions or symbols, so it is re-sent on every message. Use plain JSON values |
| State resets on reload | An app-scoped instance needs a persistence adapter and a stable explicit id |
The persistence adapter identity changed, so app-scoped state was reset | The adapter object is recreated each render. Define it at module level or memoize it |
supplied an updateRender, but no tools scope is available yet | The runtime has no tools scope yet. It installs the tool UI once one appears; if it never does, check the provider's config |
The compiler rejects an unstable_interactableTool entry | In a "use generative" file, pass an inline object literal and import the function from an assistant-ui package |
Migrating from the previous API
The earlier API is deprecated but still exported: the Interactables() scope with useAssistantInteractable and useInteractableState. See its API reference. Use the current API for new code, and when you migrate:
- Replace
interactables: Interactables()withunstable_interactables: unstable_Interactables(), andaui.interactableswithaui.unstable_interactables. Mount only one of the two scopes in a provider config, because both generateupdate_{name}tools. useAssistantInteractableanduseInteractableStatemerge into oneunstable_useInteractablehook that registers and returns state.unstable_useInteractableStateremains for secondary readers.- The old scope put each interactable's current state into the model's system prompt. The new one sends snapshots on user messages, so add
unstable_injectInteractableContextto your route. - Per-instance tools (
update_note_note-1) are gone. Each name has oneupdate_{name}tool with a requiredidparameter. - The
selectedprop andsetSelectedare removed. Represent selection as ordinary state, such as aselectedIdfield.
Full example
The with-interactables example is a working app-scoped implementation:
- Task board: one interactable whose
tasksarray the model edits withupdate_taskBoard(add, update, remove, clear) - Sticky notes: one
notesinteractable with aselectedIdfield, where the model adds, edits, removes and selects notes throughupdate_notes - localStorage persistence: state survives a refresh through a
loadandsaveadapter - Sync indicator: a spinner while a save is in flight (
isPending)
For the thread-scoped and artifact path, see with-artifacts.
Related
- Dynamic Tools: Frontend tools whose executors close over React state
- Tool UI: Inline tool call UIs rendered inside messages
- Backend tools: How tool schemas reach the model, and
sendAutomaticallyWhen - LangGraph Generative UI: Structured UI components emitted by a LangGraph graph alongside messages