> 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/ch24-browser-control/24.1-browser-architecture-overview.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 24.1 Browser Architecture Overview

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

***

In previous chapters, we analyzed how OpenClaw enables AI Agents to execute commands at the operating system level through Bash tools. However, in the modern web era, the browser is the core medium for information retrieval and interaction. OpenClaw's browser control subsystem enables Agents to browse the web like humans—navigating, clicking, filling forms, taking screenshots, and even executing JavaScript. This section will analyze the architecture design of this complex subsystem from a global perspective.

***

## 24.1.1 Playwright + CDP Hybrid Approach

### Why Two Layers?

OpenClaw's browser control adopts a **dual-layer architecture**: the lower-level CDP (Chrome DevTools Protocol) and the upper-level Playwright.

```
┌─────────────────────────────────────┐
│          OpenClaw Agent             │
│         (Tool Invocation Layer)      │
├─────────────────────────────────────┤
│     Playwright High-Level API       │
│  click / fill / snapshot / navigate │
│  Page State Management / Role Snapshot
├─────────────────────────────────────┤
│        CDP Low-Level API Layer      │
│  WebSocket → Chrome DevTools        │
│  Screenshots / JS Execution / Tab Creation
├─────────────────────────────────────┤
│    Chrome / Chromium Browser Instance │
│  (Managed by OpenClaw or User-owned)  │
└─────────────────────────────────────┘
```

> **Sidebar**: **CDP (Chrome DevTools Protocol)** is Chrome's built-in remote debugging protocol. When Chrome is launched with the `--remote-debugging-port=9222` parameter, it exposes an HTTP + WebSocket interface on that port. External programs can use this interface to control almost all browser behaviors—navigating pages, executing JavaScript, capturing screenshots, modifying the DOM, and more. It is the underlying foundation for all browser automation frameworks (Puppeteer, Playwright, Selenium 4).

> **Sidebar**: **Playwright** is a browser automation library developed by Microsoft. Unlike using CDP directly, Playwright provides higher-level abstractions—automatic waiting for elements to become interactive, intelligent selectors (locating elements via ARIA roles, text content, etc.), and cross-browser support (Chrome, Firefox, Safari). For AI Agents, Playwright's "Role Snapshot (Aria Snapshot)" feature is particularly important—it converts the page's accessibility tree into text descriptions that Agents can read.

The rationale for the hybrid approach:

| Scenario           | Layer Used | Reason                                                          |
| ------------------ | ---------- | --------------------------------------------------------------- |
| Screenshots        | CDP        | Direct call to `Page.captureScreenshot`, zero overhead          |
| Execute JS         | CDP        | Direct call to `Runtime.evaluate`, no Playwright context needed |
| Create tabs        | CDP        | `Target.createTarget` is more reliable at lower level           |
| Click/Fill forms   | Playwright | Automatic waiting, intelligent locating, error recovery         |
| Page snapshots     | Playwright | ARIA snapshots are Playwright-exclusive                         |
| Network monitoring | Playwright | Request/Response events are easier to use                       |

***

## 24.1.2 Chrome Instance Management

### Browser Discovery and Launch

`chrome.ts` is responsible for discovering Chrome/Chromium browsers on the system and managing their lifecycle:

```typescript
// src/browser/chrome.ts — RunningChrome type
type RunningChrome = {
  pid: number;                        // Process ID
  exe: BrowserExecutable;             // Browser executable info
  userDataDir: string;                // User data directory
  cdpPort: number;                    // CDP debugging port
  startedAt: number;                  // Launch time
  proc: ChildProcessWithoutNullStreams; // Child process handle
};
```

### Browser Executable Discovery

`chrome.executables.ts` provides browser discovery logic for three major platforms (macOS, Linux, Windows):

```
macOS:
  1. /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
  2. /Applications/Brave Browser.app/Contents/MacOS/Brave Browser
  3. /Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge
  4. /Applications/Chromium.app/Contents/MacOS/Chromium
  
Linux:
  1. google-chrome / google-chrome-stable (PATH search)
  2. chromium / chromium-browser
  3. brave-browser
  4. microsoft-edge
  
Windows:
  1. %PROGRAMFILES%\Google\Chrome\Application\chrome.exe
  2. %LOCALAPPDATA%\Google\Chrome\Application\chrome.exe
  3. Brave, Edge similar paths
```

### Launch Process

The `launchOpenClawChrome()` launch process includes multiple stages:

```
1. Port Check → ensurePortAvailable(cdpPort)
2. Browser Discovery → resolveBrowserExecutable()
3. User Data Directory → ~/.openclaw/browser/<profile>/user-data/
4. First-time Setup (optional):
   └─ spawn Chrome → wait for config generation → close
5. Profile Decoration:
   └─ Set OpenClaw theme color, name
6. Formal Launch:
   └─ spawn Chrome with --remote-debugging-port=<cdpPort>
7. Wait for CDP Ready:
   └─ Poll /json/version (max 15 seconds)
```

Chrome launch parameters are carefully chosen:

```typescript
const args = [
  `--remote-debugging-port=${profile.cdpPort}`,  // CDP port
  `--user-data-dir=${userDataDir}`,               // Isolated data directory
  "--no-first-run",                  // Skip first-run wizard
  "--no-default-browser-check",      // Don't check default browser
  "--disable-sync",                  // Disable Google Sync
  "--disable-background-networking", // Reduce network noise
  "--disable-component-update",      // Disable component updates
  "--disable-features=Translate,MediaRouter",
  "--disable-session-crashed-bubble",
  "--hide-crash-restore-bubble",
  "--password-store=basic",          // Simplify password storage
  "about:blank",                     // Open blank page (ensure at least one target)
];
```

### CDP Readiness Detection

```typescript
// src/browser/chrome.ts — Health check
export async function isChromeReachable(cdpUrl: string, timeoutMs = 500) {
  const version = await fetchChromeVersion(cdpUrl, timeoutMs);
  return Boolean(version);
}

// More strict check: both HTTP and WebSocket work
export async function isChromeCdpReady(cdpUrl, timeoutMs, handshakeTimeoutMs) {
  const wsUrl = await getChromeWebSocketUrl(cdpUrl, timeoutMs);
  if (!wsUrl) return false;
  return await canOpenWebSocket(wsUrl, handshakeTimeoutMs);
}
```

Two-level checks ensure Chrome not only starts the HTTP service but also establishes WebSocket connections properly.

***

## 24.1.3 Profile Management

### Multi-Profile Design

OpenClaw supports managing multiple browser profiles simultaneously, each with independent CDP ports and user data directories:

```typescript
// src/browser/config.ts — Resolved configuration
type ResolvedBrowserConfig = {
  enabled: boolean;
  controlPort: number;          // Browser control service port
  cdpProtocol: "http" | "https";
  cdpHost: string;
  headless: boolean;            // Headless mode
  noSandbox: boolean;           // Disable Chrome sandbox
  attachOnly: boolean;          // Only attach to existing browser
  defaultProfile: string;       // Default profile name
  profiles: Record<string, BrowserProfileConfig>;
};

type ResolvedBrowserProfile = {
  name: string;                 // Profile name (e.g., "openclaw", "chrome")
  cdpPort: number;              // CDP port (18800-18899)
  cdpUrl: string;               // e.g., "http://127.0.0.1:18800"
  cdpIsLoopback: boolean;       // Is local (not remote)
  color: string;                // Profile theme color
  driver: "openclaw" | "extension"; // Control method
};
```

### CDP Port Allocation

```typescript
// src/browser/profiles.ts — Port range
export const CDP_PORT_RANGE_START = 18800;
export const CDP_PORT_RANGE_END   = 18899;  // Max 100 profiles

// Reserved ports (not used for CDP):
//   18789 - Gateway WebSocket
//   18790 - Bridge
//   18791 - Browser control service
//   18792-18799 - Reserved (Canvas at 18793)
```

`allocateCdpPort()` finds the first unused port in the range. Used ports are collected from all profiles:

```typescript
export function allocateCdpPort(usedPorts: Set<number>): number | null {
  for (let port = CDP_PORT_RANGE_START; port <= CDP_PORT_RANGE_END; port++) {
    if (!usedPorts.has(port)) return port;
  }
  return null;
}
```

### Profile Theme Colors

Each profile has a visual identifier color used to distinguish different instances in Chrome's title bar:

```typescript
// src/browser/profiles.ts — Predefined color palette
export const PROFILE_COLORS = [
  "#FF4500",  // Orange-red (openclaw default)
  "#0066CC",  // Blue
  "#00AA00",  // Green
  "#9933FF",  // Purple
  "#FF6699",  // Pink
  "#00CCCC",  // Cyan
  "#FF9900",  // Orange
  "#6666FF",  // Indigo
  "#CC3366",  // Magenta
  "#339966",  // Teal
];
```

`decorateOpenClawProfile()` modifies Chrome's `Preferences` and `Local State` files, injecting the profile name and theme color. This way users can instantly recognize which Chrome window is controlled by OpenClaw.

### Two Driver Modes

| Driver      | Scenario                                                  | Principle                                     |
| ----------- | --------------------------------------------------------- | --------------------------------------------- |
| `openclaw`  | OpenClaw launches and manages Chrome                      | Full lifecycle control                        |
| `extension` | User already has Chrome with OpenClaw extension installed | Relay CDP commands via Chrome Extension Relay |

The `extension` mode solves a practical problem: users may already be using Chrome and logged into various websites. Rather than launching a brand new Chrome instance (without cookies, without login state), it's better to reuse the user's existing browser—just install an OpenClaw extension to establish a control channel.

***

## 24.1.4 Configuration Constants

```typescript
// src/browser/constants.ts
export const DEFAULT_OPENCLAW_BROWSER_ENABLED = true;
export const DEFAULT_BROWSER_EVALUATE_ENABLED = true;
export const DEFAULT_OPENCLAW_BROWSER_COLOR = "#FF4500";
export const DEFAULT_OPENCLAW_BROWSER_PROFILE_NAME = "openclaw";
export const DEFAULT_BROWSER_DEFAULT_PROFILE_NAME = "chrome";
export const DEFAULT_AI_SNAPSHOT_MAX_CHARS = 80_000;
export const DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS = 10_000;
export const DEFAULT_AI_SNAPSHOT_EFFICIENT_DEPTH = 6;
```

Among these, `DEFAULT_AI_SNAPSHOT_MAX_CHARS = 80,000` and `DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS = 10,000` control the text length limit of page snapshots sent to the LLM—the more complex the page, the larger the snapshot, but overly large snapshots consume excessive context window.

***

## Summary of This Section

1. **Dual-layer architecture**: CDP for low-level operations (screenshots, JS execution, tab management), Playwright for high-level operations (clicking, filling forms, page snapshots)
2. **Chrome lifecycle management**: Automatically discover browser executables (supporting Chrome/Brave/Edge/Chromium), create isolated user data directories, first-time profile setup, wait for CDP readiness
3. **Multi-profile support**: Each profile gets independent CDP port (18800-18899 range), theme color, user data directory
4. **Two driver modes**: `openclaw` mode launches Chrome itself, `extension` mode reuses user's existing browser via extension relay
5. **Clear port planning**—Gateway, Bridge, browser control, and Canvas each have reserved ports, CDP port pool supports up to 100 profiles
