TUI Architecture
This document covers the architecture of Book’s Terminal User Interface (TUI). It describes the component decomposition introduced by ADR-20260713, the frame layout and rendering pipeline, prompt character-wrapping, cursor arithmetic, and keyboard-driven file and command completion.
Refactoring note (ADR-20260713, 2026-07-21):
Tui.ktwas decomposed from a 1 270-line God class into 9 focused classes across dedicated sub-packages. The sections below reflect the current architecture. See the ADR for the full rationale and extraction details.
Table of Contents
Deep dives โ character-wrap rendering, cursor arithmetic, the sync contract, and file-attachment completion live in TUI Internals.
Overview
The TUI is built on Mordant and renders a full terminal
frame on every tick (~16 ms for a live agent, ~120 ms idle). Each frame is composed as a
single Mordant Widget tree, converted to an ANSI string via Terminal.render(), and written
to the terminal with a single rawPrint call to avoid flicker.
Component Map
Tui (lifecycle / wiring) โโโ InputStateMachine us.nineworlds.book.cli.tui.input keyboard dispatch, scroll, completions โ โโโ ExternalEditorLauncher Ctrl+G editor launch โ โโโ FileCompleter us.nineworlds.book.cli.tui.input @/# file-path completion โ โโโ GitIgnoreFilter us.nineworlds.book.cli.tui.input .gitignore exclusion โโโ SlashCommandRouter us.nineworlds.book.cli.tui.commands /help, /model, /new, โฆ + tab-completion โ โโโ Completion (sealed) us.nineworlds.book.cli.tui.commands CommandCompletion | FileCompletion | ArgumentCompletion โโโ TuiRenderCoordinator us.nineworlds.book.cli.tui.render render loop management, dirty state, progress โ โโโ RenderLoop us.nineworlds.book.cli.tui.render coroutines animation loop (animateInCoroutine), rawPrint, cursor positioning โ โ โโโ CursorPosition us.nineworlds.book.cli.tui.render countPromptRows / computeCursorPosition โ โโโ OverlayCompositor us.nineworlds.book.cli.tui.overlay composites active overlay panel over base frame โ โ โโโ OverlayManager us.nineworlds.book.cli.tui.overlay overlay session queue & single focus owner โ โโโ ActiveProgressRegistry us.nineworlds.book.cli.tui.registry active extension progress handle tracking โโโ Registries us.nineworlds.book.cli.tui.registry โ โโโ StatusBarRegistry extension status bar items (Text, Widget, StateFlow) โ โโโ UiSlotRegistry HEADER, ABOVE_PROMPT, BELOW_PROMPT, FOOTER layout slots โ โโโ RendererRegistry custom tool/entry/message renderers & markdown transformers โโโ RenderFrameBuilder us.nineworlds.book.cli.tui.render builds Widget from FrameSnapshot โ โโโ TuiRenderer us.nineworlds.book.cli.tui.render per-region widget methods โโโ AgentEventProcessor us.nineworlds.book.cli.agent AgentEvent dispatch + skill detection โโโ TuiAgentConfig us.nineworlds.book.cli.tui AgentLoopConfig + message queues โโโ ScreenNavigator us.nineworlds.book.cli.tui.navigation active screen state & modal transitions โโโ UiNoticeBoard us.nineworlds.book.cli.tui ephemeral UI notices โโโ SessionOrchestrator us.nineworlds.book.cli.session session lifecycle + persistence โโโ ModelSelectionScreen us.nineworlds.book.cli.screens model picker (self-loading) โโโ SessionSelectionScreen us.nineworlds.book.cli.screens session picker (self-loading) โโโ EffortSelectionScreen us.nineworlds.book.cli.screens effort picker (session-scoped with /effort-default hint) โโโ ForkScreen us.nineworlds.book.cli.screens fork-point selector โโโ TreeScreen us.nineworlds.book.cli.screens branch-point selector
Data flow on each render tick
RenderLoop.runCoroutines(scope)
โโ terminal.animation<Unit> { renderFrame() }.animateInCoroutine(fps = 20)
โโ renderFrame()
โโ Tui.buildSnapshot(spinnerFrame) โ reads lastState, currentScreen, inputBuffer, โฆ
โโ RenderFrameBuilder.build(snapshot)
โโ UiNoticeBoard.snapshot() merge ephemeral notices
โโ TuiRenderer.renderMessages(โฆ) measure viewport height
โโ onScrollUpdate(max, clamped) write back to InputStateMachine
โโ TuiRenderer.render*(โฆ) header, viewport, status, overlays, prompt, footer
โโ terminal.render(widget) โ ANSI string
โโ computeCursorPosition(CursorParams)
โโ terminal.rawPrint(ESC sync + frame + cursor)
The frame is divided into five fixed vertical regions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ Header (2 rows: app name + separator) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Viewport (variable height โ scrollable history) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Status (0โ1 rows: spinner / "Done in Xs") โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Prompt (N rows โ character-wrapped user input) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Footer (2 rows: separator + stats/phase line) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The cursor is placed at the last typed character inside the Prompt region using raw ANSI
escape sequences (\u001B[row;colH) after the frame is emitted.
Note: Additional overlay widgets (slash-command completions, tool-approval prompts, diff previews) are composed into the Viewport region above the Prompt โ they reduce available scroll height but do not shift the Prompt’s anchored row position.
Frame Layout & Dynamic Chrome Calculation
RenderFrameBuilder.build(snapshot) assembles the final Widget. Rather than static magic constants, chrome height is calculated dynamically from emitted row widgets (accounting for header, slots, status bar, horizontal divider, approval diffs, completion suggestions, input prompt, and footer).
Row Order (Top to Bottom)
-
Header & Header Slots
-
Viewport (scrollable messages)
-
Status Bar Row (rendered above the horizontal divider)
-
Horizontal Divider Line (
โ) -
Above-Prompt Slots & Pending Approval Diffs/Prompts
-
Completion Suggestions
-
Input Prompt Box (
bk: …) -
Below-Prompt Slots & Footer / Footer Slots
Height Calculation
val promptRows = countPromptRows("bk: " + snapshot.inputBuffer, width)
val approvalLines = if (snapshot.pendingApproval != null) {
1 + (snapshot.pendingDiffWidget?.render(terminal, width)?.height ?: 0)
} else 0
val completionLines = if (snapshot.completionSuggestions.isNotEmpty()) 1 else 0
val chromeLines = 2 + 2 + 1 + (if (hasStatus) 1 else 0) + promptRows + slotLines + approvalLines + completionLines
val viewportHeight = (height - chromeLines).coerceAtLeast(1)
The Prompt and Footer heights are known before the Viewport is sized, which means
computeCursorPosition can anchor the cursor relative to the bottom of the screen without
knowing how many messages are in the Viewport.
Markdown Sanitization for Streaming
While not part of the prompt input path, TuiRenderer.sanitizeMarkdown is a related
robustness concern. The agent streams responses incrementally; Mordant’s MarkdownRenderer
throws IndexOutOfBoundsException on an unclosed fenced code block (). or `~
sanitizeMarkdown scans the partial text and appends a closing fence marker if one is open:
// If still inside a fence after scanning all lines, close it:
return if (inFence) "$text\n$fenceMarker" else text
This makes every incremental streaming frame safe to render โ the fence is closed temporarily and will be removed when the next delta arrives with the real closing marker.
Extension UI Progress Integration (Active Progress Grid)
Extensions and script tools invoke ctx.ui.startProgress(description, total) to start non-blocking background progress tasks.
-
Mode-Aware Routing:
MordantExtensionUI.startProgresschecks forActiveProgressRegistry: -
TUI Mode (
activeProgressRegistry != null): Returns aTuiProgressTaskHandlethat registers, updates, and unregisters active progress items inActiveProgressRegistry. -
Headless Mode (
activeProgressRegistry == null): Returns aHeadlessProgressTaskHandlebacked by Mordant’sCoroutineProgressTaskAnimatorrendering to stderr. -
TUI Grid Rendering: In TUI mode,
ActiveProgressRegistrydirty state notifications notifyTuiRenderCoordinator, causingRenderFrameBuilderto render active progress items within the TUI layout. -
Progress Lifecycle & Cleanup:
-
Registration: When
startProgress()is called,TuiProgressTaskHandleregisters an entry withActiveProgressRegistry.registerProgress(id, description). -
Unregistration on Normal Close: When work finishes,
handle.close()removes the entry viaActiveProgressRegistry.unregisterProgress(id)(idempotent). -
Sweep on Cancellation: If an agent run is cancelled via Ctrl+C (
cancelAgent()),Tui.cancelAgent()explicitly executesactiveProgressRegistry.clearAll(). This sweeps any active or orphaned progress entries, preventing frozen progress rows from persisting across turns.
-
-
Sequence Flow:
Headless Mode Progress (Coroutine Progress Animator)
When running in headless mode (bk -p "…"), HeadlessRunner manages progress updates using HeadlessProgress.
When stderr is a TTY (isTty == true), HeadlessProgress initializes a Mordant CoroutineProgressTaskAnimator on stderr via progressBarLayout:
val layout = progressBarLayout {
spinner(Spinner.Dots())
text { currentTool ?: "thinking..." }
}
val anim = layout.animateInCoroutine(terminal)
-
Live Updates:
AgentEvent.ToolExecutionStartupdatescurrentTooland triggersanimator.update { }.AgentEvent.ToolExecutionEndcallsclearTool()to reset to"thinking…". -
Clean Teardown: Calling
stop()cancels the execution coroutine job and clears the animator. Mordant automatically erases the progress line and restores the cursor on cancellation or completion. -
Sequence Flow:
Key Files & Tests
| File | Purpose |
|---|---|
|
Widget composition for all TUI regions; |
|
Renders chat message history grid; delegates visible tool result rendering to |
|
Formats tool result messages, detects embedded unified diffs (fenced or headers), and delegates colorization to |
|
Reusable line-level colorizer styling unified diff syntax (+ green, - red, @@ cyan, +/โ dim, context gray) |
|
Computes diff widgets for file modification approval prompts, delegating line colorization to |
|
TUI lifecycle wiring (~290 lines); |
|
TUI render loop management, thread-safe dirty state signaling, frame snapshot orchestration |
|
Active extension progress handle tracking and dirty notification |
|
Assembles full-screen widget from |
|
Render coroutine; 50 ms throttle, 120 ms spinner, synchronized-output escape sequences |
|
Immutable point-in-time snapshot of all per-frame TUI state |
|
Pure arithmetic: |
|
Keyboard dispatch, scroll state, completion overlay, |
|
Persistent input history ( |
|
CWD traversal, prefix filter, dotfile + gitignore exclusion, directory-first sort, cap-at-8 |
|
Lazy |
|
11 built-in commands + extension dispatch; |
|
Sealed |
|
Active screen state & modal transitions interface |
|
Default |
|
Screen controller interface contract for interactive modal screens |
|
Full session lifecycle; persist, fork, auto-name, extension event dispatch |
|
Model picker; |
|
Session picker with type-to-filter; |
|
Modal reasoning effort selector; applies session-scoped choice with hint bar mentioning |
|
Fork-point selector โ spawns a new session file from the chosen message index |
|
In-place branch selector โ see TreeScreen data-flow below |
|
|
|
Headless |
โ |
โ |
|
TDD suite for |
|
Unit tests for |
|
Unit tests for |
|
Unit tests for |
|
TDD test suite verifying diff syntax line colorization and truncation limits |
|
Unit tests for |
|
Character-wrap sync contract regression; |
|
Full TDD suite for |
|
Screen routing, scroll update, overlay conditionals |
|
Unit tests for |
|
Key-to-action mapping without TUI harness; file-token tests with |
|
|
|
All 11 built-in commands + extension dispatch |
|
Real-filesystem tests for all four gitignore pattern forms |
|
Real-filesystem tests for traversal, filtering, sorting, and capping |
|
Full session lifecycle with mock |
|
|
|
Domain unit tests for |
|
CLI unit tests for |
TreeScreen โ In-Place Branch Data-Flow
TreeScreen.show() implements the /tree command. Unlike ForkScreen (which writes a new
session file), TreeScreen mutates the current session in place:
Tui โ SlashCommandRouter.handleTree()
โโ TreeScreen(messages, terminal, extensionRegistry, sessionManager).show()
โ
โโ fire BeforeTree intercept (extensions may cancel)
โ โณ if cancel == true โ return null
โ
โโ build selector list from messages
โโ interactiveSelectList("Select a point in history to branch from:")
โ โณ user picks item at index N, or Escape โ return null
โ
โโ sessionManager.branch(entries[N].id) โ rewrites on-disk JSONL
โโ return N
Tui (on non-null return)
โโ lastState = lastState.copy(messages = lastState.messages.take(N + 1))
Key invariants:
-
show()returnsInt?โ the selected message index on success,nullon cancel or empty history. -
The on-disk branch happens before
TuiupdateslastState, so a crash between the two leaves the JSONL consistent with the intended branch point. -
BeforeTreeis an interceptable event โ extensions can inspect thesessionFileandleafCountand setcancel = trueto abort the operation before the selector is shown. -
Empty message lists return
nullimmediately without opening the selector.
Related Planning Documents
The original TDD specs and ADRs for the TUI internals (cursor sync fix, file attachment
completion) lived in the internal prompts/plans/ tree and were removed when those efforts
completed. The surviving design record for these subsystems is this page plus
TUI Internals; for the current TUI ADR, see
ADR-20261006 (prompts/plans/adr/ADR-20261006-decompose-tui-view-renderers.md).