> 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.2-canvas-host-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 25.2 Canvas Host Implementation

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

***

The previous section introduced Canvas and A2UI concepts. This section will dive into Canvas Host's source code implementation, covering three parts: Canvas static file server, A2UI core module, and A2UI packaging process.

***

## 25.2.1 Canvas Server (`src/canvas-host/server.ts`)

### Two-Layer Architecture: Handler + Server

Canvas Host implementation is divided into two layers:

```
startCanvasHost()         ← Outer layer: Creates HTTP server, binds port
  └── createCanvasHostHandler()  ← Inner layer: File serving logic, Live Reload
```

This separation allows Canvas Handler to be **embedded into existing HTTP servers** (e.g., Gateway's HTTP layer) without always launching a separate server.

```typescript
// src/canvas-host/server.ts — Type definitions

export type CanvasHostHandler = {
  rootDir: string;       // Canvas root directory
  basePath: string;      // URL base path (default /__openclaw__/canvas)
  handleHttpRequest: (req, res) => Promise<boolean>;  // HTTP request handler
  handleUpgrade: (req, socket, head) => boolean;      // WebSocket upgrade handler
  close: () => Promise<void>;                         // Resource cleanup
};

export type CanvasHostServer = {
  port: number;          // Listen port
  rootDir: string;       // Canvas root directory
  close: () => Promise<void>;
};
```

### Canvas Root Directory Preparation

Canvas content directory defaults to `~/.openclaw/canvas/`:

```typescript
// src/canvas-host/server.ts — resolveDefaultCanvasRoot

function resolveDefaultCanvasRoot(): string {
  const candidates = [path.join(os.homedir(), ".openclaw", "canvas")];
  const existing = candidates.find(dir => {
    try { return fsSync.statSync(dir).isDirectory(); }
    catch { return false; }
  });
  return existing ?? candidates[0];
}
```

When the server starts, it ensures this directory exists and writes a default test page if `index.html` is missing:

```typescript
// src/canvas-host/server.ts — prepareCanvasRoot

async function prepareCanvasRoot(rootDir: string) {
  await ensureDir(rootDir);                      // Ensure directory exists
  const rootReal = await fs.realpath(rootDir);   // Resolve symlinks
  try {
    await fs.stat(path.join(rootReal, "index.html"));
  } catch {
    // index.html doesn't exist, write default test page
    await fs.writeFile(
      path.join(rootReal, "index.html"),
      defaultIndexHTML(),  // Contains Hello/Time/Photo/Dalek test buttons
      "utf8"
    );
  }
  return rootReal;
}
```

The default test page `defaultIndexHTML()` is a complete embedded HTML string containing four buttons (Hello, Time, Photo, Dalek) to verify Canvas and A2UI action bridge functionality.

### File Serving and Path Safety

Canvas Host's core is a static file server, but it must prevent **path traversal attacks** (Path Traversal)—malicious requests using paths like `../../etc/passwd` to access files outside the root directory.

```typescript
// src/canvas-host/server.ts — resolveFilePath (simplified)

async function resolveFilePath(rootReal: string, urlPath: string) {
  const normalized = normalizeUrlPath(urlPath);
  const rel = normalized.replace(/^\/+/, "");

  // First defense: reject paths containing ".."
  if (rel.split("/").some(p => p === "..")) {
    return null;
  }

  // Use safe file opening function
  const tryOpen = async (relative: string) => {
    try {
      return await openFileWithinRoot({ rootDir: rootReal, relativePath: relative });
    } catch (err) {
      if (err instanceof SafeOpenError) return null;
      throw err;
    }
  };

  // Directory request → auto-find index.html
  if (normalized.endsWith("/")) {
    return await tryOpen(path.posix.join(rel, "index.html"));
  }

  // Check if symlink (reject) or directory (find index.html)
  const candidate = path.join(rootReal, rel);
  const st = await fs.lstat(candidate);
  if (st.isSymbolicLink()) return null;   // Reject symlinks
  if (st.isDirectory()) {
    return await tryOpen(path.posix.join(rel, "index.html"));
  }

  return await tryOpen(rel);
}
```

Path safety is guaranteed through three mechanisms:

| Layer   | Mechanism              | Description                                                                                                      |
| ------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Layer 1 | URL Normalization      | `decodeURIComponent` + `path.posix.normalize` eliminates encoding bypasses                                       |
| Layer 2 | `..` Segment Detection | Explicitly rejects paths containing `..` segments                                                                |
| Layer 3 | `openFileWithinRoot`   | Low-level safety function (from `src/infra/fs-safe.ts`), verifies final path is truly within root via `realpath` |

> **Sidebar—Path Traversal Attack**: This is a common web security vulnerability. Attackers use `../` (parent directory references) in URLs to try accessing files outside the server's intended directory. For example, requesting `http://server/files/../../../etc/passwd` attempts to read the system password file. Defense methods include: normalizing paths, filtering `..` segments, verifying final path is within allowed directory. OpenClaw uses all three methods.

### HTTP Request Handling

`handleHttpRequest` is the entry point for the entire file serving:

```typescript
// src/canvas-host/server.ts — handleHttpRequest core logic

const handleHttpRequest = async (req, res) => {
  const url = new URL(req.url, "http://localhost");

  // 1. WebSocket path returns 426 (upgrade required)
  if (url.pathname === CANVAS_WS_PATH) {
    res.statusCode = liveReload ? 426 : 404;
    res.end(liveReload ? "upgrade required" : "not found");
    return true;
  }

  // 2. Base path matching (default /__openclaw__/canvas)
  let urlPath = url.pathname;
  if (basePath !== "/") {
    if (!urlPath.startsWith(`${basePath}/`) && urlPath !== basePath) {
      return false;  // Not Canvas request, pass to next handler
    }
    urlPath = urlPath.slice(basePath.length) || "/";
  }

  // 3. Only allow GET/HEAD
  if (req.method !== "GET" && req.method !== "HEAD") {
    res.statusCode = 405;
    res.end("Method Not Allowed");
    return true;
  }

  // 4. Resolve file path (with safety checks)
  const opened = await resolveFilePath(rootReal, urlPath);
  if (!opened) {
    res.statusCode = 404;
    res.end("not found");
    return true;
  }

  // 5. Read file, detect MIME type
  const data = await opened.handle.readFile();
  const mime = lower.endsWith(".html")
    ? "text/html"
    : (await detectMime({ filePath: realPath })) ?? "application/octet-stream";

  // 6. Inject Live Reload script into HTML files
  res.setHeader("Cache-Control", "no-store");
  if (mime === "text/html") {
    const html = data.toString("utf8");
    res.end(liveReload ? injectCanvasLiveReload(html) : html);
    return true;
  }

  res.setHeader("Content-Type", mime);
  res.end(data);
  return true;
};
```

Key design points:

* **`Cache-Control: no-store`**—Disables caching, ensuring WebView gets latest version after Agent updates files
* **HTML auto-injection**—All HTML responses get injected with Live Reload script and cross-platform action bridge
* **Return `boolean`**—`true` means handled, `false` means not Canvas's responsibility, let other handlers continue

### Live Reload: Auto-Refresh on File Changes

Live Reload uses **chokidar** to watch file changes and notifies clients via WebSocket to refresh:

```typescript
// src/canvas-host/server.ts — Live Reload implementation

// 1. Create WebSocket server (noServer mode, manual upgrade handling)
const wss = liveReload ? new WebSocketServer({ noServer: true }) : null;
const sockets = new Set<WebSocket>();
wss?.on("connection", ws => {
  sockets.add(ws);
  ws.on("close", () => sockets.delete(ws));
});

// 2. Broadcast refresh message (with 75ms debounce)
let debounce: NodeJS.Timeout | null = null;
const scheduleReload = () => {
  if (debounce) clearTimeout(debounce);
  debounce = setTimeout(() => {
    debounce = null;
    for (const ws of sockets) {
      ws.send("reload");  // Simple text message
    }
  }, 75);
  debounce.unref?.();  // Don't block process exit
};

// 3. chokidar watches file changes
const watcher = chokidar.watch(rootReal, {
  ignoreInitial: true,                                // Don't trigger on existing files
  awaitWriteFinish: { stabilityThreshold: 75, pollInterval: 10 },  // Wait for write completion
  ignored: [
    /(^|[\\/])\../,                                   // Ignore dotfiles
    /(^|[\\/])node_modules([\\/]|$)/,                 // Ignore node_modules
  ],
});
watcher.on("all", () => scheduleReload());
```

> **Sidebar—chokidar**: chokidar is the most popular file watching library in Node.js ecosystem, a high-level wrapper around `fs.watch`. It solves many cross-platform issues with native `fs.watch`: macOS's `FSEvents` sometimes doesn't report filenames, Linux's `inotify` has limited recursive watch support, some editors (like Vim) delete then recreate files causing watch failures, etc. chokidar unifies these differences, providing reliable cross-platform file watching.

Live Reload timing:

```
Agent writes file → chokidar detects change → 75ms debounce wait
                                                   │
                                       awaitWriteFinish (75ms)
                                                   │
                                           scheduleReload()
                                                   │
                                          75ms debounce timeout
                                                   │
                                         broadcastReload() → ws.send("reload")
                                                   │
                                           Client receives "reload" → location.reload()
```

The two 75ms delays have different meanings:

* `awaitWriteFinish.stabilityThreshold: 75`—Wait for file write completion (file size unchanged for 75ms)
* `setTimeout(broadcastReload, 75)`—Debounce: merge multiple file changes within short time into one refresh

### Environment Disabling

Canvas Host automatically disables in test environments:

```typescript
function isDisabledByEnv() {
  if (isTruthyEnvValue(process.env.OPENCLAW_SKIP_CANVAS_HOST)) return true;
  if (process.env.NODE_ENV === "test") return true;
  if (process.env.VITEST) return true;
  return false;
}
```

When disabled, returns a shell Handler where all methods are no-ops:

```typescript
if (isDisabledByEnv() && opts.allowInTests !== true) {
  return {
    rootDir: "",
    handleHttpRequest: async () => false,
    handleUpgrade: () => false,
    close: async () => {},
  };
}
```

### Standalone Server Mode

`startCanvasHost()` creates a standalone HTTP server on top of the Handler:

```typescript
// src/canvas-host/server.ts — startCanvasHost (simplified)

export async function startCanvasHost(opts): Promise<CanvasHostServer> {
  const handler = opts.handler ?? await createCanvasHostHandler({...});
  const bindHost = opts.listenHost || "0.0.0.0";

  const server = http.createServer((req, res) => {
    void (async () => {
      // Priority: A2UI requests > Canvas requests > 404
      if (await handleA2uiHttpRequest(req, res)) return;
      if (await handler.handleHttpRequest(req, res)) return;
      res.statusCode = 404;
      res.end("Not Found");
    })();
  });

  // WebSocket upgrade handling
  server.on("upgrade", (req, socket, head) => {
    if (handler.handleUpgrade(req, socket, head)) return;
    socket.destroy();  // Unknown upgrade requests close immediately
  });

  // Listen on port (0 means OS auto-assigns)
  const listenPort = opts.port > 0 ? opts.port : 0;
  server.listen(listenPort, bindHost);

  return { port: boundPort, rootDir: handler.rootDir, close: ... };
}
```

Request priority chain: **A2UI → Canvas → 404**. A2UI paths (`/__openclaw__/a2ui`) take priority over Canvas paths (`/__openclaw__/canvas`) because A2UI is a higher-level feature built on Canvas.

***

## 25.2.2 A2UI Core (`src/canvas-host/a2ui.ts` and `a2ui/`)

### Path Constants

The A2UI module defines three key paths:

```typescript
// src/canvas-host/a2ui.ts

export const A2UI_PATH       = "/__openclaw__/a2ui";     // A2UI renderer resources
export const CANVAS_HOST_PATH = "/__openclaw__/canvas";   // Canvas file service
export const CANVAS_WS_PATH   = "/__openclaw__/ws";       // Live Reload WebSocket
```

All paths use `/__openclaw__/` prefix, a namespace unlikely to conflict with user content.

### A2UI Root Directory Discovery

A2UI renderer resource files (`index.html` + `a2ui.bundle.js`) may be in different locations depending on how it's run:

```typescript
// src/canvas-host/a2ui.ts — resolveA2uiRoot

async function resolveA2uiRoot(): Promise<string | null> {
  const here = path.dirname(fileURLToPath(import.meta.url));
  const candidates = [
    path.resolve(path.dirname(process.execPath), "a2ui"),  // Beside executable
    path.resolve(here, "a2ui"),                             // Beside source/dist
    path.resolve(here, "../../src/canvas-host/a2ui"),       // dist → source fallback
    path.resolve(process.cwd(), "src/canvas-host/a2ui"),    // Repository root
    path.resolve(process.cwd(), "dist/canvas-host/a2ui"),   // Repository dist
  ];

  for (const dir of candidates) {
    try {
      // Must have both index.html and a2ui.bundle.js
      await fs.stat(path.join(dir, "index.html"));
      await fs.stat(path.join(dir, "a2ui.bundle.js"));
      return dir;
    } catch { /* Try next */ }
  }
  return null;
}
```

Discovery strategy priority reflects different deployment scenarios:

| Priority | Candidate Path                | Scenario                                              |
| -------- | ----------------------------- | ----------------------------------------------------- |
| 1        | Beside `process.execPath`     | Packaged as single-file executable                    |
| 2        | Beside current module `a2ui/` | Source direct run or dist with copied resources       |
| 3        | `../../src/canvas-host/a2ui`  | dist run without copied resources, fallback to source |
| 4        | `cwd()/src/canvas-host/a2ui`  | Running from repository root                          |
| 5        | `cwd()/dist/canvas-host/a2ui` | Running dist from repository root                     |

Discovery results are cached (`cachedA2uiRootReal`) and deduplicated via Promise (`resolvingA2uiRoot`) to avoid repeated searches during concurrent access.

### A2UI HTTP Request Handling

`handleA2uiHttpRequest` handles requests under `/__openclaw__/a2ui` path:

```typescript
// src/canvas-host/a2ui.ts — handleA2uiHttpRequest (simplified)

export async function handleA2uiHttpRequest(req, res): Promise<boolean> {
  const url = new URL(req.url, "http://localhost");

  // Path matching
  if (!url.pathname.startsWith(`${A2UI_PATH}/`) && url.pathname !== A2UI_PATH) {
    return false;  // Not A2UI request
  }

  // Only allow GET/HEAD
  if (req.method !== "GET" && req.method !== "HEAD") {
    res.statusCode = 405;
    res.end("Method Not Allowed");
    return true;
  }

  // Find A2UI resource root directory
  const a2uiRootReal = await resolveA2uiRootReal();
  if (!a2uiRootReal) {
    res.statusCode = 503;
    res.end("A2UI assets not found");
    return true;
  }

  // Resolve file path (with safety checks)
  const rel = url.pathname.slice(A2UI_PATH.length);
  const filePath = await resolveA2uiFilePath(a2uiRootReal, rel || "/");

  // Inject Live Reload into HTML files
  if (mime === "text/html") {
    const html = await fs.readFile(filePath, "utf8");
    res.end(injectCanvasLiveReload(html));
    return true;
  }

  res.end(await fs.readFile(filePath));
  return true;
}
```

A2UI file serving shares the same security policy as Canvas: reject `..` segments, reject symlinks, verify `realpath` is within root.

### Live Reload Injection

`injectCanvasLiveReload()` is a key function shared by Canvas and A2UI, injecting cross-platform action bridge and Live Reload client into each HTML response:

```typescript
// src/canvas-host/a2ui.ts — injectCanvasLiveReload

export function injectCanvasLiveReload(html: string): string {
  const snippet = `<script>
(() => {
  // === Cross-Platform Action Bridge ===
  function postToNode(payload) {
    const raw = JSON.stringify(payload);
    // iOS: webkit.messageHandlers
    // Android: window.openclawCanvasA2UIAction
    ...
  }
  function sendUserAction(userAction) {
    const id = userAction.id || crypto.randomUUID();
    return postToNode({ userAction: { ...userAction, id } });
  }
  globalThis.OpenClaw = { postMessage: postToNode, sendUserAction };
  globalThis.openclawSendUserAction = sendUserAction;

  // === Live Reload WebSocket ===
  const proto = location.protocol === "https:" ? "wss" : "ws";
  const ws = new WebSocket(proto + "://" + location.host + "/__openclaw__/ws");
  ws.onmessage = (ev) => {
    if (ev.data === "reload") location.reload();
  };
})();
</script>`;

  // Prefer inserting before </body>
  const idx = html.toLowerCase().lastIndexOf("</body>");
  if (idx >= 0) {
    return html.slice(0, idx) + "\n" + snippet + "\n" + html.slice(idx);
  }
  // No </body> tag, append to end
  return html + "\n" + snippet + "\n";
}
```

The injected script does two things:

1. **Action Bridge**: Exposes `window.OpenClaw.sendUserAction()` and `window.openclawSendUserAction()` global functions
2. **Live Reload**: Establishes WebSocket connection to `/__openclaw__/ws`, auto-refreshes page when receiving `"reload"` message

***

## 25.2.3 A2UI Packaging (`scripts/bundle-a2ui.sh`)

A2UI renderer's actual UI implementation consists of two parts:

| Component         | Path                                       | Tech Stack            |
| ----------------- | ------------------------------------------ | --------------------- |
| Lit Renderer      | `vendor/a2ui/renderers/lit`                | Lit Web Components    |
| Application Logic | `apps/shared/OpenClawKit/Tools/CanvasA2UI` | TypeScript + Rolldown |

Finally packaged into a single `a2ui.bundle.js` file, placed in `src/canvas-host/a2ui/` directory.

### Packaging Process

```bash
#!/usr/bin/env bash
# scripts/bundle-a2ui.sh

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HASH_FILE="$ROOT_DIR/src/canvas-host/a2ui/.bundle.hash"
OUTPUT_FILE="$ROOT_DIR/src/canvas-host/a2ui/a2ui.bundle.js"
A2UI_RENDERER_DIR="$ROOT_DIR/vendor/a2ui/renderers/lit"
A2UI_APP_DIR="$ROOT_DIR/apps/shared/OpenClawKit/Tools/CanvasA2UI"
```

### Incremental Build: Hash Verification

The packaging script uses **SHA-256 hash verification** for incremental builds—only rebuilds when source files actually change:

```bash
# 1. Collect input file list
INPUT_PATHS=(
  "$ROOT_DIR/package.json"
  "$ROOT_DIR/pnpm-lock.yaml"
  "$A2UI_RENDERER_DIR"       # Entire Lit renderer directory
  "$A2UI_APP_DIR"            # Entire application logic directory
)

# 2. Compute current hash (embedded Node.js script recursively traverses all files)
current_hash="$(compute_hash)"

# 3. Compare with previous hash
if [[ -f "$HASH_FILE" ]]; then
  previous_hash="$(cat "$HASH_FILE")"
  if [[ "$previous_hash" == "$current_hash" && -f "$OUTPUT_FILE" ]]; then
    echo "A2UI bundle up to date; skipping."
    exit 0
  fi
fi
```

The `compute_hash` function embeds a Node.js script that recursively traverses all input files, computing SHA-256 hash of each file's relative path and content. Hash result is stored in `.bundle.hash` file.

### Docker Environment Handling

In Docker builds, `vendor/` and `apps/` directories may be excluded via `.dockerignore`. The script has special handling:

```bash
# Docker builds exclude vendor/apps via .dockerignore.
# In that environment we must keep the prebuilt bundle.
if [[ ! -d "$A2UI_RENDERER_DIR" || ! -d "$A2UI_APP_DIR" ]]; then
  echo "A2UI sources missing; keeping prebuilt bundle."
  exit 0
fi
```

This means `a2ui.bundle.js` is treated as a **version-controlled prebuilt artifact**—committed to repository, Docker builds use it directly without repackaging.

### Build Toolchain

The actual build has two steps:

```bash
# Step 1: TypeScript compile Lit renderer
pnpm -s exec tsc -p "$A2UI_RENDERER_DIR/tsconfig.json"

# Step 2: Rolldown package application logic into single file
rolldown -c "$A2UI_APP_DIR/rolldown.config.mjs"

# Step 3: Save hash
echo "$current_hash" > "$HASH_FILE"
```

> **Sidebar—Rolldown**: Rolldown is a JavaScript bundler written in Rust, aiming to be a high-performance replacement for Rollup. It shares configuration format with Rollup (`rolldown.config.mjs`) but compiles much faster. OpenClaw uses Rolldown to package A2UI's multiple modules into a single `a2ui.bundle.js` file, making it loadable in WebView via a single `<script src="a2ui.bundle.js">` tag.

> **Sidebar—Lit**: Lit is a lightweight Web Components library developed by Google. It's based on browser-native Custom Elements and Shadow DOM standards, providing convenient APIs like reactive properties and template literals (`html\`...\``). OpenClaw's A2UI renderer uses Lit to implement the` \` custom element, parsing JSONL commands into actual DOM elements.

### Packaging Artifact Position in Architecture

```
Agent sends JSONL
    │
    ↓
Native App WebView loads:
    /__openclaw__/a2ui
        │
        ├── index.html      ← A2UI host page
        └── a2ui.bundle.js  ← Packaging artifact (result of this section's build)
                │
                └── Contains:
                    ├── Lit renderer (vendor/a2ui/renderers/lit)
                    │   Parses JSONL → Creates Web Components
                    └── Application logic (apps/shared/.../CanvasA2UI)
                        State management, layout calculation, theming, etc.
```

***

## Section Summary

1. Canvas Host uses **two-layer architecture**: `CanvasHostHandler` (embeddable) and `CanvasHostServer` (standalone), Handler can be embedded into Gateway's HTTP layer
2. **Static file serving** from `~/.openclaw/canvas/` directory, protected by three-layer path safety (URL normalization, `..` detection, `openFileWithinRoot`)
3. **Live Reload** uses chokidar file watching + WebSocket broadcast + 75ms debounce for auto-refresh when files change
4. All HTML responses get **auto-injected** with cross-platform action bridge (iOS/Android JS Bridge) and Live Reload client
5. A2UI root directory located via **multi-candidate path search**, supporting source run, dist run, packaged executable, etc.
6. A2UI packaging uses **SHA-256 incremental build**—hash verification skips unchanged builds, Docker uses prebuilt artifacts
7. Build toolchain is **tsc** (TypeScript compile) + **Rolldown** (Rust bundler), producing single-file `a2ui.bundle.js`
