petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation

Contents

Getting started

The petitcarnets ecosystem

Library reference

Operational


Install

As a Rust library

[dependencies]
petitcarnets = "0.0.10"

Or cargo add petitcarnets. The components (bubbles) are a default feature with no dependencies; leave them out with default-features = false. Each release on crates.io carries SLSA build provenance and a CycloneDX SBOM (Security).


Requirements

Requirement Version Why
Rust 1.85 or later edition 2024; CI tests 1.85 and stable, policy in docs/POLICIES.md
OS Linux (glibc, musl), macOS, FreeBSD each tested in CI, with a real-terminal suite
Terminal any VT-compatible terminal features a terminal lacks (kitty keyboard, synchronized output) are asked for and degrade

Windows is not supported yet (When not to use).


Quick Start

use petitcarnets as tea;

struct Counter(i64);

impl tea::Model for Counter {
    type Msg = ();

    fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
        match msg {
            tea::Msg::KeyPress(k) if k == "q" || k == "ctrl+c" => return tea::quit(),
            tea::Msg::KeyPress(k) if k == "up" => self.0 += 1,
            tea::Msg::KeyPress(k) if k == "down" => self.0 -= 1,
            _ => {}
        }
        tea::Cmd::none()
    }

    fn view(&self) -> tea::View {
        format!("Count: {}\n\nup/down to change, q to quit", self.0).into()
    }
}

fn main() -> Result<(), tea::Error> {
    tea::Program::new(Counter(0)).run()?;
    Ok(())
}

The model is your state, update turns a message into a new state and maybe a command, and view draws it. Run the same program from a clone with cargo run --example counter. This block is compiled as a doc test in CI.


The petitcarnets ecosystem

One crate, no dependencies: the runtime and three modules. Petits carnets: little notebooks.

Component Purpose Use case
petitcarnets (the runtime) Bubble Tea v2's Program, Model, Msg, Cmd and View: input, renderer, lifecycle, terminal queries Any terminal program with a model you update from keys, mouse, timers and tasks
petitcarnets::bubbles Bubbles v2's components under Go's names, with the same key maps Text input, text area, list, table, viewport, spinner, progress, help
petitcarnets::style A small Lip Gloss: colours, bold and friends, borders, padding, joins Styling a view without a dependency
petitcarnets::testing Bubble Tea's teatest: TestProgram on a virtual clock and an emulated terminal Deterministic tests and golden screens
nalufx tui The first program built on it A consumer that keeps the API honest

Capabilities at a glance

Area Capability Status
Runtime Program, commands (batch, sequence, tick, every), typed messages, window size, signals Stable since 0.0.1
Input Keys with modifiers and releases, kitty keyboard, modifyOtherKeys, SGR and X10 mouse, paste, focus, terminal replies Stable since 0.0.2
Renderer Inline or alternate screen, cell diff, wide characters and emoji measured as Go measures them, println above an inline frame Stable since 0.0.3
Lifecycle exec, Ctrl-Z suspend and resume, release and restore, colour profile, terminal queries, clipboard Stable since 0.0.4
Testing TestProgram, virtual clock, VT emulator, golden files Stable since 0.0.5
Components 13 Bubbles components with Bubbles' key maps Stable since 0.0.6
Accessibility Plain-line output for screen readers (with_accessible, ACCESSIBLE) Stable since 0.0.7
Platforms Windows console backend Planned

Ecosystem comparison

petitcarnets is the Rust Bubble Tea v2 with no dependencies and typed messages. Where it loses: a smaller ecosystem than ratatui, no Lip Gloss layers, Huh or Wish, and no Windows yet.

Project Crates in cargo tree Messages Async runtime
petitcarnets 1 your own enum none
bubbletea-rs 0.0.9 53 Box<dyn Any> tokio
charmed-bubbletea 0.3.0 about 49 downcast not checked
ratatui about 70 (with crossterm) no runtime none

See docs/COMPARISON.md for the evidence and complete matrix.


Benchmarks

Bytes written to the terminal per frame, mean over 100 frames on an 80x24 screen, inline. Byte counts do not depend on the machine.

Scenario Result Environment
log (24 lines, one new per frame) 659 bytes (Bubble Tea v2: 1,230; bubbletea-rs: 1,253) any; v0.0.5
list (20 items, cursor moves) 31.7 bytes (Bubble Tea v2: 32.4; charmed-bubbletea: 241.0) any; v0.0.5
counter (one number changes) 4.2 bytes (Bubble Tea v2: 2.3, with backspaces) any; v0.0.5
keystroke to frame under 0.6 ms at p99 Linux, Ryzen AI 9 HX 370, scripts/latency.py; 2026-11-27

See docs/BENCHMARKS.md for methodology and full results.


Features

  • No dependencies. cargo tree prints one crate. The terminal is driven through a handful of libc calls in one audited module, the only place with unsafe.
  • Typed messages. Your messages are your own enum, matched exhaustively; no downcasting.
  • No async runtime required. A command is a plain closure. Timers run on the event loop, not on threads, and an idle program does not wake up at all.
  • Restores your terminal. Raw mode and every terminal mode are undone on quit, on panic (in update or in a task), on SIGINT and SIGTERM, and around an exec or a suspend, with no key lost or read twice; a real-terminal test checks each one in CI.
  • Testable. TestProgram runs a model in the real runtime on a virtual clock and an emulated terminal: no sleeps, no pseudo-terminal, the same result every run, with golden files for screens.
  • Small, prompt frames. Frames are diffed cell by cell; an unchanged frame writes nothing, and the frame after a key is drawn at once rather than on the next tick.
  • Accessible output. For screen readers and braille displays, a program can print its frames as plain lines, with no redraws, no cursor movement, no alternate screen and no colour (Bubble Tea's issue #780): tea::Program::new(m).with_accessible(true), huh's WithAccessible. Without that call, a program in a terminal whose environment sets ACCESSIBLE (to anything but the empty string, as huh's documentation recommends) prints lines too, so the person at the terminal decides. Input works as always, so the input modes are still written: bracketed paste, modifyOtherKeys and the kitty keyboard flags (\e[?2004h, \e[>4;2m, \e[>1u) before the first line and their resets at exit, plus mouse, focus reports and the window title if the view asks for them. Output captured to a file (a script log, or a backend given to run_with) holds these few sequences at its start and end.
  • Ctrl-Z suspends by default. Unlike Bubble Tea, where each program must handle it (its pull request #500), Ctrl-Z suspends a petitcarnets program as it would any shell program: the terminal is given back, the shell's fg brings the program back, and the model gets tea::Msg::Resume. A program that wants Ctrl-Z as a key (for undo, say) opts out with tea::Program::new(m).with_suspend(false); tea::suspend() and kill -TSTP still suspend it.
  • Colours come down to what the terminal shows, detected from TERM, COLORTERM, NO_COLOR, CLICOLOR and the rest as Bubble Tea detects them: with NO_COLOR set, no colour is written anywhere (frames and println alike) while bold, italic and underline stay.
  • Inline by default. As in Bubble Tea v2, a view is drawn inline unless it sets alt_screen. When an inline program quits, its last frame stays on screen, every row of it, and the shell prompt starts on the line below; a program that wants nothing left behind returns an empty view last.

From Go

petitcarnets follows Bubble Tea v2 closely: the same loop, the same command and message names, and the same key strings. If you have written a Bubble Tea program in Go, the Rust version should read the way you expect.

Bubble Tea (Go) petitcarnets
tea.NewProgram(m).Run() tea::Program::new(m).run()
case tea.KeyPressMsg: tea::Msg::KeyPress(k) =>
msg.String() == "ctrl+c" k == "ctrl+c"
msg.Keystroke(), msg.MatchString("q", "esc") k.keystroke(), k.matches_any(&["q", "esc"])
case tea.MouseClickMsg: tea::Msg::MouseClick(m) =>
case tea.PasteMsg: tea::Msg::Paste(text) =>
v.MouseMode = tea.MouseModeAllMotion view.with_mouse_mode(tea::MouseMode::AllMotion)
v.AltScreen = true view.with_alt_screen(true)
v.Cursor = tea.NewCursor(x, y) view.with_cursor(tea::Cursor::new(x, y))
v.WindowTitle = "t" view.with_window_title("t")
tea.Println(s), tea.Printf(f, a) tea::println(s), tea::printf!(f, a)
tea.Raw(s), tea.ClearScreen tea::raw(s), tea::clear_screen()
tea.WithFPS(n) Program::new(m).with_fps(n)
tea.ExecProcess(cmd, fn), tea.Exec(c, fn) tea::exec(cmd, f), tea::exec_command(c, f)
tea.Suspend, case tea.ResumeMsg: tea::suspend(), tea::Msg::Resume =>
p.ReleaseTerminal(), p.RestoreTerminal() tea::release_terminal(), tea::restore_terminal()
tea.WithColorProfile(p), tea.WithEnvironment(env) .with_color_profile(p), .with_environment(env)
tea.RequestBackgroundColor, tea.SetClipboard(s) tea::request_background_color(), tea::set_clipboard(s)
case tea.WindowSizeMsg: tea::Msg::WindowSize(size) =>
return m, tea.Quit return tea::quit()
tea.Batch(a, b), tea.Sequence(a, b) tea::batch([a, b]), tea::sequence([a, b])
tea.Tick(d, fn), tea.Every(d, fn) tea::tick(d, f), tea::every(d, f)
p.Send(msg) program.sender().send(msg), false once the program has stopped

Every exported name of Bubble Tea v2, the idioms, and a Go program converted step by step: docs/go-to-rust.md.

Components

The bubbles module (a default feature, no dependencies; turn it off with default-features = false) has Bubbles v2's components under the names Go uses, with the same default key bindings, checked line by line against Bubbles itself, and the same behaviour (where Bubbles has a bug, it is fixed and said so in the CHANGELOG).

Bubbles (Go) petitcarnets
charm.land/bubbles/v2/key tea::bubbles::key: Binding, matches
.../help tea::bubbles::help: Model, KeyMap
.../cursor tea::bubbles::cursor
.../spinner tea::bubbles::spinner: every spinner, Spinner::DOT and the rest
.../paginator tea::bubbles::paginator
.../textinput tea::bubbles::textinput: passwords, suggestions, validation
.../textarea tea::bubbles::textarea: soft wrap, line numbers, selection
.../viewport tea::bubbles::viewport: keys, mouse wheel, soft wrap, gutter
.../list tea::bubbles::list: delegates, fuzzy filtering, pages, help
.../table tea::bubbles::table
.../progress tea::bubbles::progress: gradients, spring animation
.../timer, .../stopwatch tea::bubbles::timer, tea::bubbles::stopwatch

A component is a struct with update(&mut self, &tea::Msg<X>) -> tea::Cmd<X> and view(&self) -> String, where X is its own typed message. A parent keeps its children's messages in its own enum, maps their commands up and routes messages down:

Go petitcarnets
ti := textinput.New(); ti.Focus() let mut ti = textinput::Model::new(); let cmd = ti.focus();
m.input, cmd = m.input.Update(msg) let cmd = self.input.update(&msg);
case spinner.TickMsg: tea::Msg::App(Msg::Spinner(tick)) =>
a child's tea.Cmd returned as is child_cmd.map(Msg::Spinner)
the parent's msg passed down as is msg.route(|m| ...) gives the child's tea::Msg<X>
key.Matches(msg, m.keys.Up) m.keys.up.matches(&key) or key::matches(&key, &[&up])

Components that tick (spinners, the cursor's blink, the progress bar's animation, timers) carry an id, as in Bubbles, so several in one parent take only their own ticks. Text is measured by display width with the program's width method: no component splits a grapheme cluster or a wide character.

Testing

petitcarnets::testing::TestProgram is Bubble Tea's teatest: it runs a model in the same loop, renderer and terminal modes as a real program, in an emulated terminal, on a virtual clock. Timers, the frame rate and the escape timeout move only when the test moves time, so a test that waits ten seconds of program time takes microseconds, and gives the same result every run. Tasks still run on their own threads; the harness waits for each, and delivers their messages in the order they started.

use petitcarnets as tea;
use std::time::Duration;
use tea::testing::{TestProgram, assert_golden};

// `Counter` as in the Quick Start.

#[test]
fn counts_up() {
    let mut test = TestProgram::new(Counter(0), 40, 10);
    test.press(tea::Key::new(tea::KeyCode::Up));
    assert!(test.screen().text().starts_with("Count: 1"));
    // tests/golden/counter.golden: the screen, the cursor and the modes.
    assert_golden("counter", &test.screen().snapshot());
    test.type_text("q");
    assert!(test.wait_finished(Duration::from_secs(1)));
    assert_eq!(test.final_model().0, 1);
}
teatest (Go) petitcarnets
teatest.NewTestModel(t, m, teatest.WithInitialTermSize(w, h)) TestProgram::new(m, w, h)
teatest.WithProgramOptions(...) TestProgram::with_terminal(program, TestTerminal::new(w, h))
tm.Send(msg), tm.Type(s) test.send(msg), test.type_text(s), test.press(key), test.bytes(b)
teatest.WaitFor(t, tm.Output(), cond) test.wait_for(within, |t| cond), test.advance(d)
tm.Quit(), tm.WaitFinished(t) test.quit(), test.wait_finished(within)
tm.FinalModel(t), tm.FinalOutput(t) test.final_model(), test.final_output(), test.final_screen()
teatest.RequireEqualOutput(t, out) assert_golden(name, &escape(test.final_output()))

TestTerminal sets the terminal up: its size, whether it acts as a real terminal, and replies to the queries a program writes. test.screen() is a small terminal emulator (Vt) with the text of each row, each cell's style and link, the cursor, and the modes.


Configuration

A program is configured by builder methods on Program, as Bubble Tea's With... options:

Option Effect
.with_fps(n) Frame rate cap (default 60)
.with_suspend(on) Ctrl-Z suspends (default true) or reaches the model as "ctrl+z"
.with_accessible(on) Plain-line output for screen readers
.with_color_profile(p), .with_environment(env) Override colour detection and the environment it reads

Environment variables read at start: TERM, COLORTERM, NO_COLOR, CLICOLOR, CLICOLOR_FORCE and the rest Bubble Tea reads for colour; ACCESSIBLE for plain-line output. In tests, PETITCARNETS_UPDATE_GOLDEN=1 writes golden files instead of comparing with them. There is no logging: Bubble Tea's LogToFile is not ported.


Examples

Bubble Tea's own examples are ported under their Go names, and a few are petitcarnets' own:

cargo run --example counter     # also picker, spinner, lifecycle, notes
cargo run --example simple      # Bubble Tea's: views, http, split-editors, ...
cargo run --example textinput   # Bubbles: textarea, list-default, table, pager, ...

docs/examples.md lists every one of Bubble Tea's examples, ported or not yet; each port runs in CI, headless in a golden test or in the real-terminal suite.


When not to use petitcarnets

  • On Windows. There is no Windows console backend yet; Linux, macOS and FreeBSD only.
  • For an async-first application that wants its UI inside a tokio task. Commands are plain closures on threads; an adapter is possible, but nothing is provided.
  • If you want widgets only. ratatui has the larger widget ecosystem and draws immediate-mode frames without imposing an event loop.
  • If you need Lip Gloss layers, Huh forms or a Wish SSH server. tea::style is a small Lip Gloss; the rest is not ported.
  • If you need a stable API now. Releases are 0.0.x, and a release may break the API, always declared in the CHANGELOG (Stability guarantees).

Development

make check        # every gate CI runs on stable
make help         # every task

make check runs rustfmt, Clippy pedantic with warnings as errors (with and without the components), the tests and doc tests, rustdoc with warnings as errors, ten million fuzz inputs through the decoder, the complexity ceilings, the semver gate, the no-dependency check, the bytes-per-frame check, codespell, REUSE, markdownlint, actionlint, this README's shape and the SBOM. CI adds musl, FreeBSD, Rust 1.85, coverage at 90 percent, Miri, ThreadSanitizer and the real-terminal suite. See DEVELOPMENT.md.


Security

All unsafe code sits in src/sys.rs and its submodules, the boundary to libc; the rest of the crate denies it. Miri and ThreadSanitizer run in CI, and ten million generated inputs go through the input decoder on every pull request. The crate has no dependencies, held by a CI job. Commits and release tags are SSH-signed (KEYS.asc), every Action is pinned by SHA, and releases are published by crates.io trusted publishing with SLSA build provenance and a CycloneDX SBOM. CodeQL, secret scanning and the OpenSSF Scorecard run on main.

Report vulnerabilities according to SECURITY.md.


Documentation


Stability guarantees

Versions rise by 0.0.1 per release. The public API is checked against the last release in CI (scripts/semver-gate.sh), and a breaking change passes only when the CHANGELOG declares it with a migration note. Renamed items keep their old name, deprecated, for one release. The bytes a program writes to the terminal are part of the contract: a change to them is a CHANGELOG entry even when no signature moves, and the bytes-per-frame gate catches it. The minimum Rust version is 1.85; raising it is a declared breaking change. Details in docs/POLICIES.md.


License

Dual-licensed under either:

at your option.

Seven source files are tables generated from other projects' data (uniseg, uax29, displaywidth, go-runewidth, charmbracelet's x/ansi, Go's unicode package and Unicode's own data); their notices are in THIRD-PARTY-NOTICES.md.

Copyright © 2026 Sebastien Rousseau.