> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_12_cli_and_tui/12.2_tui_implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 12.2 TUI Implementation

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generated on**: 2026-02-17

***

OpenCode's TUI (Terminal User Interface) is the primary entry point for users to converse with the AI. Unlike traditional CLI tools that output text line by line, the TUI provides a graphical-like interactive experience—with conversation lists, message bubbles, permission confirmation dialogs, command palettes, and more, all rendered within the terminal.

> **Extended Explanation: What is a TUI?**
>
> A TUI (Terminal User Interface) is a graphical user interface implemented within a text terminal. Unlike a GUI (Graphical User Interface), which uses pixels and a window system, a TUI uses text characters and ANSI escape sequences to achieve colors, layouts, and interactivity.
>
> Classic TUI programs include `vim`, `htop`, `tmux`, and others. Modern TUI frameworks (such as Ink, Textual, and Bubbletea) allow developers to build TUI programs using languages like React, Python, or Go, significantly lowering the development barrier.

## 12.2.1 Technology Stack

OpenCode's TUI is built on the following technology stack:

| Layer               | Technology            | Purpose                                          |
| ------------------- | --------------------- | ------------------------------------------------ |
| Rendering framework | `@opentui/solid`      | Terminal rendering engine based on Solid.js      |
| Reactive system     | Solid.js              | Fine-grained reactive state management           |
| API communication   | `@opencode-ai/sdk/v2` | TypeScript SDK for communicating with the Server |
| Event streaming     | SSE / RPC             | Real-time reception of Server events             |

> **Extended Explanation: The Concept of React Renderers**
>
> The architecture of React (and React-like frameworks such as Solid.js) separates "state management and component reconciliation" from "actual rendering." React's core (the Reconciler) is responsible for computing "what changed," while the Renderer is responsible for "applying those changes to the actual target."
>
> * **react-dom**: Renders to the browser DOM
> * **react-native**: Renders to mobile native components
> * **Ink**: Renders to the terminal (using ANSI escape sequences)
> * **@opentui/solid**: A terminal renderer based on Solid.js
>
> OpenCode uses `@opentui/solid`—it transforms the Solid.js component tree into terminal output. This means developers can use familiar JSX syntax and reactive patterns to build the TUI without manually handling terminal escape sequences and cursor positioning.

## 12.2.2 Worker Thread Model

An important design decision in the TUI is running **UI rendering** and **business logic** on separate threads:

```
Main Thread (UI Thread)                  Worker Thread (Business Thread)
┌──────────────────┐                 ┌──────────────────┐
│  Terminal Render  │                 │  OpenCode Server │
│  Engine           │                 │  Session/Agent   │
│  User Input       │  ←── RPC ──→   │  MCP/Plugin      │
│  Component State  │                 │  Event Bus       │
│  Dialogs/Palette  │                 │                  │
└──────────────────┘                 └──────────────────┘
```

`thread.ts` is the entry point for the TUI command. It is responsible for creating the Worker thread and establishing communication:

```typescript
// cli/cmd/tui/thread.ts
export const TuiThreadCommand = cmd({
  command: "$0 [project]",   // Default command
  describe: "start opencode tui",
  handler: async (args) => {
    // 1. Create the Worker thread
    const worker = new Worker(workerPath, { env: /* ... */ })
    const client = Rpc.client<typeof rpc>(worker)

    // 2. Decide communication mode
    const shouldStartServer = /* whether the user explicitly specified a port or hostname */

    if (shouldStartServer) {
      // Mode A: Start an HTTP Server
      const server = await client.call("server", networkOpts)
      url = server.url
    } else {
      // Mode B: Direct RPC communication (no HTTP overhead)
      url = "http://opencode.internal"
      customFetch = createWorkerFetch(client)
      events = createEventSource(client)
    }

    // 3. Start TUI rendering
    await tui({ url, fetch: customFetch, events, args, onExit })
  },
})
```

The logic for choosing between the two communication modes:

* **Mode A (HTTP Server)**: When the user explicitly requests starting a Server via parameters like `--port` or `--hostname`, or when external clients (such as the Web UI or IDE extensions) need to connect, a full HTTP Server is started. The TUI communicates with the Server via HTTP and SSE.
* **Mode B (Direct RPC)**: The default mode. The TUI communicates directly with the business logic through the Worker thread's message channel, bypassing the HTTP layer. This mode has lower latency and less overhead. `createWorkerFetch()` simulates the `fetch` API but actually invokes `Server.App().fetch()` in the Worker via RPC.

### Worker Thread (worker.ts)

The Worker thread is responsible for running OpenCode's core business logic:

```typescript
// cli/cmd/tui/worker.ts

// Forward GlobalBus events to the main thread via RPC
GlobalBus.on("event", (event) => {
  Rpc.emit("global.event", event)
})

// Subscribe to SDK event stream and forward via RPC
const startEventStream = (directory: string) => {
  const sdk = createOpencodeClient({
    baseUrl: "http://opencode.internal",
    directory,
    fetch: /* directly calls Server.App().fetch() */,
  })

  while (!signal.aborted) {
    const events = await sdk.event.subscribe({}, { signal })
    for await (const event of events.stream) {
      Rpc.emit("event", event)  // Forward to the main thread
    }
  }
}

export const rpc = {
  // Proxy HTTP requests
  async fetch(input) { /* ... */ },
  // Start HTTP Server
  async server(input) { /* ... */ },
  // Check for upgrades
  async checkUpgrade(input) { /* ... */ },
  // Hot-reload configuration
  async reload() {
    Config.global.reset()
    await Instance.disposeAll()
  },
  // Shutdown
  async shutdown() { /* ... */ },
}

Rpc.listen(rpc)
```

The Worker exposes five RPC methods. Among them, the `reload` method supports hot-reloading configuration triggered by a `SIGUSR2` signal—after a user modifies `opencode.json`, they can trigger a reload via `kill -USR2 <pid>` or from within the TUI, without restarting the process.

## 12.2.3 TUI Application Entry (app.tsx)

The `tui()` function is the entry point for the TUI application, responsible for creating the Solid.js render tree:

```typescript
// cli/cmd/tui/app.tsx
export function tui(input: {
  url: string
  args: Args
  fetch?: typeof fetch
  events?: EventSource
  onExit?: () => Promise<void>
}) {
  return new Promise<void>(async (resolve) => {
    const mode = await getTerminalBackgroundColor()

    render(() => {
      return (
        <ErrorBoundary fallback={/* ... */}>
          <ArgsProvider>
            <ExitProvider>
              <KVProvider>
                <ToastProvider>
                  <RouteProvider>
                    <SDKProvider>
                      <SyncProvider>
                        <ThemeProvider mode={mode}>
                          <LocalProvider>
                            <KeybindProvider>
                              <PromptStashProvider>
                                <DialogProvider>
                                  <CommandProvider>
                                    <FrecencyProvider>
                                      <PromptHistoryProvider>
                                        <PromptRefProvider>
                                          <App />
                                        </PromptRefProvider>
                                      </PromptHistoryProvider>
                                    </FrecencyProvider>
                                  </CommandProvider>
                                </DialogProvider>
                              </PromptStashProvider>
                            </KeybindProvider>
                          </LocalProvider>
                        </ThemeProvider>
                      </SyncProvider>
                    </SDKProvider>
                  </RouteProvider>
                </ToastProvider>
              </KVProvider>
            </ExitProvider>
          </ArgsProvider>
        </ErrorBoundary>
      )
    }, {
      targetFps: 60,
      exitOnCtrlC: false,
      useKittyKeyboard: {},
    })
  })
}
```

The 16 layers of nested Providers form the TUI's context hierarchy—this is a common "Provider Hell" pattern in React/Solid.js applications. Each Provider passes down a specific context:

| Provider                | Responsibility                                      |
| ----------------------- | --------------------------------------------------- |
| `ArgsProvider`          | CLI startup arguments                               |
| `ExitProvider`          | Exit handling logic                                 |
| `KVProvider`            | Key-value store (persisting user preferences)       |
| `ToastProvider`         | Notification messages (similar to browser Toasts)   |
| `RouteProvider`         | Page routing management                             |
| `SDKProvider`           | OpenCode API client                                 |
| `SyncProvider`          | Data synchronization (Sessions, Messages, etc.)     |
| `ThemeProvider`         | Color theme management                              |
| `LocalProvider`         | Local configuration (current Agent, Model, etc.)    |
| `KeybindProvider`       | Keyboard shortcut bindings                          |
| `PromptStashProvider`   | Cache for unsent input                              |
| `DialogProvider`        | Modal dialog management                             |
| `CommandProvider`       | Command palette (similar to VS Code's Ctrl+Shift+P) |
| `FrecencyProvider`      | Frecency sorting (frequently used commands first)   |
| `PromptHistoryProvider` | Input history records                               |
| `PromptRefProvider`     | Input field reference                               |

### Terminal Background Color Detection

The TUI automatically detects the terminal's background color at startup to decide whether to use a dark or light theme:

```typescript
async function getTerminalBackgroundColor(): Promise<"dark" | "light"> {
  if (!process.stdin.isTTY) return "dark"

  return new Promise((resolve) => {
    const handler = (data: Buffer) => {
      const str = data.toString()
      const match = str.match(/\x1b]11;([^\x07\x1b]+)/)
      if (match) {
        const color = match[1]
        // Parse RGB values and calculate luminance
        const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
        resolve(luminance > 0.5 ? "light" : "dark")
      }
    }

    process.stdin.setRawMode(true)
    process.stdin.on("data", handler)
    // Send OSC 11 query sequence
    process.stdout.write("\x1b]11;?\x07")

    // Timeout fallback to dark
    setTimeout(() => { cleanup(); resolve("dark") }, 1000)
  })
}
```

This leverages the terminal's **OSC 11** (Operating System Command) protocol—by writing `\x1b]11;?\x07` to standard output, it requests the terminal to return its background color as an RGB value. Most modern terminals (iTerm2, Windows Terminal, Alacritty, etc.) support this protocol.

## 12.2.4 Routing System

The TUI has two "pages":

* **Home**: The session list page, displaying all sessions.
* **Session**: The session detail page, displaying conversation content and tool calls.

Routing is managed in `RouteProvider` and switched via `route.navigate()`:

```typescript
// Home page: displays the session list
// Session page: displays conversation details

function App() {
  const route = useRoute()

  return (
    <Switch>
      <Match when={route.data.type === "home"}>
        <Home />
      </Match>
      <Match when={route.data.type === "session"}>
        <Session />
      </Match>
    </Switch>
  )
}
```

## 12.2.5 Command Palette

The TUI implements a VS Code-like command palette, activated via keyboard shortcuts. The command palette provides over 40 actions:

```typescript
const commands = [
  { title: "Switch session",    value: "session.list",     keybind: "session_list" },
  { title: "New session",       value: "session.new",      keybind: "session_new" },
  { title: "Switch model",      value: "model.list",       keybind: "model_list" },
  { title: "Switch agent",      value: "agent.list",       keybind: "agent_list" },
  { title: "Toggle theme",      value: "theme.toggle",     keybind: "theme_toggle" },
  { title: "MCP status",        value: "mcp.status",       keybind: "mcp_status" },
  { title: "Session diff",      value: "session.diff" },
  { title: "Export session",    value: "session.export" },
  { title: "Copy last message", value: "message.copy" },
  // ... more commands
]
```

The command palette uses `FrecencyProvider` for intelligent sorting—commands that the user has used most recently and most frequently are ranked higher.

## 12.2.6 Component Architecture

The TUI's components are located in the `tui/component/` directory, organized by function:

```
tui/component/
├── dialog-agent.tsx       # Agent selection dialog
├── dialog-command.tsx     # Command palette
├── dialog-mcp.tsx         # MCP status dialog
├── dialog-model.tsx       # Model selection dialog
├── dialog-provider.tsx    # Dialog container
├── dialog-session-list.tsx # Session list dialog
├── dialog-status.tsx      # Status dialog
├── dialog-theme-list.tsx  # Theme selection dialog
├── prompt/                # Input field components
│   ├── history.tsx        # History records
│   ├── frecency.tsx       # Frecency sorting
│   └── stash.tsx          # Input cache
└── ...
```

## 12.2.7 TUI Events

The TUI uses an internal event bus for inter-component communication (see Section 11.2):

```typescript
// cli/cmd/tui/event.ts
export const TuiEvent = {
  PromptAppend:   BusEvent.define("tui.prompt.append",   z.object({ text: z.string() })),
  CommandExecute: BusEvent.define("tui.command.execute",  z.object({ text: z.string() })),
  ToastShow:      BusEvent.define("tui.toast.show",      z.object({ title, description })),
  SessionSelect:  BusEvent.define("tui.session.select",  z.object({ sessionID })),
}
```

For example, when a user selects "Create new session" in the command palette, a `SessionSelect` event is published. The routing component subscribes to this event and switches to the new session page.

## 12.2.8 Summary

OpenCode's TUI architecture demonstrates how several modern frontend engineering practices are applied in a terminal context:

1. **Componentization**: TUI components are written using Solid.js JSX syntax, providing a development experience consistent with web frontend development.
2. **Reactivity**: Solid.js's fine-grained reactive system ensures that only the changed parts are re-rendered, maintaining smooth terminal output.
3. **Multi-threading**: The UI thread and business thread are separated, preventing long-running LLM calls from blocking UI responsiveness.
4. **Abstracted communication**: Through `customFetch` and `EventSource` abstractions, the TUI can transparently switch between RPC mode and HTTP mode.
5. **Context hierarchy**: While the 16 layers of Providers may appear verbose, each layer has a clear responsibility, achieving clean separation of concerns.
