# /iblai-vibe-agent-canvas

> Mirrored from [`iblai/base`](https://github.com/iblai/base) · [`skills/agents/iblai-vibe-agent-canvas/SKILL.md`](https://github.com/iblai/base/blob/main/skills/agents/iblai-vibe-agent-canvas/SKILL.md). This page is generated — edit it in the repository, not here.

The **Canvas** is the panel that opens beside the chat when an agent makes
something worth keeping: a document to edit, a Python or JSON file, a pdf,
Word or Excel file, or an HTML page that runs right there, charts, buttons
and all. Every canvas keeps its versions. The SDK chat draws all of it;
vibe-starter's home chat has it, wiring included. The first half of this
page is what people see; the second half adds it to an app of your own.

![An HTML dashboard the agent made, running in the canvas beside the chat (Preview and Code tabs, Export)](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-1-html-preview.png)

> **Common setup (brand, conventions, env files, verification):** see
> [docs/skill-setup.md](https://raw.githubusercontent.com/iblai/base/refs/heads/main/docs/skill-setup.md).

## What you get

- The canvas inside the SDK `Chat` (`@iblai/iblai-js/web-containers/next`):
  a card in the reply, the panel beside the chat, a full-width panel on a
  phone, and the **Canvas** pill under the message box.
- Six views, picked by file type: document editor, read-only file view,
  HTML page, pdf, Word, Excel (plus pictures, video and sound).
- Versions on every canvas, with **Restore** for documents, code and HTML;
  Export of the real file.
- What the app must add, and vibe-starter already has:
  `app/api/html-preview/route.ts`, `lib/iblai/html-preview-frame.ts`
  (imported first in `providers/iblai-providers.tsx`), two `middleware.ts`
  changes and `public/icons/my-mentors.svg`.

## When to use / when not

| Use it for | Not for |
|---|---|
| Wiring HTML pages, file previews and versions into an app's chat | Mounting the chat itself: `/iblai-vibe-agent-chat` |
| Knowing what each kind of file opens in, and why one shows as code | Letting the agent run code and share files: `/iblai-vibe-agent-sandbox` |
| The deploy checks for previews (storage, headers) | Canvas LMS courses: `/iblai-api-canvas-course-builder` |

## Using the canvas

### 1. Where a canvas comes from

- **The Canvas pill** under the message box asks the agent to write its
  documents and code in the canvas for this chat; its × turns it off. A new
  chat starts with it off, and each chat keeps its own setting when you come
  back to it. Opening a document's card turns it on for that chat.
- **Files the agent writes or shares** open as a canvas whether the pill is
  on or not. An agent with a virtual machine (`/iblai-vibe-agent-sandbox`)
  shares the files it made there: reports, spreadsheets, scripts, pages.
  Pictures show in the reply itself, a file over 5 MB (by default) comes as
  a link, and a much larger one is not shared.
- **One card per reply**: the title, what it is ("Python file", "PDF file",
  "HTML file", or the first lines of a document) and **Open Canvas**. An
  earlier version in the conversation shows as a small **Version N** button.
- **It opens by itself.** A new document or code file opens as the reply
  starts and fills in live; a shared file opens as soon as it is ready (until
  then its **Open Canvas** waits, with "Hang tight" on hover). A document
  written in the same reply never replaces the file it shared.

### 2. What opens where

| The agent shares | Opens as | What you can do |
|---|---|---|
| An HTML file (named `….html` or `….htm`) | A running page, with **Preview** and **Code** tabs | Use the page; Copy (on Code), Export |
| HTML written into the canvas under a title in words ("Sales Dashboard") | The editor, as text | Ask for "an HTML file, `dashboard.html`" to get a page |
| Code and data: `.py`, `.js`, `.ts`, `.json`, `.yaml`, `.sql`, `.sh`, `.toml`, `Dockerfile`, `Makefile`, `.env`, `requirements.txt`, … | A read-only file view: line numbers and colours, named by kind ("Python file") | Copy, Export under its own name |
| A pdf | The pages, drawn in the app at the panel's width | Select text; web links open in a new tab; Export |
| Word (`.docx`) | The pages | Web links open in a new tab; Export |
| Excel (`.xlsx`) | A table per sheet, with sheet tabs (first 500 rows × 50 columns) | Export for the whole file |
| Pictures, video, audio | The file, with the browser's own controls | Export |
| A document (markdown, prose), `.csv`, `.tsv` | The editor (csv and tsv as a table) | Edit, ask, Export (section 4) |
| Anything else (`.doc`, `.xls`, `.pptx`, `.zip`, …) | "We can't preview this kind of file just yet" | Export |

Word, Excel and a pdf drawn in the app read the file from storage, which
must let the app's origin read it (see [Before you deploy](#before-you-deploy)).
Where it doesn't, Word and Excel show "We can't preview this kind of file
just yet" and a pdf opens in the browser's own viewer. A very large file (a
Word or Excel file over 20 MB unpacked or 2,000,000 cells, a pdf over 2,000
pages) says it is too large to preview. Export saves the file either way.

![The page answers: Monthly view, a bar's tooltip, the forecast slider at 15% and the deals sorted by value](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-2-html-interactive.png)

![The same page on the Code tab: line numbers, colours, Copy and Export](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-3-html-code.png)

![forecast.py in the read-only file view; the card says Python file](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-4-python.png)

![A two-page pdf report drawn in the app, with its link](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-5-pdf.png)

![A Word launch plan with headings, bullets and a table](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-6-word.png)

![An Excel workbook: the Regions sheet, with Products and Notes tabs](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-7-excel.png)

### 3. HTML pages run, safely

The page runs in a sandboxed frame inside the canvas. It **cannot read or
change the app or its cookies**. It has no `fetch`, XHR or WebSocket, no
forms, pop-ups, workers or frames of its own, no camera, microphone or full
screen, and its `localStorage` lasts only as long as the preview. Scripts
may come from cdnjs, jsDelivr, unpkg, the Tailwind CDN and jQuery's CDN;
styles and fonts from cdnjs, jsDelivr, unpkg and Google Fonts; pictures
from `data:` and `blob:` addresses and the first three. So ask the agent
for a self-contained page: inline data, inline SVG, or one of those
libraries for charts.

What it does not hold in, as the SDK itself says: a page can still send out
a little of what it holds through DNS lookups, can replace what is on the
clipboard when someone clicks in it, and in Safari, Firefox and phone
browsers a page that never stops running can freeze the tab. Treat a
previewed page as a stranger's page, and never type a password into one.

- A page that floods the app with messages, or keeps taking the keyboard
  without a click into it, is stopped and shown with its scripts off, with
  **Run Again**.
- **Code instead of a page** (Code view only, no tabs) means the canvas may
  not run pages here: the app is not wired (Steps 1–3), it runs in the
  desktop or mobile app, another site frames it, the browser is offline,
  or `/api/html-preview` came back with a different policy.
- **"This page couldn't be shown just now"** with **Retry** means the route
  failed, could not be reached, or the page did not start within 20 s.

### 4. Documents: edit, ask, export

The editor has Undo and Redo, three heading sizes, bold, italic, code, code
block and quote. It saves 2 s after you stop typing ("Saving…", "All
changes saved"); click the title to rename it.

![The document editor with Export open: PDF Document, Microsoft Word, Markdown Document](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-8-document-export.png)

- **Highlight to edit**: select text and an **Ask Anything** box opens under
  it; the agent rewrites just that part.
- **The pencil**, bottom right on a desktop, opens **Adjust the length**
  (Longest to Shortest), **Reading level** (Graduate School to
  Kindergarten), **Add final polish** and **Add emojis**.
- **Export** saves a PDF, a Word file (`.docx`, the document as HTML that
  Word opens) or Markdown, named after the title.

![Highlight to edit: a paragraph selected, the Ask Anything box under it](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-9-ask.png)

![The pencil's controls: Add emojis, Add final polish, Reading level, Adjust the length](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-10-ai-controls.png)

### 5. Versions

Every change the agent makes adds a version, and so does a save that
changes the text. With two or more, the ⋮ beside the title has **Previous
Version**, **Next Version** and **Version X of Y**. An earlier version opens
read-only under **You are viewing a previous version**, with **Restore this
version** and **Back to latest version**. Restore makes it the current
version again without adding a new one.

A shared binary file (pdf, Word, Excel, video, sound) keeps only its newest
bytes: an earlier version says "Only the latest version of this file is
kept" and has no Restore. HTML pages and code files keep every version.

![An earlier version of the document, with Restore this version and Back to latest version](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-11-versions.png)

### 6. On a phone

Below 768 px the canvas takes the whole width, with the message box under
it. The editor's toolbar folds into a ⋯ menu, and the pencil is hidden.

![The HTML page on a phone: the canvas full width, the message box under it](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-vibe-agent-canvas/iblai-vibe-agent-canvas-12-phone.png)

The conversation views outside the chat (an agent's History tab, a user's
own history, analytics transcripts) show the same canvases as cards that
open read-only (`SessionCanvasCards`).

## Adding the canvas to your own app

### Prerequisites

- Auth and the chat in place: `/iblai-vibe-auth` and `/iblai-vibe-agent-chat`
  (or vibe-starter).
- `@iblai/iblai-js@^3.6.0` (resolves `@iblai/web-containers` 2.6.0).
- Documents and code files work with the chat alone. In an app with a CSP
  middleware (vibe-starter has one), pdf, Word and Excel previews need
  Step 3's storage hosts, and HTML pages need Steps 1–3; without one, Steps
  1–2 make pages run. Step 4 fixes one picture.

### Step 1: The page HTML files run in

Copy `assets/html-preview-route.ts` to `app/api/html-preview/route.ts`:

```ts
import { createHtmlPreviewResponse } from "@iblai/iblai-js/security";

// The page an HTML file from the agent runs in, inside the chat's canvas. It
// answers with a policy of its own that keeps the file away from the app and
// its cookies. middleware.ts must not match this path: its policy would
// replace this one, and the canvas would show the file's code instead.
export function GET() {
  return createHtmlPreviewResponse();
}
```

It must stay on the app's own origin (the page only lets that origin frame
it) and reach the browser with exactly this policy and `Cache-Control:
no-store`.

### Step 2: Tell the canvas where it is, first

Copy `assets/html-preview-frame.ts` to `lib/iblai/html-preview-frame.ts`. It
calls `configureHtmlPreview({ frameUrl: "/api/html-preview" })` from
`@iblai/iblai-js/web-containers` (not `/next`) as it loads, which also puts
the SDK's guard against a page's messages ahead of every listener the app
adds. So import it **first** in the providers file:

```diff
 "use client";
 …
  */
 
+// First, for its side effect: the canvas's HTML preview guard must be
+// listening before any listener the imports below add.
+import "@/lib/iblai/html-preview-frame";
 import { useEffect, useMemo, useState, type ReactNode } from "react";
```

With a base path, use `${basePath}/api/html-preview` (and a trailing `/`
when `trailingSlash` is on).

### Step 3: Keep the middleware off the route, and allow storage

For an app with an `applyCsp` middleware (vibe-starter's), two changes in
`middleware.ts` (or `proxy.ts`): the matcher leaves the route out, and the
storage hosts join `connectSrc` and `frameSrc`. Without a CSP middleware,
skip this step: nothing replaces the route's policy, and storage reads are
not restricted.

```ts
import type { NextRequest } from "next/server";
import { applyCsp } from "@iblai/iblai-js/security/next";

// Files the agent shares open from a short-lived storage link: the canvas
// reads pdf, Word and Excel bytes (connect-src) and frames a pdf it could not
// draw (frame-src). Add a regional bucket's host here.
const STORAGE_HOSTS = ["https://*.s3.amazonaws.com"];

export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-pathname", request.nextUrl.pathname);
  return applyCsp(request, {
    requestHeaders,
    mode: process.env.NODE_ENV === "development" ? "report-only" : undefined,
    connectSrc: STORAGE_HOSTS,
    frameSrc: ["blob:", ...STORAGE_HOSTS],
  });
}

export const config = {
  // api/html-preview stays out: its own policy would be replaced.
  matcher: ["/((?!_next/static|_next/image|favicon.ico|api/html-preview).*)"],
};
```

- **Merge, don't replace**: if the paywall (`/iblai-vibe-monetization-app-paywall`)
  or the Assistant (`/iblai-vibe-agent-assistant`) already added hosts, add
  these to the same arrays.
- **`next dev` hides a missing matcher change**: it runs the policy
  report-only, so the route keeps its own and pages run. A production build
  shows code instead. Check with `pnpm build && pnpm start`.

### Step 4: One picture the canvas loads from the app

The **Ask Anything** box loads `/icons/my-mentors.svg` from the site root
(even under a base path). Copy `assets/my-mentors.svg` to
`public/icons/my-mentors.svg`.

Optional: the document's PDF export loads Noto fonts from `/fonts/` (under
`NEXT_PUBLIC_BASE_PATH` when it is set): `NotoSans-Regular.ttf`,
`NotoSans-Bold.ttf`, `NotoSans-Italic.ttf` and `NotoSans-BoldItalic.ttf` (or
`NotoSans-Variable.ttf` and `NotoSans-Italic-Variable.ttf` instead),
`NotoSansMono-Regular.ttf`, `NotoSansSymbols2-Regular.ttf` and
`NotoSansMath-Regular.ttf`, all from [Google Fonts](https://fonts.google.com/noto)
(SIL Open Font License). Without them the PDF uses Helvetica, and
characters Helvetica lacks (arrows, math, non-Latin scripts) print as `?`.

### Step 5: Chat options (optional)

| `config` / prop on `Chat` | Effect on the canvas |
|---|---|
| `features.canvas: false` | Hides the Canvas pill only; files and cards still open, and opening a document's card still turns canvas writing on for that chat |
| `markdownToHtml`, `htmlToMarkdown` | Richer converters for the editor (tables, math) so it matches the chat |
| `saveFile` | Saves the file and code Exports your way (a native save dialog in Tauri) |
| `labels.canvasMessagePreview.openCanvas`, `labels.chatInputFormInsideButtons.canvas` | The card's button and the pill's name; the panel's own strings come from `WebContainersI18nProvider` |

### Before you deploy

- **Storage must let the app's origin read files.** Word and Excel previews
  and a pdf drawn in the app read the file's bytes from storage with a
  plain cross-origin GET. If the storage does not allow the app's origin,
  Word and Excel show "We can't preview this kind of file just yet" and a pdf
  opens in the browser's own viewer; Export then opens the file's link in a
  new tab. HTML, code, documents, pictures, video and sound are not
  affected. Self-hosted: allow the app's origin in the media bucket's CORS
  rules. Hosted ibl.ai: check with ibl.ai that your app's origin is allowed;
  until it is, expect these fallbacks.
- **Nothing in front of `/api/html-preview` may add or change headers**: no
  proxy or CDN adding a second policy, sending it report-only, caching it,
  or adding `X-Frame-Options: DENY`.
- **`output: 'export'`** cannot build the route; drop it there, and HTML
  files show as code. The desktop and mobile shells always show HTML as code.

## Linked SDK exports

From `@iblai/iblai-js/web-containers`:

- `configureHtmlPreview`: where HTML files run (Step 2).
- `CanvasView`, `CanvasDialog`: the panel, and the panel in a dialog
  (read-only with `readOnly`, as the history cards open it).
- `SessionCanvasCards`, `useSessionCanvases`: a conversation's canvases, as
  the history and transcript views show them.
- `configureCanvasMarkdown`: app-wide editor converters.
- `isCodeFile`, `shouldUseBinaryCanvas`: which view a file opens in;
  `describeTextFile`: a code file's kind ("Python") for its card.

From `@iblai/iblai-js/security`: `createHtmlPreviewResponse`,
`HTML_PREVIEW_CSP`, `HTML_PREVIEW_HEADERS`. `Chat` and `ChatConfig` come
from `@iblai/iblai-js/web-containers/next`.

## Platform data

The agent's writes reach the chat live on its socket, as `artifact_start`,
`artifact_content` and `artifact_end` frames. The rest is REST under
`/api/ai-mentor/orgs/{org}/users/{username}/` on the DM API, as the chat's
owner (an admin's history views read with a read grant):

| Call | What it does |
|---|---|
| `GET artifacts/?session_id=` | A chat's canvases |
| `GET artifacts/{id}/` | One canvas; a file carries `is_binary`, `mime_type` and a short-lived `binary_url` |
| `PUT artifacts/{id}/` `{content, title}` | Save or rename; a new version only when the text changed and is not empty |
| `GET artifacts/{id}/versions/` | Its versions (a plain list) |
| `GET artifacts/{id}/versions/{version_id}/` | One version |
| `POST artifacts/{id}/versions/set-current/` `{version_id}` | Restore |
| `PUT sessions/{session_id}/` `{tools: null, enable_artifacts}` | The Canvas pill. Send `tools: null` to keep the chat's tools: leaving `tools` out clears them |

A shared chat shows its canvases to anyone with the link; versions, saving
and Restore work only for the chat's owner. REST for chat sessions:
[agent-session](https://raw.githubusercontent.com/iblai/base/refs/heads/main/skills/agents/iblai-api-agent-session/SKILL.md).

## Verify

1. `pnpm build`, `pnpm test` (`__tests__/html-preview.test.ts`: the route's
   policy, the matcher, the storage hosts, the import order) and
   `pnpm e2e:coverage` (checkpoint R6 in the API journey).
2. On `pnpm start`, `curl -sI localhost:3000/api/html-preview` shows one
   `content-security-policy` (starting `sandbox allow-scripts`) and
   `cache-control: no-store`.
3. Touch test as `/iblai-vibe-ops-test` says, with the Canvas pill on: ask
   for an interactive page as an HTML file, `dashboard.html` (Preview runs
   it; click into it), a Python script (the card says "Python file"), and a
   short document (edit it, Export it, ask for a change, step back a version
   and Restore). With a virtual machine, ask for a pdf, a Word file and a
   spreadsheet; Word and Excel preview only where storage allows the app's
   origin. Console clean apart from the browser's note about `webrtc`; no
   sideways scroll at phone width.

## Related skills

- [`/iblai-vibe-agent-chat`](/developer/skills/iblai-vibe-agent-chat) — the chat the canvas lives in.
- [`/iblai-vibe-agent-sandbox`](/developer/skills/iblai-vibe-agent-sandbox) — a virtual machine, so the agent can make and share files.
- [`/iblai-vibe-agent-history`](/developer/skills/iblai-vibe-agent-history), [`/iblai-vibe-history`](/developer/skills/iblai-vibe-history) — conversations with their canvas cards.
- [`/iblai-vibe-ops-deploy`](/developer/skills/iblai-vibe-ops-deploy) — the deploy the checks above apply to.
