On this page

Tenon TUI Cookbook

A practical guide to building pure, deterministic terminal interfaces with Tenon's TUI plugin suite. For package-level contracts and limits, follow the links to each plugin's DOCS.md instead of treating this cookbook as a duplicate spec.

Start from a working app by copying examples/tui/template/, or see the end-to-end inline + headless capstone in examples/tui/assistant/.

1. Mental model

Every Tenon TUI splits cleanly into a pure application (capabilities = []) and an effectful host driver (such as examples/tui/driver/lib.tn):

  1. Your application implements tui.runtime.App:
    • update(self, event: Event) -> Step<Self> returns the next immutable state and a vec<Effect> of requested actions.
    • view(self, size: Size) -> Screen returns an immutable Frame of styled Strip rows, optional Cursor, Modes, Hit regions, focus order, and optional Modal.
  2. The runtime drives App deterministically through tui.runtime.tick<A: App>(Runtime<A>, Input) -> Tick<A> after initializing with start(app, size, caps) (tests/scenarios) or start_probing(app, size, now, term, colorterm) (live terminals).
  3. Input has four variants: Bytes(bytes, now), Feed(bytes, now), Resize(Size, now), and Clock(now). Every input delivers a nonvisual Event.Time(now) before its other events; Event.Tick(now) and lone-ESC flushing (30 ms) occur only on Input.Clock.
  4. Tick<A> gives the host exact output out: bytes, wait_ms: i64 (-1 means idle with zero wakeups), requests: vec<Request> for the host to authorize, and quit: bool.
  5. Effects are data, never I/O. Pure App code never touches /dev/tty, files, clocks, or sockets. Effect values (Quit, Timer, Frame, Run, Send, Focus, Capture, Release, Request) are interpreted by the runtime or explicitly authorized by the host.

Design ADRs: 0220 Strips and canvas · 0221 Native terminal boundary · 0222 Unix feed · 0223 Commands and messages · 0224 FFI cleanup · 0225 Presented metadata and scroll diff · 0226 Capability witness · 0227 Capability delivery before layout · 0285 TUI agent surface (M24) · 0292 Application Actions API · 0293 Actions API v1.1 and derive Actions · 0325 Explicit state machines.

Core reference: plugins/tui/DOCS.md.

2. Choosing a structure

Structure When to use it Key entry points
Hand-composed App Custom geometry, split panes (tui_layout.flex.flex), modals, or full control over layers and focus. tui.runtime.App, tui.compose.compose, tui_layout/DOCS.md
derive Shell Vertically stacked independent panels implementing tui_shell.plugin.Plugin with automatic per-slot caching, chord routing, and fault isolation (error_placeholder, shell_screen_with_faults). tui_shell.lib.Shell, tui_shell.plugin.Plugin, tui_shell/DOCS.md
Inline viewport (tui_inline) Painting a bounded Block into a bottom-anchored sub-rectangle without alternate screen and committing finished turns into native scrollback. tui_inline.lib.viewport_policy, paint, grow, reanchor, commit, invalidate, rebase_policy, tui_inline/DOCS.md

Use tui_forms (or the cohesive std_tui edition = "2026" facade, which bundles tui_forms with tui.a11y accessibility tree integration) for schema-driven modal forms and structured configuration prompts (std_tui/DOCS.md, tui_forms/DOCS.md). Legacy tui_form (derive TuiForm) remains preserved for backward compatibility (tui_form/DOCS.md).

3. Width policy (Caps.cluster)

Terminals disagree on whether grapheme clusters such as ZWJ emoji (👩‍💻) occupy 2 cells (cluster = true) or the sum of their scalar widths (cluster = false).

  1. Capture Event.Capabilities(caps) in app state (cluster: bool). start queues an initial snapshot before input, and start_probing delivers the negotiated snapshot before rendering when the probe freezes (DA reply or 150 ms). In tui_shell, plugins that render width-sensitive content must return true for Event.Capabilities in wants.
  2. Pass cluster to every *_policy helper before clipping or geometry:
    • Core: tui.types.span_policy, tui.text.line_policy, width_policy, tui.canvas.canvas_policy, tui.unicode.clusters_policy, display_width_policy.
    • Widgets (tui_widgets/DOCS.md): text_view_policy, list_view_policy, input_view_policy, input_cursor_policy, border_policy, tabs_view_policy, spinner_view_policy, spinner_view_elapsed_policy, progress_view_policy, progress_bar_policy, progress_labeled_policy, progress_indeterminate_policy, progress_indeterminate_bar_policy, table_view_policy, table_render_policy.
    • Markdown / Highlight / Inline / Editor / Complete: tui_md.lib.markdown_policy, resize_policy, tui_highlight view_policy, tui_inline.lib.viewport_policy, rebase_policy, tui_editor.view.editor_view_policy, editor_height_policy, tui_complete.popup.popup_view_policy, tui_complete.palette.palette_view_policy.
  3. Never rely on runtime normalization to fix clipped text. If a widget truncates a string using legacy scalar widths (cluster = false), the dropped suffix is already gone before tui.runtime normalizes the final Screen. See ADR-0227.

4. Input and keys

Reference: plugins/tui_keys/DOCS.md.

5. Mouse, hits, capture and modals

6. Requests the host must approve

Sensitive terminal side effects never bypass the host:

  1. Pure app code emits Effect.Request(Request { port, id, payload }).
  2. tick surfaces those requests in Tick.requests.
  3. The host decides policy — for example, examples/tui/driver/lib.tn requires explicit allow_copy: bool (--allow-copy) for clipboard writes and explicit allow_notify: bool (--notify via run_options_full) for terminal notifications — and passes approved: bool to tui.present.encode_request(request, approved) -> result<bytes, str>.
  4. Supported request ports (all emit bytes only when approved == true; unapproved or invalid payloads return err):
    • clipboard.osc52: UTF-8 payload, capped at 64 KiB, Base64-encoded into OSC 52.
    • terminal.bell: empty payload, emits BEL (0x07).
    • terminal.notify: sanitized UTF-8 payload capped at 256 bytes, emits OSC 9 (ESC ] 9 ; ... ESC \).
    • terminal.progress: "<state>;<percent>" (state in 0..=4, percent in 0..=100), emits OSC 9;4 (ESC ] 9 ; 4 ; state ; percent ESC \). See ADR-0285.

7. Presented-frame approvals

Never approve a consequential action based on state that has not been painted to the user's screen yet. A fast feed can enqueue a new approval at 5 ms and a keypress can arrive at 6 ms before the 16 ms frame renders.

8. Testing

Layer deterministic checks from fastest to heaviest:

  1. In-language unit tests (test blocks): Place test name { ... } beside widget/model code using assert(cond) and assert_eq(a, b) (spec/LANGUAGE.md, spec/application-tests.md). Run on both C and the interpreter:
    tenon test plugins/tui_widgets
  2. .tui scenarios: Drive App without a TTY via tui.scenario.run_scenario(app, source) using directives size W H, caps COLOR [sync] [cluster] [kitty], at MS, time MS, clock, resize W H, key NAME, bytes [HEX], paste [TEXT], feed [TEXT], feed-hex [HEX], expect screen ... end, and expect bytes [HEX]. See examples/tui/template/template.tui.
  3. Plain and styled snapshots: Use tui.present.screen_text(frame) for plain cell grids and tui.present.screen_snapshot(frame) when style runs matter (adds a deterministic style legend).
  4. Session record and replay: Capture live sessions opt-in via examples/tui/driver/lib.tn's run_options_record (--record PATH), which uses tui.scenario.recording, recording_caps, record (64 MiB cap), and recording_text. Replay and diff deterministically with tui.scenario.replay_check(app, recorded, expected_screen, expected_out), screen_diff, and byte_diff.
  5. PTY live check: Run python3 -B examples/tui/check-live.py (examples/tui/check-live.py) on a controlling terminal to verify raw mode, Kitty push/pop, exact termios restoration, and frame parity against scenario goldens.

9. Headless twin (tui_headless)

Interactive agent apps should degrade cleanly in pipes, CI, and non-TTY scripts:

  1. Probe descriptors with tty.lib.is_terminal(fd) (0 stdin, 1 stdout, 2 stderr; plugins/tty/DOCS.md). Under tenon interp, pass an explicit --format flag because the FFI helper sees its own descriptors.
  2. Decide output mode purely with tui_headless.mode.choose_output(stdout_tty, stdin_tty, requested, no_color, term) -> result<OutputMode, str>:
    • requested == "": chooses Format.Tui only when both stdin and stdout are TTYs and term != some("dumb"), otherwise Format.Text.
    • "text", "json", "jsonl": selects that headless format.
    • "tui": succeeds only if stdout_tty is true (otherwise host exits 2).
    • color is true only when stdout_tty && no_color.is_none() && term != some("dumb").
  3. Render validated tui_dashboard.feed.WireEvent values with tui_headless.render: headless(output), step(state, event) -> Rendered, finish(state) -> Rendered, and exit_code(state) -> i64.
  4. Headless mode never approves. Pending approvals print to stderr and yield exit_code == 3 until resolved by external daemon policy (approval_ack or approval_cancelled); notices yield exit 1, clean completion exits 0.

Reference: plugins/tui_headless/DOCS.md.

Import tui_theme.theme { Theme, default_theme, light_theme, theme_for } (plugins/tui_theme/DOCS.md). Theme defines eleven semantic Style tokens: text, muted, accent, selected, border, danger, success, link, diff_add, diff_remove, and diff_context.

11. Prompt editing, completion and inline scrollback

Multi-line prompt editor (tui_editor)

Use plugins/tui_editor/DOCS.md for agent prompts while keeping tui_widgets.input for single-line inputs:

Fuzzy completion and command palette (tui_complete)

Use plugins/tui_complete/DOCS.md with caller-supplied vec<Candidate> data (no I/O or closures):

Inline scrollback commit (tui_inline) and transcript search (tui_dashboard.transcript)

12. Security notes

13. Recipes

A ticking spinner, progress bar, and scrollable table

Use tui_widgets.spinner, tui_widgets.progress, and tui_widgets.table (plugins/tui_widgets/DOCS.md) so idle apps keep Tick.wait_ms == -1 and schedule wakeups only while active:

A virtualized transcript

Store laid-out blocks in tui_dashboard.transcript.Transcript (transcript(width) and append(state, rows)). At view time, call window(state, offset, height) -> Window { rows, visited }: it binary-searches cumulative row counts and visits only the visible rows, keeping per-frame work proportional to viewport height rather than total transcript length. Rebuild the transcript cache when width or Caps.cluster changes.

Streaming Markdown

Keep a tui_md.lib.Markdown (markdown_policy(width, cluster)) in state (plugins/tui_md/DOCS.md):

A modal confirmation

  1. Keep confirm_open: bool and shown_prompt: str in app state.
  2. Render the dialog with tui_widgets.border.border_policy(body, dialog_size, "Confirm", theme.border, cluster) and place it on a higher z layer with modal: true:
    Layer { rect: dialog_rect, block: framed, z: 10, modal: true }
  3. On Event.Presented(frame), record whether the full confirmation text was actually presented in frame (tui.present.screen_text(frame)).
  4. Accept y/Enter only when confirm_open is true and the prompt matches the last presented frame; allow n/Esc to dismiss immediately.

Explicit workflow & modal state (derive StateMachine + fsm_test)

For multi-step modals, approval flows, or connection/job lifecycles where illegal transitions should fail at compile time, back the workflow with derive StateMachine (plugins/fsm/DOCS.md, plugins/fsm_gen/DOCS.md):

  1. Declare a state catalog struct with @initial, @terminal, and repeatable @on("<event>[(<Payload>)] -> <t1>[, <t2>...]") attributes, then add derive StateMachine for <Name>:
    • fsm_gen validates the graph statically (FSM001–FSM010, failing closed with E0966 on unreachable states, dead-end non-terminal sinks, or conflicting event payloads).
    • Emits <Name>State, <Name>Event, narrow <Name><State>On<Event> branch enums (making illegal target states unrepresentable), required <Name>Handlers, and a zero-wildcard <name>_step<H: <Name>Handlers>(h, state, event) -> result<<Name>State, InvalidTransition>.
  2. Gate app_actions affordances directly from the FSM:
    • Call <name>_allowed_events(state) -> vec<str> (or <name>_can_handle(state, event)) inside your ActionApp spec builder and pass the result to app_actions_gen.rt.disable_if(spec, !allowed, "not allowed in " + <name>_state_name(state)) so UI controls and AI agents see only currently legal actions.
  3. Explore and shrink automatically with fsm_test:
    • Run fsm_test.graph.explore_graph(default_config(), <name>_graph(), init, events, step_res, <name>_state_name, <name>_event_name, <name>_is_terminal, invariant) inside a test block.
    • Assert report.explore.passed (checks all 5 universal oracles: InitInvariantViolated, NonDeterministic, TerminalEscaped, StateCorruptedOnReject, InvariantViolated) and fsm_test.graph.is_full_coverage(report.coverage).
    • On failure or gaps, print fsm_test.lib.format_regression_tn(...) for a copy-pasteable minimized test block or fsm_test.graph.coverage_mermaid(<name>_graph(), report.coverage) to inspect [UNCOVERED] edges.

14. Agent-Controllable Stateful Apps (app.actions/v1.1, derive Actions & Live Co-Pilot)

Expose any pure TUI state machine to AI agents and human-in-the-loop co-pilots without PTY scraping by pairing app_actions, app_actions_gen, app_actions_mcp, app_actions_tui, and optionally app_actions_client (see ADR-0292 and ADR-0293).

Decision rule: Use derive Args + args_mcp for stateless CLIs; use app_actions + derive Actions + app_actions_mcp / app_actions_tui for stateful interactive or co-pilot apps.

1. Define actions with derive Actions (or fluent schema/args helpers)

2. Pure v1.1 session engine (app_actions.session)

3. Live Co-Pilot TUI overlays & discovery (app_actions_tui)

4. Expose over MCP (app_actions_mcp)

5. Optional Local Action Model (app_actions_client & action_model_ctl)

6. Reference Capstone (copilot-term) & Redaction Note