{"slug": "how-to-build-native-typescript-terminal-apps-with-tui", "title": "How to build native TypeScript terminal apps with tui", "summary": "Vercel Labs released tui 0.2.1, a zero-dependency TypeScript library for building terminal applications on Node.js 24+ that compiles to standalone native binaries via scriptc 0.5.0, according to a tutorial by Flavio. The library uses an immediate-mode rendering model that diffs a typed-array cell grid and emits only changed bytes — 58 bytes on a diffed frame versus 2,520 bytes on the first — and exposes a running terminal app as an MCP server for AI agents by adding one line to runApp. The author measured startup time and memory of the roughly 2 MB compiled binary against Node.js 26 on an Apple M4 Pro MacBook Pro.", "body_md": "# How to build native TypeScript terminal apps with tui\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [TypeScript](https://flaviocopes.com/tags/typescript/), [CLI](https://flaviocopes.com/tags/cli/), [AI](https://flaviocopes.com/tags/ai/)\n\nBuild 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.\n\nChris 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)**.\n\nWhat 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.\n\nYou 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.\n\nI 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.\n\nIn 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.\n\n## What makes tui different\n\nMost JavaScript terminal libraries, like Ink, recreate React’s virtual DOM and Yoga flexbox layout inside the terminal.\n\nYou 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.\n\n`tui` goes the opposite route.\n\nIt uses an **immediate-mode rendering model** with zero runtime dependencies.\n\nInstead of mutating a component tree, you write a single `view(frame)` function that draws the whole screen from your current state.\n\n`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.\n\nStep 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):\n\nWithout 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()`.\n\nWhen you are ready to ship, `scriptc` compiles that exact TypeScript file into a native binary, with no Node.js or V8 bundled inside.\n\n## Installation and setup\n\n`tui` requires **Node.js 24 or later**.\n\nNode 24+ runs `.ts` files directly, without a build step.\n\nIf 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/).\n\nCreate a project folder and add `\"type\": \"module\"` to `package.json` so both Node and `scriptc` treat `.ts` files as ES modules:\n\n```\n{\n  \"name\": \"tui-lab\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n```\n\nThen install `tui` and add `scriptc` as a dev dependency:\n\n```\nnpm install tui\nnpm install -D scriptc\n```\n\nI 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.\n\n`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`.\n\nApprove `scriptc`’s install script and rebuild it once:\n\n```\nnpm install-scripts approve scriptc\nnpm rebuild scriptc --ignore-scripts=false\nnpx scriptc --version\n```\n\nYou 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`.\n\n`tui` exposes 3 separate entry points so you only pay for what you import:\n\n| Import path | What it includes | \n|---|---|\n| `tui` | `runApp` ,`createTestApp` , layout helpers, built-in components,`definePrimitive` , drawing, Markdown, motion, search, and game helpers | \n| `tui/prompt` | Inline shell prompts ( `text` ,`select` ,`multiselect` ,`confirm` ,`spinner` ,`progress` ) | \n| `tui/agent` | `agentServer` ,`createAgent` , and`agentTools` for MCP control | \n\n## Your first tui app\n\nLet’s start with a small, complete interactive program in `hello.ts`.\n\nIt 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:\n\n``` js\nimport { Listbox, matchesShortcut, runApp, split, text } from 'tui'\n\nconst environments = [\n  { value: 'local', label: 'Local (localhost:4321)' },\n  { value: 'staging', label: 'Staging (staging.example.internal)' },\n  { value: 'production', label: 'Production (flaviocopes.com)' },\n]\n\nlet selected = 'none yet'\n\nconst app = runApp({\n  view: (frame) => {\n    const [header, list, footer] = split(frame.rect, 'rows', [1, -1, 1])\n    text(frame, header.x, header.y, 'Deploy Target', frame.theme.heading)\n    Listbox.Root(\n      frame,\n      {\n        id: 'envs',\n        label: 'Environment',\n        items: environments,\n        onValueChange: (value) => {\n          selected = value\n        },\n      },\n      (root) => Listbox.Content(root, list),\n    )\n    text(\n      frame,\n      footer.x,\n      footer.y,\n      `Selected: ${selected}  ·  Enter to pick  ·  q to quit`,\n      frame.theme.muted,\n    )\n  },\n  keys: (key) => {\n    if (key.name === 'char' && key.text === 'q') {\n      app.exit(0)\n      return true\n    }\n    if (matchesShortcut(key, 'ctrl+c')) {\n      app.exit(0)\n      return true\n    }\n    return false\n  },\n})\n```\n\nYou can run it right away on Node 24+, or compile it to a standalone executable:\n\n```\nnode hello.ts\nnpx scriptc build hello.ts --strip -o hello-strip\n./hello-strip\n```\n\nOn 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`.\n\nLook 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.\n\n## Layout math: rects instead of CSS\n\nThere 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).\n\nFour tiny helpers will handle almost every terminal layout you will ever write:\n\n- `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.\n- `inset(rect, padding)` shrinks a rect by`n` cells on all sides, or by`[vertical, horizontal]` .\n- `center(rect, columns, rows)` returns a fixed-size rect centered inside another rect, which is how you position a modal`Dialog` .\n- `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.\n\nBecause 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.\n\n## The component model and state contract\n\n`tui` ships 8 components out of the box, and every one of them follows the same `Root` + parts pattern.\n\nYou pass `id` to keep a component’s internal state stable across frames, and `label` so AI agents know what to call it.\n\n| Component | Parts | Keyboard & mouse behavior | \n|---|---|---|\n| `Listbox` | `Root` ,`Content` ,`Item` | Arrows, Home/End, Page keys, Ctrl+P/N, typeahead, click; Enter or Space picks | \n| `CheckboxGroup` | `Root` ,`Content` | Arrows move, Space toggles check, Enter fires `onSubmit` | \n| `Tabs` | `Root` ,`List` | Left/Right and Home/End switch tabs, click opens tab | \n| `Table` | `Root` ,`Content` | Header row + aligned columns ( `left` or`right` ), arrows and click pick rows | \n| `Input` | `Root` ,`Field` | Single-line shell-style editing (Ctrl+A/E/U/K/W, word jumps), bracketed paste, cursor positioning | \n| `Textarea` | `Root` ,`Field` | Wrapped multi-line editing, `root.api.rows(columns)` for auto-grow | \n| `Dialog` | `Root` ,`Content` | Centered overlay that traps Tab focus and keys while open; Escape closes it | \n| `ScrollArea` | `Root` ,`Viewport` | Scrollable viewport with scrollbar, `total` virtualization, and`stickToEnd` for logs | \n\nEvery stateful prop follows a single controlled/uncontrolled contract:\n\n- Value: `value` ,`defaultValue` ,`onValueChange(value, details)`\n- Highlight: `highlighted` ,`defaultHighlighted` ,`onHighlight(value, details)`\n- Open state (`Dialog` ):`open` ,`defaultOpen` ,`onOpenChange(open, details)`\n- Scroll offset (`ScrollArea` ):`offset` ,`defaultOffset` ,`onOffsetChange(offset, details)`\n\nEvery change callback gets a `details` object as its second argument:\n\n- `details.source` tells you who triggered the change:`'keyboard'` ,`'mouse'` ,`'paste'` ,`'programmatic'` , or`'agent'` .\n- `details.reason` tells you why:`'item-press'` ,`'list-navigation'` ,`'input-change'` ,`'escape-key'` , and so on.\n- `details.cancel()` rejects the change before it commits.\n\nOne gotcha is worth knowing early: **focus follows draw order**.\n\nThe 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.\n\n`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.\n\n## Building a real multi-panel app: a service and log inspector\n\nToy counters are nice, but they don’t show how layout, focus, virtualization, dialogs, and custom components all work together in a real tool.\n\nLet’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`).\n\nHere’s what `ops` does:\n\n- A left sidebar with a live `Input` filter, a`Listbox` of services, and a custom`Toggle` primitive at the bottom.\n- 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` ).\n- A spring-animated right drawer (`d` key) holding a`CheckboxGroup` for log levels.\n- A focus-trapped confirmation `Dialog` (`r` key) to restart the selected service.\n- Full mouse support (`mouse: true` ) and one-line MCP exposure (`agentServer` ).\n\nLet’s start with the custom `Toggle` primitive in `ops-view.ts`.\n\nUsing `definePrimitive` and `controllable`, your own components inherit focus management, keyboard handling, controlled/uncontrolled props, and MCP agent actions:\n\n``` js\nimport {\n  type ChangeDetails,\n  controllable,\n  definePrimitive,\n  matchesShortcut,\n  type PrimitiveContext,\n  type RootProps,\n  text,\n} from 'tui'\n\ninterface ToggleProps extends RootProps {\n  value?: boolean\n  defaultValue?: boolean\n  onValueChange?: (value: boolean, details: ChangeDetails) => void\n}\n\nexport const Toggle = definePrimitive({\n  name: 'toggle',\n  state: (context: PrimitiveContext<ToggleProps>) => ({\n    value: controllable(\n      context,\n      'value',\n      (props) => props.value,\n      context.props().defaultValue ?? false,\n      (props, value, details) => props.onValueChange?.(value, details),\n    ),\n  }),\n  api: (_context, state) => ({\n    toggle: () => state.value.set(!state.value.get(), 'imperative', null),\n  }),\n  agent: (root) => ({\n    state: { value: root.state.value.get() },\n    items: [],\n    actions: {\n      toggle: () => {\n        root.api.toggle()\n        return ''\n      },\n    },\n  }),\n  slots: (slot, Root) => {\n    const Switch = slot('switch', {\n      focusable: true,\n      keys: (key, view) => {\n        if (!matchesShortcut(key, 'space') && key.name !== 'enter') {\n          return false\n        }\n        view.state.value.set(!view.state.value.get(), 'item-press', key)\n        return true\n      },\n      draw: (view) => {\n        const on = view.state.value.get()\n        const label = view.props.label || 'Toggle'\n        const badge = on ? '[ON ]' : '[OFF]'\n        const style = view.focused\n          ? view.frame.theme.highlight\n          : on\n            ? view.frame.theme.success\n            : view.frame.theme.muted\n        text(view.frame, view.rect.x, view.rect.y, `${badge} ${label}`, style, view.rect)\n      },\n    })\n    return { Root, Switch }\n  },\n})\n```\n\nOne little detail I learned from `scriptc` strict type checking: the space bar is not named `'space'`, but `'char'` with `key.text === ' '`.\n\nUsing `matchesShortcut(key, 'space')` is a nice way to handle this, and it passes `scriptc` type checking without complaints.\n\nNow 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.\n\nIn the view function, look at these 2 places:\n\n1. **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.\n2. **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.\n\n``` js\n// Inside createOpsApp(logCount = 100_000) in ops-view.ts\nconst drawerWidth = Math.round(drawer.update(frame) * 26)\nconst columns = drawerWidth > 0 ? [24, -1, drawerWidth] : [24, -1]\nconst parts = split(main, 'columns', columns, 1)\nconst sidebar = parts[0]!\nconst workspace = parts[1]!\nconst drawerRect = parts[2]\n\n// Overview tab: CPU meter, latency sparkline, secret API token, deploys table\nif (state.tab === 'overview') {\n  const [metricsRect, tokenRect, deploysRect] = split(body, 'rows', [4, 1, -1], 1)\n  text(\n    frame,\n    metricsRect.x,\n    metricsRect.y,\n    `CPU ${Math.round(svc.cpu * 100)}%`,\n    svc.cpu > 0.75 ? frame.theme.destructive : frame.theme.success,\n  )\n  drawMeter(\n    frame,\n    {\n      x: metricsRect.x + 10,\n      y: metricsRect.y,\n      columns: Math.max(8, metricsRect.columns - 10),\n      rows: 1,\n    },\n    svc.cpu,\n  )\n  text(frame, metricsRect.x, metricsRect.y + 2, 'Latency (ms)', frame.theme.muted)\n  drawSparkline(\n    frame,\n    {\n      x: metricsRect.x + 14,\n      y: metricsRect.y + 2,\n      columns: Math.min(24, metricsRect.columns - 14),\n      rows: 1,\n    },\n    svc.latencyMs,\n  )\n\n  // Visible to humans, redacted to \"[redacted]\" in MCP snapshots\n  text(frame, tokenRect.x, tokenRect.y, 'API Token:', frame.theme.muted)\n  Input.Root(\n    frame,\n    {\n      id: 'api-token',\n      label: 'API Token',\n      agent: 'secret',\n      value: svc.token,\n    },\n    (root) =>\n      Input.Field(root, {\n        x: tokenRect.x + 11,\n        y: tokenRect.y,\n        columns: Math.max(8, tokenRect.columns - 11),\n        rows: 1,\n      }),\n  )\n\n  Table.Root(\n    frame,\n    {\n      id: 'deploys',\n      label: 'Recent Deploys',\n      columns: [\n        { label: 'Service', width: 16 },\n        { label: 'Release', width: 10 },\n        { label: 'State', width: 10 },\n        { label: 'When', align: 'right' },\n      ],\n      rows: DEPLOYS,\n      onValueChange: (value) => {\n        state.lastNotice = `Inspecting deploy ${value}`\n      },\n    },\n    (root) => Table.Content(root, deploysRect),\n  )\n}\n```\n\nHere is the compiled `./ops` native binary running on the Overview tab with `queue-worker` selected:\n\n### Filtering 100,000 log lines without freezing typing\n\nIf you have a huge array, you can’t filter it naively inside `view(frame)`, otherwise every keystroke will stall the terminal.\n\n`tui` solves this by using `createFilter()` and a virtualized `ScrollArea` rendering.\n\nEvery 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.\n\nWhen you append characters to the query, it only searches lines that already matched the shorter query.\n\nAnd because `ScrollArea.Viewport` receives `total: filter.count`, our loop only draws the 15 or 20 rows that are actually visible on screen:\n\n```\nfilter.update(logs, state.query)\nconst [statusRow, logArea] = split(body, 'rows', [1, -1])\ntext(\n  frame,\n  statusRow.x,\n  statusRow.y,\n  `${formatCount(filter.count)} / ${formatCount(logs.length)} lines matched${filter.done ? '' : ' (scanning…)'}`,\n  frame.theme.muted,\n  statusRow,\n)\nScrollArea.Root(\n  frame,\n  { id: 'log-scroll', label: 'Logs', total: filter.count, stickToEnd: true },\n  (area) =>\n    ScrollArea.Viewport(area, logArea, (viewport) => {\n      const offset = viewport.api.offset()\n      for (let row = 0; row < viewport.rect.rows && offset + row < filter.count; row++) {\n        const line = logs[filter.at(offset + row)] ?? ''\n        drawMatches(\n          frame,\n          viewport.rect.x,\n          viewport.rect.y + row,\n          line,\n          state.query,\n          0,\n          viewport.rect,\n        )\n      }\n    }),\n)\n```\n\nNotice 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:\n\n```\nerror SC3002: the macos-arm64 runtime pack has no Intl support:\nit ships no ICU objects, and only the linux-x64-gnu runtime pack\n(@scriptc/runtime-linux-x64-gnu) provides Intl\n```\n\n`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.\n\nNotice 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`.\n\nHere is `./ops` on the Logs tab filtering 100,000 lines for `ERROR` with the spring-animated `Levels` drawer open on the right:\n\nAnd here is the centered confirmation `Dialog` trapping focus over the filtered logs after pressing `r`:\n\n### Rendering Markdown in the Runbook tab\n\nFor 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.\n\nPassing those lines to `drawLines` inside a `ScrollArea.Viewport` gives you a scrollable documentation pane in 7 lines:\n\n``` js\nconst rendered = markdown.lines(svc.runbook, Math.max(10, body.columns - 2))\nScrollArea.Root(\n  frame,\n  { id: 'runbook-scroll', label: 'Runbook', total: rendered.length },\n  (area) =>\n    ScrollArea.Viewport(area, body, (viewport) => {\n      drawLines(frame, viewport.rect, rendered, viewport.api.offset())\n    }),\n)\n```\n\n### Graphics, shaders, and images\n\nIf 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`.\n\nOn 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.\n\n### Complete runnable `ops-view.ts`\n\nIf 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`:\n\n## Show the complete ops-view.ts (491 lines)\n\n``` js\nimport {\n  center,\n  type ChangeDetails,\n  CheckboxGroup,\n  controllable,\n  createFilter,\n  createMarkdown,\n  createSpring,\n  definePrimitive,\n  Dialog,\n  drawBox,\n  drawLines,\n  drawMatches,\n  drawMeter,\n  drawSparkline,\n  type Frame,\n  Input,\n  inset,\n  type Key,\n  Listbox,\n  matchesShortcut,\n  paint,\n  type PrimitiveContext,\n  type RootProps,\n  ScrollArea,\n  split,\n  Table,\n  Tabs,\n  text,\n} from 'tui'\n\nexport interface Service {\n  id: string\n  name: string\n  status: 'healthy' | 'degraded'\n  cpu: number\n  latencyMs: number[]\n  token: string\n  runbook: string\n}\n\nexport const SERVICES: Service[] = [\n  {\n    id: 'api',\n    name: 'edge-api',\n    status: 'healthy',\n    cpu: 0.34,\n    latencyMs: [18, 21, 19, 24, 22, 17, 20, 23, 19, 18, 21, 16],\n    token: 'tok_live_9f8a2c41e0',\n    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\\`\\`\\``,\n  },\n  {\n    id: 'worker',\n    name: 'queue-worker',\n    status: 'degraded',\n    cpu: 0.82,\n    latencyMs: [45, 52, 68, 94, 112, 108, 125, 119, 134, 141, 128, 136],\n    token: 'tok_live_7b31d99a12',\n    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`,\n  },\n  {\n    id: 'postgres',\n    name: 'postgres-primary',\n    status: 'healthy',\n    cpu: 0.27,\n    latencyMs: [4, 5, 4, 6, 5, 4, 7, 5, 4, 5, 4, 4],\n    token: 'tok_live_4c10e82f55',\n    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\\``,\n  },\n  {\n    id: 'redis',\n    name: 'redis-cache',\n    status: 'healthy',\n    cpu: 0.14,\n    latencyMs: [1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2],\n    token: 'tok_live_1a55b70c33',\n    runbook: `## redis-cache runbook\\n\\nIn-memory rate limiter and session cache.\\n\\n- Eviction policy: \\`allkeys-lru\\``,\n  },\n]\n\nconst DEPLOYS = [\n  { value: 'd-412', cells: ['edge-api', 'v2.14.0', 'live', '14m ago'] },\n  { value: 'd-411', cells: ['queue-worker', 'v1.9.3', 'degraded', '2h ago'] },\n  { value: 'd-410', cells: ['edge-api', 'v2.13.9', 'previous', '1d ago'] },\n  { value: 'd-409', cells: ['redis-cache', 'v7.4.2', 'live', '6d ago'] },\n]\n\ninterface ToggleProps extends RootProps {\n  value?: boolean\n  defaultValue?: boolean\n  onValueChange?: (value: boolean, details: ChangeDetails) => void\n}\n\nexport const Toggle = definePrimitive({\n  name: 'toggle',\n  state: (context: PrimitiveContext<ToggleProps>) => ({\n    value: controllable(\n      context,\n      'value',\n      (props) => props.value,\n      context.props().defaultValue ?? false,\n      (props, value, details) => props.onValueChange?.(value, details),\n    ),\n  }),\n  api: (_context, state) => ({\n    toggle: () => state.value.set(!state.value.get(), 'imperative', null),\n  }),\n  agent: (root) => ({\n    state: { value: root.state.value.get() },\n    items: [],\n    actions: {\n      toggle: () => {\n        root.api.toggle()\n        return ''\n      },\n    },\n  }),\n  slots: (slot, Root) => {\n    const Switch = slot('switch', {\n      focusable: true,\n      keys: (key, view) => {\n        if (!matchesShortcut(key, 'space') && key.name !== 'enter') {\n          return false\n        }\n        view.state.value.set(!view.state.value.get(), 'item-press', key)\n        return true\n      },\n      draw: (view) => {\n        const on = view.state.value.get()\n        const label = view.props.label || 'Toggle'\n        const badge = on ? '[ON ]' : '[OFF]'\n        const style = view.focused\n          ? view.frame.theme.highlight\n          : on\n            ? view.frame.theme.success\n            : view.frame.theme.muted\n        text(view.frame, view.rect.x, view.rect.y, `${badge} ${label}`, style, view.rect)\n      },\n    })\n    return { Root, Switch }\n  },\n})\n\nexport function buildSampleLogs(count: number) {\n  const levels = ['INFO', 'INFO', 'INFO', 'WARN', 'ERROR']\n  const services = ['edge-api', 'queue-worker', 'postgres-primary', 'redis-cache']\n  const messages = [\n    'GET /api/posts 200 18ms',\n    'webhook retry scheduled attempt=2',\n    'checkpoint complete wrote=412 buffers',\n    'job timeout waiting for upstream socket',\n    'rate-limit window rotated keys=1284',\n  ]\n  const lines: string[] = new Array(count)\n  for (let i = 0; i < count; i++) {\n    const lvl = levels[i % levels.length] ?? 'INFO'\n    const svc = services[i % services.length] ?? 'edge-api'\n    const msg = messages[i % messages.length] ?? 'ok'\n    lines[i] = `12:${String(Math.floor(i / 60) % 60).padStart(2, '0')}:${String(i % 60).padStart(2, '0')} [${lvl}] ${svc} #${i} ${msg}`\n  }\n  return lines\n}\n\nexport function createOpsApp(logCount = 100_000) {\n  const logs = buildSampleLogs(logCount)\n  const filter = createFilter()\n  const drawer = createSpring(0)\n  let markdown: ReturnType<typeof createMarkdown> | null = null\n\n  const state = {\n    query: '',\n    serviceId: 'api',\n    tab: 'overview',\n    levels: ['INFO', 'WARN', 'ERROR'] as readonly string[],\n    autoRefresh: true,\n    confirmRestart: false,\n    restarts: 0,\n    lastNotice: 'Tab moves focus · r restarts service · d toggles drawer · q quits',\n    lastSource: 'none',\n  }\n\n  function currentService() {\n    return SERVICES.find((s) => s.id === state.serviceId) ?? SERVICES[0]!\n  }\n\n  function view(frame: Frame) {\n    markdown ??= createMarkdown(frame.styles, frame.theme)\n    const [topBar, main, footer] = split(frame.rect, 'rows', [1, -1, 1])\n\n    const svc = currentService()\n    text(\n      frame,\n      topBar.x,\n      topBar.y,\n      ` ops · ${svc.name} (${svc.status}) · restarts: ${state.restarts}`,\n      frame.theme.heading,\n      topBar,\n    )\n\n    const drawerWidth = Math.round(drawer.update(frame) * 26)\n    const columns = drawerWidth > 0 ? [24, -1, drawerWidth] : [24, -1]\n    const parts = split(main, 'columns', columns, 1)\n    const sidebar = parts[0]!\n    const workspace = parts[1]!\n    const drawerRect = parts[2]\n\n    const sideInside = drawBox(frame.cells, sidebar, { title: 'Services' })\n    const [searchRect, listRect, toggleRect] = split(sideInside, 'rows', [1, -1, 1])\n\n    Input.Root(\n      frame,\n      {\n        id: 'filter',\n        label: 'Filter',\n        value: state.query,\n        placeholder: 'Filter services or logs…',\n        onValueChange: (value, details) => {\n          state.query = value\n          state.lastSource = details.source\n        },\n      },\n      (root) => Input.Field(root, searchRect),\n    )\n\n    const matchingServices = SERVICES.filter((item) =>\n      item.name.toLowerCase().includes(state.query.toLowerCase()),\n    ).map((item) => ({\n      value: item.id,\n      label: `${item.status === 'healthy' ? '●' : '▲'} ${item.name}`,\n    }))\n\n    Listbox.Root(\n      frame,\n      {\n        id: 'services',\n        label: 'Services',\n        items: matchingServices.length\n          ? matchingServices\n          : [{ value: svc.id, label: `${svc.status === 'healthy' ? '●' : '▲'} ${svc.name}` }],\n        value: state.serviceId,\n        onValueChange: (value, details) => {\n          state.serviceId = value\n          state.lastSource = details.source\n          state.lastNotice = `Selected ${value} (${details.source})`\n        },\n      },\n      (root) => Listbox.Content(root, listRect),\n    )\n\n    Toggle.Root(\n      frame,\n      {\n        id: 'auto-refresh',\n        label: 'Auto-refresh',\n        value: state.autoRefresh,\n        onValueChange: (value) => {\n          state.autoRefresh = value\n        },\n      },\n      (root) => Toggle.Switch(root, toggleRect),\n    )\n\n    const workInside = drawBox(frame.cells, workspace, { title: svc.name })\n    const [tabsRect, bodyRect] = split(workInside, 'rows', [1, -1])\n\n    Tabs.Root(\n      frame,\n      {\n        id: 'views',\n        label: 'View',\n        value: state.tab,\n        items: [\n          { value: 'overview', label: 'Overview' },\n          { value: 'logs', label: 'Logs' },\n          { value: 'runbook', label: 'Runbook' },\n        ],\n        onValueChange: (value) => {\n          state.tab = value\n        },\n      },\n      (root) => Tabs.List(root, tabsRect),\n    )\n\n    const body = inset(bodyRect, [1, 0])\n\n    if (state.tab === 'overview') {\n      const [metricsRect, tokenRect, deploysRect] = split(body, 'rows', [4, 1, -1], 1)\n      text(\n        frame,\n        metricsRect.x,\n        metricsRect.y,\n        `CPU ${Math.round(svc.cpu * 100)}%`,\n        svc.cpu > 0.75 ? frame.theme.destructive : frame.theme.success,\n      )\n      drawMeter(\n        frame,\n        {\n          x: metricsRect.x + 10,\n          y: metricsRect.y,\n          columns: Math.max(8, metricsRect.columns - 10),\n          rows: 1,\n        },\n        svc.cpu,\n      )\n      text(frame, metricsRect.x, metricsRect.y + 2, 'Latency (ms)', frame.theme.muted)\n      drawSparkline(\n        frame,\n        {\n          x: metricsRect.x + 14,\n          y: metricsRect.y + 2,\n          columns: Math.min(24, metricsRect.columns - 14),\n          rows: 1,\n        },\n        svc.latencyMs,\n      )\n\n      text(frame, tokenRect.x, tokenRect.y, 'API Token:', frame.theme.muted)\n      Input.Root(\n        frame,\n        {\n          id: 'api-token',\n          label: 'API Token',\n          agent: 'secret',\n          value: svc.token,\n        },\n        (root) =>\n          Input.Field(root, {\n            x: tokenRect.x + 11,\n            y: tokenRect.y,\n            columns: Math.max(8, tokenRect.columns - 11),\n            rows: 1,\n          }),\n      )\n\n      Table.Root(\n        frame,\n        {\n          id: 'deploys',\n          label: 'Recent Deploys',\n          columns: [\n            { label: 'Service', width: 16 },\n            { label: 'Release', width: 10 },\n            { label: 'State', width: 10 },\n            { label: 'When', align: 'right' },\n          ],\n          rows: DEPLOYS,\n          onValueChange: (value) => {\n            state.lastNotice = `Inspecting deploy ${value}`\n          },\n        },\n        (root) => Table.Content(root, deploysRect),\n      )\n    } else if (state.tab === 'logs') {\n      filter.update(logs, state.query)\n      const [statusRow, logArea] = split(body, 'rows', [1, -1])\n      text(\n        frame,\n        statusRow.x,\n        statusRow.y,\n        `${formatCount(filter.count)} / ${formatCount(logs.length)} lines matched${filter.done ? '' : ' (scanning…)'}`,\n        frame.theme.muted,\n        statusRow,\n      )\n      ScrollArea.Root(\n        frame,\n        { id: 'log-scroll', label: 'Logs', total: filter.count, stickToEnd: true },\n        (area) =>\n          ScrollArea.Viewport(area, logArea, (viewport) => {\n            const offset = viewport.api.offset()\n            for (let row = 0; row < viewport.rect.rows && offset + row < filter.count; row++) {\n              const line = logs[filter.at(offset + row)] ?? ''\n              drawMatches(\n                frame,\n                viewport.rect.x,\n                viewport.rect.y + row,\n                line,\n                state.query,\n                0,\n                viewport.rect,\n              )\n            }\n          }),\n      )\n    } else {\n      const rendered = markdown.lines(svc.runbook, Math.max(10, body.columns - 2))\n      ScrollArea.Root(\n        frame,\n        { id: 'runbook-scroll', label: 'Runbook', total: rendered.length },\n        (area) =>\n          ScrollArea.Viewport(area, body, (viewport) => {\n            drawLines(frame, viewport.rect, rendered, viewport.api.offset())\n          }),\n      )\n    }\n\n    if (drawerRect && drawerRect.columns >= 8) {\n      const drawerInside = drawBox(frame.cells, drawerRect, { title: 'Levels' })\n      CheckboxGroup.Root(\n        frame,\n        {\n          id: 'levels',\n          label: 'Log Levels',\n          items: [\n            { value: 'INFO', label: 'Info' },\n            { value: 'WARN', label: 'Warn' },\n            { value: 'ERROR', label: 'Error' },\n          ],\n          value: state.levels,\n          onValueChange: (values) => {\n            state.levels = values\n          },\n        },\n        (root) => CheckboxGroup.Content(root, drawerInside),\n      )\n    }\n\n    paint(frame, footer, frame.theme.muted)\n    text(frame, footer.x, footer.y, ` ${state.lastNotice}`, frame.theme.muted, footer)\n\n    Dialog.Root(\n      frame,\n      {\n        id: 'restart-dialog',\n        label: 'Restart Service',\n        title: `Restart ${svc.name}?`,\n        open: state.confirmRestart,\n        onOpenChange: (open) => {\n          state.confirmRestart = open\n        },\n      },\n      (root) =>\n        Dialog.Content(root, center(frame.rect, 44, 8), (dialog) => {\n          const [promptRow, actionsRect] = split(inset(dialog.rect, [1, 1]), 'rows', [2, -1])\n          text(dialog.frame, promptRow.x, promptRow.y, `Restart ${svc.name} right now?`)\n          Listbox.Root(\n            dialog.frame,\n            {\n              id: 'restart-actions',\n              label: 'Restart Actions',\n              items: [\n                { value: 'confirm', label: 'Restart now' },\n                { value: 'cancel', label: 'Cancel' },\n              ],\n              onValueChange: (choice, details) => {\n                if (details.source === 'agent') {\n                  details.cancel()\n                  return\n                }\n                state.confirmRestart = false\n                if (choice === 'confirm') {\n                  state.restarts++\n                  state.lastNotice = `Restarted ${svc.name} (total: ${state.restarts})`\n                }\n              },\n            },\n            (actions) => Listbox.Content(actions, actionsRect),\n          )\n        }),\n    )\n  }\n\n  function handleKey(key: Key, exit?: () => void) {\n    if (matchesShortcut(key, 'ctrl+c')) {\n      exit?.()\n      return true\n    }\n    if (key.name === 'char' && key.alone && key.text === 'r') {\n      state.confirmRestart = true\n      return true\n    }\n    if (key.name === 'char' && key.alone && key.text === 'd') {\n      drawer.to(drawer.target ? 0 : 1)\n      return true\n    }\n    if (key.name === 'char' && key.alone && key.text === 'q') {\n      exit?.()\n      return true\n    }\n    return false\n  }\n\n  return { state, view, handleKey, drawer, filter }\n}\n\nfunction formatCount(n: number) {\n  return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n}\n```\n\n## Inline shell prompts with tui/prompt\n\nNot 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/).\n\n`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 })`).\n\nTwo design choices in `tui/prompt` stand out in practice:\n\n- Pass `output: process.stderr` so interactive prompts and spinners draw to stderr while stdout stays clean for JSON or piped data.\n- 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.\n\nHere is `deploy-wizard.ts`:\n\n``` js\nimport { confirm, multiselect, progress, select, spinner, text } from 'tui/prompt'\n\nconst io = { output: process.stderr }\n\nconst service = await text({\n  ...io,\n  message: 'Service name',\n  placeholder: 'api-worker',\n  validate: (value) =>\n    /^[a-z0-9-]+$/.test(value) ? null : 'Use lowercase letters, numbers, and hyphens only',\n})\nif (service === null) process.exit(130)\n\nconst region = await select({\n  ...io,\n  message: 'Primary region',\n  items: [\n    { value: 'fra', label: 'Frankfurt (fra)' },\n    { value: 'iad', label: 'Ashburn (iad)' },\n    { value: 'sin', label: 'Singapore (sin)' },\n  ],\n  defaultValue: 'fra',\n})\nif (region === null) process.exit(130)\n\nconst checks = await multiselect({\n  ...io,\n  message: 'Pre-deploy checks',\n  items: [\n    { value: 'typecheck', label: 'TypeScript check' },\n    { value: 'tests', label: 'Unit tests' },\n    { value: 'migrations', label: 'DB migrations' },\n  ],\n  defaultValues: ['typecheck', 'tests'],\n  required: true,\n})\nif (checks === null) process.exit(130)\n\nconst proceed = await confirm({\n  ...io,\n  message: `Deploy ${service} to ${region}?`,\n  defaultValue: true,\n})\nif (proceed === null || !proceed) process.exit(130)\n\nconst building = spinner({ ...io, message: 'Compiling native binary' })\nawait new Promise((resolve) => setTimeout(resolve, 250))\nbuilding.stop('Compiled native binary')\n\nconst upload = progress({ ...io, message: 'Uploading artifact', max: 100 })\nfor (let pct = 25; pct <= 100; pct += 25) {\n  await new Promise((resolve) => setTimeout(resolve, 60))\n  upload.update(pct)\n}\nupload.stop('Artifact uploaded')\n\nprocess.stdout.write(JSON.stringify({ service, region, checks, deployed: true }) + '\\n')\n```\n\nEvery 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.\n\nNotice that `confirm` checks `key.alone` when bracketed paste is active, so an accidental paste with the letter `y` will never confirm a destructive action.\n\nCompiling `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:\n\n## Testing without a terminal using createTestApp\n\nTesting terminal UIs usually involves spawning a fragile PTY wrapper, sleeping for arbitrary timeouts and scraping raw ANSI escape codes.\n\n`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`:\n\n- `app.type(text)` and`app.press(shortcut)` simulate keyboard input.\n- `app.click(x, y)` and`app.wheel(x, y, 'down')` simulate mouse events.\n- `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.\n- `app.advance(ms)` moves the virtual clock forward so you can test springs, transitions, and`fps` loops step by step.\n- `app.resize(columns, rows)` tests responsive layouts at narrow widths.\n\nHere is `ops.test.ts`, testing keyboard filtering, mouse clicking a tab, dialog focus trapping, spring drawer animation, and agent permissions:\n\n``` python\nimport assert from 'node:assert/strict'\nimport { test } from 'node:test'\nimport { createTestApp } from 'tui'\nimport { createAgent } from 'tui/agent'\nimport { createOpsApp } from './ops-view.ts'\n\ntest('filters services, switches tabs, and searches logs', () => {\n  const ops = createOpsApp(5_000)\n  const app = createTestApp({\n    columns: 96,\n    rows: 24,\n    mouse: true,\n    view: ops.view,\n    keys: (key) => ops.handleKey(key),\n  })\n\n  app.type('worker')\n  assert.equal(ops.state.query, 'worker')\n\n  app.press('tab')\n  app.press('enter')\n  assert.equal(ops.state.serviceId, 'worker')\n\n  const logsTab = app.find('Logs')\n  assert.ok(logsTab)\n  app.click(logsTab.x, logsTab.y)\n  assert.equal(ops.state.tab, 'logs')\n\n  assert.ok(ops.filter.count > 0)\n  assert.ok(app.screen().some((line) => line.includes('queue-worker')))\n})\n\ntest('opens restart dialog, traps focus, and confirms on Enter', () => {\n  const ops = createOpsApp(100)\n  const app = createTestApp({\n    columns: 96,\n    rows: 24,\n    view: ops.view,\n    keys: (key) => ops.handleKey(key),\n  })\n\n  app.press('tab')\n  app.press('r')\n  assert.equal(ops.state.confirmRestart, true)\n  assert.ok(app.find('Restart edge-api right now?'))\n\n  app.press('enter')\n  assert.equal(ops.state.confirmRestart, false)\n  assert.equal(ops.state.restarts, 1)\n})\n\ntest('animates the spring drawer across frames with advance()', () => {\n  const ops = createOpsApp(100)\n  const app = createTestApp({\n    columns: 100,\n    rows: 24,\n    view: ops.view,\n    keys: (key) => ops.handleKey(key),\n  })\n\n  app.press('tab')\n  app.press('d')\n  for (let i = 0; i < 30; i++) {\n    app.advance(16)\n  }\n  assert.ok(app.find('Levels'))\n})\n\ntest('agent snapshot redacts secrets and allow blocks dialog actions', () => {\n  const ops = createOpsApp(1_000)\n  const app = createTestApp({\n    columns: 96,\n    rows: 24,\n    view: ops.view,\n    keys: (key) => ops.handleKey(key),\n  })\n\n  const agent = createAgent(app, {\n    allow: (step) => step.component !== 'dialog',\n  })\n\n  const initial = agent.snapshot()\n  const tokenField = initial.components.find((c) => c.ref === 'api-token')\n  assert.ok(tokenField)\n  assert.equal(tokenField.state.value, '[redacted]')\n\n  const result = agent.act({\n    steps: [\n      { ref: 'services', action: 'select', args: ['postgres'] },\n      { ref: 'views', action: 'open', args: ['runbook'] },\n      { ref: 'auto-refresh', action: 'toggle', args: [] },\n    ],\n  })\n  assert.equal(result.ok, true)\n  assert.equal(ops.state.serviceId, 'postgres')\n  assert.equal(ops.state.tab, 'runbook')\n  assert.equal(ops.state.autoRefresh, false)\n  assert.equal(ops.state.lastSource, 'agent')\n\n  ops.state.confirmRestart = true\n  app.press('tab')\n  const blocked = agent.act({\n    steps: [{ ref: 'restart-dialog', action: 'close', args: [] }],\n  })\n  assert.equal(blocked.ok, false)\n  assert.match(blocked.error, /refused/)\n})\n```\n\nAll 4 tests pass in 178 ms, and `scriptc` builds the stripped native `ops-strip` binary right after:\n\n## Exposing your terminal app to AI agents over MCP\n\nThis 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.\n\nIf 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.\n\nWith `tui` you don’t have to write the JSON-RPC server yourself. You just pass `agentServer` to `runApp` in `ops.ts`:\n\n``` js\nimport { runApp } from 'tui'\nimport { agentServer } from 'tui/agent'\nimport { createOpsApp } from './ops-view.ts'\n\nconst ops = createOpsApp(100_000)\n\nconst app = runApp({\n  mouse: true,\n  view: ops.view,\n  keys: (key) => ops.handleKey(key, () => app.exit(0)),\n  agent: agentServer({\n    name: 'ops',\n    allow: (step) => step.component !== 'dialog',\n  }),\n})\n```\n\nHere is how the two processes talk to each other when `ops` is running:\n\nWhen 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).\n\nWhen 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:\n\n- `snapshot` (`readOnlyHint: true` ): returns every drawn component’s`ref` ,`component` type,`label` ,`state` ,`items` ,`actions` ,`focused` flag, plus the plain-text`screen` lines.\n- `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.\n\nI started the compiled `./ops` binary in a PTY and drove `./ops mcp` directly over JSON-RPC to inspect the real wire output.\n\nCalling `snapshot` returned our built-in components AND our custom `Toggle` primitive, while automatically redacting `api-token` because we marked it `agent: 'secret'`:\n\n```\n[\n  {\n    \"ref\": \"auto-refresh\",\n    \"component\": \"toggle\",\n    \"label\": \"Auto-refresh\",\n    \"state\": { \"value\": true },\n    \"items\": [],\n    \"actions\": [\"toggle\"],\n    \"focused\": false\n  },\n  {\n    \"ref\": \"api-token\",\n    \"component\": \"input\",\n    \"label\": \"API Token\",\n    \"state\": {\n      \"value\": \"[redacted]\",\n      \"placeholder\": \"[redacted]\"\n    },\n    \"items\": [],\n    \"actions\": [\"setValue\", \"submit\"],\n    \"focused\": false\n  }\n]\n```\n\nComponents marked `agent: 'hidden'` are completely removed from the `snapshot`.\n\nNext I sent a 3-step `act` call (`services` -> `select` `\"worker\"`, `views` -> `open` `\"logs\"`, `filter` -> `type` `\"ERROR\"`).\n\nIn 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`:\n\n```\n{\n  \"ok\": true,\n  \"error\": \"\",\n  \"changes\": [\n    { \"ref\": \"services\", \"key\": \"highlighted\", \"value\": \"worker\" },\n    { \"ref\": \"services\", \"key\": \"value\", \"value\": \"worker\" },\n    { \"ref\": \"views\", \"key\": \"value\", \"value\": \"logs\" },\n    { \"ref\": \"filter\", \"key\": \"value\", \"value\": \"ERROR\" }\n  ]\n}\n```\n\nThen I sent `{ \"ref\": \"restart-dialog\", \"action\": \"open\", \"args\": [] }`.\n\nBecause our `allow` callback rejects any step that targets a `dialog`, the server blocked it before any state changed:\n\n```\n{\n  \"ok\": false,\n  \"error\": \"restart-dialog open: refused\"\n}\n```\n\nBecause `ops` is just a regular stdio MCP server (`ops mcp`), you can register it in Codex or Claude Code with one command:\n\n```\ncodex mcp add ops -- ./ops mcp\n# or in Claude Code:\nclaude mcp add ops -- ./ops mcp\n```\n\n### Driving `ops` live from Codex (and a real security caveat)\n\nI 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.\n\nTwo real details showed up right away.\n\nFirst, `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\"`).\n\nSecond, 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.\n\nOnce 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:\n\n## Real benchmarks: Node.js 26 vs scriptc native binary\n\nI 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):\n\n| Metric | `hello` native (`scriptc` ) | `hello` Node 26 | `ops` native (100k logs) | `ops` Node 26 (100k logs) | \n|---|---|---|---|---|\n| 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) | \n| Startup speedup | **40.4× faster** | baseline | **16.5× faster** | baseline | \n| Peak memory (RSS) | **3.9 MB** | 70.8 MB (18.2× higher) | **14.8 MB** | 127.5 MB (8.6× higher) | \n| Stripped binary size | **1.83 MB** | 61.02 MB runtime | **2.47 MB** | 61.02 MB runtime | \n\nOne 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.\n\nEven 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.\n\n## How tui compares to Ink, Bubble Tea, and Ratatui\n\nChoosing a TUI framework usually comes down to your language, your distribution target and if you need agent automation.\n\n| Framework | Language | Rendering model | Binary distribution | Built-in testing & MCP | \n|---|---|---|---|---|\n| **tui** | TypeScript | Immediate-mode cell grid + diff | Node 24+ or ~2 MB `scriptc` native binary | `createTestApp` + 1-line`tui/agent` MCP | \n| **Ink** | TypeScript / React | React reconciler + Yoga flexbox | Requires Node/Bun runtime (~60+ MB) | `ink-testing-library` , no built-in MCP | \n| **Bubble Tea** | Go | Elm architecture (Model / Update / View) | Single static Go binary (~5–15 MB) | `teatest` helper, no built-in MCP | \n| **Ratatui** | Rust | Immediate-mode widget buffer | Single native Rust binary (~1–5 MB) | `TestBackend` , no built-in MCP | \n\nIf your team already writes Rust or Go, Ratatui and Bubble Tea are mature, battle-tested ecosystems with years of community widgets behind them.\n\n`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.\n\n## How I would use tui (and where I would skip it)\n\nI 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.\n\nI 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.\n\nI 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.\n\nWhere would I skip `tui`?\n\n- **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.\n- **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.\n- **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.\n\nIf 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+.\n\nOnce 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.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/how-to-build-native-typescript-terminal-apps-with-tui", "canonical_source": "https://flaviocopes.com/tui/", "published_at": "2026-12-06 07:00:00+00:00", "updated_at": "2026-12-06 07:14:57.125693+00:00", "lang": "en", "topics": ["developer-tools", "ai-agents", "agent-protocols", "ai-tools"], "entities": ["Vercel Labs", "Chris Tate", "tui", "scriptc", "Node.js", "Flavio", "MCP", "Ink"], "also_reported_by": [], "takeaway": "tui 0.2.1 renders by diffing a typed-array cell grid so a one-row selection move emits 58 bytes instead of 2,520, and adding one line to runApp exposes the running terminal app as an MCP server for AI agents.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/how-to-build-native-typescript-terminal-apps-with-tui", "markdown": "https://wpnews.pro/news/how-to-build-native-typescript-terminal-apps-with-tui.md", "text": "https://wpnews.pro/news/how-to-build-native-typescript-terminal-apps-with-tui.txt", "jsonld": "https://wpnews.pro/news/how-to-build-native-typescript-terminal-apps-with-tui.jsonld"}}