# How to build native TypeScript terminal apps with tui

> Build fast terminal interfaces in TypeScript with Vercel Labs' tui, test them without a terminal, wire up one-line MCP control, and compile to native binaries with scriptc.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2026-12-06 | Topics: [TypeScript](https://flaviocopes.com/tags/typescript/), [CLI](https://flaviocopes.com/tags/cli/), [AI](https://flaviocopes.com/tags/ai/) | Canonical: https://flaviocopes.com/tui/

<video controls playsinline preload="metadata" poster="/images/tui/intro-poster.jpg" width="1920" height="1080" style="width: 100%; height: auto;">
  <source src="https://images.flaviocopes.com/tui/intro.mp4?v=835399b8" type="video/mp4" />
</video>

Chris Tate at Vercel Labs just released **[tui](https://github.com/vercel-labs/tui)**, a zero-dependency TypeScript library to build terminal applications that run on Node.js 24+ and compile to standalone native binaries with **[scriptc](https://scriptc.dev)**.

What caught my attention right away in [the launch post](https://x.com/ctatedev/status/2129033440440017207) was the combination of 3 things that usually live in separate worlds.

You write plain TypeScript. You compile it to a ~2 MB native executable that starts in a few milliseconds. Adding one line to `runApp` exposes your running terminal app as an MCP server for AI agents.

I installed `tui@0.2.1` and `scriptc@0.5.0` on my MacBook Pro (Apple M4 Pro) and built a real multi-panel app from scratch, ran its headless test suite, drove the compiled binary over MCP, and measured startup time and memory against Node.js 26.

In this tutorial we'll go through everything `tui` gives you, from a 20-line picker to a full service and log inspector with 100,000 searchable lines, custom primitives, spring animations, inline prompts, headless tests, MCP control, and native compilation.

## What makes tui different

Most JavaScript terminal libraries, like Ink, recreate React's virtual DOM and Yoga flexbox layout inside the terminal.

You keep React on the hook, pay for Node's startup cost every time a user invokes your CLI, and ship a runtime that weighs tens of megabytes.

`tui` goes the opposite route.

It uses an **immediate-mode rendering model** with zero runtime dependencies.

Instead of mutating a component tree, you write a single `view(frame)` function that draws the whole screen from your current state.

`tui` writes your drawing calls into a flat typed-array grid of cells, diffs that grid against the previous frame, and emits only the changed bytes inside terminal synchronized-output markers so frames never tear.

```mermaid
flowchart LR
  accTitle: Immediate-mode rendering loop in tui
  accDescr: Input events update app state, the view function redraws the full screen into a cell grid, and the renderer diffs the grid to emit only changed ANSI bytes.
  A["Key, mouse, resize, or agent event"] --> B["Update app state"]
  B --> C["view(frame) draws full cell grid"]
  C --> D["Diff against previous frame"]
  D --> E["Write changed ANSI bytes"]
```

Step through the figure below to see what happens on screen when you move a list selection by one row (2,520 bytes on the first frame vs 58 bytes on the diffed frame):

Without an `fps` option, `tui` does zero background work when idle. It only redraws when a key arrives, the window resizes, a spring asks for the next frame, or your code calls `app.redraw()`.

When you are ready to ship, `scriptc` compiles that exact TypeScript file into a native binary, with no Node.js or V8 bundled inside.

## Installation and setup

`tui` requires **Node.js 24 or later**.

Node 24+ runs `.ts` files directly, without a build step.

If you're brushing up on TypeScript syntax or types before diving in, keep the [TypeScript Handbook](https://flaviocopes.com/ebooks/typescript-handbook/) handy. You can [get a free copy in PDF or EPUB](https://flaviocopes.com/access/).

Create a project folder and add `"type": "module"` to `package.json` so both Node and `scriptc` treat `.ts` files as ES modules:

```json
{
  "name": "tui-lab",
  "private": true,
  "type": "module"
}
```

Then install `tui` and add `scriptc` as a dev dependency:

```bash
npm install tui
npm install -D scriptc
```

I hit a real problem here on npm 11, and you might too if you have `ignore-scripts=true` in your `~/.npmrc` or if you rely on the new npm 11 script approval prompts.

`scriptc` uses a postinstall script (`node scripts/install-native.mjs`) to install its native compiler binary, so running `npx scriptc --version` right after install, I got `scriptc: native installation is incomplete`.

Approve `scriptc`'s install script and rebuild it once:

```bash
npm install-scripts approve scriptc
npm rebuild scriptc --ignore-scripts=false
npx scriptc --version
```

You also need `clang` and a linker on your machine to build native executables. On macOS, Xcode Command Line Tools already provide `clang`. On Debian or Ubuntu, you can install `clang`, `lld`, `binutils` and `libc6-dev`.

`tui` exposes 3 separate entry points so you only pay for what you import:

| Import path | What it includes |
| --- | --- |
| `tui` | `runApp`, `createTestApp`, layout helpers, built-in components, `definePrimitive`, drawing, Markdown, motion, search, and game helpers |
| `tui/prompt` | Inline shell prompts (`text`, `select`, `multiselect`, `confirm`, `spinner`, `progress`) |
| `tui/agent` | `agentServer`, `createAgent`, and `agentTools` for MCP control |

## Your first tui app

Let's start with a small, complete interactive program in `hello.ts`.

It splits the screen into a header, a list of deploy targets, and a status bar at the bottom, and lets you pick an environment using the arrow keys and Enter:

```ts
import { Listbox, matchesShortcut, runApp, split, text } from 'tui'

const environments = [
  { value: 'local', label: 'Local (localhost:4321)' },
  { value: 'staging', label: 'Staging (staging.example.internal)' },
  { value: 'production', label: 'Production (flaviocopes.com)' },
]

let selected = 'none yet'

const app = runApp({
  view: (frame) => {
    const [header, list, footer] = split(frame.rect, 'rows', [1, -1, 1])
    text(frame, header.x, header.y, 'Deploy Target', frame.theme.heading)
    Listbox.Root(
      frame,
      {
        id: 'envs',
        label: 'Environment',
        items: environments,
        onValueChange: (value) => {
          selected = value
        },
      },
      (root) => Listbox.Content(root, list),
    )
    text(
      frame,
      footer.x,
      footer.y,
      `Selected: ${selected}  ·  Enter to pick  ·  q to quit`,
      frame.theme.muted,
    )
  },
  keys: (key) => {
    if (key.name === 'char' && key.text === 'q') {
      app.exit(0)
      return true
    }
    if (matchesShortcut(key, 'ctrl+c')) {
      app.exit(0)
      return true
    }
    return false
  },
})
```

You can run it right away on Node 24+, or compile it to a standalone executable:

```bash
node hello.ts
npx scriptc build hello.ts --strip -o hello-strip
./hello-strip
```

On my machine, `hello.ts` compiled to a **1.83 MB** stripped native executable that emits the same 338-byte initial ANSI frame as `node hello.ts`.

Look at the `keys` callback too. `runApp` always delivers keys to the focused component first (so Up, Down, PageUp, PageDown, Home, End, typeahead, and Enter go straight to `Listbox`). Only keys the focused component does not consume fall through to your top-level `keys` handler.

## Layout math: rects instead of CSS

There is no Flexbox or CSS engine in `tui`. Every component and drawing helper takes a plain `Rect` object: `{ x, y, columns, rows }`, starting from `frame.rect` (the full terminal size).

Four tiny helpers will handle almost every terminal layout you will ever write:

- `split(rect, direction, sizes, gap?)` divides a rect into `'rows'` or `'columns'`. Positive numbers are fixed cell counts. Negative numbers are proportional shares of whatever space remains. For example, `[1, -1, 1]` gives you a 1-row header, a flexible body, and a 1-row footer. `[24, -1]` with a gap of `1` gives you a 24-column sidebar, a 1-column gutter, and the rest of the screen.
- `inset(rect, padding)` shrinks a rect by `n` cells on all sides, or by `[vertical, horizontal]`.
- `center(rect, columns, rows)` returns a fixed-size rect centered inside another rect, which is how you position a modal `Dialog`.
- `drawBox(frame.cells, rect, { title, border })` draws a border (`'rounded'`, `'single'`, `'double'`, or `'heavy'`) and returns the inner rect ready to pass to `split` or a component.

Because the layout is recomputed inside `view(frame)` on every frame, resizing your terminal window, or animating a panel width with a spring, works out of the box, with no additional layout listeners needed.

## The component model and state contract

`tui` ships 8 components out of the box, and every one of them follows the same `Root` + parts pattern.

You pass `id` to keep a component's internal state stable across frames, and `label` so AI agents know what to call it.

| Component | Parts | Keyboard & mouse behavior |
| --- | --- | --- |
| `Listbox` | `Root`, `Content`, `Item` | Arrows, Home/End, Page keys, Ctrl+P/N, typeahead, click; Enter or Space picks |
| `CheckboxGroup` | `Root`, `Content` | Arrows move, Space toggles check, Enter fires `onSubmit` |
| `Tabs` | `Root`, `List` | Left/Right and Home/End switch tabs, click opens tab |
| `Table` | `Root`, `Content` | Header row + aligned columns (`left` or `right`), arrows and click pick rows |
| `Input` | `Root`, `Field` | Single-line shell-style editing (Ctrl+A/E/U/K/W, word jumps), bracketed paste, cursor positioning |
| `Textarea` | `Root`, `Field` | Wrapped multi-line editing, `root.api.rows(columns)` for auto-grow |
| `Dialog` | `Root`, `Content` | Centered overlay that traps Tab focus and keys while open; Escape closes it |
| `ScrollArea` | `Root`, `Viewport` | Scrollable viewport with scrollbar, `total` virtualization, and `stickToEnd` for logs |

Every stateful prop follows a single controlled/uncontrolled contract:

- Value: `value`, `defaultValue`, `onValueChange(value, details)`
- Highlight: `highlighted`, `defaultHighlighted`, `onHighlight(value, details)`
- Open state (`Dialog`): `open`, `defaultOpen`, `onOpenChange(open, details)`
- Scroll offset (`ScrollArea`): `offset`, `defaultOffset`, `onOffsetChange(offset, details)`

Every change callback gets a `details` object as its second argument:

- `details.source` tells you who triggered the change: `'keyboard'`, `'mouse'`, `'paste'`, `'programmatic'`, or `'agent'`.
- `details.reason` tells you why: `'item-press'`, `'list-navigation'`, `'input-change'`, `'escape-key'`, and so on.
- `details.cancel()` rejects the change before it commits.

One gotcha is worth knowing early: **focus follows draw order**.

The first focusable part drawn in `view(frame)` will get keyboard focus on startup, and `Tab` / `Shift+Tab` will cycle through parts in the order you draw them.

`ScrollArea.Viewport` is focusable, so always draw your search `Input` or chat `Textarea` before a `ScrollArea`, otherwise typing will scroll the viewport instead of entering text.

## Building a real multi-panel app: a service and log inspector

Toy counters are nice, but they don't show how layout, focus, virtualization, dialogs, and custom components all work together in a real tool.

Let's build a complete **Service & Log Inspector** (`ops`) that puts together all the major pieces of `tui` in one shared module (`ops-view.ts`) and a thin entry point (`ops.ts`).

Here's what `ops` does:

- A left sidebar with a live `Input` filter, a `Listbox` of services, and a custom `Toggle` primitive at the bottom.
- A right workspace with `Tabs` switching between **Overview** (`drawMeter` CPU bar, `drawSparkline` latency chart, a secret `API Token` field, and a `Table` of recent deploys), **Logs** (virtualized `ScrollArea` filtering **100,000 log lines** incrementally with `createFilter` and `drawMatches`), and **Runbook** (live rendered Markdown via `createMarkdown` and `drawLines`).
- A spring-animated right drawer (`d` key) holding a `CheckboxGroup` for log levels.
- A focus-trapped confirmation `Dialog` (`r` key) to restart the selected service.
- Full mouse support (`mouse: true`) and one-line MCP exposure (`agentServer`).

Let's start with the custom `Toggle` primitive in `ops-view.ts`.

Using `definePrimitive` and `controllable`, your own components inherit focus management, keyboard handling, controlled/uncontrolled props, and MCP agent actions:

```ts
import {
  type ChangeDetails,
  controllable,
  definePrimitive,
  matchesShortcut,
  type PrimitiveContext,
  type RootProps,
  text,
} from 'tui'

interface ToggleProps extends RootProps {
  value?: boolean
  defaultValue?: boolean
  onValueChange?: (value: boolean, details: ChangeDetails) => void
}

export const Toggle = definePrimitive({
  name: 'toggle',
  state: (context: PrimitiveContext<ToggleProps>) => ({
    value: controllable(
      context,
      'value',
      (props) => props.value,
      context.props().defaultValue ?? false,
      (props, value, details) => props.onValueChange?.(value, details),
    ),
  }),
  api: (_context, state) => ({
    toggle: () => state.value.set(!state.value.get(), 'imperative', null),
  }),
  agent: (root) => ({
    state: { value: root.state.value.get() },
    items: [],
    actions: {
      toggle: () => {
        root.api.toggle()
        return ''
      },
    },
  }),
  slots: (slot, Root) => {
    const Switch = slot('switch', {
      focusable: true,
      keys: (key, view) => {
        if (!matchesShortcut(key, 'space') && key.name !== 'enter') {
          return false
        }
        view.state.value.set(!view.state.value.get(), 'item-press', key)
        return true
      },
      draw: (view) => {
        const on = view.state.value.get()
        const label = view.props.label || 'Toggle'
        const badge = on ? '[ON ]' : '[OFF]'
        const style = view.focused
          ? view.frame.theme.highlight
          : on
            ? view.frame.theme.success
            : view.frame.theme.muted
        text(view.frame, view.rect.x, view.rect.y, `${badge} ${label}`, style, view.rect)
      },
    })
    return { Root, Switch }
  },
})
```

One little detail I learned from `scriptc` strict type checking: the space bar is not named `'space'`, but `'char'` with `key.text === ' '`.

Using `matchesShortcut(key, 'space')` is a nice way to handle this, and it passes `scriptc` type checking without complaints.

Now we wire up the app factory `createOpsApp(logCount)` so that both the live executable (`ops.ts`) and our headless test suite (`ops.test.ts`) share the same view and key handler.

In the view function, look at these 2 places:

1. **Spring animation without `fps`:** `const drawer = createSpring(0)` starts closed. Pressing `d` calls `drawer.to(drawer.target ? 0 : 1)`. Inside `view(frame)`, `drawer.update(frame)` calls `frame.animate()` automatically while the spring is moving, then stops redrawing the instant it settles.
2. **Dialog focus trapping:** While `Dialog.Root` has `open: true`, `Dialog.Content` traps all keys and Tab cycles inside the modal. Putting a `Listbox` of actions (`Restart now` / `Cancel`) inside `Dialog.Content` gives you both keyboard and mouse confirmation, and checking `details.source === 'agent'` lets us cancel programmatic restarts even inside the component itself.

```ts
// Inside createOpsApp(logCount = 100_000) in ops-view.ts
const drawerWidth = Math.round(drawer.update(frame) * 26)
const columns = drawerWidth > 0 ? [24, -1, drawerWidth] : [24, -1]
const parts = split(main, 'columns', columns, 1)
const sidebar = parts[0]!
const workspace = parts[1]!
const drawerRect = parts[2]

// Overview tab: CPU meter, latency sparkline, secret API token, deploys table
if (state.tab === 'overview') {
  const [metricsRect, tokenRect, deploysRect] = split(body, 'rows', [4, 1, -1], 1)
  text(
    frame,
    metricsRect.x,
    metricsRect.y,
    `CPU ${Math.round(svc.cpu * 100)}%`,
    svc.cpu > 0.75 ? frame.theme.destructive : frame.theme.success,
  )
  drawMeter(
    frame,
    {
      x: metricsRect.x + 10,
      y: metricsRect.y,
      columns: Math.max(8, metricsRect.columns - 10),
      rows: 1,
    },
    svc.cpu,
  )
  text(frame, metricsRect.x, metricsRect.y + 2, 'Latency (ms)', frame.theme.muted)
  drawSparkline(
    frame,
    {
      x: metricsRect.x + 14,
      y: metricsRect.y + 2,
      columns: Math.min(24, metricsRect.columns - 14),
      rows: 1,
    },
    svc.latencyMs,
  )

  // Visible to humans, redacted to "[redacted]" in MCP snapshots
  text(frame, tokenRect.x, tokenRect.y, 'API Token:', frame.theme.muted)
  Input.Root(
    frame,
    {
      id: 'api-token',
      label: 'API Token',
      agent: 'secret',
      value: svc.token,
    },
    (root) =>
      Input.Field(root, {
        x: tokenRect.x + 11,
        y: tokenRect.y,
        columns: Math.max(8, tokenRect.columns - 11),
        rows: 1,
      }),
  )

  Table.Root(
    frame,
    {
      id: 'deploys',
      label: 'Recent Deploys',
      columns: [
        { label: 'Service', width: 16 },
        { label: 'Release', width: 10 },
        { label: 'State', width: 10 },
        { label: 'When', align: 'right' },
      ],
      rows: DEPLOYS,
      onValueChange: (value) => {
        state.lastNotice = `Inspecting deploy ${value}`
      },
    },
    (root) => Table.Content(root, deploysRect),
  )
}
```

Here is the compiled `./ops` native binary running on the Overview tab with `queue-worker` selected:

![Compiled native ops app showing the Services sidebar, Overview tab with CPU meter, latency sparkline, API Token field, Recent Deploys table, and custom Toggle](https://images.flaviocopes.com/tui/ops-overview.webp?v=cf7e2b94)

### Filtering 100,000 log lines without freezing typing

If you have a huge array, you can't filter it naively inside `view(frame)`, otherwise every keystroke will stall the terminal.

`tui` solves this by using `createFilter()` and a virtualized `ScrollArea` rendering.

Every frame, `filter.update(logs, state.query)` scans for a small amount of time (a few milliseconds) and returns immediately with whatever matches it found so far.

When you append characters to the query, it only searches lines that already matched the shorter query.

And because `ScrollArea.Viewport` receives `total: filter.count`, our loop only draws the 15 or 20 rows that are actually visible on screen:

```ts
filter.update(logs, state.query)
const [statusRow, logArea] = split(body, 'rows', [1, -1])
text(
  frame,
  statusRow.x,
  statusRow.y,
  `${formatCount(filter.count)} / ${formatCount(logs.length)} lines matched${filter.done ? '' : ' (scanning…)'}`,
  frame.theme.muted,
  statusRow,
)
ScrollArea.Root(
  frame,
  { id: 'log-scroll', label: 'Logs', total: filter.count, stickToEnd: true },
  (area) =>
    ScrollArea.Viewport(area, logArea, (viewport) => {
      const offset = viewport.api.offset()
      for (let row = 0; row < viewport.rect.rows && offset + row < filter.count; row++) {
        const line = logs[filter.at(offset + row)] ?? ''
        drawMatches(
          frame,
          viewport.rect.x,
          viewport.rect.y + row,
          line,
          state.query,
          0,
          viewport.rect,
        )
      }
    }),
)
```

Notice I used `formatCount()` above instead of `.toLocaleString()`. I wrote `filter.count.toLocaleString()` initially, and it worked under Node 26, but I had a `scriptc` build error on macOS:

```text
error SC3002: the macos-arm64 runtime pack has no Intl support:
it ships no ICU objects, and only the linux-x64-gnu runtime pack
(@scriptc/runtime-linux-x64-gnu) provides Intl
```

`scriptc` does not include ICU on macOS ARM64 to keep the binary size small, and calling `.toLocaleString()` or `Intl.NumberFormat` is causing the build to fail on Apple Silicon. Replacing it with a one-line regex formatter (`String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')`) fixed the issue immediately.

Notice how `createFilter` handles case sensitivity automatically, like ripgrep's smart-case: a lowercase query is case-insensitive, but if you add an uppercase letter (like `ERROR`), it becomes case-sensitive. `drawMatches` highlights every match using `frame.theme.match`.

Here is `./ops` on the Logs tab filtering 100,000 lines for `ERROR` with the spring-animated `Levels` drawer open on the right:

![Compiled native ops app on the Logs tab filtering 100,000 lines for ERROR with highlighted matches and the spring-animated Levels drawer open](https://images.flaviocopes.com/tui/ops-logs-drawer.webp?v=d2391418)

And here is the centered confirmation `Dialog` trapping focus over the filtered logs after pressing `r`:

![Compiled native ops app showing the centered Restart confirmation Dialog trapping focus over the filtered logs](https://images.flaviocopes.com/tui/ops-dialog.webp?v=8512e0d4)

### Rendering Markdown in the Runbook tab

For the Runbook tab, `createMarkdown(frame.styles, frame.theme)` parses headings, paragraphs, bold, italics, inline code, fenced code blocks, lists, task lists, blockquotes, and tables into pre-wrapped styled lines cached by width.

Passing those lines to `drawLines` inside a `ScrollArea.Viewport` gives you a scrollable documentation pane in 7 lines:

```ts
const rendered = markdown.lines(svc.runbook, Math.max(10, body.columns - 2))
ScrollArea.Root(
  frame,
  { id: 'runbook-scroll', label: 'Runbook', total: rendered.length },
  (area) =>
    ScrollArea.Viewport(area, body, (viewport) => {
      drawLines(frame, viewport.rect, rendered, viewport.api.offset())
    }),
)
```

### Graphics, shaders, and images

If you're building dashboards, charts, or terminal games, `tui` also includes `createCanvas` (half-block pixels or 2x4 braille dots), `createChart` (multi-series braille line charts with labeled axes), `drawShader` (per-pixel `0xrrggbb` functions at 60 fps without allocating styles) and `drawImage`.

On terminals that support the kitty graphics protocol, like [Ghostty](https://flaviocopes.com/ghostty/) and kitty, `drawImage` will send real images, using Unicode placeholders so modals and dialogs can still layer on top of them. On other terminals or inside tmux, it will automatically fall back to colored half-block characters.

### Complete runnable `ops-view.ts`

If you want to run the tests and native build from the next sections yourself, expand the full `ops-view.ts` file below and save it next to `ops.ts` and `ops.test.ts`:

<details>
<summary>Show the complete ops-view.ts (491 lines)</summary>

```ts
import {
  center,
  type ChangeDetails,
  CheckboxGroup,
  controllable,
  createFilter,
  createMarkdown,
  createSpring,
  definePrimitive,
  Dialog,
  drawBox,
  drawLines,
  drawMatches,
  drawMeter,
  drawSparkline,
  type Frame,
  Input,
  inset,
  type Key,
  Listbox,
  matchesShortcut,
  paint,
  type PrimitiveContext,
  type RootProps,
  ScrollArea,
  split,
  Table,
  Tabs,
  text,
} from 'tui'

export interface Service {
  id: string
  name: string
  status: 'healthy' | 'degraded'
  cpu: number
  latencyMs: number[]
  token: string
  runbook: string
}

export const SERVICES: Service[] = [
  {
    id: 'api',
    name: 'edge-api',
    status: 'healthy',
    cpu: 0.34,
    latencyMs: [18, 21, 19, 24, 22, 17, 20, 23, 19, 18, 21, 16],
    token: 'tok_live_9f8a2c41e0',
    runbook: `## edge-api runbook\n\nHandles public HTTPS traffic behind **Caddy**.\n\n- Health check: \`GET /healthz\`\n- Restart takes ~1.2 s with zero dropped connections\n\n\`\`\`sh\nsystemctl reload edge-api\n\`\`\``,
  },
  {
    id: 'worker',
    name: 'queue-worker',
    status: 'degraded',
    cpu: 0.82,
    latencyMs: [45, 52, 68, 94, 112, 108, 125, 119, 134, 141, 128, 136],
    token: 'tok_live_7b31d99a12',
    runbook: `## queue-worker runbook\n\nDrains background email and webhook jobs.\n\n- Watch queue depth when CPU stays above **80%**\n- Check \`WARN\` and \`ERROR\` lines in the Logs tab before restarting`,
  },
  {
    id: 'postgres',
    name: 'postgres-primary',
    status: 'healthy',
    cpu: 0.27,
    latencyMs: [4, 5, 4, 6, 5, 4, 7, 5, 4, 5, 4, 4],
    token: 'tok_live_4c10e82f55',
    runbook: `## postgres-primary runbook\n\nPrimary PostgreSQL 17 instance with WAL archiving enabled.\n\n- Never restart during a base backup\n- Check active locks with \`pg_stat_activity\``,
  },
  {
    id: 'redis',
    name: 'redis-cache',
    status: 'healthy',
    cpu: 0.14,
    latencyMs: [1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2],
    token: 'tok_live_1a55b70c33',
    runbook: `## redis-cache runbook\n\nIn-memory rate limiter and session cache.\n\n- Eviction policy: \`allkeys-lru\``,
  },
]

const DEPLOYS = [
  { value: 'd-412', cells: ['edge-api', 'v2.14.0', 'live', '14m ago'] },
  { value: 'd-411', cells: ['queue-worker', 'v1.9.3', 'degraded', '2h ago'] },
  { value: 'd-410', cells: ['edge-api', 'v2.13.9', 'previous', '1d ago'] },
  { value: 'd-409', cells: ['redis-cache', 'v7.4.2', 'live', '6d ago'] },
]

interface ToggleProps extends RootProps {
  value?: boolean
  defaultValue?: boolean
  onValueChange?: (value: boolean, details: ChangeDetails) => void
}

export const Toggle = definePrimitive({
  name: 'toggle',
  state: (context: PrimitiveContext<ToggleProps>) => ({
    value: controllable(
      context,
      'value',
      (props) => props.value,
      context.props().defaultValue ?? false,
      (props, value, details) => props.onValueChange?.(value, details),
    ),
  }),
  api: (_context, state) => ({
    toggle: () => state.value.set(!state.value.get(), 'imperative', null),
  }),
  agent: (root) => ({
    state: { value: root.state.value.get() },
    items: [],
    actions: {
      toggle: () => {
        root.api.toggle()
        return ''
      },
    },
  }),
  slots: (slot, Root) => {
    const Switch = slot('switch', {
      focusable: true,
      keys: (key, view) => {
        if (!matchesShortcut(key, 'space') && key.name !== 'enter') {
          return false
        }
        view.state.value.set(!view.state.value.get(), 'item-press', key)
        return true
      },
      draw: (view) => {
        const on = view.state.value.get()
        const label = view.props.label || 'Toggle'
        const badge = on ? '[ON ]' : '[OFF]'
        const style = view.focused
          ? view.frame.theme.highlight
          : on
            ? view.frame.theme.success
            : view.frame.theme.muted
        text(view.frame, view.rect.x, view.rect.y, `${badge} ${label}`, style, view.rect)
      },
    })
    return { Root, Switch }
  },
})

export function buildSampleLogs(count: number) {
  const levels = ['INFO', 'INFO', 'INFO', 'WARN', 'ERROR']
  const services = ['edge-api', 'queue-worker', 'postgres-primary', 'redis-cache']
  const messages = [
    'GET /api/posts 200 18ms',
    'webhook retry scheduled attempt=2',
    'checkpoint complete wrote=412 buffers',
    'job timeout waiting for upstream socket',
    'rate-limit window rotated keys=1284',
  ]
  const lines: string[] = new Array(count)
  for (let i = 0; i < count; i++) {
    const lvl = levels[i % levels.length] ?? 'INFO'
    const svc = services[i % services.length] ?? 'edge-api'
    const msg = messages[i % messages.length] ?? 'ok'
    lines[i] = `12:${String(Math.floor(i / 60) % 60).padStart(2, '0')}:${String(i % 60).padStart(2, '0')} [${lvl}] ${svc} #${i} ${msg}`
  }
  return lines
}

export function createOpsApp(logCount = 100_000) {
  const logs = buildSampleLogs(logCount)
  const filter = createFilter()
  const drawer = createSpring(0)
  let markdown: ReturnType<typeof createMarkdown> | null = null

  const state = {
    query: '',
    serviceId: 'api',
    tab: 'overview',
    levels: ['INFO', 'WARN', 'ERROR'] as readonly string[],
    autoRefresh: true,
    confirmRestart: false,
    restarts: 0,
    lastNotice: 'Tab moves focus · r restarts service · d toggles drawer · q quits',
    lastSource: 'none',
  }

  function currentService() {
    return SERVICES.find((s) => s.id === state.serviceId) ?? SERVICES[0]!
  }

  function view(frame: Frame) {
    markdown ??= createMarkdown(frame.styles, frame.theme)
    const [topBar, main, footer] = split(frame.rect, 'rows', [1, -1, 1])

    const svc = currentService()
    text(
      frame,
      topBar.x,
      topBar.y,
      ` ops · ${svc.name} (${svc.status}) · restarts: ${state.restarts}`,
      frame.theme.heading,
      topBar,
    )

    const drawerWidth = Math.round(drawer.update(frame) * 26)
    const columns = drawerWidth > 0 ? [24, -1, drawerWidth] : [24, -1]
    const parts = split(main, 'columns', columns, 1)
    const sidebar = parts[0]!
    const workspace = parts[1]!
    const drawerRect = parts[2]

    const sideInside = drawBox(frame.cells, sidebar, { title: 'Services' })
    const [searchRect, listRect, toggleRect] = split(sideInside, 'rows', [1, -1, 1])

    Input.Root(
      frame,
      {
        id: 'filter',
        label: 'Filter',
        value: state.query,
        placeholder: 'Filter services or logs…',
        onValueChange: (value, details) => {
          state.query = value
          state.lastSource = details.source
        },
      },
      (root) => Input.Field(root, searchRect),
    )

    const matchingServices = SERVICES.filter((item) =>
      item.name.toLowerCase().includes(state.query.toLowerCase()),
    ).map((item) => ({
      value: item.id,
      label: `${item.status === 'healthy' ? '●' : '▲'} ${item.name}`,
    }))

    Listbox.Root(
      frame,
      {
        id: 'services',
        label: 'Services',
        items: matchingServices.length
          ? matchingServices
          : [{ value: svc.id, label: `${svc.status === 'healthy' ? '●' : '▲'} ${svc.name}` }],
        value: state.serviceId,
        onValueChange: (value, details) => {
          state.serviceId = value
          state.lastSource = details.source
          state.lastNotice = `Selected ${value} (${details.source})`
        },
      },
      (root) => Listbox.Content(root, listRect),
    )

    Toggle.Root(
      frame,
      {
        id: 'auto-refresh',
        label: 'Auto-refresh',
        value: state.autoRefresh,
        onValueChange: (value) => {
          state.autoRefresh = value
        },
      },
      (root) => Toggle.Switch(root, toggleRect),
    )

    const workInside = drawBox(frame.cells, workspace, { title: svc.name })
    const [tabsRect, bodyRect] = split(workInside, 'rows', [1, -1])

    Tabs.Root(
      frame,
      {
        id: 'views',
        label: 'View',
        value: state.tab,
        items: [
          { value: 'overview', label: 'Overview' },
          { value: 'logs', label: 'Logs' },
          { value: 'runbook', label: 'Runbook' },
        ],
        onValueChange: (value) => {
          state.tab = value
        },
      },
      (root) => Tabs.List(root, tabsRect),
    )

    const body = inset(bodyRect, [1, 0])

    if (state.tab === 'overview') {
      const [metricsRect, tokenRect, deploysRect] = split(body, 'rows', [4, 1, -1], 1)
      text(
        frame,
        metricsRect.x,
        metricsRect.y,
        `CPU ${Math.round(svc.cpu * 100)}%`,
        svc.cpu > 0.75 ? frame.theme.destructive : frame.theme.success,
      )
      drawMeter(
        frame,
        {
          x: metricsRect.x + 10,
          y: metricsRect.y,
          columns: Math.max(8, metricsRect.columns - 10),
          rows: 1,
        },
        svc.cpu,
      )
      text(frame, metricsRect.x, metricsRect.y + 2, 'Latency (ms)', frame.theme.muted)
      drawSparkline(
        frame,
        {
          x: metricsRect.x + 14,
          y: metricsRect.y + 2,
          columns: Math.min(24, metricsRect.columns - 14),
          rows: 1,
        },
        svc.latencyMs,
      )

      text(frame, tokenRect.x, tokenRect.y, 'API Token:', frame.theme.muted)
      Input.Root(
        frame,
        {
          id: 'api-token',
          label: 'API Token',
          agent: 'secret',
          value: svc.token,
        },
        (root) =>
          Input.Field(root, {
            x: tokenRect.x + 11,
            y: tokenRect.y,
            columns: Math.max(8, tokenRect.columns - 11),
            rows: 1,
          }),
      )

      Table.Root(
        frame,
        {
          id: 'deploys',
          label: 'Recent Deploys',
          columns: [
            { label: 'Service', width: 16 },
            { label: 'Release', width: 10 },
            { label: 'State', width: 10 },
            { label: 'When', align: 'right' },
          ],
          rows: DEPLOYS,
          onValueChange: (value) => {
            state.lastNotice = `Inspecting deploy ${value}`
          },
        },
        (root) => Table.Content(root, deploysRect),
      )
    } else if (state.tab === 'logs') {
      filter.update(logs, state.query)
      const [statusRow, logArea] = split(body, 'rows', [1, -1])
      text(
        frame,
        statusRow.x,
        statusRow.y,
        `${formatCount(filter.count)} / ${formatCount(logs.length)} lines matched${filter.done ? '' : ' (scanning…)'}`,
        frame.theme.muted,
        statusRow,
      )
      ScrollArea.Root(
        frame,
        { id: 'log-scroll', label: 'Logs', total: filter.count, stickToEnd: true },
        (area) =>
          ScrollArea.Viewport(area, logArea, (viewport) => {
            const offset = viewport.api.offset()
            for (let row = 0; row < viewport.rect.rows && offset + row < filter.count; row++) {
              const line = logs[filter.at(offset + row)] ?? ''
              drawMatches(
                frame,
                viewport.rect.x,
                viewport.rect.y + row,
                line,
                state.query,
                0,
                viewport.rect,
              )
            }
          }),
      )
    } else {
      const rendered = markdown.lines(svc.runbook, Math.max(10, body.columns - 2))
      ScrollArea.Root(
        frame,
        { id: 'runbook-scroll', label: 'Runbook', total: rendered.length },
        (area) =>
          ScrollArea.Viewport(area, body, (viewport) => {
            drawLines(frame, viewport.rect, rendered, viewport.api.offset())
          }),
      )
    }

    if (drawerRect && drawerRect.columns >= 8) {
      const drawerInside = drawBox(frame.cells, drawerRect, { title: 'Levels' })
      CheckboxGroup.Root(
        frame,
        {
          id: 'levels',
          label: 'Log Levels',
          items: [
            { value: 'INFO', label: 'Info' },
            { value: 'WARN', label: 'Warn' },
            { value: 'ERROR', label: 'Error' },
          ],
          value: state.levels,
          onValueChange: (values) => {
            state.levels = values
          },
        },
        (root) => CheckboxGroup.Content(root, drawerInside),
      )
    }

    paint(frame, footer, frame.theme.muted)
    text(frame, footer.x, footer.y, ` ${state.lastNotice}`, frame.theme.muted, footer)

    Dialog.Root(
      frame,
      {
        id: 'restart-dialog',
        label: 'Restart Service',
        title: `Restart ${svc.name}?`,
        open: state.confirmRestart,
        onOpenChange: (open) => {
          state.confirmRestart = open
        },
      },
      (root) =>
        Dialog.Content(root, center(frame.rect, 44, 8), (dialog) => {
          const [promptRow, actionsRect] = split(inset(dialog.rect, [1, 1]), 'rows', [2, -1])
          text(dialog.frame, promptRow.x, promptRow.y, `Restart ${svc.name} right now?`)
          Listbox.Root(
            dialog.frame,
            {
              id: 'restart-actions',
              label: 'Restart Actions',
              items: [
                { value: 'confirm', label: 'Restart now' },
                { value: 'cancel', label: 'Cancel' },
              ],
              onValueChange: (choice, details) => {
                if (details.source === 'agent') {
                  details.cancel()
                  return
                }
                state.confirmRestart = false
                if (choice === 'confirm') {
                  state.restarts++
                  state.lastNotice = `Restarted ${svc.name} (total: ${state.restarts})`
                }
              },
            },
            (actions) => Listbox.Content(actions, actionsRect),
          )
        }),
    )
  }

  function handleKey(key: Key, exit?: () => void) {
    if (matchesShortcut(key, 'ctrl+c')) {
      exit?.()
      return true
    }
    if (key.name === 'char' && key.alone && key.text === 'r') {
      state.confirmRestart = true
      return true
    }
    if (key.name === 'char' && key.alone && key.text === 'd') {
      drawer.to(drawer.target ? 0 : 1)
      return true
    }
    if (key.name === 'char' && key.alone && key.text === 'q') {
      exit?.()
      return true
    }
    return false
  }

  return { state, view, handleKey, drawer, filter }
}

function formatCount(n: number) {
  return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
```

</details>

## Inline shell prompts with tui/prompt

Not every CLI needs to take over the whole alternate screen. Sometimes you want an interactive setup wizard that renders below your cursor, and leaves the answers in your normal shell scrollback, like the tools in the [CLI Handbook](https://flaviocopes.com/ebooks/cli-commands-handbook/).

`tui/prompt` gives you `text`, `select`, `multiselect`, `confirm`, `spinner`, `progress` built on the same components (and you can also build your own inline app with `runApp({ view, rows: 3 })`).

Two design choices in `tui/prompt` stand out in practice:

- Pass `output: process.stderr` so interactive prompts and spinners draw to stderr while stdout stays clean for JSON or piped data.
- When `stdin` is not a TTY (for example, in CI or a shell pipe), prompts switch automatically to line-by-line input, and `spinner`/`progress` print only their final completion line.

Here is `deploy-wizard.ts`:

```ts
import { confirm, multiselect, progress, select, spinner, text } from 'tui/prompt'

const io = { output: process.stderr }

const service = await text({
  ...io,
  message: 'Service name',
  placeholder: 'api-worker',
  validate: (value) =>
    /^[a-z0-9-]+$/.test(value) ? null : 'Use lowercase letters, numbers, and hyphens only',
})
if (service === null) process.exit(130)

const region = await select({
  ...io,
  message: 'Primary region',
  items: [
    { value: 'fra', label: 'Frankfurt (fra)' },
    { value: 'iad', label: 'Ashburn (iad)' },
    { value: 'sin', label: 'Singapore (sin)' },
  ],
  defaultValue: 'fra',
})
if (region === null) process.exit(130)

const checks = await multiselect({
  ...io,
  message: 'Pre-deploy checks',
  items: [
    { value: 'typecheck', label: 'TypeScript check' },
    { value: 'tests', label: 'Unit tests' },
    { value: 'migrations', label: 'DB migrations' },
  ],
  defaultValues: ['typecheck', 'tests'],
  required: true,
})
if (checks === null) process.exit(130)

const proceed = await confirm({
  ...io,
  message: `Deploy ${service} to ${region}?`,
  defaultValue: true,
})
if (proceed === null || !proceed) process.exit(130)

const building = spinner({ ...io, message: 'Compiling native binary' })
await new Promise((resolve) => setTimeout(resolve, 250))
building.stop('Compiled native binary')

const upload = progress({ ...io, message: 'Uploading artifact', max: 100 })
for (let pct = 25; pct <= 100; pct += 25) {
  await new Promise((resolve) => setTimeout(resolve, 60))
  upload.update(pct)
}
upload.stop('Artifact uploaded')

process.stdout.write(JSON.stringify({ service, region, checks, deployed: true }) + '\n')
```

Every prompt returns `null` if the user cancels with Ctrl+C or Escape, so checking `=== null` and exiting with code `130` makes shell scripts well-behaved.

Notice that `confirm` checks `key.alone` when bracketed paste is active, so an accidental paste with the letter `y` will never confirm a destructive action.

Compiling `deploy-wizard.ts` with `npx scriptc build deploy-wizard.ts --strip -o deploy-wizard` gives us a **1.8 MB** binary, and piping answers into it works out of the box:

![Compiled deploy-wizard prompt binary running in a shell pipe and outputting clean JSON on stdout](https://images.flaviocopes.com/tui/deploy-wizard-piped.webp?v=3de3bd6c)

## Testing without a terminal using createTestApp

Testing terminal UIs usually involves spawning a fragile PTY wrapper, sleeping for arbitrary timeouts and scraping raw ANSI escape codes.

`tui` ships `createTestApp` in the main package. It runs your `view` and `keys` against an in-memory cell grid with zero terminal I/O, redrawing synchronously after every action, so tests are deterministic and run in milliseconds under `node --test`:

- `app.type(text)` and `app.press(shortcut)` simulate keyboard input.
- `app.click(x, y)` and `app.wheel(x, y, 'down')` simulate mouse events.
- `app.find(text)` locates where a string appears on screen, and `app.cell(x, y)` inspects any cell's character, colors, bold/dim/inverse attributes, and hyperlink.
- `app.advance(ms)` moves the virtual clock forward so you can test springs, transitions, and `fps` loops step by step.
- `app.resize(columns, rows)` tests responsive layouts at narrow widths.

Here is `ops.test.ts`, testing keyboard filtering, mouse clicking a tab, dialog focus trapping, spring drawer animation, and agent permissions:

```ts
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createTestApp } from 'tui'
import { createAgent } from 'tui/agent'
import { createOpsApp } from './ops-view.ts'

test('filters services, switches tabs, and searches logs', () => {
  const ops = createOpsApp(5_000)
  const app = createTestApp({
    columns: 96,
    rows: 24,
    mouse: true,
    view: ops.view,
    keys: (key) => ops.handleKey(key),
  })

  app.type('worker')
  assert.equal(ops.state.query, 'worker')

  app.press('tab')
  app.press('enter')
  assert.equal(ops.state.serviceId, 'worker')

  const logsTab = app.find('Logs')
  assert.ok(logsTab)
  app.click(logsTab.x, logsTab.y)
  assert.equal(ops.state.tab, 'logs')

  assert.ok(ops.filter.count > 0)
  assert.ok(app.screen().some((line) => line.includes('queue-worker')))
})

test('opens restart dialog, traps focus, and confirms on Enter', () => {
  const ops = createOpsApp(100)
  const app = createTestApp({
    columns: 96,
    rows: 24,
    view: ops.view,
    keys: (key) => ops.handleKey(key),
  })

  app.press('tab')
  app.press('r')
  assert.equal(ops.state.confirmRestart, true)
  assert.ok(app.find('Restart edge-api right now?'))

  app.press('enter')
  assert.equal(ops.state.confirmRestart, false)
  assert.equal(ops.state.restarts, 1)
})

test('animates the spring drawer across frames with advance()', () => {
  const ops = createOpsApp(100)
  const app = createTestApp({
    columns: 100,
    rows: 24,
    view: ops.view,
    keys: (key) => ops.handleKey(key),
  })

  app.press('tab')
  app.press('d')
  for (let i = 0; i < 30; i++) {
    app.advance(16)
  }
  assert.ok(app.find('Levels'))
})

test('agent snapshot redacts secrets and allow blocks dialog actions', () => {
  const ops = createOpsApp(1_000)
  const app = createTestApp({
    columns: 96,
    rows: 24,
    view: ops.view,
    keys: (key) => ops.handleKey(key),
  })

  const agent = createAgent(app, {
    allow: (step) => step.component !== 'dialog',
  })

  const initial = agent.snapshot()
  const tokenField = initial.components.find((c) => c.ref === 'api-token')
  assert.ok(tokenField)
  assert.equal(tokenField.state.value, '[redacted]')

  const result = agent.act({
    steps: [
      { ref: 'services', action: 'select', args: ['postgres'] },
      { ref: 'views', action: 'open', args: ['runbook'] },
      { ref: 'auto-refresh', action: 'toggle', args: [] },
    ],
  })
  assert.equal(result.ok, true)
  assert.equal(ops.state.serviceId, 'postgres')
  assert.equal(ops.state.tab, 'runbook')
  assert.equal(ops.state.autoRefresh, false)
  assert.equal(ops.state.lastSource, 'agent')

  ops.state.confirmRestart = true
  app.press('tab')
  const blocked = agent.act({
    steps: [{ ref: 'restart-dialog', action: 'close', args: [] }],
  })
  assert.equal(blocked.ok, false)
  assert.match(blocked.error, /refused/)
})
```

All 4 tests pass in 178 ms, and `scriptc` builds the stripped native `ops-strip` binary right after:

![Running node --test ops.test.ts and compiling ops-strip with scriptc](https://images.flaviocopes.com/tui/build-and-test.webp?v=167d1905)

## Exposing your terminal app to AI agents over MCP

This is the feature that makes `tui` feel like it's made for 2026. Instead of asking a coding agent to scrape raw terminal characters, or guess keystrokes blindly, `tui/agent` exposes your live component tree over the Model Context Protocol.

If you want to know more about how local stdio MCP servers work, read my [MCP Server Handbook](https://flaviocopes.com/ebooks/mcp-handbook/) or my [how to build an MCP server in TypeScript](https://flaviocopes.com/build-mcp-server/) tutorial.

With `tui` you don't have to write the JSON-RPC server yourself. You just pass `agentServer` to `runApp` in `ops.ts`:

```ts
import { runApp } from 'tui'
import { agentServer } from 'tui/agent'
import { createOpsApp } from './ops-view.ts'

const ops = createOpsApp(100_000)

const app = runApp({
  mouse: true,
  view: ops.view,
  keys: (key) => ops.handleKey(key, () => app.exit(0)),
  agent: agentServer({
    name: 'ops',
    allow: (step) => step.component !== 'dialog',
  }),
})
```

Here is how the two processes talk to each other when `ops` is running:

```mermaid
flowchart LR
  accTitle: How tui/agent connects an AI agent to a live terminal app
  accDescr: An AI coding agent talks MCP JSON-RPC over stdio to the ops mcp subcommand, which forwards snapshot and act calls over a private Unix socket to the running ops TUI after checking the allow policy.
  A["AI coding agent"] -->|"MCP JSON-RPC (stdio)"| B["./ops mcp"]
  B -->|"Private Unix socket (0600)"| C["Running ./ops TUI"]
  C -->|"allow() check + redaction"| D["Components & screen"]
  D -->|"Structured JSON result"| B
  B -->|"Tool reply"| A
```

When you launch `./ops` in your terminal, `agentServer` opens a Unix domain socket under your OS temp directory with `0700` directory permissions and `0600` socket permissions (only your user account can connect).

When an agent runs `./ops mcp`, `agentServer` intercepts `process.argv[2] === 'mcp'` before the TUI ever touches your terminal, starts a stdio MCP server speaking protocol `2025-11-25`, and proxies two tools to the newest running `./ops` instance:

- `snapshot` (`readOnlyHint: true`): returns every drawn component's `ref`, `component` type, `label`, `state`, `items`, `actions`, `focused` flag, plus the plain-text `screen` lines.
- `act` (`destructiveHint: true`): executes an ordered array of steps (`select`, `open`, `setValue`, `submit`, `toggle`, or built-in `focus`, `press`, `type`), reports every state change it caused, and returns the updated snapshot.

I started the compiled `./ops` binary in a PTY and drove `./ops mcp` directly over JSON-RPC to inspect the real wire output.

Calling `snapshot` returned our built-in components AND our custom `Toggle` primitive, while automatically redacting `api-token` because we marked it `agent: 'secret'`:

```json
[
  {
    "ref": "auto-refresh",
    "component": "toggle",
    "label": "Auto-refresh",
    "state": { "value": true },
    "items": [],
    "actions": ["toggle"],
    "focused": false
  },
  {
    "ref": "api-token",
    "component": "input",
    "label": "API Token",
    "state": {
      "value": "[redacted]",
      "placeholder": "[redacted]"
    },
    "items": [],
    "actions": ["setValue", "submit"],
    "focused": false
  }
]
```

Components marked `agent: 'hidden'` are completely removed from the `snapshot`.

Next I sent a 3-step `act` call (`services` -> `select` `"worker"`, `views` -> `open` `"logs"`, `filter` -> `type` `"ERROR"`).

In a single call, the running `./ops` terminal updated live, returned the exact list of changes, and sent back the new screen with `20,000 / 100,000 lines matched`:

```json
{
  "ok": true,
  "error": "",
  "changes": [
    { "ref": "services", "key": "highlighted", "value": "worker" },
    { "ref": "services", "key": "value", "value": "worker" },
    { "ref": "views", "key": "value", "value": "logs" },
    { "ref": "filter", "key": "value", "value": "ERROR" }
  ]
}
```

Then I sent `{ "ref": "restart-dialog", "action": "open", "args": [] }`.

Because our `allow` callback rejects any step that targets a `dialog`, the server blocked it before any state changed:

```json
{
  "ok": false,
  "error": "restart-dialog open: refused"
}
```

Because `ops` is just a regular stdio MCP server (`ops mcp`), you can register it in Codex or Claude Code with one command:

```bash
codex mcp add ops -- ./ops mcp
# or in Claude Code:
claude mcp add ops -- ./ops mcp
```

### Driving `ops` live from Codex (and a real security caveat)

I wired `./ops mcp` into `codex exec` while `./ops` was running in a PTY and asked Codex to inspect the degraded service, filter its `ERROR` logs, and try opening the restart dialog.

Two real details showed up right away.

First, `tui/agent` sets MCP tool annotations automatically: `snapshot` is marked `readOnlyHint: true`, while `act` is marked `destructiveHint: true`. Codex let `snapshot` run immediately, and prompted for approval before calling `act` unless I explicitly approved `ops` tools in Codex's config (`mcp_servers.ops.default_tools_approval_mode="approve"`).

Second, Codex caught an important caveat in `agent: 'secret'`. While `api-token` came back as `"[redacted]"` inside `snapshot.components`, `snapshot.screen` still includes the plain-text cells currently painted on the terminal. Because `ops-view.ts` drew `svc.token` in plaintext inside the input box, Codex could still read it off `snapshot.screen`. If you want to hide a real secret from agents, mask the rendered string on screen too (for example, draw `'••••••••'` unless the user explicitly toggles reveal), instead of relying on `agent: 'secret'` alone.

Once approved, Codex completed all 3 MCP tool calls cleanly against the running native binary, matching `20,000 / 100,000 lines` on `ERROR` and getting `restart-dialog open: refused` from our `allow` policy:

![Live Codex exec session calling snapshot and act against the running compiled ops binary over MCP](https://images.flaviocopes.com/tui/agent-mcp-session.webp?v=0f087138)

## Real benchmarks: Node.js 26 vs scriptc native binary

I ran 15 interleaved PTY cold-start runs and 5 peak-RSS samples on my MacBook Pro (Apple M4 Pro) comparing Homebrew **Node.js v26.14.0** (61.02 MB for `node` + `libnode`) against **scriptc 0.5.0** `--strip` binaries for both `hello.ts` and `ops.ts` (including allocating 100,000 log lines before the first frame):

| Metric | `hello` native (`scriptc`) | `hello` Node 26 | `ops` native (100k logs) | `ops` Node 26 (100k logs) |
| --- | --- | --- | --- | --- |
| First frame (median) | **3.77 ms** (3.15–4.05 ms) | 152.53 ms (146.65–154.92 ms) | **10.89 ms** (8.78–372.28 ms) | 179.95 ms (174.83–183.19 ms) |
| Startup speedup | **40.4× faster** | baseline | **16.5× faster** | baseline |
| Peak memory (RSS) | **3.9 MB** | 70.8 MB (18.2× higher) | **14.8 MB** | 127.5 MB (8.6× higher) |
| Stripped binary size | **1.83 MB** | 61.02 MB runtime | **2.47 MB** | 61.02 MB runtime |

One detail on that `372.28 ms` max for `ops` native: macOS Gatekeeper validates a newly linked executable once on its very first run, and the remaining 14 runs settled between 8.78 ms and 11.4 ms.

Even when allocating 100,000 strings upfront and bundling the MCP server, the native binary still paints its first frame in ~11 ms using under 15 MB of RAM.

## How tui compares to Ink, Bubble Tea, and Ratatui

Choosing a TUI framework usually comes down to your language, your distribution target and if you need agent automation.

| Framework | Language | Rendering model | Binary distribution | Built-in testing & MCP |
| --- | --- | --- | --- | --- |
| **tui** | TypeScript | Immediate-mode cell grid + diff | Node 24+ or ~2 MB `scriptc` native binary | `createTestApp` + 1-line `tui/agent` MCP |
| **Ink** | TypeScript / React | React reconciler + Yoga flexbox | Requires Node/Bun runtime (~60+ MB) | `ink-testing-library`, no built-in MCP |
| **Bubble Tea** | Go | Elm architecture (Model / Update / View) | Single static Go binary (~5–15 MB) | `teatest` helper, no built-in MCP |
| **Ratatui** | Rust | Immediate-mode widget buffer | Single native Rust binary (~1–5 MB) | `TestBackend`, no built-in MCP |

If your team already writes Rust or Go, Ratatui and Bubble Tea are mature, battle-tested ecosystems with years of community widgets behind them.

`tui` is the first library that brings Ratatui-like immediate-mode speed and tiny native binaries to TypeScript, without dragging React or a full JavaScript engine along for the ride.

## How I would use tui (and where I would skip it)

I haven't shipped a production CLI with `tui` yet, since it just launched on December 5, but here's where I would actually reach for it in my own workflow.

I would use `tui` for **internal developer dashboards, release tools, and companion CLIs** where I already write TypeScript for everything else (like the automation scripts in this site repo, or Cloudflare Workers tooling). Being able to write a single `.ts` file, test every keyboard flow in `node --test` with `createTestApp`, compile it to a 2 MB binary I drop in `~/.local/bin`, and still let a coding agent inspect it over MCP via `mytool mcp` is a huge ergonomic jump over hand-rolling ANSI scripts or maintaining a separate Go/Rust repo.

I would also use `tui/prompt` for interactive setup wizards in small Node CLIs, specifically because `output: process.stderr` and automatic non-TTY line mode mean the same binary works cleanly for humans and for scripts piping stdin/stdout.

Where would I skip `tui`?

- **Long-lived production CLIs that cannot tolerate breaking API changes.** `tui` is at `0.2.1` and explicitly warns that its API will change before 1.0, and `scriptc` is at `0.5.0`. If you need a rock-solid API that won't move for three years, wait for 1.0 or use Bubble Tea / Ratatui.
- **Apps that depend heavily on Node-only npm packages or `Intl`.** `scriptc` compiles a strict subset of TypeScript and omits ICU/`Intl` in its `macos-arm64` runtime pack. If your TUI needs heavy third-party Node libraries, you may end up running on Node 24+ instead of compiling native, which gives up the startup and memory win.
- **Simple flag-driven CLIs.** If your tool only needs subcommands and `--json` output (especially for agent use, as I covered in [MCP vs direct API integrations (and CLIs)](https://flaviocopes.com/mcp-vs-direct-api/)), a plain argument-parsing CLI is simpler and composes better in pipes than a full-screen TUI.

If you want to try `tui` today, start with `npm install tui`, write a small `Listbox` or `Table` view, and run `node app.ts` on Node 24+.

Once the layout feels right, add `scriptc` and run `npx scriptc build app.ts --strip -o app` to feel the difference of a 3 ms TypeScript terminal app.
