# Custom canvas

A plain starting point for a canvas no typed one fits: a plan, a brief or a runbook built from headings, text, key values, checklists and callouts. The user and the agent edit the same blocks, the agent's changes are marked, and your footer buttons act on the result.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

A plain starting point for a canvas no typed one fits: a plan, a brief or a runbook built from headings, text, key values, checklists and callouts. The user and the agent edit the same blocks, the agent's changes are marked, and your footer buttons act on the result.

## When to use it

**Use it when:** None of the typed canvases fits: a plan, a brief, a runbook or a review the user and the agent shape together from headings, text, key values, checklists and callouts. The SDK adds no rule for OTHER, so your action's own prompt must say what the agent may change and what it must leave alone.

**Use something else when:** The content is a form, a table, a document, code or a report: use that canvas, whose type tells the agent how to behave. A one-off answer (a chat card). Mobile: the canvas isn't available; use the card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.setState({ blocks })` | `Canvas state` | 600 ms after the user stops editing, and when a field loses focus. The agent edits the same blocks by id. |
| `actions.onAction(id, state)` | `Your app` | A footer button. The patch it returns (a new status, say) is drawn and shared. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile card: as soon as it shows. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While execute reads what the plan starts from. The skeleton has the canvas's shape: a title, key values, text and a checklist. |
| Empty | There's nothing to build the canvas from, for example a workspace that's already in the target region. Say why, and what the user can do. |
| Error | execute couldn't read what the canvas needs. Nothing changed; Try again loads it in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### CustomCanvasState

| Field | Type | Notes |
| --- | --- | --- |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: title. |
| `eyebrow` (optional) | `string` | A small label above the title, e.g. "Migration plan". |
| `title` | `string` |  |
| `subtitle` (optional) | `string` | One or two lines under the title. |
| `status` (optional) | `CustomCanvasStatus` | A status pill beside the eyebrow. |
| `blocks` | `CustomCanvasBlock[]` | The body, top to bottom. Each block keeps its id when the agent edits it, so the canvas can mark the change. |
| `buttons` (optional) | `CustomCanvasButton[]` | Footer buttons. Their clicks go to actions.onAction(id); the last primary one is the main action. |
| `footnote` (optional) | `string` | A line in the footer, e.g. who decides what. |

### CustomCanvasBlock

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Stable id. |
| `type` | `"heading" \| "text" \| "keyValue" \| "checklist" \| "callout"` | heading, text (paragraphs), keyValue (label and value rows), checklist (items the user ticks), callout (a note with a tone). |
| `text` (optional) | `string` | heading, text and callout: the text. A blank line starts a paragraph. |
| `items` (optional) | `CustomCanvasItem[]` | keyValue and checklist: the rows. |
| `tone` (optional) | `"info" \| "success" \| "warning" \| "error"` | callout: info (default), success, warning or error. |
| `editable` (optional) | `boolean` | text and keyValue: the user can edit it in place. Checklists are always tickable. |

### CustomCanvasItem

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Stable id. |
| `label` | `string` |  |
| `value` (optional) | `string` | keyValue: the value. |
| `done` (optional) | `boolean` | checklist: ticked. |
| `hint` (optional) | `string` | A muted line under the label or value. |

### CustomCanvasButton

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | What actions.onAction receives. |
| `label` | `string` |  |
| `primary` (optional) | `boolean` | The filled button. Default: outlined. |

### CustomCanvasActions

| Field | Type | Notes |
| --- | --- | --- |
| `onAction()` (optional) | `(id: string, state: CustomCanvasState) => Promise<Partial<CustomCanvasState> \| void> \| Partial<CustomCanvasState> \| void` | A footer button was clicked. Return a state patch to apply and share (e.g. a new status). Throw to show why it failed. |
| `onChange()` (optional) | `(state: CustomCanvasState) => void` | Called each time the state is shared with the agent (debounced). |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/custom-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/custom-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/custom-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/custom-canvas.canvas.js)
- custom-canvas: [TypeScript](/ui-catalog/files/ts/custom-canvas.ts), [JavaScript](/ui-catalog/files/js/custom-canvas.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/plan_region_move/index.ts"
// agent/actions/plan_region_move/index.ts: a hosted canvas action (desktop).
// Copy the template (custom-canvas.ts) and fs-kit.ts into agent/ui/.
//
// OTHER adds no rule for the agent, so write the rules in this action's prompt. For this plan, for example:
// "Fill in and update the plan's blocks by id. You may tick checklist items you've confirmed, add steps to a checklist
//  and change the facts. Don't untick what the user ticked, don't rewrite the user's notes, and never change status:
//  only the user marks the plan as ready."

type Result = CustomCanvasState | { error: string };

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB.
export async function execute(args: { workspaceId: string; region: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/workspaces/${encodeURIComponent(args.workspaceId)}`);
  if (!res.ok) return { error: `The workspace didn't load (${res.status}). Nothing changed.` };
  const ws = await res.json();
  return {
    eyebrow: "Migration plan",
    title: `Move ${ws.name} to ${args.region}`,
    status: { label: "Draft", tone: "warning" },
    blocks: [
      { id: "facts", type: "keyValue", editable: true, items: [
        { id: "from", label: "From", value: ws.region },
        { id: "to", label: "To", value: args.region },
        { id: "users", label: "Users affected", value: `${ws.userCount} people` },
        { id: "window", label: "Window", value: "", hint: "Pick a low-traffic hour" },
      ] },
      { id: "steps", type: "checklist", items: [
        { id: "export", label: "Export the audit log" },
        { id: "notify", label: "Tell workspace admins about the read-only hour" },
      ] },
      { id: "notes", type: "text", editable: true, text: "" },
    ],
    buttons: [{ id: "ready", label: "Mark as ready", primary: true }],
  };
}

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("OTHER");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both edit
  const state = canvas.state as Result;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Migration plan", state: { kind: "error", text: state.error } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // A footer button. The patch you return is drawn and shared with the agent. Throw to show why it failed.
      onAction: async (id, plan) => {
        if (id !== "ready") return;
        const res = await ctx.fetch("/api/migrations", { method: "POST", body: JSON.stringify(plan), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The plan wasn't saved. Your changes are kept. Try again.");
        canvas.setStatus("READ_MODE");
        return { status: { label: "Ready", tone: "success" }, buttons: [] };
      },
    },
  });
}
```

```js title="agent/actions/plan_region_move/index.js"
// agent/actions/plan_region_move/index.js: a hosted canvas action (desktop).
// Copy the template (custom-canvas.ts) and fs-kit.ts into agent/ui/.
//
// OTHER adds no rule for the agent, so write the rules in this action's prompt. For this plan, for example:
// "Fill in and update the plan's blocks by id. You may tick checklist items you've confirmed, add steps to a checklist
//  and change the facts. Don't untick what the user ticked, don't rewrite the user's notes, and never change status:
//  only the user marks the plan as ready."

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB.
export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/workspaces/${encodeURIComponent(args.workspaceId)}`);
  if (!res.ok) return { error: `The workspace didn't load (${res.status}). Nothing changed.` };
  const ws = await res.json();
  return {
    eyebrow: "Migration plan",
    title: `Move ${ws.name} to ${args.region}`,
    status: { label: "Draft", tone: "warning" },
    blocks: [
      { id: "facts", type: "keyValue", editable: true, items: [
        { id: "from", label: "From", value: ws.region },
        { id: "to", label: "To", value: args.region },
        { id: "users", label: "Users affected", value: `${ws.userCount} people` },
        { id: "window", label: "Window", value: "", hint: "Pick a low-traffic hour" },
      ] },
      { id: "steps", type: "checklist", items: [
        { id: "export", label: "Export the audit log" },
        { id: "notify", label: "Tell workspace admins about the read-only hour" },
      ] },
      { id: "notes", type: "text", editable: true, text: "" },
    ],
    buttons: [{ id: "ready", label: "Mark as ready", primary: true }],
  };
}

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("OTHER");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both edit
  const state = canvas.state;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Migration plan", state: { kind: "error", text: state.error } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // A footer button. The patch you return is drawn and shared with the agent. Throw to show why it failed.
      onAction: async (id, plan) => {
        if (id !== "ready") return;
        const res = await ctx.fetch("/api/migrations", { method: "POST", body: JSON.stringify(plan), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The plan wasn't saved. Your changes are kept. Try again.");
        canvas.setStatus("READ_MODE");
        return { status: { label: "Ready", tone: "success" }, buttons: [] };
      },
    },
  });
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the card below.
//
// OTHER adds no rule for the agent: this action's prompt must say what the agent may change and what it must leave alone,
// for example "Update the brief's blocks by id. Don't change the budget the user set."

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    draft_campaign_brief: {
      // { title, blocks, buttons }: the agent reads and edits this state, block by block.
      execute: async ({ campaignId }: { campaignId: string }): Promise<CustomCanvasState> => {
        const c = await myApi.campaign(campaignId);
        return {
          eyebrow: "Campaign brief", title: c.name, status: { label: "Draft", tone: "warning" },
          blocks: [
            { id: "facts", type: "keyValue", editable: true, items: [
              { id: "audience", label: "Audience", value: c.audience }, { id: "budget", label: "Budget", value: c.budget },
            ] },
            { id: "goal", type: "text", editable: true, text: c.goal ?? "" },
            { id: "todo", type: "checklist", items: c.tasks.map((t: { id: string; title: string }) => ({ id: t.id, label: t.title })) },
          ],
          buttons: [{ id: "send", label: "Send for review", primary: true }],
        };
      },

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("OTHER");
        ctx.setStatus("EDIT_MODE");
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            onAction: async (id, brief) => {
              if (id === "send") { await myApi.sendBriefForReview(brief); return { status: { label: "In review", tone: "primary" } }; }
            },
            onChange: (brief) => myApi.saveBriefDraft(brief), // your copy, besides the agent's
          },
        });
      },
    },

    // Mobile: a read-only card of the same state.
    show_campaign_brief: {
      execute: async ({ campaignId }: { campaignId: string }): Promise<CustomCanvasState> => myApi.briefState(campaignId),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<CustomCanvasState>) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

```js title="in-page handler.js"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the card below.
//
// OTHER adds no rule for the agent: this action's prompt must say what the agent may change and what it must leave alone,
// for example "Update the brief's blocks by id. Don't change the budget the user set."

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    draft_campaign_brief: {
      // { title, blocks, buttons }: the agent reads and edits this state, block by block.
      execute: async ({ campaignId }) => {
        const c = await myApi.campaign(campaignId);
        return {
          eyebrow: "Campaign brief", title: c.name, status: { label: "Draft", tone: "warning" },
          blocks: [
            { id: "facts", type: "keyValue", editable: true, items: [
              { id: "audience", label: "Audience", value: c.audience }, { id: "budget", label: "Budget", value: c.budget },
            ] },
            { id: "goal", type: "text", editable: true, text: c.goal ?? "" },
            { id: "todo", type: "checklist", items: c.tasks.map((t) => ({ id: t.id, label: t.title })) },
          ],
          buttons: [{ id: "send", label: "Send for review", primary: true }],
        };
      },

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("OTHER");
        ctx.setStatus("EDIT_MODE");
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            onAction: async (id, brief) => {
              if (id === "send") { await myApi.sendBriefForReview(brief); return { status: { label: "In review", tone: "primary" } }; }
            },
            onChange: (brief) => myApi.saveBriefDraft(brief), // your copy, besides the agent's
          },
        });
      },
    },

    // Mobile: a read-only card of the same state.
    show_campaign_brief: {
      execute: async ({ campaignId }) => myApi.briefState(campaignId),
      renderComponent: ({ data, host, header, readyState }) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

### custom-canvas

```ts title="agent/ui/custom-canvas.ts"
// Template: custom-canvas. A generic canvas (type OTHER) drawn from simple blocks, as a starting point to adapt (desktop), plus its mobile card.

export const meta = {
  id: "custom-canvas",
  title: "Custom canvas",
  surface: "canvas",
  canvasType: "OTHER",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "None of the typed canvases fits: a plan, a brief, a runbook or a review the user and the agent shape together from headings, text, key values, checklists and callouts. The SDK adds no rule for OTHER, so your action's own prompt must say what the agent may change and what it must leave alone.",
  whenNotToUse: "The content is a form, a table, a document, code or a report: use that canvas, whose type tells the agent how to behave. A one-off answer (a chat card). Mobile: the canvas isn't available; use the card (mountMobile).",
};

const CSS = `
.fsk-cu { container: fsk-cu / inline-size; height: 100%; min-height: 440px; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-cu-main { flex: 1; min-height: 0; overflow: auto; }
.fsk-cu-doc { max-width: 720px; margin: 0 auto; padding: 22px 24px 32px; }
.fsk-cu-top { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 18px; }
.fsk-cu-top > div { flex: 1; min-width: 0; }
.fsk-cu-eyebrow { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.fsk-cu-title { margin: 10px 0 4px; font-size: 1.45em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.22; }
.fsk-cu-sub { margin: 0; color: var(--k-text-2); max-width: 62ch; }
.fsk-cu-blocks { display: flex; flex-direction: column; gap: 14px; }

.fsk-cu-block { position: relative; border-radius: var(--k-r-lg); transition: background-color .2s; }
.fsk-cu-block[data-agent]::before { content: ""; position: absolute; left: -12px; top: 4px; bottom: 4px; width: 3px; border-radius: 3px; background: var(--k-primary); }
.fsk-cu-mark { display: inline-flex; align-items: center; gap: 4px; margin: 0 0 6px; padding: 1px 8px 1px 6px; border-radius: 999px; font-size: .72em; font-weight: 600; line-height: 1.5;
  color: var(--k-primary); background: var(--k-tint); animation: fsk-in .3s var(--k-ease) both; }
.fsk-cu-flash { animation: fsk-cu-flash 2.4s var(--k-ease); }

.fsk-cu-h { margin: 12px 0 -4px; font-size: 1.05em; font-weight: 600; letter-spacing: -0.01em; line-height: 1.35; }
.fsk-cu-block:first-child .fsk-cu-h { margin-top: 0; }
.fsk-cu-text { margin: 0; white-space: pre-line; line-height: 1.6; }
.fsk-cu-field { display: block; width: 100%; min-height: 3lh; margin: 0; padding: 10px 12px; font: inherit; line-height: 1.6; color: var(--k-text); resize: vertical;
  background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-md); field-sizing: content; transition: border-color .15s, box-shadow .15s; }
.fsk-cu-field::placeholder, .fsk-cu-input::placeholder { color: var(--k-text-2); opacity: 1; }
.fsk-cu-field:hover, .fsk-cu-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-cu-field:focus, .fsk-cu-input:focus { outline: none; border-color: var(--k-primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 20%, transparent); }

.fsk-cu-kv { display: grid; grid-template-columns: minmax(0, 1fr); margin: 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); overflow: hidden; }
.fsk-cu-kv > div { display: grid; grid-template-columns: minmax(110px, 34%) minmax(0, 1fr); align-items: center; gap: 12px; min-height: 42px; padding: 6px 14px; }
.fsk-cu-kv > div + div { border-top: 1px solid var(--k-divider); }
.fsk-cu-kv dt { color: var(--k-text-2); font-size: .93em; }
.fsk-cu-kv dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-cu-ph { color: var(--k-text-2); font-weight: 400; font-style: italic; }
.fsk-cu-kv dd small { display: block; font-weight: 400; color: var(--k-text-2); font-size: .86em; }
.fsk-cu-input { width: 100%; min-height: 32px; margin: 0 -9px; width: calc(100% + 18px); padding: 4px 8px; font: inherit; font-weight: 500; color: var(--k-text);
  background: transparent; border: 1px solid transparent; border-radius: var(--k-r-md); transition: border-color .15s, box-shadow .15s, background .15s; }
.fsk-cu-input:hover { border-color: var(--k-border); }
.fsk-cu-input:not(:focus) { background: var(--k-sunken); }

.fsk-cu-check-head { display: flex; align-items: center; gap: 10px; margin: 0 0 6px; font-size: .86em; color: var(--k-text-2); }
.fsk-cu-bar { flex: 1; max-width: 160px; height: 5px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-cu-bar > span { display: block; height: 100%; border-radius: inherit; background: var(--k-success); transition: width .4s var(--k-ease); }
.fsk-cu-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); overflow: hidden; }
.fsk-cu-list li + li { border-top: 1px solid var(--k-divider); }
.fsk-cu-item { display: flex; align-items: flex-start; gap: 12px; padding: 11px 14px; cursor: pointer; transition: background .15s; }
.fsk-cu-item:hover { background: var(--k-sunken); }
.fsk-cu-item input { appearance: none; flex: none; display: grid; place-items: center; width: 18px; height: 18px; margin: 1px 0 0; cursor: pointer;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); border-radius: max(4px, calc(var(--k-r) * .8)); background: var(--k-paper); transition: background .15s, border-color .15s; }
.fsk-cu-item input:checked { background: var(--k-success); border-color: var(--k-success); }
.fsk-cu-item input:checked::after { content: ""; width: 4px; height: 9px; margin-top: -2px; border: solid var(--k-paper); border-width: 0 2px 2px 0; transform: rotate(45deg); }
.fsk-cu-item input:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-cu-item-text { flex: 1; min-width: 0; }
.fsk-cu-item-text b { display: block; font-weight: 500; }
.fsk-cu-item-text small { display: block; margin-top: 1px; color: var(--k-text-2); font-size: .86em; }
.fsk-cu-item[data-done] b { color: var(--k-text-2); text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 55%, transparent); }
.fsk-cu-item[data-new] { background: color-mix(in srgb, var(--k-primary) 6%, var(--k-paper)); }
.fsk-cu-new { flex: none; align-self: center; font-size: .72em; font-weight: 600; color: var(--k-primary); }

.fsk-cu-callout { display: flex; gap: 10px; align-items: flex-start; padding: 12px 14px; border-radius: var(--k-r-lg); --tone: var(--k-primary);
  background: color-mix(in srgb, var(--tone) 8%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--tone) 24%, var(--k-paper)); }
.fsk-cu-callout > .fsk-icon { color: var(--tone); margin-top: 2px; }
.fsk-cu-callout p { margin: 0; line-height: 1.55; white-space: pre-line; }
.fsk-cu-callout--success { --tone: var(--k-success); } .fsk-cu-callout--warning { --tone: var(--k-warning); } .fsk-cu-callout--error { --tone: var(--k-error); }

/* Footer */
.fsk-cu-foot { flex: none; border-top: 1px solid var(--k-divider); background: color-mix(in srgb, var(--k-paper) 94%, transparent);
  -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); box-shadow: 0 -10px 24px -20px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-cu-foot-in { max-width: 720px; margin: 0 auto; display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; padding: 12px 24px; }
.fsk-cu-foot-note { flex: 1; min-width: 180px; display: flex; flex-direction: column; gap: 2px; font-size: .86em; color: var(--k-text-2); }
.fsk-cu-foot-err { display: inline-flex; align-items: center; gap: 5px; color: var(--k-error); font-weight: 500; }
.fsk-cu-share { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cu-share[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-cu-share[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-cu-share[data-s="error"] { color: var(--k-error); }
.fsk-cu-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); animation: fsk-cu-pulse 1.1s ease-in-out infinite; }
.fsk-cu-btns { display: flex; gap: 8px; margin-left: auto; }

/* States in the panel */
.fsk-cu-center { flex: 1; display: grid; place-items: center; padding: 24px; }
.fsk-cu-center > div { width: 100%; max-width: 420px; }
.fsk-cu-skel-kv { display: flex; flex-direction: column; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); }
.fsk-cu-skel-kv > div { display: flex; align-items: center; gap: 24px; height: 42px; padding: 0 14px; }
.fsk-cu-skel-kv > div + div { border-top: 1px solid var(--k-divider); }

@keyframes fsk-cu-flash { 0%, 30% { background-color: var(--k-tint); } }
@keyframes fsk-cu-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-cu (max-width: 520px) {
  .fsk-cu-doc { padding: 18px 16px 24px; }
  .fsk-cu-foot-in { padding: 12px 16px; }
  .fsk-cu-kv > div { grid-template-columns: minmax(0, 1fr); gap: 0; padding: 8px 14px; }
}
@media (prefers-reduced-motion: reduce) { .fsk-cu-flash { animation: none; } }

/* Mobile card */
.fsk-cum .fsk-cu-kv { margin: 0 0 12px; font-size: .93em; }
.fsk-cum .fsk-cu-kv > div { min-height: 40px; padding: 6px 12px; }
.fsk-cum-prog { display: flex; align-items: center; gap: 12px; margin: 0 0 12px; font-size: .86em; color: var(--k-text-2); }
.fsk-cum-prog .fsk-cu-bar { max-width: none; }
.fsk-cum-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-cum-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cum-desk strong { display: block; font-weight: 600; }
.fsk-cum-desk span { color: var(--k-text-2); }
`;

/** The canvas state the agent reads and edits. Keep it under about 3 KB. */
export interface CustomCanvasState {
  /** The canvas header (setTitle, up to 80 characters). Default: title. */
  canvasTitle?: string;
  /** A small label above the title, e.g. "Migration plan". */
  eyebrow?: string;
  title: string;
  /** One or two lines under the title. */
  subtitle?: string;
  /** A status pill beside the eyebrow. */
  status?: CustomCanvasStatus;
  /** The body, top to bottom. Each block keeps its id when the agent edits it, so the canvas can mark the change. */
  blocks: CustomCanvasBlock[];
  /** Footer buttons. Their clicks go to actions.onAction(id); the last primary one is the main action. */
  buttons?: CustomCanvasButton[];
  /** A line in the footer, e.g. who decides what. */
  footnote?: string;
}

export interface CustomCanvasStatus {
  label: string;
  /** Default: neutral. */
  tone?: Tone;
}

export interface CustomCanvasBlock {
  /** Stable id. */
  id: string;
  /** heading, text (paragraphs), keyValue (label and value rows), checklist (items the user ticks), callout (a note with a tone). */
  type: "heading" | "text" | "keyValue" | "checklist" | "callout";
  /** heading, text and callout: the text. A blank line starts a paragraph. */
  text?: string;
  /** keyValue and checklist: the rows. */
  items?: CustomCanvasItem[];
  /** callout: info (default), success, warning or error. */
  tone?: "info" | "success" | "warning" | "error";
  /** text and keyValue: the user can edit it in place. Checklists are always tickable. */
  editable?: boolean;
}

export interface CustomCanvasItem {
  /** Stable id. */
  id: string;
  label: string;
  /** keyValue: the value. */
  value?: string;
  /** checklist: ticked. */
  done?: boolean;
  /** A muted line under the label or value. */
  hint?: string;
}

export interface CustomCanvasButton {
  /** What actions.onAction receives. */
  id: string;
  label: string;
  /** The filled button. Default: outlined. */
  primary?: boolean;
}

export interface CustomCanvasActions {
  /** A footer button was clicked. Return a state patch to apply and share (e.g. a new status). Throw to show why it failed. */
  onAction?(id: string, state: CustomCanvasState): Promise<Partial<CustomCanvasState> | void> | Partial<CustomCanvasState> | void;
  /** Called each time the state is shared with the agent (debounced). */
  onChange?(state: CustomCanvasState): void;
}

export interface CustomCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas: the in-page renderCanvas ctx or a hosted ctx.canvas. Its state wins over data. */
  canvas?: CanvasApi;
  data?: CustomCanvasState;
  actions?: CustomCanvasActions;
}

export interface CustomCanvasCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: CustomCanvasState;
  api?: CardApi;
}

export interface CustomCanvasStateProps extends StateProps {
  /** Desktop: the canvas, so the header shows the title. */
  canvas?: Pick<CanvasApi, "setTitle">;
}

const SHARE_DELAY_MS = 600;
const TONE_ICON: Record<string, IconName> = { info: "info", success: "check", warning: "alert", error: "alert" };
const TYPES = new Set(["heading", "text", "keyValue", "checklist", "callout"]);
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
let seq = 0;

/** Fills the gaps the agent may leave (no id, an unknown type), so the canvas never breaks. */
function normalize(raw: unknown): CustomCanvasState {
  const s = (raw ?? {}) as Partial<CustomCanvasState>;
  const blocks = (Array.isArray(s.blocks) ? s.blocks : []).filter((b) => b && TYPES.has(b.type)).map((b, i): CustomCanvasBlock => ({
    ...b, id: String(b.id ?? `b${i + 1}`),
    ...(b.text != null ? { text: String(b.text) } : {}),
    ...(Array.isArray(b.items) ? { items: b.items.map((it, j) => ({ ...it, id: String(it?.id ?? `${b.id ?? `b${i + 1}`}-${j + 1}`), label: String(it?.label ?? "") })) } : {}),
  }));
  return { ...s, title: String(s.title ?? ""), blocks };
}

/** Merges one block: what the agent changed (remote vs base) wins, what only the user changed (local vs base) stays. */
function mergeBlock(base: CustomCanvasBlock | undefined, local: CustomCanvasBlock | undefined, remote: CustomCanvasBlock): { block: CustomCanvasBlock; changed: boolean; added: string[] } {
  if (!base || !local) return { block: remote, changed: true, added: [] };
  if (same(base, remote)) return { block: local, changed: false, added: [] };
  const block: CustomCanvasBlock = { ...remote };
  if (remote.text === base.text && local.text !== base.text) block.text = local.text;
  const added: string[] = [];
  if (remote.items) {
    const bItems = new Map((base.items ?? []).map((x) => [x.id, x]));
    const lItems = new Map((local.items ?? []).map((x) => [x.id, x]));
    block.items = remote.items.map((r) => {
      const b = bItems.get(r.id), l = lItems.get(r.id);
      if (!b) { added.push(r.id); return r; }
      if (!l) return r;
      return { ...r, ...(r.done === b.done ? { done: l.done } : {}), ...(r.value === b.value ? { value: l.value } : {}) };
    });
  }
  return { block, changed: true, added };
}

type Share = "saved" | "pending" | "partial" | "error";

/**
 * Desktop canvas (OTHER, EDIT_MODE). Draws the blocks; the user ticks checklists and edits editable text and values.
 * The user's changes are shared 600 ms after they stop (setState({ blocks })); the agent's arrive through onStateChange,
 * merged per block and item, and marked until the user touches that block.
 */
export function mount({ root, head, canvas, data, actions }: CustomCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode() as Document | ShadowRoot;
  const n = ++seq;

  let shared = normalize(structuredClone(canvas?.state ?? data));
  let model = structuredClone(shared);
  const agentBlocks = new Set<string>();
  const newItems = new Set<string>();
  const blockEls = new Map<string, HTMLElement>();
  let timer = 0;
  let busy: string | null = null;
  let lastTitle = "";

  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const top = h("header", { class: "fsk-cu-top" });
  const list = h("div", { class: "fsk-cu-blocks" });
  const shareEl = h("span", { class: "fsk-cu-share" });
  const footErr = h("span", { class: "fsk-cu-foot-err", role: "alert", hidden: true });
  const footText = h("span");
  const btns = h("div", { class: "fsk-cu-btns" });

  // ---------- painting ----------
  function paintTop(): void {
    const t = (model.canvasTitle ?? model.title).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
    top.replaceChildren(h("div", {},
      h("div", { class: "fsk-cu-eyebrow" },
        h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), model.eyebrow ?? "Canvas"),
        model.status && pill(model.status.label, model.status.tone ?? "neutral")),
      h("h2", { class: "fsk-cu-title", id: `fsk-cu${n}-t` }, model.title),
      model.subtitle && h("p", { class: "fsk-cu-sub" }, model.subtitle)));
  }

  function paintFoot(): void {
    footText.textContent = model.footnote ?? "";
    footText.hidden = !model.footnote;
    btns.replaceChildren(...(model.buttons ?? []).map((b) => h("button", {
      class: `fsk-btn ${b.primary ? "fsk-btn--primary" : "fsk-btn--ghost"}`, type: "button", disabled: !!busy || !actions?.onAction,
      "aria-busy": busy === b.id ? "true" : null, onclick: () => void press(b),
    }, busy === b.id ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), b.label] : b.label)));
  }

  function paintShare(s: Share): void {
    shareEl.dataset.s = s;
    shareEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-cu-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 12), "Too large: the agent sees part of it"]
      : s === "error" ? [icon("alert", 12), "Not shared. Change something to retry."]
      : [icon("check", 12), "The agent sees your changes"]));
  }

  function blockEl(b: CustomCanvasBlock): HTMLElement {
    const mark = agentBlocks.has(b.id) ? h("span", { class: "fsk-cu-mark" }, icon("sparkle", 11), "Updated by the agent") : null;
    let body: HTMLElement;
    if (b.type === "heading") body = h("h3", { class: "fsk-cu-h" }, b.text ?? "");
    else if (b.type === "callout") {
      const tone = b.tone ?? "info";
      body = h("div", { class: `fsk-cu-callout fsk-cu-callout--${tone}`, role: tone === "error" || tone === "warning" ? "note" : null },
        icon(TONE_ICON[tone] ?? "info", 16), h("p", {}, h("span", { class: "fsk-sr" }, `${tone === "info" ? "Note" : tone[0].toUpperCase() + tone.slice(1)}: `), b.text ?? ""));
    } else if (b.type === "text") {
      if (b.editable) {
        const prevHeading = model.blocks[model.blocks.indexOf(b) - 1];
        const ta = h<HTMLTextAreaElement>("textarea", { class: "fsk-cu-field", rows: 3, "data-block": b.id,
          "aria-label": prevHeading?.type === "heading" ? prevHeading.text ?? "Text" : "Text", placeholder: "Write here, or ask the agent" });
        ta.value = b.text ?? "";
        body = ta;
      } else body = h("p", { class: "fsk-cu-text" }, b.text ?? "");
    } else if (b.type === "keyValue") {
      body = h("dl", { class: "fsk-cu-kv" }, (b.items ?? []).map((it) => {
        const id = `fsk-cu${n}-${b.id}-${it.id}`;
        return h("div", {},
          h("dt", {}, b.editable ? h("label", { for: id }, it.label) : it.label),
          h("dd", {}, b.editable
            ? h<HTMLInputElement>("input", { class: "fsk-cu-input", id, value: it.value ?? "", "data-block": b.id, "data-item": it.id, autocomplete: "off", placeholder: "Not set" })
            : it.value || h("span", { class: "fsk-cu-ph" }, "Not set"),
          it.hint && h("small", {}, it.hint)));
      }));
    } else {
      const items = b.items ?? [];
      const done = items.filter((x) => x.done).length;
      const pct = items.length ? Math.round((done / items.length) * 100) : 0;
      body = h("div", {},
        h("div", { class: "fsk-cu-check-head" },
          h("span", { class: "fsk-num" }, `${done} of ${items.length} done`),
          h("span", { class: "fsk-cu-bar", role: "progressbar", "aria-label": "Checklist progress", "aria-valuemin": 0, "aria-valuemax": items.length, "aria-valuenow": done },
            h("span", { style: { width: `${pct}%` } }))),
        h("ul", { class: "fsk-cu-list" }, items.map((it) => {
          const id = `fsk-cu${n}-${b.id}-${it.id}`;
          const fresh = newItems.has(`${b.id}\n${it.id}`);
          return h("li", {}, h("label", { class: "fsk-cu-item", for: id, "data-done": it.done ? "" : null, "data-new": fresh ? "" : null },
            h("input", { type: "checkbox", id, checked: !!it.done, "data-block": b.id, "data-item": it.id, "aria-describedby": it.hint ? `${id}-h` : null }),
            h("span", { class: "fsk-cu-item-text" }, h("b", {}, it.label), it.hint && h("small", { id: `${id}-h` }, it.hint)),
            fresh && h("span", { class: "fsk-cu-new" }, "New")));
        })));
    }
    const el = h("section", { class: "fsk-cu-block", "data-id": b.id, "data-agent": agentBlocks.has(b.id) ? "" : null }, mark, body);
    blockEls.set(b.id, el);
    return el;
  }

  /** Redraws blocks; keeps focus and the caret in the field the user is in. */
  function paintBlocks(flash: string[] = []): void {
    const active = rootNode.activeElement;
    const keep = active instanceof HTMLElement && list.contains(active)
      ? { block: active.dataset.block, item: active.dataset.item, tag: active.tagName, sel: active instanceof HTMLTextAreaElement || active instanceof HTMLInputElement ? [active.selectionStart, active.selectionEnd] : null }
      : null;
    blockEls.clear();
    list.replaceChildren(...model.blocks.map(blockEl));
    if (keep) {
      const sel = `${keep.tag.toLowerCase()}[data-block="${keep.block}"]${keep.item ? `[data-item="${keep.item}"]` : ""}`;
      const el = list.querySelector<HTMLElement>(sel);
      el?.focus({ preventScroll: true });
      if (keep.sel && (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) && el.type !== "checkbox") {
        try { el.setSelectionRange(keep.sel[0], keep.sel[1]); } catch { /* not a text field */ }
      }
    }
    if (!reduce) for (const id of flash) blockEls.get(id)?.classList.add("fsk-cu-flash");
  }

  // ---------- the user's changes ----------
  const findBlock = (id: string | undefined): CustomCanvasBlock | undefined => model.blocks.find((b) => b.id === id);

  function touch(blockId: string): void {
    if (!agentBlocks.delete(blockId)) return;
    const el = blockEls.get(blockId);
    el?.removeAttribute("data-agent");
    el?.querySelector(".fsk-cu-mark")?.remove();
    for (const k of [...newItems]) if (k.startsWith(`${blockId}\n`)) newItems.delete(k);
    el?.querySelectorAll("[data-new]").forEach((x) => x.removeAttribute("data-new"));
    el?.querySelectorAll(".fsk-cu-new").forEach((x) => x.remove());
  }

  function onInput(e: Event): void {
    const t = e.target;
    if (!(t instanceof HTMLTextAreaElement || t instanceof HTMLInputElement) || t.type === "checkbox") return;
    const b = findBlock(t.dataset.block);
    if (!b) return;
    if (t.dataset.item) { const it = b.items?.find((x) => x.id === t.dataset.item); if (it) it.value = t.value; }
    else b.text = t.value;
    touch(b.id);
    later();
  }

  function onChange(e: Event): void {
    const t = e.target;
    if (!(t instanceof HTMLInputElement) || t.type !== "checkbox") return;
    const b = findBlock(t.dataset.block);
    const it = b?.items?.find((x) => x.id === t.dataset.item);
    if (!b || !it) return;
    it.done = t.checked;
    touch(b.id);
    paintBlocks();
    const done = (b.items ?? []).filter((x) => x.done).length;
    live.textContent = `${it.label}: ${it.done ? "done" : "not done"}. ${done} of ${b.items?.length ?? 0} done.`;
    later();
  }

  // ---------- sharing ----------
  function later(): void {
    paintShare("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush(): void {
    win.clearTimeout(timer);
    timer = 0;
    if (same(model.blocks, shared.blocks)) { paintShare("saved"); return; }
    const before = shared;
    shared = { ...shared, blocks: structuredClone(model.blocks) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.({ blocks: structuredClone(model.blocks) }), (out) => {
      if (out?.ok === false) { shared = before; paintShare("error"); return; }
      paintShare(out?.notSent?.length ? "partial" : "saved");
    });
    actions?.onChange?.(structuredClone(model));
  }

  /** The agent's edit: blocks it changed win, blocks and items only the user changed (not shared yet) stay. */
  function applyRemote(next: Record<string, any>): void {
    const remote = normalize(structuredClone(next));
    const base = new Map(shared.blocks.map((b) => [b.id, b]));
    const local = new Map(model.blocks.map((b) => [b.id, b]));
    const changed: string[] = [];
    const blocks = remote.blocks.map((r) => {
      const m = mergeBlock(base.get(r.id), local.get(r.id), r);
      if (m.changed) { changed.push(r.id); agentBlocks.add(r.id); m.added.forEach((id) => newItems.add(`${r.id}\n${id}`)); }
      return m.block;
    });
    // blocks the user added since the last share don't exist: users only edit blocks in place
    model = { ...remote, blocks };
    shared = remote;
    paintTop();
    paintFoot();
    paintBlocks(changed);
    if (changed.length) live.textContent = `The agent updated ${changed.length === 1 ? "a section" : `${changed.length} sections`}.`;
    if (!same(model.blocks, shared.blocks)) later(); else paintShare("saved");
  }

  // ---------- buttons ----------
  async function press(b: CustomCanvasButton): Promise<void> {
    if (!actions?.onAction || busy) return;
    flush(); // the agent sees what the button acts on
    busy = b.id;
    footErr.hidden = true;
    paintFoot();
    try {
      const patch = await actions.onAction(b.id, structuredClone(model));
      busy = null;
      if (patch && Object.keys(patch).length) {
        model = normalize({ ...model, ...patch });
        shared = normalize({ ...shared, ...patch });
        canvas?.setState?.(structuredClone(patch));
        paintTop();
        paintBlocks();
      }
      paintFoot();
      live.textContent = `${b.label}: done.`;
    } catch (err) {
      busy = null;
      paintFoot();
      footErr.replaceChildren(icon("alert", 13), (err instanceof Error && err.message) || `${b.label} didn't work. Nothing changed. Try again.`);
      footErr.hidden = false;
    }
  }

  // ---------- draw ----------
  root.replaceChildren(h("div", { class: "fsk fsk-cu" },
    h("div", { class: "fsk-cu-main" },
      h("article", { class: "fsk-cu-doc", "aria-labelledby": `fsk-cu${n}-t`, oninput: onInput, onchange: onChange, onfocusout: () => { if (timer) flush(); } },
        top, list)),
    h("footer", { class: "fsk-cu-foot" }, h("div", { class: "fsk-cu-foot-in" },
      h("div", { class: "fsk-cu-foot-note" }, footText, footErr, shareEl), btns)),
    live));
  paintTop();
  paintBlocks();
  paintFoot();
  paintShare("saved");
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (timer) flush(); // closing keeps the state: share the last change
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with the first key values, checklist progress, the first warning and the way to desktop. */
export function mountMobile({ root, head, data, api }: CustomCanvasCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  const s = normalize(structuredClone(data));
  const kv = s.blocks.find((b) => b.type === "keyValue");
  const checks = s.blocks.filter((b) => b.type === "checklist").flatMap((b) => b.items ?? []);
  const done = checks.filter((x) => x.done).length;
  const callout = s.blocks.find((b) => b.type === "callout" && (b.tone === "warning" || b.tone === "error"));
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cum", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("doc", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title),
        s.eyebrow && h("p", { class: "fsk-sub" }, s.eyebrow)),
      s.status && h("span", { style: { marginLeft: "auto", alignSelf: "flex-start" } }, pill(s.status.label, s.status.tone ?? "neutral"))),
    kv && h("dl", { class: "fsk-cu-kv" }, (kv.items ?? []).slice(0, 4).map((it) => h("div", {}, h("dt", {}, it.label), h("dd", {}, it.value || "Not set")))),
    checks.length > 0 && h("div", { class: "fsk-cum-prog" },
      h("span", { class: "fsk-num" }, `${done} of ${checks.length} steps done`),
      h("span", { class: "fsk-cu-bar", role: "progressbar", "aria-label": "Checklist progress", "aria-valuemin": 0, "aria-valuemax": checks.length, "aria-valuenow": done },
        h("span", { style: { width: `${Math.round((done / checks.length) * 100)}%` } }))),
    callout && h("div", { class: `fsk-cu-callout fsk-cu-callout--${callout.tone}`, style: { fontSize: ".93em" } }, icon("alert", 16),
      h("p", {}, h("span", { class: "fsk-sr" }, "Warning: "), callout.text ?? "")),
    h("p", { class: "fsk-cum-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Open on desktop"), "The full canvas opens beside the chat on a larger screen, where you can edit it with the agent."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this canvas draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton of the title and blocks,
 * or the message centered in the panel. Mobile: the card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }: CustomCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-cum", icon: "doc", title, subtitle, surface, skeleton: () => h("div", { class: "fsk-cu-skel-kv" },
      [0, 1, 2, 3].map((i) => h("div", {}, bone("28%", "9px", { i }), bone(`${[44, 36, 52, 30][i]}%`, "10px", { i })))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  let dispose = (): void => {};
  let body: HTMLElement;
  if (state.kind === "loading") {
    body = h("div", { class: "fsk-cu-main", "aria-hidden": "true" }, h("div", { class: "fsk-cu-doc" },
      h("div", { class: "fsk-cu-top" }, h("div", {},
        h("div", { class: "fsk-cu-eyebrow" }, bone("92px", "20px", { cls: "fsk-bone--box" })),
        title ? h("h2", { class: "fsk-cu-title" }, title) : h("div", { style: { margin: "12px 0 8px" } }, bone("46%", "18px")),
        bone("64%", "10px"))),
      h("div", { class: "fsk-cu-blocks" },
        h("div", { class: "fsk-cu-skel-kv" }, [0, 1, 2, 3].map((i) => h("div", {}, bone("22%", "9px", { i }), bone(`${[38, 30, 46, 26][i]}%`, "10px", { i })))),
        h("div", { style: { marginTop: "10px" } }, bone("30%", "12px", { i: 2 })),
        skeletonLines(3),
        h("div", { class: "fsk-cu-skel-kv" }, [0, 1, 2].map((i) => h("div", {}, bone("18px", "18px", { cls: "fsk-bone--box", i }), bone(`${[52, 40, 60][i]}%`, "10px", { i })))))));
  } else {
    let block: HTMLElement;
    if (state.kind === "empty") block = emptyBlock({ icon: "doc", ...state }, surface);
    else { const e = errorBlock(state, surface); dispose = e.dispose; block = e.el; }
    body = h("div", { class: "fsk-cu-center" }, h("div", {}, block));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-cu fsk-cu-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    body,
    loading && h("div", { class: "fsk-cu-foot", "aria-hidden": "true" }, h("div", { class: "fsk-cu-foot-in" },
      h("div", { class: "fsk-cu-foot-note" }, bone("50%", "10px")), h("div", { class: "fsk-cu-btns" }, bone("88px", "36px", { cls: "fsk-bone--box" }), bone("120px", "36px", { cls: "fsk-bone--box" }))))));
  return () => { dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, CustomCanvasState> = {
  default: {
    canvasTitle: "Region move plan",
    eyebrow: "Migration plan",
    title: "Move the EU workspace to Frankfurt",
    subtitle: "A one-hour, read-only window. I drafted the plan from your workspace settings; change anything, or ask me to.",
    status: { label: "Draft", tone: "warning" },
    blocks: [
      { id: "facts", type: "keyValue", editable: true, items: [
        { id: "from", label: "From", value: "Dublin (eu-west)" },
        { id: "to", label: "To", value: "Frankfurt (eu-central)" },
        { id: "users", label: "Users affected", value: "214 people in 6 teams" },
        { id: "window", label: "Window", value: "", hint: "Pick a low-traffic hour" },
      ] },
      { id: "h-before", type: "heading", text: "Before the window" },
      { id: "steps", type: "checklist", items: [
        { id: "export", label: "Export the audit log", hint: "Kept for 90 days after the move", done: true },
        { id: "notify", label: "Tell workspace admins about the read-only hour" },
        { id: "pause", label: "Pause scheduled reports" },
        { id: "sso", label: "Check the SSO redirect URLs" },
      ] },
      { id: "risk", type: "callout", tone: "warning", text: "Scheduled reports pause during the window. Recipients don't get a copy of a report that was due in that hour." },
      { id: "h-notes", type: "heading", text: "Notes for the admins" },
      { id: "notes", type: "text", editable: true, text: "The workspace stays readable during the move. Anything saved in the hour before it starts is moved with it." },
    ],
    buttons: [{ id: "export", label: "Export plan" }, { id: "ready", label: "Mark as ready", primary: true }],
    footnote: "The agent drafts and updates the plan. You decide when it's ready.",
  },
};
```

```js title="agent/ui/custom-canvas.js"
// Template: custom-canvas. A generic canvas (type OTHER) drawn from simple blocks, as a starting point to adapt (desktop), plus its mobile card.

export const meta = {
  id: "custom-canvas",
  title: "Custom canvas",
  surface: "canvas",
  canvasType: "OTHER",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "None of the typed canvases fits: a plan, a brief, a runbook or a review the user and the agent shape together from headings, text, key values, checklists and callouts. The SDK adds no rule for OTHER, so your action's own prompt must say what the agent may change and what it must leave alone.",
  whenNotToUse: "The content is a form, a table, a document, code or a report: use that canvas, whose type tells the agent how to behave. A one-off answer (a chat card). Mobile: the canvas isn't available; use the card (mountMobile).",
};

const CSS = `
.fsk-cu { container: fsk-cu / inline-size; height: 100%; min-height: 440px; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-cu-main { flex: 1; min-height: 0; overflow: auto; }
.fsk-cu-doc { max-width: 720px; margin: 0 auto; padding: 22px 24px 32px; }
.fsk-cu-top { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 18px; }
.fsk-cu-top > div { flex: 1; min-width: 0; }
.fsk-cu-eyebrow { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.fsk-cu-title { margin: 10px 0 4px; font-size: 1.45em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.22; }
.fsk-cu-sub { margin: 0; color: var(--k-text-2); max-width: 62ch; }
.fsk-cu-blocks { display: flex; flex-direction: column; gap: 14px; }

.fsk-cu-block { position: relative; border-radius: var(--k-r-lg); transition: background-color .2s; }
.fsk-cu-block[data-agent]::before { content: ""; position: absolute; left: -12px; top: 4px; bottom: 4px; width: 3px; border-radius: 3px; background: var(--k-primary); }
.fsk-cu-mark { display: inline-flex; align-items: center; gap: 4px; margin: 0 0 6px; padding: 1px 8px 1px 6px; border-radius: 999px; font-size: .72em; font-weight: 600; line-height: 1.5;
  color: var(--k-primary); background: var(--k-tint); animation: fsk-in .3s var(--k-ease) both; }
.fsk-cu-flash { animation: fsk-cu-flash 2.4s var(--k-ease); }

.fsk-cu-h { margin: 12px 0 -4px; font-size: 1.05em; font-weight: 600; letter-spacing: -0.01em; line-height: 1.35; }
.fsk-cu-block:first-child .fsk-cu-h { margin-top: 0; }
.fsk-cu-text { margin: 0; white-space: pre-line; line-height: 1.6; }
.fsk-cu-field { display: block; width: 100%; min-height: 3lh; margin: 0; padding: 10px 12px; font: inherit; line-height: 1.6; color: var(--k-text); resize: vertical;
  background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-md); field-sizing: content; transition: border-color .15s, box-shadow .15s; }
.fsk-cu-field::placeholder, .fsk-cu-input::placeholder { color: var(--k-text-2); opacity: 1; }
.fsk-cu-field:hover, .fsk-cu-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-cu-field:focus, .fsk-cu-input:focus { outline: none; border-color: var(--k-primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 20%, transparent); }

.fsk-cu-kv { display: grid; grid-template-columns: minmax(0, 1fr); margin: 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); overflow: hidden; }
.fsk-cu-kv > div { display: grid; grid-template-columns: minmax(110px, 34%) minmax(0, 1fr); align-items: center; gap: 12px; min-height: 42px; padding: 6px 14px; }
.fsk-cu-kv > div + div { border-top: 1px solid var(--k-divider); }
.fsk-cu-kv dt { color: var(--k-text-2); font-size: .93em; }
.fsk-cu-kv dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-cu-ph { color: var(--k-text-2); font-weight: 400; font-style: italic; }
.fsk-cu-kv dd small { display: block; font-weight: 400; color: var(--k-text-2); font-size: .86em; }
.fsk-cu-input { width: 100%; min-height: 32px; margin: 0 -9px; width: calc(100% + 18px); padding: 4px 8px; font: inherit; font-weight: 500; color: var(--k-text);
  background: transparent; border: 1px solid transparent; border-radius: var(--k-r-md); transition: border-color .15s, box-shadow .15s, background .15s; }
.fsk-cu-input:hover { border-color: var(--k-border); }
.fsk-cu-input:not(:focus) { background: var(--k-sunken); }

.fsk-cu-check-head { display: flex; align-items: center; gap: 10px; margin: 0 0 6px; font-size: .86em; color: var(--k-text-2); }
.fsk-cu-bar { flex: 1; max-width: 160px; height: 5px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-cu-bar > span { display: block; height: 100%; border-radius: inherit; background: var(--k-success); transition: width .4s var(--k-ease); }
.fsk-cu-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); overflow: hidden; }
.fsk-cu-list li + li { border-top: 1px solid var(--k-divider); }
.fsk-cu-item { display: flex; align-items: flex-start; gap: 12px; padding: 11px 14px; cursor: pointer; transition: background .15s; }
.fsk-cu-item:hover { background: var(--k-sunken); }
.fsk-cu-item input { appearance: none; flex: none; display: grid; place-items: center; width: 18px; height: 18px; margin: 1px 0 0; cursor: pointer;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); border-radius: max(4px, calc(var(--k-r) * .8)); background: var(--k-paper); transition: background .15s, border-color .15s; }
.fsk-cu-item input:checked { background: var(--k-success); border-color: var(--k-success); }
.fsk-cu-item input:checked::after { content: ""; width: 4px; height: 9px; margin-top: -2px; border: solid var(--k-paper); border-width: 0 2px 2px 0; transform: rotate(45deg); }
.fsk-cu-item input:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-cu-item-text { flex: 1; min-width: 0; }
.fsk-cu-item-text b { display: block; font-weight: 500; }
.fsk-cu-item-text small { display: block; margin-top: 1px; color: var(--k-text-2); font-size: .86em; }
.fsk-cu-item[data-done] b { color: var(--k-text-2); text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 55%, transparent); }
.fsk-cu-item[data-new] { background: color-mix(in srgb, var(--k-primary) 6%, var(--k-paper)); }
.fsk-cu-new { flex: none; align-self: center; font-size: .72em; font-weight: 600; color: var(--k-primary); }

.fsk-cu-callout { display: flex; gap: 10px; align-items: flex-start; padding: 12px 14px; border-radius: var(--k-r-lg); --tone: var(--k-primary);
  background: color-mix(in srgb, var(--tone) 8%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--tone) 24%, var(--k-paper)); }
.fsk-cu-callout > .fsk-icon { color: var(--tone); margin-top: 2px; }
.fsk-cu-callout p { margin: 0; line-height: 1.55; white-space: pre-line; }
.fsk-cu-callout--success { --tone: var(--k-success); } .fsk-cu-callout--warning { --tone: var(--k-warning); } .fsk-cu-callout--error { --tone: var(--k-error); }

/* Footer */
.fsk-cu-foot { flex: none; border-top: 1px solid var(--k-divider); background: color-mix(in srgb, var(--k-paper) 94%, transparent);
  -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); box-shadow: 0 -10px 24px -20px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-cu-foot-in { max-width: 720px; margin: 0 auto; display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; padding: 12px 24px; }
.fsk-cu-foot-note { flex: 1; min-width: 180px; display: flex; flex-direction: column; gap: 2px; font-size: .86em; color: var(--k-text-2); }
.fsk-cu-foot-err { display: inline-flex; align-items: center; gap: 5px; color: var(--k-error); font-weight: 500; }
.fsk-cu-share { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cu-share[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-cu-share[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-cu-share[data-s="error"] { color: var(--k-error); }
.fsk-cu-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); animation: fsk-cu-pulse 1.1s ease-in-out infinite; }
.fsk-cu-btns { display: flex; gap: 8px; margin-left: auto; }

/* States in the panel */
.fsk-cu-center { flex: 1; display: grid; place-items: center; padding: 24px; }
.fsk-cu-center > div { width: 100%; max-width: 420px; }
.fsk-cu-skel-kv { display: flex; flex-direction: column; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); }
.fsk-cu-skel-kv > div { display: flex; align-items: center; gap: 24px; height: 42px; padding: 0 14px; }
.fsk-cu-skel-kv > div + div { border-top: 1px solid var(--k-divider); }

@keyframes fsk-cu-flash { 0%, 30% { background-color: var(--k-tint); } }
@keyframes fsk-cu-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-cu (max-width: 520px) {
  .fsk-cu-doc { padding: 18px 16px 24px; }
  .fsk-cu-foot-in { padding: 12px 16px; }
  .fsk-cu-kv > div { grid-template-columns: minmax(0, 1fr); gap: 0; padding: 8px 14px; }
}
@media (prefers-reduced-motion: reduce) { .fsk-cu-flash { animation: none; } }

/* Mobile card */
.fsk-cum .fsk-cu-kv { margin: 0 0 12px; font-size: .93em; }
.fsk-cum .fsk-cu-kv > div { min-height: 40px; padding: 6px 12px; }
.fsk-cum-prog { display: flex; align-items: center; gap: 12px; margin: 0 0 12px; font-size: .86em; color: var(--k-text-2); }
.fsk-cum-prog .fsk-cu-bar { max-width: none; }
.fsk-cum-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-cum-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cum-desk strong { display: block; font-weight: 600; }
.fsk-cum-desk span { color: var(--k-text-2); }
`;

const SHARE_DELAY_MS = 600;
const TONE_ICON = { info: "info", success: "check", warning: "alert", error: "alert" };
const TYPES = new Set(["heading", "text", "keyValue", "checklist", "callout"]);
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
let seq = 0;

/** Fills the gaps the agent may leave (no id, an unknown type), so the canvas never breaks. */
function normalize(raw) {
  const s = (raw ?? {});
  const blocks = (Array.isArray(s.blocks) ? s.blocks : []).filter((b) => b && TYPES.has(b.type)).map((b, i) => ({
    ...b, id: String(b.id ?? `b${i + 1}`),
    ...(b.text != null ? { text: String(b.text) } : {}),
    ...(Array.isArray(b.items) ? { items: b.items.map((it, j) => ({ ...it, id: String(it?.id ?? `${b.id ?? `b${i + 1}`}-${j + 1}`), label: String(it?.label ?? "") })) } : {}),
  }));
  return { ...s, title: String(s.title ?? ""), blocks };
}

/** Merges one block: what the agent changed (remote vs base) wins, what only the user changed (local vs base) stays. */
function mergeBlock(base, local, remote) {
  if (!base || !local) return { block: remote, changed: true, added: [] };
  if (same(base, remote)) return { block: local, changed: false, added: [] };
  const block = { ...remote };
  if (remote.text === base.text && local.text !== base.text) block.text = local.text;
  const added = [];
  if (remote.items) {
    const bItems = new Map((base.items ?? []).map((x) => [x.id, x]));
    const lItems = new Map((local.items ?? []).map((x) => [x.id, x]));
    block.items = remote.items.map((r) => {
      const b = bItems.get(r.id), l = lItems.get(r.id);
      if (!b) { added.push(r.id); return r; }
      if (!l) return r;
      return { ...r, ...(r.done === b.done ? { done: l.done } : {}), ...(r.value === b.value ? { value: l.value } : {}) };
    });
  }
  return { block, changed: true, added };
}

/**
 * Desktop canvas (OTHER, EDIT_MODE). Draws the blocks; the user ticks checklists and edits editable text and values.
 * The user's changes are shared 600 ms after they stop (setState({ blocks })); the agent's arrive through onStateChange,
 * merged per block and item, and marked until the user touches that block.
 */
export function mount({ root, head, canvas, data, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode();
  const n = ++seq;

  let shared = normalize(structuredClone(canvas?.state ?? data));
  let model = structuredClone(shared);
  const agentBlocks = new Set();
  const newItems = new Set();
  const blockEls = new Map();
  let timer = 0;
  let busy = null;
  let lastTitle = "";

  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const top = h("header", { class: "fsk-cu-top" });
  const list = h("div", { class: "fsk-cu-blocks" });
  const shareEl = h("span", { class: "fsk-cu-share" });
  const footErr = h("span", { class: "fsk-cu-foot-err", role: "alert", hidden: true });
  const footText = h("span");
  const btns = h("div", { class: "fsk-cu-btns" });

  // ---------- painting ----------
  function paintTop() {
    const t = (model.canvasTitle ?? model.title).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
    top.replaceChildren(h("div", {},
      h("div", { class: "fsk-cu-eyebrow" },
        h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), model.eyebrow ?? "Canvas"),
        model.status && pill(model.status.label, model.status.tone ?? "neutral")),
      h("h2", { class: "fsk-cu-title", id: `fsk-cu${n}-t` }, model.title),
      model.subtitle && h("p", { class: "fsk-cu-sub" }, model.subtitle)));
  }

  function paintFoot() {
    footText.textContent = model.footnote ?? "";
    footText.hidden = !model.footnote;
    btns.replaceChildren(...(model.buttons ?? []).map((b) => h("button", {
      class: `fsk-btn ${b.primary ? "fsk-btn--primary" : "fsk-btn--ghost"}`, type: "button", disabled: !!busy || !actions?.onAction,
      "aria-busy": busy === b.id ? "true" : null, onclick: () => void press(b),
    }, busy === b.id ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), b.label] : b.label)));
  }

  function paintShare(s) {
    shareEl.dataset.s = s;
    shareEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-cu-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 12), "Too large: the agent sees part of it"]
      : s === "error" ? [icon("alert", 12), "Not shared. Change something to retry."]
      : [icon("check", 12), "The agent sees your changes"]));
  }

  function blockEl(b) {
    const mark = agentBlocks.has(b.id) ? h("span", { class: "fsk-cu-mark" }, icon("sparkle", 11), "Updated by the agent") : null;
    let body;
    if (b.type === "heading") body = h("h3", { class: "fsk-cu-h" }, b.text ?? "");
    else if (b.type === "callout") {
      const tone = b.tone ?? "info";
      body = h("div", { class: `fsk-cu-callout fsk-cu-callout--${tone}`, role: tone === "error" || tone === "warning" ? "note" : null },
        icon(TONE_ICON[tone] ?? "info", 16), h("p", {}, h("span", { class: "fsk-sr" }, `${tone === "info" ? "Note" : tone[0].toUpperCase() + tone.slice(1)}: `), b.text ?? ""));
    } else if (b.type === "text") {
      if (b.editable) {
        const prevHeading = model.blocks[model.blocks.indexOf(b) - 1];
        const ta = h("textarea", { class: "fsk-cu-field", rows: 3, "data-block": b.id,
          "aria-label": prevHeading?.type === "heading" ? prevHeading.text ?? "Text" : "Text", placeholder: "Write here, or ask the agent" });
        ta.value = b.text ?? "";
        body = ta;
      } else body = h("p", { class: "fsk-cu-text" }, b.text ?? "");
    } else if (b.type === "keyValue") {
      body = h("dl", { class: "fsk-cu-kv" }, (b.items ?? []).map((it) => {
        const id = `fsk-cu${n}-${b.id}-${it.id}`;
        return h("div", {},
          h("dt", {}, b.editable ? h("label", { for: id }, it.label) : it.label),
          h("dd", {}, b.editable
            ? h("input", { class: "fsk-cu-input", id, value: it.value ?? "", "data-block": b.id, "data-item": it.id, autocomplete: "off", placeholder: "Not set" })
            : it.value || h("span", { class: "fsk-cu-ph" }, "Not set"),
          it.hint && h("small", {}, it.hint)));
      }));
    } else {
      const items = b.items ?? [];
      const done = items.filter((x) => x.done).length;
      const pct = items.length ? Math.round((done / items.length) * 100) : 0;
      body = h("div", {},
        h("div", { class: "fsk-cu-check-head" },
          h("span", { class: "fsk-num" }, `${done} of ${items.length} done`),
          h("span", { class: "fsk-cu-bar", role: "progressbar", "aria-label": "Checklist progress", "aria-valuemin": 0, "aria-valuemax": items.length, "aria-valuenow": done },
            h("span", { style: { width: `${pct}%` } }))),
        h("ul", { class: "fsk-cu-list" }, items.map((it) => {
          const id = `fsk-cu${n}-${b.id}-${it.id}`;
          const fresh = newItems.has(`${b.id}\n${it.id}`);
          return h("li", {}, h("label", { class: "fsk-cu-item", for: id, "data-done": it.done ? "" : null, "data-new": fresh ? "" : null },
            h("input", { type: "checkbox", id, checked: !!it.done, "data-block": b.id, "data-item": it.id, "aria-describedby": it.hint ? `${id}-h` : null }),
            h("span", { class: "fsk-cu-item-text" }, h("b", {}, it.label), it.hint && h("small", { id: `${id}-h` }, it.hint)),
            fresh && h("span", { class: "fsk-cu-new" }, "New")));
        })));
    }
    const el = h("section", { class: "fsk-cu-block", "data-id": b.id, "data-agent": agentBlocks.has(b.id) ? "" : null }, mark, body);
    blockEls.set(b.id, el);
    return el;
  }

  /** Redraws blocks; keeps focus and the caret in the field the user is in. */
  function paintBlocks(flash = []) {
    const active = rootNode.activeElement;
    const keep = active instanceof HTMLElement && list.contains(active)
      ? { block: active.dataset.block, item: active.dataset.item, tag: active.tagName, sel: active instanceof HTMLTextAreaElement || active instanceof HTMLInputElement ? [active.selectionStart, active.selectionEnd] : null }
      : null;
    blockEls.clear();
    list.replaceChildren(...model.blocks.map(blockEl));
    if (keep) {
      const sel = `${keep.tag.toLowerCase()}[data-block="${keep.block}"]${keep.item ? `[data-item="${keep.item}"]` : ""}`;
      const el = list.querySelector(sel);
      el?.focus({ preventScroll: true });
      if (keep.sel && (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) && el.type !== "checkbox") {
        try { el.setSelectionRange(keep.sel[0], keep.sel[1]); } catch { /* not a text field */ }
      }
    }
    if (!reduce) for (const id of flash) blockEls.get(id)?.classList.add("fsk-cu-flash");
  }

  // ---------- the user's changes ----------
  const findBlock = (id) => model.blocks.find((b) => b.id === id);

  function touch(blockId) {
    if (!agentBlocks.delete(blockId)) return;
    const el = blockEls.get(blockId);
    el?.removeAttribute("data-agent");
    el?.querySelector(".fsk-cu-mark")?.remove();
    for (const k of [...newItems]) if (k.startsWith(`${blockId}\n`)) newItems.delete(k);
    el?.querySelectorAll("[data-new]").forEach((x) => x.removeAttribute("data-new"));
    el?.querySelectorAll(".fsk-cu-new").forEach((x) => x.remove());
  }

  function onInput(e) {
    const t = e.target;
    if (!(t instanceof HTMLTextAreaElement || t instanceof HTMLInputElement) || t.type === "checkbox") return;
    const b = findBlock(t.dataset.block);
    if (!b) return;
    if (t.dataset.item) { const it = b.items?.find((x) => x.id === t.dataset.item); if (it) it.value = t.value; }
    else b.text = t.value;
    touch(b.id);
    later();
  }

  function onChange(e) {
    const t = e.target;
    if (!(t instanceof HTMLInputElement) || t.type !== "checkbox") return;
    const b = findBlock(t.dataset.block);
    const it = b?.items?.find((x) => x.id === t.dataset.item);
    if (!b || !it) return;
    it.done = t.checked;
    touch(b.id);
    paintBlocks();
    const done = (b.items ?? []).filter((x) => x.done).length;
    live.textContent = `${it.label}: ${it.done ? "done" : "not done"}. ${done} of ${b.items?.length ?? 0} done.`;
    later();
  }

  // ---------- sharing ----------
  function later() {
    paintShare("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush() {
    win.clearTimeout(timer);
    timer = 0;
    if (same(model.blocks, shared.blocks)) { paintShare("saved"); return; }
    const before = shared;
    shared = { ...shared, blocks: structuredClone(model.blocks) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.({ blocks: structuredClone(model.blocks) }), (out) => {
      if (out?.ok === false) { shared = before; paintShare("error"); return; }
      paintShare(out?.notSent?.length ? "partial" : "saved");
    });
    actions?.onChange?.(structuredClone(model));
  }

  /** The agent's edit: blocks it changed win, blocks and items only the user changed (not shared yet) stay. */
  function applyRemote(next) {
    const remote = normalize(structuredClone(next));
    const base = new Map(shared.blocks.map((b) => [b.id, b]));
    const local = new Map(model.blocks.map((b) => [b.id, b]));
    const changed = [];
    const blocks = remote.blocks.map((r) => {
      const m = mergeBlock(base.get(r.id), local.get(r.id), r);
      if (m.changed) { changed.push(r.id); agentBlocks.add(r.id); m.added.forEach((id) => newItems.add(`${r.id}\n${id}`)); }
      return m.block;
    });
    // blocks the user added since the last share don't exist: users only edit blocks in place
    model = { ...remote, blocks };
    shared = remote;
    paintTop();
    paintFoot();
    paintBlocks(changed);
    if (changed.length) live.textContent = `The agent updated ${changed.length === 1 ? "a section" : `${changed.length} sections`}.`;
    if (!same(model.blocks, shared.blocks)) later(); else paintShare("saved");
  }

  // ---------- buttons ----------
  async function press(b) {
    if (!actions?.onAction || busy) return;
    flush(); // the agent sees what the button acts on
    busy = b.id;
    footErr.hidden = true;
    paintFoot();
    try {
      const patch = await actions.onAction(b.id, structuredClone(model));
      busy = null;
      if (patch && Object.keys(patch).length) {
        model = normalize({ ...model, ...patch });
        shared = normalize({ ...shared, ...patch });
        canvas?.setState?.(structuredClone(patch));
        paintTop();
        paintBlocks();
      }
      paintFoot();
      live.textContent = `${b.label}: done.`;
    } catch (err) {
      busy = null;
      paintFoot();
      footErr.replaceChildren(icon("alert", 13), (err instanceof Error && err.message) || `${b.label} didn't work. Nothing changed. Try again.`);
      footErr.hidden = false;
    }
  }

  // ---------- draw ----------
  root.replaceChildren(h("div", { class: "fsk fsk-cu" },
    h("div", { class: "fsk-cu-main" },
      h("article", { class: "fsk-cu-doc", "aria-labelledby": `fsk-cu${n}-t`, oninput: onInput, onchange: onChange, onfocusout: () => { if (timer) flush(); } },
        top, list)),
    h("footer", { class: "fsk-cu-foot" }, h("div", { class: "fsk-cu-foot-in" },
      h("div", { class: "fsk-cu-foot-note" }, footText, footErr, shareEl), btns)),
    live));
  paintTop();
  paintBlocks();
  paintFoot();
  paintShare("saved");
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (timer) flush(); // closing keeps the state: share the last change
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with the first key values, checklist progress, the first warning and the way to desktop. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  const s = normalize(structuredClone(data));
  const kv = s.blocks.find((b) => b.type === "keyValue");
  const checks = s.blocks.filter((b) => b.type === "checklist").flatMap((b) => b.items ?? []);
  const done = checks.filter((x) => x.done).length;
  const callout = s.blocks.find((b) => b.type === "callout" && (b.tone === "warning" || b.tone === "error"));
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cum", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("doc", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title),
        s.eyebrow && h("p", { class: "fsk-sub" }, s.eyebrow)),
      s.status && h("span", { style: { marginLeft: "auto", alignSelf: "flex-start" } }, pill(s.status.label, s.status.tone ?? "neutral"))),
    kv && h("dl", { class: "fsk-cu-kv" }, (kv.items ?? []).slice(0, 4).map((it) => h("div", {}, h("dt", {}, it.label), h("dd", {}, it.value || "Not set")))),
    checks.length > 0 && h("div", { class: "fsk-cum-prog" },
      h("span", { class: "fsk-num" }, `${done} of ${checks.length} steps done`),
      h("span", { class: "fsk-cu-bar", role: "progressbar", "aria-label": "Checklist progress", "aria-valuemin": 0, "aria-valuemax": checks.length, "aria-valuenow": done },
        h("span", { style: { width: `${Math.round((done / checks.length) * 100)}%` } }))),
    callout && h("div", { class: `fsk-cu-callout fsk-cu-callout--${callout.tone}`, style: { fontSize: ".93em" } }, icon("alert", 16),
      h("p", {}, h("span", { class: "fsk-sr" }, "Warning: "), callout.text ?? "")),
    h("p", { class: "fsk-cum-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Open on desktop"), "The full canvas opens beside the chat on a larger screen, where you can edit it with the agent."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this canvas draws besides its data. */
export const states = ["loading", "empty", "error"];

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton of the title and blocks,
 * or the message centered in the panel. Mobile: the card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cu", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-cum", icon: "doc", title, subtitle, surface, skeleton: () => h("div", { class: "fsk-cu-skel-kv" },
      [0, 1, 2, 3].map((i) => h("div", {}, bone("28%", "9px", { i }), bone(`${[44, 36, 52, 30][i]}%`, "10px", { i })))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  let dispose = () => {};
  let body;
  if (state.kind === "loading") {
    body = h("div", { class: "fsk-cu-main", "aria-hidden": "true" }, h("div", { class: "fsk-cu-doc" },
      h("div", { class: "fsk-cu-top" }, h("div", {},
        h("div", { class: "fsk-cu-eyebrow" }, bone("92px", "20px", { cls: "fsk-bone--box" })),
        title ? h("h2", { class: "fsk-cu-title" }, title) : h("div", { style: { margin: "12px 0 8px" } }, bone("46%", "18px")),
        bone("64%", "10px"))),
      h("div", { class: "fsk-cu-blocks" },
        h("div", { class: "fsk-cu-skel-kv" }, [0, 1, 2, 3].map((i) => h("div", {}, bone("22%", "9px", { i }), bone(`${[38, 30, 46, 26][i]}%`, "10px", { i })))),
        h("div", { style: { marginTop: "10px" } }, bone("30%", "12px", { i: 2 })),
        skeletonLines(3),
        h("div", { class: "fsk-cu-skel-kv" }, [0, 1, 2].map((i) => h("div", {}, bone("18px", "18px", { cls: "fsk-bone--box", i }), bone(`${[52, 40, 60][i]}%`, "10px", { i })))))));
  } else {
    let block;
    if (state.kind === "empty") block = emptyBlock({ icon: "doc", ...state }, surface);
    else { const e = errorBlock(state, surface); dispose = e.dispose; block = e.el; }
    body = h("div", { class: "fsk-cu-center" }, h("div", {}, block));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-cu fsk-cu-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    body,
    loading && h("div", { class: "fsk-cu-foot", "aria-hidden": "true" }, h("div", { class: "fsk-cu-foot-in" },
      h("div", { class: "fsk-cu-foot-note" }, bone("50%", "10px")), h("div", { class: "fsk-cu-btns" }, bone("88px", "36px", { cls: "fsk-bone--box" }), bone("120px", "36px", { cls: "fsk-bone--box" }))))));
  return () => { dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    canvasTitle: "Region move plan",
    eyebrow: "Migration plan",
    title: "Move the EU workspace to Frankfurt",
    subtitle: "A one-hour, read-only window. I drafted the plan from your workspace settings; change anything, or ask me to.",
    status: { label: "Draft", tone: "warning" },
    blocks: [
      { id: "facts", type: "keyValue", editable: true, items: [
        { id: "from", label: "From", value: "Dublin (eu-west)" },
        { id: "to", label: "To", value: "Frankfurt (eu-central)" },
        { id: "users", label: "Users affected", value: "214 people in 6 teams" },
        { id: "window", label: "Window", value: "", hint: "Pick a low-traffic hour" },
      ] },
      { id: "h-before", type: "heading", text: "Before the window" },
      { id: "steps", type: "checklist", items: [
        { id: "export", label: "Export the audit log", hint: "Kept for 90 days after the move", done: true },
        { id: "notify", label: "Tell workspace admins about the read-only hour" },
        { id: "pause", label: "Pause scheduled reports" },
        { id: "sso", label: "Check the SSO redirect URLs" },
      ] },
      { id: "risk", type: "callout", tone: "warning", text: "Scheduled reports pause during the window. Recipients don't get a copy of a report that was due in that hour." },
      { id: "h-notes", type: "heading", text: "Notes for the admins" },
      { id: "notes", type: "text", editable: true, text: "The workspace stays readable during the move. Anything saved in the hour before it starts is moved with it." },
    ],
    buttons: [{ id: "export", label: "Export plan" }, { id: "ready", label: "Mark as ready", primary: true }],
    footnote: "The agent drafts and updates the plan. You decide when it's ready.",
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
