TUI Framework¶
Widget-based TUI framework built on top of ascii_colors.
Public surface:
App— the application event loop (alternate screen, render thread, focus cycling, modals).ScreenBuffer/ScreenRenderer— 2D styled cell grid and diff-based renderer.Layout containers:
VBox,HBox,Box,Container,ScrollView,Tabs.Leaf widgets:
Label,Divider,Button,Checkbox,TextInput,ListBox,Table,Spinner,StatusBar.Charts:
Sparkline,BarChart,BigValue.Borders:
BORDERS,get_border().Chatbot:
ChatbotApp,GeneratorProtocol,CallableGenerator,LollmsAdapter.
Example:
from ascii_colors.tui import App, VBox, Label, ListBox
body = VBox(gap=1, pad=1)
body.add(Label("[bold cyan]My App[/bold cyan]", align="center"))
body.add(ListBox(["one", "two", "three"]))
app = App()
app.set_root(body)
app.run()
ascii_colors ships a curses-style, widget-based TUI framework for building
richly-styled interactive console applications with focus handling, diff-based
rendering, and alternate-screen support. It has no external dependencies and
works on Windows, macOS, and Linux.
Use the TUI layer when you need persistent full-screen interfaces,
keyboard-driven navigation across multiple widgets, or real-time dashboards.
For lighter interactions prefer API Reference (questionary-style
prompts) or ascii_colors.ProgressBar.
Quick example¶
from ascii_colors.tui import App, VBox, Label, ListBox
body = VBox(gap=1, pad=1)
body.add(Label("[bold cyan]My App[/bold cyan]", align="center"))
body.add(ListBox(["one", "two", "three"]))
app = App()
app.set_root(body)
app.run()
Press Tab / Shift+Tab to cycle focus, Up / Down to navigate,
Enter to activate the focused widget, and Esc to quit.
Application runtime¶
- class ascii_colors.tui.app.App(*, fps=20.0, stream=None, alt_screen=True, hide_cursor=True, quit_keys=None, force_terminal=None, mouse=False, synchronized_output=True)[source]¶
Bases:
objectA curses-style application with queued events and mouse routing.
- Parameters:
- post(callback, *args, **kwargs)[source]¶
Schedule
callbackon the UI thread.This is the supported way for model/network worker threads to update widget state. The callable is serialized with keyboard and mouse input.
- Parameters:
callback (Callable)
- Return type:
None
- call_soon(callback, *args, **kwargs)¶
Schedule
callbackon the UI thread.This is the supported way for model/network worker threads to update widget state. The callable is serialized with keyboard and mouse input.
- Parameters:
callback (Callable)
- Return type:
None
- bind(key, callback)[source]¶
Bind a named key to an application-level callback.
Bindings are intended for commands such as
CTRL_NandF1. They run before focused-widget dispatch; unbound printable keys keep flowing to text editors normally.
- push_modal(widget)[source]¶
Push a centered modal overlay; input focus is restricted to it.
- Parameters:
widget (Widget)
- Return type:
None
- refresh_focus()[source]¶
Recompute focusable widgets while preserving the current focus.
- Return type:
None
- focus(widget)[source]¶
Focus
widgetand return whether it is currently focusable.Applications use this to choose an intentional initial focus target, such as a chat composer, instead of accepting the first widget found during tree traversal.
- refresh(*, clear=False)[source]¶
Relayout and repaint the application immediately.
Use this after changing several pieces of application state at once, such as applying settings or replacing a generator. Rendering remains synchronized with the background renderer through the app lock.
clear=Truealso clears the physical terminal before repainting; this is useful after overlays close or stale cells are visible.- Parameters:
clear (bool)
- Return type:
None
Screen buffer & rendering¶
Screen buffer and diff-based renderer for TUI applications.
The ScreenBuffer holds a 2D grid of styled cells. ScreenRenderer
compares the current buffer to the previously-drawn one and emits only the
rows that changed, using ANSI cursor addressing so we never have to clear
the whole screen between frames.
- class ascii_colors.tui.screen.Cell(char=' ', style='')[source]¶
Bases:
objectA single character cell with an attached SGR style prefix.
- char¶
- style¶
- class ascii_colors.tui.screen.ScreenBuffer(width, height)[source]¶
Bases:
objectA 2D grid of styled characters.
- box(x, y, w, h, chars, style='')[source]¶
Draw a border using a border-charset dict (see
tui.borders).
- draw_text(x, y, text, style='', max_width=None)[source]¶
Draw text with optional embedded ANSI SGR sequences.
- draw_wrapped(x, y, w, h, text, style='', align='left')[source]¶
Word-wrap styled text inside the rectangle (x, y, w, h).
- render_rows()[source]¶
Produce one ANSI-encoded string per row (self-contained).
Only cells whose style is a valid ANSI SGR sequence are emitted with that style. Anything else (a color name like
"cyan", a stray markup fragment, a typo) is treated as “no style” so raw text likecyancan never leak onto the screen via the row serializer.
- class ascii_colors.tui.screen.ScreenRenderer(stream=None, *, synchronized_output=True)[source]¶
Bases:
objectWrite terminal-friendly, synchronized screen updates.
Rendering happens at span granularity instead of repainting every changed row in full. DEC mode 2026 brackets each frame on supporting terminals, so a frame is presented atomically and does not visibly tear while several spans are being updated.
- Parameters:
synchronized_output (bool)
- draw(buffer, force=False)[source]¶
- Parameters:
buffer (ScreenBuffer)
force (bool)
- Return type:
None
Borders¶
Border character presets for TUI widgets.
Use named presets with any bordered widget:
Box(title="Panel", border="rounded")
Box(title="Panel", border="double")
Or pass a custom mapping with the same keys:
Box(chars={"tl": "╭", "tr": "╮", "bl": "╰", "br": "╯", "h": "─", "v": "│"})
Widgets¶
The widget set covers layout containers, text and status displays, input controls, data views, and lightweight charts.
Widget toolkit for the ascii_colors TUI framework.
- Every widget knows how to:
layout itself inside a rectangular region (
layout),draw onto a
ScreenBuffer(draw),optionally handle keyboard events when focused (
handle_key).
- class ascii_colors.tui.widgets.Widget(style='', pad=0)[source]¶
Bases:
objectBase class for all TUI widgets.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- measure(available_width, available_height)[source]¶
Return the widget’s intrinsic
(width, height)requirements.
- class ascii_colors.tui.widgets.Container(style='', pad=0)[source]¶
Bases:
WidgetA widget that contains children.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.VBox(gap=0, style='', pad=0)[source]¶
Bases:
ContainerStacks children vertically.
- class ascii_colors.tui.widgets.HBox(gap=0, style='', pad=0)[source]¶
Bases:
ContainerArranges children horizontally.
- class ascii_colors.tui.widgets.Box(*, title=None, border='simple', border_style='', inner_style='', chars=None, padding=1, gap=0, style='', opaque=True)[source]¶
Bases:
VBoxA vertical stack surrounded by a border and optional padding.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Label(text='', *, style='', align='left', wrap=False)[source]¶
Bases:
WidgetA text label. Single-line by default; set
wrap=Truefor multi-line.- measure(available_width, available_height)[source]¶
Return the widget’s intrinsic
(width, height)requirements.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.AsciiArt(art, *, style='', char_styles=None, align='center', valign='top', transparent=True)[source]¶
Bases:
WidgetRender multi-line block/Unicode art with alignment and transparency.
Unlike
Label, every line is drawn independently: embedded newlines never collapse into one row, spaces can remain transparent, and oversized art is clipped instead of forcing the surrounding layout to overflow.char_stylesoptionally assigns ANSI or rich-markup styles to selected characters, enabling shaded block-art without preprocessing the source.- Parameters:
- measure(available_width, available_height)[source]¶
Return the widget’s intrinsic
(width, height)requirements.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Divider(*, char='─', style='', title='')[source]¶
Bases:
WidgetA horizontal dividing line with an optional centered title.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.ProgressBar(value=0.0, *, style='', fill_style='', empty_style='', show_percent=True, bar_char='█', empty_char='░')[source]¶
Bases:
WidgetA horizontal progress bar (value in 0..100).
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Button(label, *, on_press=None, style='', focus_style='')[source]¶
Bases:
WidgetA button activated via ENTER or SPACE.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.ListBox(items, *, style='', selected_style='', on_select=None)[source]¶
Bases:
WidgetA vertically scrollable list with selection and scrollbar.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.TextInput(value='', *, placeholder='', style='', focus_style='', placeholder_style='', on_submit=None)[source]¶
Bases:
WidgetA single-line text editor with cursor and optional submit callback.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.MultiLineInput(value='', *, placeholder='', style='', focus_style='', placeholder_style='', on_submit=None, max_height=None, completions=None)[source]¶
Bases:
WidgetMulti-line editor with history and interactive text completions.
Completion providers return
(typed_prefix, replacement, description)tuples. Suggestions support Up/Down, Tab/Right acceptance, Enter execution, Escape dismissal, mouse clicks and wheel navigation.- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.ChatView(messages=None, *, user_style='', assistant_style='', system_style='', tool_style='', error_style='', user_label='You', assistant_label='AI', system_label='system', tool_label='tool', error_label='error', show_labels=True)[source]¶
Bases:
WidgetA scrollable, streaming-friendly chat transcript.
Renders a list of
{"role", "content"}messages, each prefixed by a role-coloured label header and wrapped to the available width. Designed for streaming: useappend_to_last()/update_last()to feed incremental model output while keeping the view pinned to the bottom unless the user has scrolled up.- Parameters:
- handle_mouse(event)[source]¶
Handle a mouse event; return
Truewhen consumed.The base widget ignores mouse input. Override in interactive widgets (
ListBox,Table,Button,TextInput, scroll views, …) to react to clicks and wheel events.- Return type:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Table(headers, rows, *, style='', header_style='', selected_style='', on_select=None, column_widths=None, column_aligns=None)[source]¶
Bases:
WidgetA scrollable, selectable data grid with headers, alignment and scrollbar.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Spinner(*, label='', frames=None, interval=0.1, style='', spinner_style='')[source]¶
Bases:
WidgetAn animated single-line spinner (advances each frame via wall clock).
- FRAMES_DOTS = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'¶
- FRAMES_LINE = '|/-\\'¶
- FRAMES_ARROW = '←↖↑↗→↘↓↙'¶
- FRAMES_BLOCK = '▁▂▃▄▅▆▇█▇▆▅▄▃▂▁'¶
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Checkbox(label, *, checked=False, on_change=None, style='', focus_style='')[source]¶
Bases:
WidgetA toggleable boolean control.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.StatusBar(*, left='', right='', style='', pad=1)[source]¶
Bases:
WidgetA chrome bar with left and right aligned segments.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.ScrollView(*, style='', gap=0, pad=0)[source]¶
Bases:
VBoxA vertically scrollable container with scrollbar and clipping.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Tabs(*, header_style='', active_style='', style='', gap=1)[source]¶
Bases:
ContainerA header row plus swap-in content panels (one visible at a time).
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.Sparkline(values, *, style='', min_value=None, max_value=None)[source]¶
Bases:
WidgetA single-row mini-chart built from horizontal block characters.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.BarChart(values, *, labels=None, style='', fill_style='', bar_char='█', max_value=None, gap=1)[source]¶
Bases:
WidgetA vertical bar chart with optional X labels.
- Parameters:
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.BigValue(value, *, label='', style='', big_style='', label_style='')[source]¶
Bases:
WidgetA dashboard-style KPI tile: big block digits with an optional label.
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
- class ascii_colors.tui.widgets.BigText(text, *, style='', shadow=False, shadow_style='', gap=1, scale=1, align='center', responsive=True)[source]¶
Bases:
WidgetA banner rendered from a 5-row block-letter font.
Supports an optional drop-shadow (offset
+1row /+1column, drawn withshadow_styleunderneath the main glyphs) which is what produces the classic “HERMES-AGENT” style banner look.- Parameters:
text (str) – Source string. Lowercase letters map to their uppercase glyphs; unknown characters are rendered as blanks.
style (str) – ANSI / rich-markup style for the main glyphs (default: bold yellow).
shadow (bool) – When
True, a drop-shadow is rendered behind the glyphs.shadow_style (str) – Style for the shadow (default:
bright_black).gap (int) – Blank columns between letters (default:
1).scale (int) – Duplicate each glyph cell into a
scale × scaleblock.2gives a chunky, extra-large banner. Default:1.align (str)
responsive (bool)
- draw(buffer)[source]¶
- Parameters:
buffer (ScreenBuffer)
- Return type:
None
Advanced agent console¶
ChatbotApp wraps any streaming or non-streaming generator in the responsive
lollms console, with a responsive block-letter welcome banner, compact
mascot, wordmark, and session sidebar. The composer receives initial focus so
users can type immediately. It includes clickable sessions, mouse-wheel scrolling,
Markdown/code/tool transcript cards, token and latency metadata, a multi-line
composer, slash commands, and background generation marshalled through
App.post() so worker threads never mutate widgets during rendering.
from ascii_colors.tui import ChatbotApp
def generate(prompt, history, on_chunk):
for token in ("Hello", " from", " the agent"):
on_chunk(token)
return "Hello from the agent"
app = ChatbotApp(generate, title="My Agent")
app.run()
Use Ctrl+N for a new conversation, Ctrl+L to clear one, F1 for
help, and Ctrl+Q to exit. Composer commands include /new, /clear,
/title NAME, /model, /logs, /logs clear, /settings and
/help. Typing / opens command autocomplete with descriptions. Use
Up/Down to choose, Tab or Right to accept, Enter to run, Escape to dismiss,
or click a suggestion. add_tool_event() inserts tool
activity cards into the active transcript. RichChatView is also exported
for applications that want the advanced transcript inside a custom layout.
The complete example in examples/tui/tui_chatbot_demo.py also provides an
F2 settings panel (or /settings) for the discussion workspace, image
generation/editing, and end-tag enforcement. Online operation requires the
optional lollms_client package and uses LollmsDiscussion.chat() with
MSG_TYPE_CHUNK streaming callbacks:
pip install lollms_client
python examples/tui/tui_chatbot_demo.py --online
Connection creation is delegated to get_client_from_env(create_tti=True);
configure lollms through its normal environment/saved configuration. Applying
the settings panel while offline connects on demand. The console itself still
works without lollms_client by supplying any other generator. Applying
settings calls ChatbotApp.refresh() so connection status and transcript
state are repainted immediately. App.refresh(clear=True) is available to
applications that also need to clear stale terminal cells after an overlay.
Captured terminal logs¶
Every ChatbotApp installs a bounded, thread-safe TerminalLogBuffer
handler before generator construction. It captures all ASCIIColors levels,
including lollms configuration logs, without writing raw output over the TUI.
Use /logs or F3 to open the viewer, type to filter, choose Errors to
filter by level, use Clear to empty it, and Escape to return to Compose.
/logs clear clears it directly. Repeated console creation is idempotent.
The standalone API is also exported:
from ascii_colors.tui import TerminalLogBuffer, attach_log_capture
logs = attach_log_capture(TerminalLogBuffer(max_entries=4000))
print(logs.text(level="ERROR"))
Captured terminal logs¶
Every ChatbotApp installs a bounded, thread-safe TerminalLogBuffer
handler before generator construction. It captures ASCIIColors records,
including lollms configuration logs, without writing raw output over the TUI.
Use /logs or F3 to open the viewer, type to filter, choose Errors to
filter by level, use Clear to empty it, and Escape to return to Compose.
/logs clear clears it directly. Repeated console creation is idempotent.
The standalone API is also exported:
from ascii_colors.tui import TerminalLogBuffer, attach_log_capture
logs = attach_log_capture(TerminalLogBuffer(max_entries=4000))
print(logs.text(level="ERROR"))
Custom widgets¶
Subclass ascii_colors.tui.widgets.Widget and implement layout()
(optional), draw(buffer), and — if interactive — handle_key(key). The
ascii_colors.tui.screen.ScreenBuffer passed to draw exposes
set_cell, put, draw_text, draw_wrapped, and related helpers that
respect wide characters and ANSI styling.
from ascii_colors.tui import Widget
from ascii_colors.tui.screen import ScreenBuffer
class Hello(Widget):
def draw(self, buffer: ScreenBuffer) -> None:
buffer.draw_text(
self.x, self.y,
"[bold green]Hello![/bold green]",
max_width=self.w,
)