> 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/ch36-native-client-apps/36.4-shared-components.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 36.4 Shared Components

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

***

There is substantial shared logic between the macOS and iOS applications—Gateway WebSocket protocol, chat UI, Canvas command parsing, device authentication, and more. This shared code is unified in `apps/shared/OpenClawKit/`.

## 36.4.1 OpenClawKit Architecture

### Swift Package Structure

OpenClawKit is a Swift package containing three library targets:

```swift
// apps/shared/OpenClawKit/Package.swift
let package = Package(
    name: "OpenClawKit",
    platforms: [.iOS(.v18), .macOS(.v15)],
    products: [
        .library(name: "OpenClawProtocol", targets: ["OpenClawProtocol"]),
        .library(name: "OpenClawKit", targets: ["OpenClawKit"]),
        .library(name: "OpenClawChatUI", targets: ["OpenClawChatUI"]),
    ],
    dependencies: [
        .package(url: "ElevenLabsKit", exact: "0.1.0"),   // TTS speech synthesis
        .package(url: "textual", exact: "0.3.1"),          // Markdown rendering
    ],
)
```

### Three-Layer Architecture

```
┌──────────────────────┐
│   OpenClawChatUI     │  ← SwiftUI chat components (macOS + iOS shared)
│   depends on: OpenClawKit   │
│   depends on: Textual       │  ← Markdown rendering
├──────────────────────┤
│   OpenClawKit        │  ← Core business logic
│   depends on: OpenClawProtocol│
│   depends on: ElevenLabsKit │  ← TTS provider
├──────────────────────┤
│   OpenClawProtocol   │  ← Pure data models + protocol definitions
│   no external dependencies  │
└──────────────────────┘
```

| Layer                | Responsibility                                                                                    | File Count |
| -------------------- | ------------------------------------------------------------------------------------------------- | ---------- |
| **OpenClawProtocol** | Gateway JSON models (`GatewayModels`), Wizard helpers, AnyCodable                                 | 3          |
| **OpenClawKit**      | WebSocket client, device authentication, Canvas commands, TTS, capability declaration, Deep Links | 39         |
| **OpenClawChatUI**   | SwiftUI chat views, message rendering, Markdown, session management                               | 13         |

### OpenClawProtocol — Pure Data Layer

The bottom layer contains only data models for Gateway communication with no external dependencies:

```
Sources/OpenClawProtocol/
├── AnyCodable.swift       # Dynamic JSON value type
├── GatewayModels.swift    # Gateway frames, Hello, events, etc. types
└── WizardHelpers.swift    # Onboarding wizard helper types
```

This layering ensures that protocol types can be referenced by any target without introducing unnecessary dependencies.

### OpenClawKit — Core Logic

The middle layer contains all core logic for interacting with the Gateway:

```
Sources/OpenClawKit/
├── GatewayChannel.swift          # WebSocket client (protocol + actor)
├── GatewayNodeSession.swift      # Node session management
├── GatewayTLSPinning.swift       # TLS certificate pinning
├── GatewayPush.swift             # Push notification integration
├── DeviceIdentity.swift          # Ed25519 device keys
├── DeviceAuthStore.swift         # Device token storage
├── Capabilities.swift            # Capability declaration enum
├── CanvasCommands.swift          # Canvas manipulation commands
├── CanvasA2UIAction.swift        # Agent-to-UI actions
├── CanvasA2UICommands.swift      # A2UI command definitions
├── CanvasCommandParams.swift     # Canvas parameter types
├── CameraCommands.swift          # Camera commands
├── ScreenCommands.swift          # Screen recording commands
├── LocationCommands.swift        # Location commands
├── SystemCommands.swift          # System commands
├── TalkDirective.swift           # Talk Mode directives
├── TalkPromptBuilder.swift       # Talk prompt construction
├── TalkSystemSpeechSynthesizer.swift  # System TTS
├── TalkHistoryTimestamp.swift    # Conversation history timestamps
├── BonjourTypes.swift            # Bonjour service discovery types
├── BonjourEscapes.swift          # Bonjour name escaping
├── DeepLinks.swift               # Deep link handling
├── StoragePaths.swift            # File path constants
├── JPEGTranscoder.swift          # JPEG encoding/decoding
└── ...
```

#### WebSocket Client

`GatewayChannel` is the shared WebSocket client, decoupled from concrete network implementations through protocol abstraction (`WebSocketTasking`):

```swift
// apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayChannel.swift
public protocol WebSocketTasking: AnyObject {
    var state: URLSessionTask.State { get }
    func resume()
    func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
    func send(_ message: URLSessionWebSocketTask.Message) async throws
    func receive() async throws -> URLSessionWebSocketTask.Message
}

extension URLSessionWebSocketTask: WebSocketTasking {}
```

The default `URLSession` implementation sets a maximum message size of 16MB—large snapshots and history payloads may exceed the default limit:

```swift
extension URLSession: WebSocketSessioning {
    public func makeWebSocketTask(url: URL) -> WebSocketTaskBox {
        let task = self.webSocketTask(with: url)
        task.maximumMessageSize = 16 * 1024 * 1024  // 16 MB
        return WebSocketTaskBox(task: task)
    }
}
```

Connection options are passed through the `GatewayConnectOptions` struct:

```swift
public struct GatewayConnectOptions: Sendable {
    public var role: String          // "node" or "operator"
    public var scopes: [String]      // Permission scopes
    public var caps: [String]        // Device capabilities
    public var commands: [String]    // Supported commands
    public var permissions: [String: Bool]  // Acquired permissions
    public var clientId: String
    public var clientMode: String
}
```

#### Capability System

Device capabilities are defined through a concise enum:

```swift
public enum OpenClawCapability: String, Codable, Sendable {
    case canvas       // Canvas manipulation
    case camera       // Camera
    case screen       // Screen recording
    case voiceWake    // Voice wake
    case location     // Location information
}
```

Each capability corresponds to a set of command types (such as `CameraCommands`, `ScreenCommands`). The Gateway decides which tools to expose to AI agents based on the list of capabilities declared by the node.

### OpenClawChatUI — Shared Chat Interface

The top layer is a SwiftUI chat component used by both macOS and iOS:

```
Sources/OpenClawChatUI/
├── ChatView.swift                 # Main chat view
├── ChatViewModel.swift            # Chat view model
├── ChatComposer.swift             # Message input component
├── ChatMessageViews.swift         # Message bubble rendering
├── ChatModels.swift               # Chat data models
├── ChatTransport.swift            # Chat transport protocol
├── ChatPayloadDecoding.swift      # Message payload decoding
├── ChatSessions.swift             # Session management
├── ChatSheets.swift               # Chat-related Sheet views
├── ChatTheme.swift                # Chat theme colors
├── ChatMarkdownPreprocessor.swift # Markdown preprocessing
├── ChatMarkdownRenderer.swift     # Markdown rendering (using Textual)
└── AssistantTextParser.swift      # Assistant text parsing
```

`ChatView` is a complete SwiftUI view containing message list, input box, session switching, and more. It is decoupled from the concrete network layer through the `ChatTransport` protocol—macOS and iOS each provide different transport implementations.

### Android's Sharing Strategy

The Android application cannot directly use Swift packages. Its sharing strategy is:

1. **Resource file reuse**: Directly reference `OpenClawKit/Resources` through Gradle's `assets.srcDir`
2. **Protocol reimplementation**: Capability enums, command types, etc. are redefined in Kotlin in the `ai.openclaw.android.protocol` package
3. **Communication protocol consistency**: Although the languages differ, the JSON format of WebSocket frames is unified across platforms

***

## Summary of This Section

1. **OpenClawKit is a shared Swift package for macOS and iOS**, adopting a three-layer architecture: Protocol (pure data) → Kit (core logic) → ChatUI (SwiftUI components).
2. **WebSocket client** is decoupled from URLSession through protocol abstraction, supporting 16MB large messages and TLS certificate pinning.
3. **Capability system** declares device hardware capabilities through 5 enum values, with the Gateway deciding available tools based on this.
4. **ChatUI layer** provides a complete SwiftUI chat interface, supporting different network backends through the `ChatTransport` protocol.
5. **Android maintains cross-platform consistency through resource sharing and protocol reimplementation**, with JSON frame format being the unified contract across all three platforms.
