runtime library TUI

Platform-safe core runtime for terminal applications.

This entrypoint exposes the TEA model, messages, commands, program hosting, rendering contracts, input bindings, tracing, and replay APIs without loading optional Markdown and native process helpers from the broader package:artisanal/tui.dart library.

Prefer this library when implementing reusable packages or browser-capable applications that only need the core runtime.

Classes

ArtisanalDevTools
DevTools integration for artisanal TUI programs.
BackendTerminal
Terminal implementation that layers ANSI/OSC semantics over a TerminalBackend.
BackgroundColorMsg
Message containing the terminal's background color.
BatchMsg
Message containing multiple messages to be processed sequentially.
BrowserTerminalHostServer
Reusable browser host server for remote TUI sessions.
BufferedTuiRenderer
A renderer that buffers output for efficient writes.
CapabilityMsg
Message sent when a terminal capability is reported.
CapturedOutputModel
Optional interface for models that receive captured output automatically.
CapturedOutputMsg
Message sent when a print() or stderr write is intercepted by the output-capture system.
CellSizeMsg
Message sent when the terminal reports its cell size in pixels.
ClearScreenMsg
Internal message to clear the screen.
ClipboardMsg
Clipboard content message.
ClipboardSetMsg
Message emitted after a best-effort clipboard write is attempted.
Cmd TUI
A command that produces a message asynchronously.
ColorPaletteMsg
Message containing a terminal palette entry color.
ColorProfileMsg
Message sent when the terminal color profile is detected or changed.
ColorSchemeMsg
Message sent when the terminal reports its preferred light/dark scheme.
CommonKeyBindings
Commonly used key bindings for navigation.
CompositeModel
A model that wraps another model, useful for composition.
CursorColorMsg
Message containing the terminal's cursor color.
CursorPositionMsg
Message sent when the terminal reports the cursor position.
CustomMsg<T>
Message wrapper for custom user-defined messages.
DebugOverlayModel
Draggable render-metrics overlay for debugging TUI performance.
DevToolsMessageEntry
A recorded message dispatch entry for the message log.
DevToolsRenderStats
Render timing statistics accumulated over the program lifetime.
DisableBracketedPasteMsg
Internal message to disable bracketed paste.
DisableMouseMsg
Internal message to disable mouse tracking.
DisableReportFocusMsg
Internal message to disable focus reporting.
EmbeddedTerminalBackend
Generic embedded backend backed by callbacks and externally supplied streams.
EnableBracketedPasteMsg
Internal message to enable bracketed paste.
EnableMouseAllMotionMsg
Internal message to enable mouse all motion tracking.
EnableMouseCellMotionMsg
Internal message to enable mouse cell motion tracking.
EnableReportFocusMsg
Internal message to enable focus reporting.
EnterAltScreenMsg
Internal message to enter alt screen.
EveryCmd
A repeating command that fires at regular intervals.
ExecProcessMsg
Message signaling that an external process should be executed.
ExecResult
Result of executing an external process.
ExitAltScreenMsg
Internal message to exit alt screen.
FixedViewport
A fixed terminal rectangle, using zero-based cell coordinates.
FocusMsg
Message sent when focus is gained or lost.
ForegroundColorMsg
Message containing the terminal's foreground color.
Frame TUI
Positioned string composition for one immediate-mode render pass.
FrameArea
A rectangular region in a structured terminal Frame.
FrameConstraint
A requested size along one axis of a FrameLayout.
FrameFill
A weighted share of space left after fixed and percentage constraints.
FrameInsets
Space removed from the edges of a FrameArea before layout.
FrameLayout
Pure helpers for splitting terminal frame areas.
FrameLength
A fixed number of terminal cells.
FramePercentage
A percentage of the available axis before fixed sizes are allocated.
FrameRenderable
A value that can paint itself directly into a terminal Frame.
FrameTickModel
Optional interface for models that want to control frame ticks.
FrameTickMsg
Message sent automatically by the TUI runtime every frame.
FrameView TUI
A View that composes styled strings into positioned terminal regions.
FullScreenTuiRenderer
Full-screen renderer using the alternate screen buffer.
Help
Help information for a key binding.
HideCursorMsg
Internal message to hide cursor.
HitTestMouseMsg
Message dispatched to an element when render-tree hit-testing determines that a MouseMsg landed within its render object's bounds.
HotReloadStatusMsg
Message sent when the hot reload system changes state.
InlineTuiRenderer
Inline renderer that renders below the current cursor position.
InterruptMsg
Message sent when the runtime receives a terminal interrupt.
JsonTerminalBackend
Message-oriented backend that speaks the terminal bridge JSON protocol.
Key
Represents a parsed keyboard input event.
KeyBinding
A key binding that maps keys to actions with optional help text.
KeyboardEnhancements
KeyboardEnhancements describes the requested keyboard enhancement features.
KeyboardEnhancementsMsg
Message sent when keyboard enhancements are reported.
KeyChordBinding
A declarative chord binding made of a prefix key and a continuation key.
KeyChordCancelledMsg
Message emitted when a pending chord is cancelled or times out.
KeyChordInterceptor
Interceptor that turns prefix key sequences into chord messages.
KeyChordPrefixMsg
Message emitted when a chord prefix key is recognized.
KeyChordResolvedMsg
Message emitted when a chord resolves to a configured binding.
KeyMap
A collection of key bindings forming a key map.
KeymapActionMsg
A shortcut action was resolved by KeymapHub / a ShortcutSurface.
KeymapHub
Program interceptor that owns a dynamic surface-first stack plus optional base layers.
KeymapLayerClaim
Surface claims the message (optionally transformed). Stops the stack.
KeymapLayerDrop
Surface swallows the message. Stops the stack; nothing is enqueued.
KeymapLayerPass
Surface did not handle the message — try the next layer (or drop if ShortcutSurface.exclusive).
KeymapLayerResult
Outcome of a ShortcutSurface handling one message.
KeymapPendingSequence
Live multi-key sequence state (which-key input).
KeymapSequenceCancelledMsg
A pending multi-key sequence was cancelled or timed out.
KeymapSequencePrefixMsg
A multi-key sequence prefix was recognized (which-key should show).
KeyMsg
Message sent when a key is pressed.
KeyParser
Parses raw terminal input bytes into Key objects and Msg objects.
Keys
Key constants and utilities for keyboard input handling.
LineSpanEdit
One minimal terminal edit for a single row: move the cursor to the 0-based display column and write text (which starts from a reset pen).
Model TUI
Abstract interface for TUI application models.
ModeReportMsg
Message sent when the terminal replies to a mode status query.
ModifyOtherKeysMsg
Message sent when the terminal reports a ModifyOtherKeys mode.
MouseMsg
Message sent for mouse events.
Msg TUI
Base class for all messages in the TUI runtime.
NullTuiRenderer
A renderer that does nothing (for testing).
OutputLog
An immutable, bounded log of captured output entries.
OutputLogEntry
A single entry in an OutputLog.
PaneLayout
A complete computed layout for all leaf panes and split handles.
PaneLeaf
PaneRect
Rectangle coordinates for leaf pane geometry.
PaneSnapTarget
A target split handle used for snap behavior.
PaneSplit
PaneTreeNode
ParallelCmd
A command that executes multiple commands in parallel through the Program's command execution system.
PasteMsg
Message sent when bracketed paste content is received.
PasteTextMsg
Message used by the runtime to deliver collapsed large rune bursts as a single text payload (paste-like behavior).
PreparedReplay
Prepared replay data including session selection and scenario.
PrimaryDeviceAttributesMsg
Message sent when the terminal replies with primary device attributes.
PrintLineMsg
Message for printing a line above the program output.
ProfileHarnessCommand
Profile subcommand provided by HarnessCommandsMixin.
ProfileHarnessConfig
Configuration for profile harness commands.
Program<M extends Model> TUI
The TUI program runtime.
ProgramDevToolsController
Program-owned state for the universal diagnostics overlay.
ProgramDiagnostics
The single diagnostics data store owned by one running Program.
ProgramDiagnosticsMetrics
Shared registry for metrics contributed by applications and frameworks.
ProgramDiagnosticsOptions
Configuration for the universal in-app program diagnostics overlay.
ProgramHost
Reusable launch target for a Program.
ProgramHostBinding
Resolved runtime configuration produced by a ProgramHost.
ProgramInterceptor
Intercepts program messages and lifecycle events.
ProgramMacro
Recorded user-input macro that can be replayed later.
ProgramOptions
Options for configuring the TUI program.
ProgramRenderCapture
Bundles deterministic snapshot recording with aggregate render monitoring.
ProgramRenderCapturePayload
Structured export payload for one ProgramRenderCapture state snapshot.
ProgramRenderCaptureReport
Structured summary emitted from ProgramRenderCapture.
ProgramRenderChangeSummary
Aggregated native-change summary for one render.
ProgramRenderEvent
One live render event emitted by ProgramRenderFeed.
ProgramRenderFeed
Program interceptor that publishes live render events.
ProgramRenderMonitor
Higher-level render activity monitor built on the live render hook.
ProgramRenderRecorder
Program interceptor that records deterministic render snapshots.
ProgramRenderSnapshot
One deterministic render snapshot captured by ProgramRenderRecorder.
ProgramRenderSnapshotSummary
Compact summary of the most recent captured render snapshot.
ProgramRenderStats
Aggregated render activity across one program run.
ProgramReplay
Message replay source for ProgramOptions.replay.
ProgramReplayStep
One replay step for ProgramReplay.script.
QuitMsg
Internal message signaling that the program should quit.
RawModeGuard
Guard object returned by Terminal.enableRawMode.
ReassemblableModel
Optional interface for models that support hot-reload reassembly.
RenderBudgetController
Tracks render budget pressure and adjusts degradation levels.
RenderBudgetMsg
Message sent when the runtime changes render-budget degradation state.
RenderBudgetOptions
Configuration for budget-aware render degradation.
RenderBudgetState
The current state of a RenderBudgetController.
RenderMetrics
Tracks render performance metrics including FPS, frame times, and render durations.
RenderMetricsModel
Optional interface for models that want render metrics updates.
RenderMetricsMsg
Message sent periodically with renderer performance metrics.
RepaintMsg
Message sent to force a repaint of the view.
RepaintRequestMsg
Internal message to request a repaint.
ReplayAction
Replay action schema used by TUI scenario JSON files.
ReplayCoordinateInterceptor
Coordinate interceptor that scales replay mouse coordinates to current runtime window dimensions.
ReplayCustomEvent
Structured custom event embedded in replay actions.
ReplayEventDirective
Hook decision produced for ReplayCustomEvent actions.
ReplayEventMsg
Replay message emitted for custom event actions.
ReplayEventPresentation
Shared replay-event summary for debug UIs and status surfaces.
ReplayHarnessCommand
Replay subcommand provided by HarnessCommandsMixin.
ReplayHarnessConfig
Configuration for replay harness commands.
ReplayMouseMsg
Replay-only mouse message marker.
ReplayRenderCaptureEvent
Typed replay-side view of one runtime.render_capture custom event.
ReplayScenario
Replay scenario document.
ReplayScreen
Screen metadata captured for replay coordinate scaling.
ReplayTraceConversionOptions
Trace conversion options for ReplayTraceConverter.
ReplayTraceConversionResult
Conversion output returned by ReplayTraceConverter.convertFile.
ReplayTraceConverter
Converts TuiTrace logs into replay scenarios.
ReplayTraceSummary
Summarizes the slowest spans in a trace file.
ReplayTraceSummarySpan
One timed span in a trace summary.
RequestWindowSizeMsg
Internal message to request window size.
ResettableInterceptor
Interceptors that hold multi-step state (chords, macros) implement this so KeymapHub can clear them when a surface is popped or deactivated.
ResolvedReplay
Resolved replay plan ready for inline use in a Program command.
ResumeMsg
Message sent when the program resumes from suspension.
ScrollbarChars
SecondaryDeviceAttributesMsg
Message sent when the terminal replies with secondary device attributes.
SequenceMsg
Message produced by Cmd.sequence, wrapping commands that the runtime will execute one at a time, delivering each result via send as it completes before proceeding to the next command.
SetWindowTitleMsg
Internal message to set window title.
ShortcutBinding
A named action bound to a key sequence of length ≥ 1.
ShortcutContinuation
One which-key row for the next key in a pending sequence.
ShortcutSurface
A named, stackable input layer (route, dialog, editor chrome, …).
ShowCursorMsg
Internal message to show cursor.
SimpleTuiRenderer
TuiRenderer that writes output without diffing or clearing (nil renderer mode).
SocketTerminalBackend
Socket-backed backend for remote/shell-mode terminal hosts.
SocketTerminalHostServer
Reusable raw socket host server for remote TUI sessions.
Spinner
A spinner animation definition.
SpinnerModel
A spinner widget for showing loading/activity states.
Spinners
Pre-defined spinner animations.
SpinnerTickMsg
Message indicating a spinner should advance to the next frame.
SplitHandle
Geometry for a split handle used by resize/snap calculations.
SplitTerminal
A terminal that splits "control/input" from "display/output".
StaticComponent
A ViewComponent that only has a view and no state/updates.
StdioTerminal
Standard terminal implementation using dart:io.
StdioTerminalBackend
Native stdio backend for BackendTerminal.
StreamCmd<T>
A command that manages a stream subscription.
StringSinkTuiRenderer
A renderer that writes to a StringSink (for testing).
StringTerminal
A terminal that captures output to a string buffer (for testing).
SuspendMsg
Message signaling the program should suspend (like Ctrl+Z).
TerminalBackend
Low-level I/O backend for a terminal host.
TerminalBridge
Bridge controller for embedded terminal hosts such as xterm.js, sockets, or custom UI surfaces.
TerminalBridgeJsonChannel
JSON message channel layered over a TerminalBridge.
TerminalBridgeMessage
JSON-serializable bridge message for remote/browser terminal hosts.
TerminalColorSchemeState
Tracks terminal color-scheme preference separately from terminal colors.
TerminalDirtySpan
Dirty cell range captured from the UV buffer.
TerminalNativeCell
One captured native cell.
TerminalNativeCellDelta
One changed cell between two native frames.
TerminalNativeCellDeltaFrame
Delta snapshot containing changed cells between two native frames.
TerminalNativeColor
Snapshot of a UV color.
TerminalNativeDeltaFrame
Delta snapshot containing only dirty lines from a native frame.
TerminalNativeFrame
Native cell-buffer snapshot of rendered terminal output.
TerminalNativeLine
One captured line from a native frame.
TerminalNativeLineDelta
One changed line in a cell-delta snapshot.
Snapshot of UV link metadata.
TerminalNativeSpan
One grouped semantic span from a native line.
TerminalNativeSpanDelta
Grouped span deltas for one line.
TerminalNativeStyle
Snapshot of UV cell style metadata.
TerminalPaletteService
Message-driven cache and probe helper for terminal palette reports.
TerminalPaletteSnapshot
Immutable snapshot of terminal-reported colors.
TerminalProgressBar
TerminalProgressBar represents the terminal taskbar progress (OSC 9;4).
TerminalRenderFrame
Parsed representation of rendered terminal output.
TerminalRenderLine
Parsed representation of a rendered terminal line.
TerminalState
Terminal state snapshot for saving/restoring.
TerminalThemeState
Tracks terminal-reported colors and background truth.
TerminalVersionMsg
Message sent when the terminal version is reported.
TertiaryDeviceAttributesMsg
Message sent when the terminal replies with tertiary device attributes.
TickMsg
Message sent when a timer tick occurs.
TilingPaneManager
Immutable tiling pane manager with split tree and focused pane id.
TraceEventRecord
A structured event decoded from one trace log line.
TraceEventType
Structured trace event names emitted by TuiTrace.event.
TraceSessionSelection
Selected trace session information.
TraceSessionSplit
Session data from splitting trace logs.
TraceSpan
A timing span for hierarchical tracing.
TtyTerminal
POSIX /dev/tty terminal implementation.
TuiEvidence
Structured runtime evidence logging for diagnostic replayability.
TuiEvidenceRecord
A decoded evidence event line.
TuiRenderer TUI
Abstract renderer interface for TUI output.
TuiRendererOptions
Options for configuring a TuiRenderer.
TuiTrace
Lightweight debug tracer for TUI frame rendering and message dispatch.
UltravioletTuiRenderer
Ultraviolet-inspired renderer backed by a cell buffer + diffing updates.
UvEventMsg
Raw Ultraviolet event message (only emitted when UV input decoding is enabled).
View TUI
View represents a terminal view that can contain metadata for terminal control.
ViewComponent
A lightweight, composable TUI component.
ViewDegradation
Opt-in degraded content stages for a View.
ViewportKeyMap
Key bindings for viewport navigation.
ViewportModel
A viewport widget for scrollable content.
ViewportScrollPane
WebSocketTerminalBackend
WebSocket-backed backend that speaks the terminal bridge JSON protocol.
WindowPixelSizeMsg
Message sent when the terminal window reports its pixel dimensions.
WindowSizeMsg
Message sent when the terminal window is resized.
ZoneInBoundsMsg
Message sent when a zone is within bounds of a mouse event.
ZoneInfo
Holds information about the start and end positions of a zone.

Enums

ClipboardSelection
Clipboard selection targets for OSC 52 operations.
ClipboardSetMethod
Clipboard write transport used by ClipboardSetMsg.
DegradationLevel
Ordered render degradation levels used by the runtime.
FrameAxis
Axis used by FrameLayout.split.
HotReloadStatus
Status of the hot reload system.
KeyType
Types of keyboard input events.
ModeReportValue
The reported state of a terminal mode query.
MouseAction
Mouse event action types.
MouseButton
Mouse button identifiers.
MouseMode
Mouse tracking modes for the terminal.
OutputSource
The origin of a captured output line.
PaneNavigationDirection
Navigation direction used for focus traversal.
PaneSnapAlignment
Snap alignment for drag gestures near a split handle.
PaneSplitDirection
Direction for pane geometry splits.
ProgramDiagnosticsPosition
ReplayEventControl
Replay control decision for a custom replay event.
ScreenMode
Controls how the TUI renders relative to the terminal's primary screen.
TerminalBridgeMessageType
Message kinds used by TerminalBridgeMessage.
TerminalColorKind
Types of terminal colors reported via OSC sequences.
TerminalProgressBarState
TerminalProgressBarState represents the state of the terminal taskbar progress.
TraceTag
Trace categories for filtering and grouping trace output.
UiAnchor
Which edge of the terminal the inline UI region is anchored to.

Mixins

ComponentHost
A mixin for Models that host one or more ViewComponents.
CopyWithModel
Mixin that documents the copyWith pattern for models.
HarnessCommandsMixin
Mixin that adds replay and profile subcommands to a CommandRunner.
ProfileHarnessMixin<T>
Mixin that adds profile harness functionality on top of ReplayHarnessMixin.
ReplayHarnessMixin<T>
Mixin providing replay harness functionality for Command subclasses.
TerminalThemeHost
Mixin for models/components that want terminal theme state with minimal boilerplate.

Extensions

CmdExtension on Cmd?
Extension methods for nullable Cmd.
KeyMatchExtension on Key
Extension to check key matches more fluently.
KeyMsgMatchExtension on KeyMsg
Extension to check KeyMsg matches.
ProfileFlagsArgParser on ArgParser
Extension to register profile flags on any ArgParser (standalone usage).
ReplayFlagsArgParser on ArgParser
Extension to register replay flags on any ArgParser (standalone usage).
TuiTerminalRendererExtension on TuiTerminal
Extension to create renderers from terminals.

Constants

shortcutHelpActionId → const String
Default action id for “show shortcuts for this view” (OpenCode help_show).

Properties

isSharedStdinStreamStarted → bool
Returns true if the shared stdin stream has started listening to stdin.
no setter
sharedStdinStream → Stream<List<int>>
Shared broadcast stream for stdin to allow multiple listeners and restarts.
no setter

Functions

analyzeReplayTrace(String path, {int limit = 12}) → Future<ReplayTraceSummary>
Analyze a trace file and return the slowest spans.
chordBindings(KeyMap keyMap) → List<KeyChordBinding>
Extracts chord bindings from keyMap for use with KeyChordInterceptor.
compressAnsi(String input) → String
Removes redundant SGR sequences to reduce output size.
deriveInactive(Color bright, {double factor = 0.2}) → Color
Derives the inactive color for scanner background positions.
deriveTrail(Color bright, {int steps = 6}) → List<Color>
Derives a gradient of trail colors from a single bright color.
every(Duration interval, Msg? callback(DateTime time), {Object? id, DateTime nowProvider()?}) → Cmd
Helper to create a repeating timer command.
formatShortcutKeys(List<String> labels, {String separator = ' '}) → String
Join key labels for display (ctrl+x + b → ctrl+x b).
keyMapFromShortcutBindings(Iterable<ShortcutBinding> bindings) → KeyMap
Build a KeyMap for HelpView from shortcut bindings.
keyMatches(Key key, List<KeyBinding> bindings) → bool
Checks if a key message matches any of the given bindings.
keyMatchesSingle(Key key, KeyBinding binding) → bool
Checks if a key matches a single binding.
lineSpanEdit(TerminalRenderLine oldLine, TerminalRenderLine newLine) → LineSpanEdit?
Computes the minimal single-span edit that turns oldLine (currently on the terminal) into newLine, both taken from parsed render frames of the same row. Returns null when the difference has no visible effect (e.g. only zero-width sequences changed, with no impact on later cells).
loadReplayPlan(ReplayHarnessConfig config, {ReplayEventHook? eventHook}) → Future<ResolvedReplay?>
Load a replay plan from configuration for inline use.
noCmd(Model model) → UpdateResult
Helper function to create an update result with no command.
quit(Model model) → UpdateResult
Helper function to create an update result that quits.
replayScenarioStream(List<ReplayAction> actions, {required bool loop, required bool keepOpen, required double speed, ReplayEventHook? eventHook}) → Stream<Msg>
Builds a replay message stream from a list of replay actions.
runProgram<M extends Model>(M model, {ProgramOptions options = const ProgramOptions(), ProgramHost? host, TuiTerminal? terminal, TuiRenderer? renderer}) → Future<void>
Runs a TUI program with the given model.
runProgramDebug<M extends Model>(M model, {ProgramOptions? options, ProgramHost? host, TuiTerminal? terminal}) → Future<void>
Runs a TUI program without panic catching (for debugging).
runProgramWithResult<M extends Model>(M model, {ProgramOptions options = const ProgramOptions(), ProgramHost? host, TuiTerminal? terminal, TuiRenderer? renderer}) → Future<M>
Runs a TUI program and returns the final model after exit.
shortcutBindingsFromChords(Iterable<KeyChordBinding> chords) → List<ShortcutBinding>
Map chord bindings into ShortcutBindings.
shutdownSharedStdinStream() → Future<void>
Shuts down the shared stdin stream so the process can exit cleanly.
splitTraceSessions(List<String> lines) → List<TraceSessionSplit>
Splits trace lines into sessions based on # trace start: markers.
tryParseTraceSpan(String path, int lineNumber, String line) → ReplayTraceSummarySpan?
Try to parse a single trace line as a timed span.
writeLines(String path, List<String> lines) → Future<void>
Writes lines to a file, creating parent directories if needed.

Typedefs

BrowserTerminalSessionHandler = Future<void> Function(WebSocket socket)
Session handler invoked for each accepted browser websocket connection.
CmdFunc = Cmd Function()
Type alias for a function that creates commands.
CmdFunc1<T> = Cmd Function(T value)
Type alias for a function that creates commands from a value.
FramePainter = void Function(Frame frame)
Signature used by FrameView to paint a structured terminal frame.
MessageFilter = Msg? Function(Model model, Msg msg)
A function that filters messages before they reach the model.
ProgramHostResolver = ProgramHostBinding Function(ProgramOptions options)
Resolves a reusable launch target for a Program.
ReplayEventHook = FutureOr<ReplayEventDirective?> Function(ReplayCustomEvent event)
Hook invoked when replay reaches an event action.
SocketTerminalSessionHandler = Future<void> Function(Socket socket)
Session handler invoked for each accepted raw socket terminal connection.
TerminalDimensions = ({int height, int width})
Terminal dimensions expressed in cells.
TuiTerminal = Terminal
Alias for backward compatibility.
UpdateResult = (Model, Cmd?)
Type alias for the update function return type.

Exceptions / Errors

ProgramCancelledError
Error thrown when a program is cancelled via an external signal.