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

# 41.1 TUI Architecture

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

***

OpenClaw provides a fully-featured Terminal User Interface (TUI) that allows users to interact with AI Agents directly in the terminal through interactive conversations. The TUI is not merely a simple command-line REPL—it features syntax highlighting, Markdown rendering, tool call visualization, multi-Agent switching, session management, and other complete functionality.

> **Sidebar: The Difference Between TUI and CLI** CLI (Command Line Interface) is the traditional command-line tool—users input commands, the program returns results, and interaction is linear. TUI (Terminal User Interface), on the other hand, constructs an interface similar to a GUI within the terminal, featuring layout systems, interactive components, and real-time updates. Classic TUI applications include `vim`, `htop`, and `tmux`. TUI controls terminal cursor position, text color, and screen regions through ANSI escape codes.

## 41.1.1 pi-tui Integration

OpenClaw's TUI is built on the `@mariozechner/pi-tui` library, which provides a set of terminal UI components including layout containers, text rendering, editors, loading animations, list selection, and other basic components.

### Core Dependencies

```typescript
import {
  CombinedAutocompleteProvider,  // Combined autocomplete
  Container,                     // Layout container
  Loader,                        // Loading animation
  ProcessTerminal,               // Terminal adapter
  Text,                          // Text component
  TUI,                           // TUI root instance
} from "@mariozechner/pi-tui";
```

### TUI Component Tree

The TUI interface is composed of a component tree:

```
TUI (root)
└── root (Container)
    ├── header (Text)         ← Title bar: URL / Agent / Session
    ├── chatLog (ChatLog)     ← Chat history area
    ├── statusContainer       ← Status line (loading animation / messages)
    ├── footer (Text)         ← Bottom info bar
    └── editor (CustomEditor) ← Input editor
```

```typescript
// src/tui/tui.ts (simplified)

export async function runTui(opts: TuiOptions) {
  const tui = new TUI(new ProcessTerminal());
  const header = new Text("", 1, 0);
  const statusContainer = new Container();
  const footer = new Text("", 1, 0);
  const chatLog = new ChatLog();
  const editor = new CustomEditor(tui, editorTheme);

  const root = new Container();
  root.addChild(header);
  root.addChild(chatLog);
  root.addChild(statusContainer);
  root.addChild(footer);
  root.addChild(editor);

  tui.addChild(root);
  tui.setFocus(editor);  // Focus defaults to editor
}
```

`ProcessTerminal` is the low-level terminal adapter, encapsulating `process.stdin` / `process.stdout` read/write and terminal size detection.

### Custom Components

In addition to `pi-tui`'s built-in components, OpenClaw implements the following custom components (located in `src/tui/components/`):

| Component              | File                        | Function                                                |
| ---------------------- | --------------------------- | ------------------------------------------------------- |
| `ChatLog`              | `chat-log.ts`               | Chat history display with scrolling and history loading |
| `CustomEditor`         | `custom-editor.ts`          | Input editor with multi-line support and autocomplete   |
| `AssistantMessage`     | `assistant-message.ts`      | Markdown rendering of AI replies                        |
| `UserMessage`          | `user-message.ts`           | Formatted display of user messages                      |
| `ToolExecution`        | `tool-execution.ts`         | Visualization of tool calls                             |
| `FilterableSelectList` | `filterable-select-list.ts` | Filterable selection list                               |
| `SearchableSelectList` | `searchable-select-list.ts` | Searchable selection list (fuzzy matching)              |

## 41.1.2 TUI Adaptation Layer

Files in the `src/tui/` directory are clearly layered by responsibility:

```
tui.ts                    — Main entry: component tree construction + state management
tui-types.ts              — Type definitions
├── gateway-chat.ts       — Gateway WebSocket client adapter
├── tui-event-handlers.ts — Gateway event handling
├── tui-command-handlers.ts — Slash command handling
├── tui-session-actions.ts  — Session operations (switch/reset/load history)
├── tui-stream-assembler.ts — Streaming response assembly
├── tui-formatters.ts     — Text formatting
├── tui-overlays.ts       — Overlays (Agent selector/session selector)
├── tui-local-shell.ts    — Local Shell execution (!command)
├── tui-waiting.ts        — Waiting state messages
├── tui-status-summary.ts — Gateway status summary
├── commands.ts           — Slash command definitions
└── theme/                — Themes and color schemes
```

### Gateway Client

TUI communicates with Gateway through `GatewayChatClient`:

```typescript
// src/tui/gateway-chat.ts (simplified)

export class GatewayChatClient {
  private client: GatewayClient;

  constructor(opts: GatewayConnectionOptions) {
    this.client = new GatewayClient({
      url: resolveUrl(opts),
      token: opts.token,
      password: opts.password,
      clientName: GATEWAY_CLIENT_NAMES.TUI,
      mode: GATEWAY_CLIENT_MODES.TUI,
      onEvent: (evt) => { /* forward events */ },
      onHelloOk: () => { /* connection success callback */ },
      onClose: () => { /* disconnect callback */ },
    });
  }

  async sendMessage(opts: ChatSendOptions) {
    return this.client.request("chat.send", {
      sessionKey: opts.sessionKey,
      message: opts.message,
      thinking: opts.thinking,
      deliver: opts.deliver,
      idempotencyKey: opts.runId ?? randomUUID(),
    }, { expectFinal: true });
  }

  async listSessions(params) {
    return this.client.request("sessions.list", params);
  }

  async patchSession(params) {
    return this.client.request("sessions.patch", params);
  }
}
```

### State Management

TUI state is centrally managed through the `TuiStateAccess` interface, using getter/setter proxy patterns:

```typescript
export type TuiStateAccess = {
  agentDefaultId: string;       // Default Agent ID
  currentAgentId: string;       // Currently active Agent
  currentSessionKey: string;    // Current session key
  currentSessionId: string | null;
  activeChatRunId: string | null; // Current run ID
  historyLoaded: boolean;        // Whether history is loaded
  sessionInfo: SessionInfo;      // Session info (model/token/thinking, etc.)
  isConnected: boolean;          // WebSocket connection status
  toolsExpanded: boolean;        // Whether tool output is expanded
  showThinking: boolean;         // Whether to show thinking process
  connectionStatus: string;      // "connecting" / "connected" / "reconnecting"
  activityStatus: string;        // "idle" / "sending" / "waiting" / "streaming"
  // ...
};
```

State changes automatically trigger UI updates. For example, when `activityStatus` changes from `"idle"` to `"streaming"`, the status bar switches to a loading animation.

### Input Handling

The editor's submit handler supports three input modes:

```typescript
export function createEditorSubmitHandler(params) {
  return (text: string) => {
    const raw = text;
    const value = raw.trim();
    params.editor.setText("");

    if (!value) return;  // Ignore empty input

    // Mode 1: Bash command (starts with !)
    if (raw.startsWith("!") && raw !== "!") {
      params.editor.addToHistory(raw);
      void params.handleBangLine(raw);
      return;
    }

    params.editor.addToHistory(value);

    // Mode 2: Slash command (starts with /)
    if (value.startsWith("/")) {
      void params.handleCommand(value);
      return;
    }

    // Mode 3: Regular message
    void params.sendMessage(value);
  };
}
```

Three input modes:

| Prefix | Mode    | Example                   | Behavior                       |
| ------ | ------- | ------------------------- | ------------------------------ |
| `!`    | Bash    | `!ls -la`                 | Execute command in local Shell |
| `/`    | Command | `/think high`             | Execute slash command          |
| None   | Message | `Write a function for me` | Send to AI Agent               |

Note that `!` mode uses **raw untrimmed text** (`raw`), ensuring leading spaces don't accidentally trigger Bash mode. A standalone `!` is treated as a regular message.

## 41.1.3 Terminal Rendering

### Theme System

TUI's color scheme is defined in `src/tui/theme/theme.ts`:

```typescript
const palette = {
  text: "#E8E3D5",        // Main text color
  dim: "#7B7F87",         // Dim text
  accent: "#F6C453",      // Accent color (golden)
  accentSoft: "#F2A65A",  // Soft accent color
  border: "#3C414B",      // Border color
  userBg: "#2B2F36",      // User message background
  userText: "#F3EEE0",    // User message text
  systemText: "#9BA3B2",  // System prompt text
  toolPendingBg: "#1F2A2F", // Tool executing background
  toolSuccessBg: "#1E2D23",  // Tool success background
  toolErrorBg: "#2F1F1F",    // Tool failure background
  toolTitle: "#F6C453",   // Tool title color
  quote: "#8CC8FF",       // Quote text color (blue)
  code: "#F0C987",        // Inline code color
  codeBlock: "#1E232A",   // Code block background
  link: "#7DD3A5",        // Link color (green)
  error: "#F97066",       // Error color (red)
  success: "#7DD3A5",     // Success color (green)
};
```

The color scheme is carefully designed to provide comfortable reading in dark terminals. Code highlighting is based on the `cli-highlight` library, supporting syntax coloring for major programming languages.

### Terminal Utilities

`src/terminal/` provides low-level terminal operation tools:

| File               | Function                                              |
| ------------------ | ----------------------------------------------------- |
| `ansi.ts`          | ANSI escape code constants and utility functions      |
| `palette.ts`       | Global color palette (independent of TUI theme)       |
| `links.ts`         | Terminal hyperlinks (OSC 8 protocol)                  |
| `table.ts`         | Terminal table rendering                              |
| `stream-writer.ts` | Stream writer (supports throttling and buffering)     |
| `progress-line.ts` | Progress line (single-line updates)                   |
| `note.ts`          | Note box rendering                                    |
| `restore.ts`       | Terminal state restoration (restore on abnormal exit) |

### Streaming Response Assembly

`TuiStreamAssembler` is responsible for assembling Gateway's incremental events into complete display text:

```typescript
export class TuiStreamAssembler {
  private runs = new Map<string, RunStreamState>();

  // Process incremental updates
  ingestDelta(
    runId: string,
    message: unknown,
    showThinking: boolean,
  ): string | null {
    const state = this.getOrCreateRun(runId);
    const previousDisplayText = state.displayText;

    // Extract thinking process and content separately
    const thinkingText = extractThinkingFromMessage(message);
    const contentText = extractContentFromMessage(message);
    if (thinkingText) state.thinkingText = thinkingText;
    if (contentText) state.contentText = contentText;

    // Compose display text
    state.displayText = composeThinkingAndContent({
      thinkingText: state.thinkingText,
      contentText: state.contentText,
      showThinking,
    });

    // Only return if text actually changed
    if (state.displayText === previousDisplayText) return null;
    return state.displayText;
  }

  // Finalize: clean up run state
  finalize(runId: string, message: unknown, showThinking: boolean) {
    // ... final assembly + cleanup
    this.runs.delete(runId);
    return finalText;
  }
}
```

Each run (`runId`) maintains independent state: `thinkingText` (thinking process) and `contentText` (main content) are tracked separately and composed into display text as needed. The `showThinking` parameter controls whether to display the thinking process (such as Claude's `<thinking>` tag content) to the user.

### Status Line and Waiting Animation

When the Agent is processing, the status line displays a dynamic waiting message:

```typescript
const busyStates = new Set([
  "sending",    // Sending message
  "waiting",    // Waiting for Agent response
  "streaming",  // Receiving streaming output
  "running",    // Agent executing tool
]);

// Update status line every second
const startStatusTimer = () => {
  statusTimer = setInterval(() => {
    if (!busyStates.has(activityStatus)) return;
    updateBusyStatusMessage();
  }, 1000);
};

// Example waiting message: "thinking... • 12s | connected"
```

`tui-waiting.ts` provides a set of random waiting phrases (such as "thinking...", "reasoning..."), adding interest to the interface.

## 41.1.4 Slash Command System

TUI provides rich slash commands covering Agent management, session control, model switching, and more:

```typescript
export function getSlashCommands(options): SlashCommand[] {
  return [
    { name: "help", description: "Show slash command help" },
    { name: "status", description: "Show gateway status summary" },
    { name: "agent", description: "Switch agent (or open picker)" },
    { name: "session", description: "Switch session" },
    { name: "model", description: "Set model (or open picker)" },
    {
      name: "think",
      description: "Set thinking level",
      getArgumentCompletions: (prefix) =>
        thinkLevels.filter(v => v.startsWith(prefix))
          .map(value => ({ value, label: value })),
    },
    { name: "verbose", description: "Set verbose on/off" },
    { name: "reasoning", description: "Set reasoning on/off" },
    { name: "elevated", description: "Toggle elevated mode" },
    { name: "activation", description: "Set group activation mode" },
    { name: "usage", description: "Toggle usage footer" },
    { name: "queue", description: "Adjust queue mode" },
    { name: "bash", description: "Run a host command" },
    { name: "compact", description: "Compact session history" },
    { name: "new", description: "Start new session" },
    { name: "reset", description: "Reset session" },
    { name: "stop", description: "Stop current run" },
    // ...
  ];
}
```

Commands support **argument autocomplete**—for example, the `/think` command autocompletes levels like `off`, `minimal`, `low`, `medium`, `high`, `xhigh`. The command alias mechanism (`COMMAND_ALIASES`) supports shortcuts, such as `/elev` → `/elevated`.

### Overlay Selectors

Complex selection operations (such as Agent switching, session selection, model selection) are implemented through **overlays**:

```typescript
// src/tui/tui-overlays.ts
// Agent selector → fuzzy search list
// Session selector → filterable list + session metadata preview
// Model selector → searchable list + model capability info
```

Overlays use the `SearchableSelectList` component, supporting keyboard navigation and fuzzy search (`fuzzy-filter.ts`), providing an interaction experience similar to VS Code's command palette.

## 41.1.5 Local Shell

TUI's `!` prefix supports executing local Shell commands directly in the terminal:

```typescript
// src/tui/tui-local-shell.ts

export function createLocalShellRunner(params: {
  chatLog: ChatLog;
  editor: CustomEditor;
}) {
  return async (bangLine: string) => {
    const command = bangLine.slice(1); // Remove ! prefix
    // Display command in chatLog
    // Execute via subprocess
    // Stream output in real-time
    // Error handling
  };
}
```

This allows users to execute file operations, run scripts, and more without leaving the TUI interface—very practical in AI-assisted programming workflows.

***

## Section Summary

1. **pi-tui framework**: TUI is built on `@mariozechner/pi-tui`, using a component tree model (header → chatLog → status → footer → editor).
2. **Gateway communication**: `GatewayChatClient` wraps the WebSocket client, providing high-level APIs like `sendMessage`/`listSessions`/`patchSession`.
3. **Three input modes**: `!` prefix executes local Shell, `/` prefix triggers slash commands, no prefix sends message to Agent.
4. **Streaming response assembly**: `TuiStreamAssembler` separately tracks thinking process and main content, composing display text as needed, supporting incremental updates.
5. **Theme system**: Carefully designed 20+ color palette with syntax highlighting (`cli-highlight`), providing comfortable reading in dark terminals.
6. **Slash commands**: 20+ commands covering Agent/session/model management, supporting argument autocomplete and command aliases.
7. **Overlay selectors**: Fuzzy search lists for Agent/session/model selection, providing interaction experience similar to VS Code's command palette.
8. **Terminal utilities layer**: `src/terminal/` provides low-level capabilities like ANSI control, table rendering, stream writing, and hyperlinks.
