> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch25-canvas-and-a2ui/25.1-canvas-concepts.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 25.1 Canvas Concepts

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~180k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In previous chapters, we've seen how OpenClaw's Agent interacts with users through text replies, executes commands via Bash tools, and manipulates web pages through browser control tools. However, all these interaction methods share a common limitation—Agent output is fundamentally a **text stream**. When an Agent needs to display a dynamic chart, an interactive form, or even a complete mini-application to the user, plain text falls short.

The Canvas system was designed precisely to solve this problem. It provides Agents with a **visual workspace**—a canvas capable of rendering HTML/CSS/JavaScript where Agents can push arbitrary web content and users can interact with it.

***

## 25.1.1 What is Canvas: Agent-Driven Visual Workspace

### Core Concept

The core idea of Canvas is simple: **give Agents a WebView where they can freely render content**.

In traditional chat-based AI interactions, Agent output is confined to the message stream—text, code blocks, Markdown tables. Canvas provides an independent rendering surface where Agents can:

1. **Push HTML pages**—Agents generate HTML/CSS/JS files, Canvas Host serves and renders them
2. **Inject JavaScript**—Execute arbitrary JS code in the running page via `canvas.eval`
3. **Capture snapshots**—Get screenshots of the current rendering via `canvas.snapshot`
4. **Control visibility**—Control Canvas visibility via `canvas.present` / `canvas.hide`

This design elevates Agents from "assistants that only type" to "assistants that can manipulate screens."

### Architectural Position

Canvas occupies a position within the **Node subsystem** of OpenClaw's overall architecture. Recalling the architecture diagram from Chapter 1:

```
User ←→ Native Client (macOS/iOS/Android)
             ↑
             │ WebSocket
             ↓
        Gateway Control Plane
             ↑
             │ Gateway Protocol
             ↓
        Agent Runtime
             │
             ├── Text Replies (Message Channels)
             ├── Tool Invocation (Bash / Browser / Web, etc.)
             └── Canvas (Visual Workspace) ← Focus of this chapter
```

Canvas's data flow works like this:

1. Agent invokes a `canvas` tool (e.g., `canvas.present`)
2. Tool implementation sends a command to the target node via Gateway's `node.invoke`
3. Target node (iOS/Android/macOS native app) executes the command in its local WebView
4. WebView fetches HTML content from Canvas Host server and renders it

```
Agent ──canvas.present──→ Gateway ──node.invoke──→ Native App
                                                      │
                                    Canvas Host ←──HTTP──┘
                                   (Static File Server)     WebView Rendering
```

> **Sidebar—WebView**: WebView is a browser component embedded in native applications. On iOS it's `WKWebView` (based on WebKit engine), on Android it's `android.webkit.WebView` (based on Chromium), and on macOS it's also `WKWebView`. It allows native apps to embed a complete web rendering engine in their interface, capable of executing HTML/CSS/JavaScript. OpenClaw leverages WebView as Canvas's rendering surface, enabling Agents to construct arbitrary UIs using web technologies.

### Canvas Host: Static File Server

Canvas content requires an HTTP server to host it. OpenClaw implements this server in `src/canvas-host/server.ts`, called **Canvas Host**. Its responsibilities are straightforward:

| Responsibility      | Description                                                          |
| ------------------- | -------------------------------------------------------------------- |
| Static File Serving | Provides HTML/CSS/JS/images from `~/.openclaw/canvas/` directory     |
| Path Safety         | Prevents path traversal attacks (`../` cannot escape root directory) |
| Live Reload         | Notifies clients via WebSocket when files change for auto-refresh    |
| A2UI Hosting        | Also hosts A2UI renderer resource files                              |

Agent workflow:

1. Write HTML files to `~/.openclaw/canvas/` directory
2. Call `canvas.present` to have target node's WebView load the file
3. Canvas Host provides file service, WebView renders content
4. When files change, Live Reload automatically refreshes WebView

This "filesystem as API" design is elegantly simple—Agents don't need to learn any special rendering protocol, just need to know how to write HTML.

### Difference Between Canvas and Browser Control

Readers might ask: doesn't Chapter 24's browser control also manipulate web pages? What's the difference between Canvas and it?

| Dimension          | Browser Control (Ch. 16)                    | Canvas                         |
| ------------------ | ------------------------------------------- | ------------------------------ |
| **Control Target** | User's desktop browser (Chrome/Edge/Brave)  | WebView embedded in native app |
| **Content Source** | Any internet webpage                        | HTML generated by Agent        |
| **Use Case**       | Web automation, scraping, form filling      | Agent-driven visual display    |
| **Protocol**       | CDP / Playwright                            | Gateway node.invoke            |
| **Platform**       | Desktop only (requires Chrome installation) | macOS / iOS / Android          |

In short: browser control is "manipulating someone else's webpage," Canvas is "rendering your own webpage."

***

## 25.1.2 A2UI (Agent-to-UI): AI Agents Directly Manipulate User Interface

### From HTML Push to Structured UI

Canvas's basic mode—Agents write HTML, WebView renders—is already powerful. But it has a problem: **every UI update requires rewriting the entire HTML file**. If an Agent only wants to append a line of text or update a progress bar, it must regenerate the complete HTML and trigger a page refresh.

A2UI (Agent-to-UI) solves this problem. It's a **structured UI protocol** proposed by OpenClaw that allows Agents to incrementally manipulate user interfaces through a JSONL (JSON Lines) command stream.

> **Sidebar—A2UI**: A2UI stands for Agent-to-UI and is an original OpenClaw concept. It refers to AI Agents being able to directly push structured UI descriptions (rather than raw HTML) to users, which a dedicated renderer (A2UI Renderer) interprets and presents as interactive interface elements. Think of it as "AI-driven frontend rendering"—Agents can not only reply with text, but also display buttons, forms, charts, and other interactive UI elements.

> **Sidebar—JSONL (JSON Lines)**: JSONL is a text format where each line contains one JSON object, separated by newlines. Compared to regular JSON arrays, JSONL's advantage is **stream processing support**—you don't need to wait for the entire data to complete; you can parse an object as soon as you read a line. This is perfect for Agents progressively building UIs: Agents can send UI instructions one by one, and the renderer executes each one as it arrives.

### How A2UI Works

A2UI's core flow:

```
Agent ──a2ui_push(jsonl)──→ Gateway ──node.invoke──→ Native App
                                                        │
                                                   WebView with
                                                 <openclaw-a2ui-host>
                                                   Custom Element
                                                        │
                                                  a2ui.bundle.js
                                                   Renderer Parses JSONL
                                                   and Updates DOM
```

1. Agent calls `canvas` tool's `a2ui_push` action with JSONL data
2. Command is forwarded through Gateway to target node
3. Node's WebView runs A2UI host page (`index.html`)
4. `<openclaw-a2ui-host>` custom element in host page receives JSONL and renders it

### Bidirectional Communication: User Actions Returned

A2UI isn't just one-way push. When users click buttons or submit forms in A2UI-rendered interfaces, **user actions can be returned to the Agent**.

This is implemented through a cross-platform "action bridge." The `injectCanvasLiveReload()` function injects JavaScript into each Canvas page, providing a global function `window.openclawSendUserAction()`:

```typescript
// Injected cross-platform action bridge (simplified)
function postToNode(payload) {
  const raw = JSON.stringify(payload);

  // iOS path: via WKWebView's messageHandler
  const iosHandler = window.webkit?.messageHandlers?.openclawCanvasA2UIAction;
  if (iosHandler) {
    iosHandler.postMessage(raw);
    return true;
  }

  // Android path: via Android WebView's JS interface
  const androidHandler = window.openclawCanvasA2UIAction;
  if (androidHandler) {
    androidHandler.postMessage(raw);
    return true;
  }

  return false;
}

// Global exposure
window.OpenClaw = { postMessage: postToNode, sendUserAction: ... };
window.openclawSendUserAction = sendUserAction;
```

Message paths for three platforms:

| Platform | API                                                                    | Principle                                                                                       |
| -------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| iOS      | `window.webkit.messageHandlers.openclawCanvasA2UIAction.postMessage()` | WKWebView's `WKScriptMessageHandler` mechanism, allowing JS to send messages to Swift           |
| Android  | `window.openclawCanvasA2UIAction.postMessage()`                        | Android WebView's `@JavascriptInterface` annotation, exposing Java/Kotlin objects as JS globals |
| macOS    | Same as iOS (`WKWebView`)                                              | macOS's `WKWebView` shares the same WebKit API as iOS                                           |

> **Sidebar—JavaScript Bridge (JS Bridge)**: In a WebView within a native app, JavaScript code runs in a sandboxed environment and cannot access native features by default (camera, filesystem, notifications, etc.). A JS bridge is a mechanism allowing JavaScript and native code to call each other. On iOS, Swift listens for messages from JS via `WKScriptMessageHandler`; on Android, Kotlin/Java exposes methods to JS via `@JavascriptInterface` annotation. OpenClaw uses this mechanism to implement A2UI's user action return.

### A2UI Host Page

A2UI rendering happens in a dedicated host page (`src/canvas-host/a2ui/index.html`). This page's structure includes three layers:

```
┌──────────────────────────────────────────┐
│ body (Animated Gradient Background)      │
│  ├── <canvas> (Bottom 2D Canvas, z: 1)   │
│  ├── #openclaw-status (Status Overlay, z: 3) │
│  └── <openclaw-a2ui-host> (A2UI Layer, z: 4) │
└──────────────────────────────────────────┘
```

| Layer             | Element                         | Purpose                                                                  |
| ----------------- | ------------------------------- | ------------------------------------------------------------------------ |
| Bottom Canvas     | `<canvas id="openclaw-canvas">` | For low-level 2D drawing, auto-adapts to device pixel ratio (DPR)        |
| Status Overlay    | `#openclaw-status`              | Shows debug status info (hidden by default, enable via `?debugStatus=1`) |
| A2UI Render Layer | `<openclaw-a2ui-host>`          | Custom element hosting A2UI renderer output, main content users see      |

The host page also exposes a global API `window.__openclaw`:

```javascript
window.__openclaw = {
  canvas,              // <canvas> element reference
  ctx,                 // CanvasRenderingContext2D
  setStatus,           // Show/hide status card
  setDebugStatusEnabled, // Enable/disable debug status
};
```

### Platform Adaptation

A2UI host page achieves cross-platform adaptation through CSS custom properties and platform detection:

```css
/* CSS Custom Properties for A2UI Custom Element */
openclaw-a2ui-host {
  --openclaw-a2ui-inset-top: 28px;      /* Top Safe Area */
  --openclaw-a2ui-inset-right: 0px;
  --openclaw-a2ui-inset-bottom: 0px;
  --openclaw-a2ui-inset-left: 0px;
  --openclaw-a2ui-scroll-pad-bottom: 0px;
}
```

These custom properties correspond to mobile device safe areas, and native apps inject actual safe area values into these properties when loading WebView, ensuring A2UI content isn't obscured by notches, bottom gesture bars, etc.

Platform detection happens at page load:

```javascript
// Platform detection (simplified)
const params = new URLSearchParams(window.location.search);
const platform = params.get("platform");  // Prefer URL parameter
if (platform) {
  document.documentElement.dataset.platform = platform;
} else if (/android/i.test(navigator.userAgent)) {
  document.documentElement.dataset.platform = "android";
}
```

Android platform uses higher opacity gradient backgrounds to adapt to OLED screen display characteristics:

```css
/* Android-specific styles: higher contrast gradient */
:root[data-platform="android"] body {
  background:
    radial-gradient(... rgba(42, 113, 255, 0.62) ...),  /* iOS: 0.18 */
    radial-gradient(... rgba(255, 0, 138, 0.52) ...),   /* iOS: 0.14 */
    #0b1328;                                             /* iOS: #000 */
}
```

### Relationship Between Canvas and A2UI

Finally, let's clarify the relationship between Canvas and A2UI:

```
Canvas (Broad Sense)
├── Canvas Basic Mode
│   └── Agent writes HTML → Canvas Host hosts → WebView renders
│       Use case: Complete web apps, custom pages
│
└── A2UI Mode
    └── Agent sends JSONL → Renderer parses → Incremental DOM updates
        Use case: Structured UI, real-time updates, conversational interfaces

Both modes share the same Canvas Host server and WebView container.
```

Canvas is the underlying infrastructure (WebView + static file service), A2UI is a high-level abstraction built on Canvas (structured UI protocol). Agents can choose based on needs:

* Need fully customized UI → Use Canvas basic mode, push HTML directly
* Need to quickly build standardized interfaces → Use A2UI mode, send JSONL commands

***

## Section Summary

1. **Canvas** is OpenClaw's visual workspace, elevating Agents from "can only type" to "can render interfaces"
2. Canvas's core is a **static file server** (Canvas Host); Agents write HTML files to a specified directory, which WebView loads and renders
3. Canvas forwards commands to native app nodes via Gateway's `node.invoke` mechanism, where nodes execute in local WebView
4. **A2UI** (Agent-to-UI) is an advanced protocol built on Canvas, enabling incremental UI updates through JSONL command streams
5. A2UI implements bidirectional communication via **cross-platform action bridge**—iOS uses `WKScriptMessageHandler`, Android uses `@JavascriptInterface`
6. A2UI host page contains three layers: bottom Canvas drawing surface, status overlay, A2UI render layer
7. Platform adaptation is achieved through CSS custom properties and `data-platform` dataset, with Android having specific high-contrast styling
