> 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/ch35-web-console-ui/35.2-console-ui-architecture.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 35.2 Console UI Architecture

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

***

The previous section introduced the Control UI's technology selection (Lit + Vite + Legacy Decorators). This section expands from an architectural perspective: how Gateway embeds this SPA within its own HTTP service, how frontend source code is organized, and how the browser-side WebSocket client communicates with Gateway.

## 35.2.1 Gateway Embedded UI Service

The Control UI's build artifacts (HTML, JS, CSS, SVG) are packaged and stored in the `dist/control-ui/` directory. When the Gateway process starts, it doesn't need a separate Nginx or CDN—it serves as the UI's HTTP server itself. The core logic is in `src/gateway/control-ui.ts`.

### Static File Service and SPA Fallback

The `handleControlUiHttpRequest` function handles all UI-related HTTP requests with the following flow:

```typescript
// src/gateway/control-ui.ts (simplified)
export function handleControlUiHttpRequest(
  req: IncomingMessage,
  res: ServerResponse,
  opts?: ControlUiRequestOptions,
): boolean {
  // 1. Only accept GET / HEAD
  if (req.method !== "GET" && req.method !== "HEAD") {
    res.statusCode = 405;
    res.end("Method Not Allowed");
    return true;
  }

  // 2. Parse basePath (support reverse proxy mounting to subpath)
  const basePath = normalizeControlUiBasePath(opts?.basePath);
  
  // 3. Locate static asset root directory
  const root = resolveControlUiRootSync({ ... });
  if (!root) {
    res.statusCode = 503;
    res.end("Control UI assets not found...");
    return true;
  }

  // 4. Try to match file; if file exists, return directly
  const filePath = path.join(root, fileRel);
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
    serveFile(res, filePath);
    return true;
  }

  // 5. SPA fallback: all unmatched paths return index.html
  const indexPath = path.join(root, "index.html");
  serveIndexHtml(res, indexPath, { basePath, config, agentId });
  return true;
}
```

This is the classic **SPA fallback pattern**: the frontend uses the History API for client-side routing (e.g., `/chat`, `/agents`), but these paths don't have corresponding physical files on the server. Gateway redirects all unmatched GET requests to `index.html`, letting the frontend JavaScript decide which page to display based on the URL.

> **Sidebar — SPA Fallback (History API Fallback)**
>
> Single-page applications (SPAs) use the browser's History API (`pushState` / `popstate`) to implement page switching without full page reloads. When a user directly visits `/agents` or refreshes the page, the browser requests the `/agents` path from the server. If the server has no corresponding file, it needs to "fall back" to `index.html`, letting the frontend router take over. This is why Nginx SPA configuration commonly includes the `try_files $uri /index.html;` rule.

### Security Header Injection

Each response includes security headers:

```typescript
function applyControlUiSecurityHeaders(res: ServerResponse) {
  res.setHeader("X-Frame-Options", "DENY");
  res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
  res.setHeader("X-Content-Type-Options", "nosniff");
}
```

| Security Header           | Value                    | Purpose                                               |
| ------------------------- | ------------------------ | ----------------------------------------------------- |
| `X-Frame-Options`         | `DENY`                   | Prevent embedding in `<iframe>`, prevent clickjacking |
| `Content-Security-Policy` | `frame-ancestors 'none'` | CSP-level iframe embedding prohibition                |
| `X-Content-Type-Options`  | `nosniff`                | Prevent browser MIME type sniffing                    |

### Configuration Injection: Dynamic index.html Writing

Before returning `index.html`, Gateway dynamically injects a `<script>` tag to pass runtime configuration to the frontend:

```typescript
function injectControlUiConfig(html: string, opts: ControlUiInjectionOpts): string {
  const script =
    `<script>` +
    `window.__OPENCLAW_CONTROL_UI_BASE_PATH__=${JSON.stringify(basePath)};` +
    `window.__OPENCLAW_ASSISTANT_NAME__=${JSON.stringify(assistantName)};` +
    `window.__OPENCLAW_ASSISTANT_AVATAR__=${JSON.stringify(assistantAvatar)};` +
    `</script>`;
  // Inject before </head>
  const headClose = html.indexOf("</head>");
  return `${html.slice(0, headClose)}${script}${html.slice(headClose)}`;
}
```

This "HTML injection" pattern has the advantage that build artifacts are static, but each Gateway instance can have different assistant names and avatars without needing to rebuild. The frontend reads these values through global variables like `window.__OPENCLAW_CONTROL_UI_BASE_PATH__`.

### Avatar Endpoint

Besides static file service, Gateway provides a dedicated avatar endpoint `/_avatar/{agentId}`. The `handleControlUiAvatarRequest` supports two modes:

1. **Direct Image Output** (default): If the avatar is a local file, return binary content directly
2. **Metadata Query** (`?meta=1`): Return JSON `{ avatarUrl }` for the frontend to decide—the avatar might be a local file, remote URL, or data URI

## 35.2.2 UI Source Code Structure

Frontend code is located in `ui/src/ui/` directory with about 50 files, adopting a "single component + module decomposition" architecture.

### Overall File Organization

```
ui/src/ui/
├── app.ts                   # OpenClawApp main component (LitElement subclass)
├── app-view-state.ts        # AppViewState type definition (render contract)
├── app-render.ts            # renderApp() entry → dispatch to each view
├── app-render.helpers.ts    # Render helper functions (Tab rendering, theme switching)
├── app-gateway.ts           # Gateway WebSocket connection and event dispatch
├── app-lifecycle.ts          # Lit lifecycle hook proxy
├── app-settings.ts          # Settings persistence, URL parameter sync, Tab switching
├── app-chat.ts              # Chat sending/aborting/queuing
├── app-channels.ts          # WhatsApp/Nostr channel management
├── app-scroll.ts            # Chat/log auto-scrolling
├── app-polling.ts           # Nodes/Logs/Debug polling
├── app-tool-stream.ts       # Tool call streaming display
├── app-events.ts            # Event log types
├── app-defaults.ts          # Default value constants
├── navigation.ts            # 12 Tab definitions and routing
├── gateway.ts               # GatewayBrowserClient class
├── storage.ts               # localStorage persistence
├── types.ts                 # Shared types (~775 lines)
├── ui-types.ts              # UI-specific types
├── views/                   # View render functions for each Tab
│   ├── chat.ts, agents.ts, channels.ts, config.ts, ...
│   └── (15+ view files total)
├── controllers/             # Data loading/operation functions for each feature
│   ├── chat.ts, agents.ts, config.ts, sessions.ts, ...
│   └── (23 controller files total)
├── chat/                    # Chat message rendering helpers
│   ├── grouped-render.ts, message-normalizer.ts, ...
│   └── (10 files total)
└── components/              # Reusable UI components
    └── resizable-divider.ts
```

### Single Component Architecture

The entire UI has only one Lit component `OpenClawApp` (`<openclaw-app>` tag) with **100+ `@state()` reactive fields**. This isn't a textbook "component-oriented" approach, but for management panel applications, it has merit:

1. **Centralized State Management**: All state in one place, no need for Context/Store state management solutions
2. **Eliminates Inter-component Communication Overhead**: Props passing and event bubbling between parent-child and sibling components are completely eliminated with only one component
3. **Reduces Lit-specific Serialization Cost**: Custom Elements' attribute passing only supports strings; complex objects need property passing

The tradeoff is that this component becomes very large. OpenClaw's response is **module decomposition**—logic is split into 20+ independent files:

```typescript
// ui/src/ui/app.ts (simplified structure)
@customElement("openclaw-app")
export class OpenClawApp extends LitElement {
  // ─── State Declaration (100+ fields) ───
  @state() settings: UiSettings = loadSettings();
  @state() connected = false;
  @state() tab: Tab = "chat";
  @state() chatMessages: unknown[] = [];
  // ...

  // ─── No Shadow DOM ───
  createRenderRoot() { return this; }

  // ─── Lifecycle Delegation ───
  connectedCallback()   { super.connectedCallback(); handleConnected(this); }
  firstUpdated()        { handleFirstUpdated(this); }
  disconnectedCallback(){ handleDisconnected(this); super.disconnectedCallback(); }
  updated(changed)      { handleUpdated(this, changed); }

  // ─── Method Delegation to Modules ───
  connect()             { connectGateway(this); }
  applySettings(next)   { applySettingsInternal(this, next); }
  setTab(next)          { setTabInternal(this, next); }
  async handleSendChat(){ await handleSendChatInternal(this); }
  
  // ─── Render Delegation ───
  render() { return renderApp(this); }
}
```

Note the `createRenderRoot() { return this; }` line—it skips Shadow DOM, letting the component render directly to Light DOM. This means global CSS (`styles.css`) can directly affect elements inside the component without needing CSS Modules or `::part()` pseudo-elements.

> **Sidebar — Light DOM vs Shadow DOM**
>
> Shadow DOM is a core Web Components feature that creates an isolated DOM subtree for a component, preventing external CSS from penetrating. This is valuable for general-purpose component libraries (like Material Design components), but for application-level components, style isolation becomes an obstacle—you need additional mechanisms to share theme variables. OpenClaw's choice of Light DOM is pragmatic.

### Render Model: AppViewState Contract

The `OpenClawApp` class and `renderApp()` function establish a contract through the `AppViewState` type:

```typescript
// ui/src/ui/app-view-state.ts (excerpt)
export type AppViewState = {
  // Data fields
  settings: UiSettings;
  connected: boolean;
  tab: Tab;
  chatMessages: unknown[];
  sessionKey: string;
  // ...

  // Behavior methods
  connect: () => void;
  setTab: (tab: Tab) => void;
  applySettings: (next: UiSettings) => void;
  handleSendChat: (msg?: string) => Promise<void>;
  resetToolStream: () => void;
  scrollToBottom: () => void;
  // ... 40+ methods total
};
```

`AppViewState` contains both data fields and behavior methods. `renderApp()` receives this type rather than the `OpenClawApp` class itself—this means the render function depends only on the interface, not the concrete implementation, facilitating testing and refactoring.

### View Dispatch

The `renderApp()` function selectively renders the corresponding view based on the current Tab:

```typescript
// ui/src/ui/app-render.ts (simplified)
export function renderApp(state: AppViewState) {
  return html`
    <div class="shell ${state.tab === 'chat' ? 'shell--chat' : ''}">
      <header class="topbar">...</header>
      <aside class="nav">
        ${TAB_GROUPS.map(group => html`
          <div class="nav-group">
            ${group.tabs.map(tab => renderTab(state, tab))}
          </div>
        `)}
      </aside>
      <main class="content">
        ${state.tab === "chat"     ? renderChat({...})     : nothing}
        ${state.tab === "agents"   ? renderAgents({...})   : nothing}
        ${state.tab === "overview" ? renderOverview({...}) : nothing}
        ${state.tab === "config"   ? renderConfig({...})   : nothing}
        <!-- ... 12 Tab views total -->
      </main>
    </div>
  `;
}
```

This uses Lit's special `nothing` value—when a condition isn't met, Lit generates no DOM nodes for that position, implementing lazy rendering.

### Navigation System

The 12 Tabs are divided into 4 groups:

| Group    | Tab                                                              | Description           |
| -------- | ---------------------------------------------------------------- | --------------------- |
| Chat     | `chat`                                                           | WebChat interface     |
| Control  | `overview`, `channels`, `instances`, `sessions`, `usage`, `cron` | Operations management |
| Agent    | `agents`, `skills`, `nodes`                                      | Agent configuration   |
| Settings | `config`, `debug`, `logs`                                        | System settings       |

The routing mechanism is based on the browser History API, with each Tab corresponding to a path (e.g., `/agents`):

```typescript
// ui/src/ui/navigation.ts
const TAB_PATHS: Record<Tab, string> = {
  chat: "/chat", overview: "/overview", channels: "/channels",
  instances: "/instances", sessions: "/sessions", usage: "/usage",
  cron: "/cron", agents: "/agents", skills: "/skills",
  nodes: "/nodes", config: "/config", debug: "/debug", logs: "/logs",
};

export function tabFromPath(pathname: string, basePath = ""): Tab | null {
  // Strip basePath prefix
  let path = pathname;
  if (basePath && path.startsWith(`${basePath}/`)) {
    path = path.slice(basePath.length);
  }
  // Root path defaults to chat
  if (normalizePath(path) === "/") return "chat";
  return PATH_TO_TAB.get(normalizePath(path)) ?? null;
}
```

The `inferBasePathFromPathname` function supports automatic basePath inference—when Gateway is reverse-proxied to a subpath like `/admin/ui/`, the frontend automatically senses it and generates correct links.

### Controller Layer

The `controllers/` directory contains 23 files, each encapsulating data operations for a functional domain. Controllers aren't classes but pure functions, taking an `OpenClawApp` instance (or its type projection) as a parameter:

```
controllers/
├── chat.ts          # Chat history loading + chat event handling
├── agents.ts        # Agent list loading
├── config.ts        # Config read/write + Schema loading
├── sessions.ts      # Session list + CRUD
├── channels.ts      # Channel status queries
├── skills.ts        # Skill management
├── nodes.ts         # Node list
├── devices.ts       # Device pairing management
├── cron.ts          # Scheduled task CRUD
├── usage.ts         # Usage statistics
├── logs.ts          # Log fetching
├── debug.ts         # Debug RPC calls
├── presence.ts      # Online instances
├── exec-approval.ts # Execution approval (single)
├── exec-approvals.ts# Execution approval (batch policy)
├── assistant-identity.ts  # Assistant identity
├── agent-identity.ts      # Agent identity
├── agent-files.ts         # Agent workspace files
├── agent-skills.ts        # Agent skill report
└── config/                # Config editor submodule
```

All controllers communicate with Gateway WebSocket via `host.client.request(method, params)`. For example, loading the agent list:

```typescript
// ui/src/ui/controllers/agents.ts (conceptual example)
export async function loadAgents(host: OpenClawApp) {
  host.agentsLoading = true;
  host.agentsError = null;
  try {
    const result = await host.client!.request<AgentsListResult>("agents.list");
    host.agentsList = result;
  } catch (err) {
    host.agentsError = String(err);
  } finally {
    host.agentsLoading = false;
  }
}
```

This pattern's characteristic is: **controllers directly modify the host component's `@state()` fields**. Since changes to `@state()` fields automatically trigger Lit re-rendering, controllers don't need to manually notify the UI to update.

## 35.2.3 Gateway WebSocket Client

All real-time communication between the frontend and Gateway happens through a single WebSocket connection, encapsulated in the `GatewayBrowserClient` class.

### Connection Protocol

The connection establishment flow is:

```
Browser                              Gateway
  │                                    │
  ├──── WebSocket open ───────────────→│
  │                                    │
  │←─── event: connect.challenge ──────┤  (carries nonce)
  │                                    │
  ├──── req: connect (with signature) ─→│
  │                                    │
  │←─── res: hello-ok (with snapshot)──┤
  │                                    │
  │←─── event: chat/agent/presence ────┤  (continuous push)
  ├──── req: agents.list ─────────────→│
  │←─── res: { agents: [...] } ────────┤
```

After WebSocket opens, Gateway first sends a `connect.challenge` event carrying a nonce (random number). The client signs it for authentication and sends a `connect` request. After authentication succeeds, Gateway returns `hello-ok`.

### Frame Format

Communication uses three types of JSON frames:

```typescript
// Event frame (Gateway → Browser, push)
type GatewayEventFrame = {
  type: "event";
  event: string;       // "chat" | "agent" | "presence" | "cron" | ...
  payload?: unknown;
  seq?: number;        // Monotonically increasing sequence number
};

// Request frame (Browser → Gateway, RPC)
// { type: "req", id: "uuid", method: "agents.list", params: {...} }

// Response frame (Gateway → Browser, RPC reply)
type GatewayResponseFrame = {
  type: "res";
  id: string;          // Match request UUID
  ok: boolean;
  payload?: unknown;
  error?: { code: string; message: string };
};
```

Event frames are server-initiated pushes; request/response frames are client-initiated RPC calls. The sequence number `seq` detects lost events—if the received seq isn't the previous +1, the client triggers an `onGap` callback to alert the user.

### Device Identity Authentication

`GatewayBrowserClient` supports Ed25519 device identity authentication. On first connection, the browser generates a key pair using Web Crypto API and stores it in IndexedDB. On subsequent connections, it signs `{deviceId, clientId, nonce, signedAtMs, ...}` with the private key:

```typescript
// ui/src/ui/gateway.ts (simplified)
private async sendConnect() {
  const isSecureContext = typeof crypto !== "undefined" && !!crypto.subtle;
  
  if (isSecureContext) {
    // Load or create Ed25519 key pair
    const deviceIdentity = await loadOrCreateDeviceIdentity();
    // Try to use previously stored device token
    const storedToken = loadDeviceAuthToken({ deviceId, role })?.token;
    authToken = storedToken ?? this.opts.token;
    
    // Sign connection parameters
    const payload = buildDeviceAuthPayload({
      deviceId, clientId, clientMode, role, scopes, signedAtMs, token, nonce,
    });
    const signature = await signDevicePayload(privateKey, payload);
    device = { id: deviceId, publicKey, signature, signedAt, nonce };
  }

  const hello = await this.request<GatewayHelloOk>("connect", {
    minProtocol: 3, maxProtocol: 3,
    client: { id: "openclaw-control-ui", mode: "webchat", ... },
    role: "operator", scopes: ["operator.admin", ...],
    device, auth: { token: authToken, password },
  });
  
  // Save device token issued by Gateway for next use
  if (hello.auth?.deviceToken) {
    storeDeviceAuthToken({ deviceId, role, token: hello.auth.deviceToken });
  }
}
```

> **Sidebar — Ed25519**
>
> Ed25519 is an elliptic curve digital signature algorithm, part of the Edwards-curve Digital Signature Algorithm (EdDSA) family. Its characteristics are: short keys (32-byte public key), fast signing and verification, and no random number pitfalls like ECDSA (deterministic signatures). Web Crypto API provides native Ed25519 support in secure contexts (HTTPS or localhost). OpenClaw uses `@noble/ed25519` as a compatibility layer.

In non-secure contexts (like plain HTTP access), `crypto.subtle` is unavailable, and the client falls back to pure token authentication mode.

### Automatic Reconnection and Backoff

After disconnection, the client automatically reconnects using exponential backoff strategy:

```typescript
private backoffMs = 800;  // Initial delay

private scheduleReconnect() {
  if (this.closed) return;
  const delay = this.backoffMs;
  this.backoffMs = Math.min(this.backoffMs * 1.7, 15_000);  // Max 15 seconds
  window.setTimeout(() => this.connect(), delay);
}
```

Reconnection sequence: 800ms → 1360ms → 2312ms → 3930ms → ... → 15000ms (capped). After successful connection, `backoffMs` resets to 800ms. Special case: WebSocket close code 1012 (Service Restart) doesn't show an error message—this typically happens when the user saves configuration through the UI and Gateway restarts.

### Event Dispatch

After connection, Gateway continuously pushes events. The `handleGatewayEvent` function routes events by type to different handlers:

```typescript
// ui/src/ui/app-gateway.ts (simplified)
function handleGatewayEventUnsafe(host: GatewayHost, evt: GatewayEventFrame) {
  // Event log (keep last 250 entries)
  host.eventLogBuffer = [
    { ts: Date.now(), event: evt.event, payload: evt.payload },
    ...host.eventLogBuffer,
  ].slice(0, 250);

  switch (evt.event) {
    case "agent":
      handleAgentEvent(host, evt.payload);       // Tool streaming output
      break;
    case "chat":
      handleChatEvent(host, evt.payload);         // Chat message update
      break;
    case "presence":
      host.presenceEntries = evt.payload.presence; // Online instances list
      break;
    case "cron":
      loadCron(host);                             // Refresh scheduled tasks
      break;
    case "device.pair.requested":
    case "device.pair.resolved":
      loadDevices(host);                          // Refresh device list
      break;
    case "exec.approval.requested":
      // Add to approval queue, set expiration timer
      const entry = parseExecApprovalRequested(evt.payload);
      host.execApprovalQueue = addExecApproval(host.execApprovalQueue, entry);
      setTimeout(() => removeExecApproval(host.execApprovalQueue, entry.id),
                 entry.expiresAtMs - Date.now() + 500);
      break;
  }
}
```

Particularly noteworthy is the handling of execution approval events: when an Agent requests execution of an operation requiring approval, Gateway pushes an `exec.approval.requested` event, and the UI adds it to the queue and displays an approval dialog. Approval entries have expiration times and are automatically removed from the queue when expired.

### Initial Snapshot

The `hello-ok` response may carry a `snapshot` field containing online instances list and health status:

```typescript
export function applySnapshot(host: GatewayHost, hello: GatewayHelloOk) {
  const snapshot = hello.snapshot as {
    presence?: PresenceEntry[];
    health?: HealthSnapshot;
    sessionDefaults?: SessionDefaultsSnapshot;
  } | undefined;
  
  if (snapshot?.presence) host.presenceEntries = snapshot.presence;
  if (snapshot?.health)   host.debugHealth = snapshot.health;
  if (snapshot?.sessionDefaults) applySessionDefaults(host, snapshot.sessionDefaults);
}
```

This avoids immediately making multiple RPC requests after connection to fetch initial data—Gateway pushes critical state all at once during handshake.

### Lifecycle Orchestration

`app-lifecycle.ts` organizes Lit component lifecycle hooks into clear startup/update/teardown flows:

| Lit Hook               | Operations                                                                                                                     |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `connectedCallback`    | Infer basePath → Read settings from URL → Sync Tab → Sync theme → Listen to `popstate` → Connect Gateway → Start Nodes polling |
| `firstUpdated`         | Listen to topbar element size (ResizeObserver)                                                                                 |
| `updated(changed)`     | Auto-scroll to bottom when chat content changes; track scroll when log content changes                                         |
| `disconnectedCallback` | Clean up event listeners, stop polling, disconnect Gateway                                                                     |

The auto-scroll logic in `handleUpdated` reflects careful UX consideration: only auto-scroll to bottom when the user hasn't manually scrolled up (tracked by `chatHasAutoScrolled` flag); force scroll when switching to Chat Tab.

***

## Section Summary

1. **Gateway itself is the UI's HTTP server**, providing the console interface through static file service + SPA fallback + HTML configuration injection, requiring no separate frontend deployment.
2. **Single component + module decomposition** is the core architecture: a 100+ field `OpenClawApp` component holds all state, but logic is distributed across `app-*.ts` (behavior), `views/` (rendering), `controllers/` (data) three layers.
3. **`AppViewState` type** defines the contract between component and render function, containing both data fields and behavior methods, decoupling render logic from component implementation.
4. **GatewayBrowserClient** encapsulates WebSocket communication, supporting three frame formats (event/request/response), Ed25519 device identity authentication, exponential backoff reconnection, sequence number gap detection.
5. **Event dispatcher** routes events by type to corresponding handlers, supporting chat, tool streaming, online status, scheduled tasks, device pairing, execution approval event types.
6. **Initial snapshot mechanism** pushes critical state during handshake, reducing post-connection request round trips.
