Skip to content
Talk to an engineer

Agentic UI

Canvas actions

A canvas action opens its result in a large panel beside the agent, where the user and the agent work on the same content over several turns: a document they write together, a report, a plan, a form.

An action becomes a canvas action when its handler has renderCanvas instead of render or renderComponent. execute still runs, and what it returns is the canvas’s first state. The agent sees that state with every message and edits it; your component draws it and shares the user’s edits back.

Chat card (renderComponent)Canvas (renderCanvas)
Where it showsIn the conversationIn a large panel beside the agent
Use it forA one-off result, a confirmation, a single choiceLong or wide content the user refines with the agent: articles, emails, plans, reports, multi-field forms
The agent waitsUntil the card calls callback, cancel, or readyStateNo. It is told once that the canvas is shown.
Later changesThe agent can’t change a card after it’s drawnThe agent edits the canvas state on later turns
Mobile and headless agentsSupportedNot supported: the action isn’t registered there

Pick a canvas when the user is expected to say things like “shorten the intro” or “switch to monthly billing” about the same content. Pick a chat card when the result fits in the chat or needs one answer.

sequenceDiagram
  participant U as User
  participant A as Agent
  participant E as execute(params)
  participant C as renderCanvas(ctx)
  U->>A: Natural-language request
  A->>E: Call execute
  E-->>C: Result becomes ctx.state
  C->>U: Canvas opens beside the agent
  U->>C: Edits content
  C->>C: setState(patch)
  U->>A: Next message (the agent sees the state)
  A->>C: update_application_state
  C->>C: onStateChange(listener)
  1. The agent calls the action and execute runs. Its result is the canvas’s first state. An object is used as is; anything else becomes { value: <result> }.
  2. The canvas opens beside the agent, and the chat gets a card for this call. The agent is told once that the canvas is shown.
  3. The user edits the content, and your component calls setState. The agent sees the new state with the user’s next message. In a voice conversation it gets it right away.
  4. The agent edits the state with update_application_state. Your component gets the new state through onStateChange and updates the view in place.

The canvas is shared with the agent as an application state named canvas:<actionKey>:<callId>, in two parts:

  • state is yours: while the canvas is open, the agent sees { canvas_status: "open", ...state }. canvas_status belongs to the SDK: a field of yours with that name is dropped.
  • schema is the SDK’s: JSON with the canvas’s type, status, title, and the rules the SDK writes for the agent. You pick the type and the status from fixed lists, and the title is one cleaned line, so nothing you write is read by the agent as an instruction.
What the agent sees in schema (open, edit mode)
{
"kind": "canvas",
"type": "CONTENT_EDITOR",
"status": "EDIT_MODE",
"open": true,
"title": "Draft: launch post",
"rules": "This canvas is open beside the chat and the user sees it. Its content is this state. …"
}

This draft_post action opens a blog post editor. execute returns the first draft, and renderCanvas draws a text area the user and the agent both edit.

draft-post.js
foldspace("when", "ready", () => {
foldspace.agent({ /* …common setup… */ })
.addActionHandlers({
draft_post: {
// 1. The first state of the canvas
execute: async ({ topic }) => ({ title: `Draft: ${topic}`, body: '' }),
// 2. Draw the canvas from the state
renderCanvas: ({ state, host, setState, onStateChange, setTitle, setType, setStatus }) => {
setTitle(state.title);
setType('CONTENT_EDITOR'); // a document the agent writes with the user
setStatus('EDIT_MODE'); // the agent may change it (the default is READ_MODE)
const editor = host.ownerDocument.createElement('textarea');
editor.style.cssText =
'display:block;width:100%;height:100%;min-height:400px;border:none;padding:16px;box-sizing:border-box';
editor.value = state.body;
host.append(editor);
// The user's edits: shared when the text area loses focus
editor.addEventListener('change', () => setState({ body: editor.value }));
// The agent's edits: update the view in place
onStateChange((next) => {
setTitle(next.title);
if (next.body !== editor.value) editor.value = next.body;
});
}
}
});
});

renderCanvas runs each time the canvas opens, including when the user reopens it from its chat card. Draw from state every time, not from values you kept from an earlier run.

Call setState(patch) when the user changes something. The patch is merged (shallow) into the state, and the agent sees the result with the user’s next message.

The agent knows the canvas only through its state. An edit you don’t share is one the agent can’t see: it answers about the old content, and its next change writes over what the user did. Share every change the user makes.

  • Debounce typing. The agent reads the state on the user’s next message, so it doesn’t need every keystroke. Share 500 to 1,000 ms after the user stops typing, and on blur.
  • Check the return value. setState returns { ok, notSent }. notSent lists the paths that were too large for the agent to get whole (see Large state): tell the user the agent can only read part of the canvas. ok is false, and nothing changes, only when the state isn’t plain JSON or is over 1 MB.
  • Keep the state small and meaningful. Put content in it, not presentation. Keep raw rows, images, and long records in your app or backend, and share IDs and summaries.

Register onStateChange(listener) to update the view in place when the agent changes the state. Keep the user’s focus, scroll position, and selection: write a field only when its value changed. The listener isn’t called for your own setState, and it returns the function that unsubscribes.

Without a listener, the SDK runs your cleanup, clears host (not header: remove your <style> tags in the cleanup), and runs renderCanvas again with the new state. That’s fine for a read-only canvas, and loses the cursor in an editor.

Two calls tell the agent what the canvas is and whether it may change it. The SDK turns them into the rules in the canvas’s schema; there’s no free text of yours for the agent. Call both in renderCanvas, and call setStatus again whenever the real status changes.

setType(type) adds one rule to what the agent is told:

TypeUse it forThe agent
CONTENT_EDITORArticles, emails, replies, postsWrites with the user. It puts the text it writes into the state’s fields, not into the chat.
FORMLong forms the user sends from your appFills or fixes fields when asked, and never says the form was sent.
REPORTDashboards, summaries, resultsTreats the canvas as something the user reads. It changes what it shows only when the user asks.
TABLERows the user reviews or edits in bulkChanges only the rows and columns the user asks for, and never adds or removes rows unless asked.
CODEQueries, formulas, scripts, configKeeps it valid and complete, in the state’s fields, not the chat.
OTHER (default)Anything elseGets no extra rule.

setStatus(status) says whether the agent may change the canvas, and the SDK enforces it:

StatusThe agent
READ_MODE (default)Reads the canvas. Every change it sends is refused, and it’s told: “This canvas is in read mode, so nothing changed. Tell the user it can’t be changed now.” So it tells the user instead of claiming it changed something.
EDIT_MODEChanges the state with update_application_state. A field it sends replaces that whole field.

The agent can close the canvas in either mode. The status is yours to keep true:

  • EDIT_MODE while the user drafts with the agent.
  • READ_MODE for a canvas the agent only reads, while your app saves it, and once it’s saved, sent, deleted, or no longer available.

What the fields mean and your app’s limits (such as “title is under 80 characters”) belong in the action’s parameter descriptions and instructions in Agent Studio, which the agent reads when it calls the action.

Give the canvas a specific title with setTitle, such as Article: password reset. It shows in the canvas header and its chat card, and the agent gets it as data. It’s one line of up to 80 characters: line breaks and control characters are removed, and longer is cut.

The canvas shares the agent’s application state limit, 4 KB of JSON, with any other state your page shares, and the canvas’s own type, title and rules take about 0.7 KB of it. That leaves about 3 KB for the canvas state when nothing else is shared: an article of about 400 words. You don’t control what ends up in a canvas: the agent may write a long article, or a report may hold thousands of rows. So before every send, the SDK measures the state and, if it doesn’t fit, sends the agent a cut copy:

  • The biggest parts go first, at any depth: a long string, then the tail of a long array, then a whole object.
  • Each cut leaves a marker the agent can read, such as [NOT SENT: 9000 bytes, too large] or [NOT SENT: 120 more items]. In READ_MODE a cut string keeps its start, followed by [NOT SENT: N more bytes], so the agent can answer from part of it. In EDIT_MODE it’s only the marker.
  • The schema lists the cut paths in notSent, and the agent is told it can see only part of the canvas. The SDK logs a console warning for each.
  • In EDIT_MODE, the agent can’t change a top-level field with a cut inside: the SDK refuses, so a partial copy never overwrites the user’s full content.
  • The canvas always keeps the full state. Only what the agent gets is cut.

setState returns the same notSent list. Keep large content out of the state where you can: IDs and summaries for the agent, the rest fetched in renderCanvas.

A canvas the agent only reads keeps the default READ_MODE: the agent sees the state and answers follow-ups from it, and the SDK refuses any change it tries. Use the REPORT type.

For large data, return IDs and a summary from execute, and fetch the rows in renderCanvas for display. This show_todos_report action shares counts with the agent and draws the full list.

show-todos-report.js
foldspace("when", "ready", () => {
foldspace.agent({ /* …common setup… */ })
.addActionHandlers({
show_todos_report: {
// What the agent sees: a summary, not every row
execute: async ({ userId }) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}/todos`
);
const todos = await response.json();
const open = todos.filter((todo) => !todo.completed);
return {
userId,
total: todos.length,
open: open.length,
firstOpen: open.slice(0, 3).map((todo) => todo.title),
};
},
renderCanvas: ({ state, host, header, setTitle, setType }) => {
setTitle(`Tasks: user ${state.userId}`);
setType('REPORT'); // and the default READ_MODE: the agent only reads it
const doc = host.ownerDocument;
const style = doc.createElement('style');
style.textContent = `
.todos-report {
padding: 20px 24px;
color: var(--fs-text);
font-family: var(--fs-font-family), system-ui, sans-serif;
font-size: var(--fs-font-size);
}
.todos-report li.done {
color: var(--fs-text-secondary);
text-decoration: line-through;
}
`;
header.appendChild(style);
const report = doc.createElement('div');
report.className = 'todos-report';
const summary = doc.createElement('p');
summary.textContent = `${state.open} of ${state.total} tasks open`;
const list = doc.createElement('ul');
report.append(summary, list);
host.appendChild(report);
// The rows are for display only; the agent doesn't need them
const controller = new AbortController();
fetch(`https://jsonplaceholder.typicode.com/users/${state.userId}/todos`, {
signal: controller.signal,
})
.then((response) => response.json())
.then((todos) => {
for (const todo of todos) {
const item = doc.createElement('li');
item.textContent = todo.title;
if (todo.completed) item.className = 'done';
list.appendChild(item);
}
})
.catch(() => {});
return () => {
controller.abort();
style.remove();
};
}
}
});
});

setActions(elements) puts your own controls in the canvas header, before the SDK’s full-screen and close buttons. Pass any elements: buttons, toggles, a select. Each call replaces the previous ones, and [] removes them.

The header is in your page, outside the canvas frame. Create its elements from the page’s document, and style them with your page’s CSS. To keep an editor’s focus and selection in the canvas (for a Bold button, say), call event.preventDefault() on the button’s mousedown.

draft-email.js
foldspace("when", "ready", () => {
foldspace.agent({ /* …common setup… */ })
.addActionHandlers({
draft_email: {
execute: async ({ subject }) => ({ subject, body: '' }),
renderCanvas: ({ state, host, setState, onStateChange, setTitle, setType, setStatus, setActions }) => {
setTitle(`Email: ${state.subject}`);
setType('CONTENT_EDITOR');
setStatus('EDIT_MODE');
const editor = host.ownerDocument.createElement('textarea');
editor.style.cssText =
'display:block;width:100%;height:100%;min-height:400px;border:none;padding:16px;box-sizing:border-box';
editor.value = state.body;
editor.addEventListener('change', () => setState({ body: editor.value }));
host.append(editor);
// The header is in the page: use the page's document
const copy = document.createElement('button');
copy.type = 'button';
copy.textContent = 'Copy';
copy.addEventListener('mousedown', (event) => event.preventDefault());
copy.addEventListener('click', () => navigator.clipboard.writeText(editor.value));
setActions([copy]);
onStateChange((next) => {
if (next.body !== editor.value) editor.value = next.body;
});
}
}
});
});

The agent edits the canvas state, never your data. Saving, sending, or deleting happens in your app, from a control the user clicks:

  1. When the user clicks, switch to setStatus('READ_MODE'), so the agent can’t change what is being saved.
  2. After it succeeds, put the result in the state (such as a savedId) and stay in read mode. The agent sees it’s saved, and tells the user it can’t change it now.
  3. If it fails, keep the draft, say why, and go back to setStatus('EDIT_MODE').

Edit an article with the agent shows the full flow.

In the default IFRAME render mode, the canvas content has its own iframe document, so your page’s CSS doesn’t reach it.

  • Create elements with host.ownerDocument, not document.
  • Put <style> and <link> tags in header, the <head> of that document.
  • Use the --fs-* theme variables, or read theme, so the canvas follows the agent’s colors and dark mode. Follow theme.onChange for anything CSS doesn’t cover.
  • Give fonts a fallback: font-family: var(--fs-font-family), system-ui, sans-serif.

In INLINE render mode, the canvas content is in your page, and header is your page’s <head>. Scope your selectors to the canvas so they don’t restyle your app, and remove your styles in the cleanup. host has no fixed height there: give a text area or editor its own min-height.

Render into host, and unmount in the cleanup that renderCanvas returns. A React root stored on host.root is also unmounted when the canvas closes.

post-editor.jsx
import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
function PostEditor({ ctx }) {
const [post, setPost] = useState(ctx.state);
// The agent's edits; the returned function unsubscribes
useEffect(() => ctx.onStateChange(setPost), [ctx]);
// The user's edits, shared 700 ms after they stop typing
useEffect(() => {
ctx.setTitle(post.title || 'Untitled post');
const timer = setTimeout(() => ctx.setState(post), 700);
return () => clearTimeout(timer);
}, [ctx, post]);
return (
<div style={{ display: 'grid', gap: 12, padding: 16 }}>
<input
value={post.title}
onChange={(event) => setPost({ ...post, title: event.target.value })}
/>
<textarea
rows={16}
value={post.body}
onChange={(event) => setPost({ ...post, body: event.target.value })}
/>
</div>
);
}
foldspace("when", "ready", () => {
foldspace.agent({ /* …common setup… */ })
.addActionHandlers({
draft_post: {
execute: async ({ topic }) => ({ title: `Draft: ${topic}`, body: '' }),
renderCanvas: (ctx) => {
ctx.setType('CONTENT_EDITOR');
ctx.setStatus('EDIT_MODE');
const root = createRoot(ctx.host);
root.render(<PostEditor ctx={ctx} />);
return () => root.unmount();
}
}
});
});

renderCanvas may return a cleanup function. The SDK calls it when the canvas closes and before it runs renderCanvas again. Remove your listeners, clear timers, abort requests, and unmount your framework’s root there.

  • One canvas per conversation. A new canvas call (“now an article on dogs”) opens with its own execute result and replaces the previous canvas: that one closes, its state is forgotten, the agent stops seeing it, and its chat card can’t open it again. Keep what the user needs in your app before they move on.
  • One canvas open on the page. Opening a canvas closes the one that’s open in another agent on the page.
  • Closing keeps the state. The user’s close button, close(), or the agent closes the canvas, in either mode. Its last state stays in memory, and its chat card, or the agent when the user asks, opens it again as it was left.
  • The canvas closes with the agent. Closing, collapsing, or hiding the agent for more than half a second closes the canvas, and your cleanup runs. Its state is kept: when the user reopens the agent in the same conversation, the chat card opens it again. Dragging or resizing the agent, a brief hide, or the agent stepping aside for a navigation keeps it open.
  • The agent can’t change a closed canvas. It sees { canvas_status: "closed" } and the schema with the title and type, not the content. It can open it again when the user asks.
  • The canvas belongs to its conversation. Its state is kept in memory, in the page, while the user stays in the conversation it opened in. Moving between your app’s routes (in a single-page app) keeps it. A new chat, or another conversation opened from the history, closes it and forgets it: the agent stops seeing it, and its chat card can’t open it.
  • The chat history doesn’t bring it back. A conversation loaded from the history, after a reload or when the user goes back to an earlier one, shows each canvas card as “Canvas closed”, with no button. Keep anything the user needs in your app, saved with a button in the canvas, not in the canvas state.
  • The canvas sits on the setPosition side of the agent (default "LEFT"), in the overlay panel or embedded agent. It’s as tall as the agent and as wide as the room up to the window edge, or setMaxWidth.
  • It moves and resizes with the agent, and closes when the agent closes.
  • With little room it keeps a minimum width of 360 px (less if the window is narrower) and covers part of the agent, never more than half of it.
  • Its header has the title, your setActions controls, a full-screen button, and a close button.
  • On mobile devices (tablets included), in windows whose shorter side is 500 px or less when the page loads, and on headless agents, there’s no canvas: the action isn’t registered, so the agent isn’t offered it. An action that has renderCanvas and also render or renderComponent isn’t registered either. With enableDebugLogs on, the SDK logs why.

This draft_article action opens an article editor. The agent writes the draft into the state, the user edits it in the canvas, and only the user saves it, with Save. The canvas is in edit mode while the user drafts and in read mode from the moment they click Save. After the save, the canvas shows a saved view, and reopening it from the chat card shows the same.

draft-article.js
const SHARE_DELAY_MS = 700;
const ARTICLE_CSS = `
.article {
display: flex;
flex-direction: column;
gap: 12px;
box-sizing: border-box;
min-height: 100%;
padding: 20px 24px;
color: var(--fs-text);
font-family: var(--fs-font-family), system-ui, sans-serif;
font-size: var(--fs-font-size);
color-scheme: var(--fs-color-scheme);
}
.article input,
.article textarea {
box-sizing: border-box;
width: 100%;
padding: 8px 10px;
border: 1px solid var(--fs-border);
border-radius: var(--fs-radius);
background: var(--fs-paper);
color: inherit;
font: inherit;
}
.article input {
font-size: 20px;
font-weight: 600;
}
.article textarea {
flex: 1;
min-height: 320px;
line-height: 1.6;
}
.article-status {
min-height: 18px;
color: var(--fs-text-secondary);
font-size: 12px;
}
.article button {
align-self: flex-end;
padding: 6px 14px;
border: none;
border-radius: var(--fs-radius);
background: var(--fs-primary);
color: var(--fs-primary-text);
font: inherit;
cursor: pointer;
}
.article button:disabled {
opacity: 0.55;
cursor: default;
}
`;
function renderArticle(ctx) {
const doc = ctx.host.ownerDocument;
const style = doc.createElement('style');
style.textContent = ARTICLE_CSS;
ctx.header.appendChild(style);
ctx.setMaxWidth(720);
const showTitle = (title) => ctx.setTitle(`Article: ${title || 'Untitled'}`);
const showSaved = (title) => {
const done = doc.createElement('div');
done.className = 'article';
done.textContent = `"${title || 'Untitled'}" is saved.`;
ctx.host.replaceChildren(done);
ctx.setStatus('READ_MODE'); // saved: the agent can't change it here
};
ctx.setType('CONTENT_EDITOR');
showTitle(ctx.state.title);
// Reopened after a save: show the saved view
if (ctx.state.savedId) {
showSaved(ctx.state.title);
return () => style.remove();
}
ctx.setStatus('EDIT_MODE'); // a draft: the agent may change it
const root = doc.createElement('div');
root.className = 'article';
const title = doc.createElement('input');
title.placeholder = 'Untitled';
title.value = ctx.state.title ?? '';
const body = doc.createElement('textarea');
body.placeholder = 'Write the article, or ask the agent to.';
body.value = ctx.state.body ?? '';
const status = doc.createElement('div');
status.className = 'article-status';
status.setAttribute('role', 'status');
const save = doc.createElement('button');
save.type = 'button';
save.textContent = 'Save';
root.append(title, body, status, save);
ctx.host.appendChild(root);
// The user's edits: shared a moment after they stop typing
let timer;
let saved = false;
const share = () => {
clearTimeout(timer);
if (saved) return;
const { notSent } = ctx.setState({ title: title.value, body: body.value });
status.textContent = notSent.length
? 'This article is too long for the agent to read whole. You can still edit and save it.'
: '';
showTitle(title.value);
};
const later = () => {
clearTimeout(timer);
timer = setTimeout(share, SHARE_DELAY_MS);
};
title.addEventListener('input', later);
body.addEventListener('input', later);
title.addEventListener('blur', share);
body.addEventListener('blur', share);
// The agent's edits: update the fields in place
const unsubscribe = ctx.onStateChange((next) => {
if (saved) return;
clearTimeout(timer);
if (next.title !== title.value) title.value = next.title ?? '';
if (next.body !== body.value) body.value = next.body ?? '';
showTitle(title.value);
});
// Only the user saves, through your app's own API
save.addEventListener('click', async () => {
share();
save.disabled = true;
ctx.setStatus('READ_MODE'); // the agent can't change it while it saves
status.textContent = 'Saving…';
try {
const response = await fetch('/api/articles', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: title.value, body: body.value }),
});
if (!response.ok) throw new Error(`Save failed: ${response.status}`);
const { id } = await response.json();
// Tell the agent it's saved. The body now lives in your app.
saved = true;
ctx.setState({ savedId: id, body: '' });
showSaved(title.value);
} catch {
status.textContent = 'The article could not be saved. Try again.';
ctx.setStatus('EDIT_MODE');
save.disabled = false;
}
});
return () => {
clearTimeout(timer);
unsubscribe();
style.remove();
};
}
foldspace("when", "ready", () => {
foldspace.agent({ /* …common setup… */ })
.addActionHandlers({
draft_article: {
execute: async (params) => ({
title: params.title ?? '',
body: params.body ?? '',
}),
renderCanvas: renderArticle,
}
});
});

renderCanvas receives one object with these keys.

KeyTypeDescription
stateRecord<string, any>The state when the component runs: what execute returned the first time, then the latest state. Keep it plain JSON and small.
hostHTMLElementWhere the canvas content goes. Create elements with host.ownerDocument.
headerHTMLElementThe <head> of host’s document, for <style> and <link> tags.
themeComponentThemeThe agent’s mode and colors, the same object a chat card receives.
setState(patch)(patch: object) => { ok: boolean, notSent: string[] }Merges patch (shallow) into the state. The agent sees it with the user’s next message. notSent lists the paths too large for the agent to get whole ("*": none of it). ok is false, and nothing changes, when the state isn’t plain JSON or is over 1 MB.
onStateChange(listener)(listener: (state) => void) => () => voidCalls listener with the new state when the agent changes it (EDIT_MODE only). Returns the function that unsubscribes. Without a listener, the SDK runs renderCanvas again.
setTitle(title)(title: string) => voidThe title in the canvas header, its chat card, and what the agent is told. One line, up to 80 characters. Defaults to the action key.
setType(type)(type: string) => voidWhat the canvas is: "CONTENT_EDITOR", "FORM", "REPORT", "TABLE", "CODE", or "OTHER" (default). An unknown value is ignored, with a console warning.
setStatus(status)(status: string) => void"READ_MODE" (default: the SDK refuses the agent’s changes) or "EDIT_MODE". An unknown value is ignored, with a console warning.
setActions(elements)(elements: Element[]) => voidYour controls in the canvas header, before the full-screen and close buttons. Each call replaces the previous ones.
setPosition(position)("LEFT" | "RIGHT") => voidThe side of the agent the canvas sits on. Default "LEFT".
setMaxWidth(px)(px: number | null) => voidThe canvas’s largest width in pixels. null (default) fills the room between the agent and the window edge.
close()() => voidCloses the canvas, as its close button does. Its state is kept.

renderCanvas returns nothing, or a cleanup function. There is no callback, cancel, or readyState: everything after the canvas opens goes through setState or your app’s own APIs.

LimitValue
Application state the agent sees4 KB of JSON (UTF-8 bytes) for all application state on the page, the canvas and its rules included. The SDK cuts a larger canvas state before it’s sent: see Large state.
Canvas state kept in the page1 MB of JSON. A larger setState, or an agent change that would pass it, is refused.
TitleOne line, 80 characters. Longer is cut.
CanvasesOne per conversation, and one open on the page. A new canvas replaces the previous one.
How long it’s keptUntil the page reloads or the user starts or opens another conversation. A conversation loaded from the history shows “Canvas closed”.
Where it runsOverlay and embedded agents on desktop. Not on mobile devices, windows with a shorter side of 500 px or less, or headless agents.

An error thrown in renderCanvas is silent unless you turn on enableDebugLogs: the canvas opens empty, and the agent is told it’s shown.