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.kt was 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)
Diagram
Diagram

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)

  1. Header & Header Slots

  2. Viewport (scrollable messages)

  3. Status Bar Row (rendered above the horizontal divider)

  4. Horizontal Divider Line (โ”€)

  5. Above-Prompt Slots & Pending Approval Diffs/Prompts

  6. Completion Suggestions

  7. Input Prompt Box (bk: …​)

  8. 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.startProgress checks for ActiveProgressRegistry:

  • TUI Mode (activeProgressRegistry != null): Returns a TuiProgressTaskHandle that registers, updates, and unregisters active progress items in ActiveProgressRegistry.

  • Headless Mode (activeProgressRegistry == null): Returns a HeadlessProgressTaskHandle backed by Mordant’s CoroutineProgressTaskAnimator rendering to stderr.

  • TUI Grid Rendering: In TUI mode, ActiveProgressRegistry dirty state notifications notify TuiRenderCoordinator, causing RenderFrameBuilder to render active progress items within the TUI layout.

  • Progress Lifecycle & Cleanup:

    1. Registration: When startProgress() is called, TuiProgressTaskHandle registers an entry with ActiveProgressRegistry.registerProgress(id, description).

    2. Unregistration on Normal Close: When work finishes, handle.close() removes the entry via ActiveProgressRegistry.unregisterProgress(id) (idempotent).

    3. Sweep on Cancellation: If an agent run is cancelled via Ctrl+C (cancelAgent()), Tui.cancelAgent() explicitly executes activeProgressRegistry.clearAll(). This sweeps any active or orphaned progress entries, preventing frozen progress rows from persisting across turns.

  • Sequence Flow:

Diagram

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.ToolExecutionStart updates currentTool and triggers animator.update { }. AgentEvent.ToolExecutionEnd calls clearTool() 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:

Diagram

Key Files & Tests

File Purpose

us.nineworlds.book.cli.tui.render/TuiRenderer.kt

Widget composition for all TUI regions; charWrap, renderPrompt, sanitizeMarkdown; renderCompletions(List<Completion>, โ€ฆ)

us.nineworlds.book.cli.tui.render/MessageListRenderer.kt

Renders chat message history grid; delegates visible tool result rendering to ToolResultDiffRenderer

us.nineworlds.book.cli.tui.render/ToolResultDiffRenderer.kt

Formats tool result messages, detects embedded unified diffs (fenced or headers), and delegates colorization to DiffSyntaxColorizer

us.nineworlds.book.cli.tui.render/DiffSyntaxColorizer.kt

Reusable line-level colorizer styling unified diff syntax (+ green, - red, @@ cyan, +/โ€” dim, context gray)

us.nineworlds.book.cli.tui.render/DiffRenderer.kt

Computes diff widgets for file modification approval prompts, delegating line colorization to DiffSyntaxColorizer

us.nineworlds.book.cli.tui/Tui.kt

TUI lifecycle wiring (~290 lines); start(), buildSnapshot(), screen key handlers; defines TuiScreen enum

us.nineworlds.book.cli.tui.render/TuiRenderCoordinator.kt

TUI render loop management, thread-safe dirty state signaling, frame snapshot orchestration

us.nineworlds.book.cli.tui.registry/ActiveProgressRegistry.kt

Active extension progress handle tracking and dirty notification

us.nineworlds.book.cli.tui.render/RenderFrameBuilder.kt

Assembles full-screen widget from FrameSnapshot; screen routing, overlay conditionals

us.nineworlds.book.cli.tui.render/RenderLoop.kt

Render coroutine; 50 ms throttle, 120 ms spinner, synchronized-output escape sequences

us.nineworlds.book.cli.tui.render/FrameSnapshot.kt

Immutable point-in-time snapshot of all per-frame TUI state

us.nineworlds.book.cli.tui.render/CursorPosition.kt

Pure arithmetic: CursorParams, CursorPosition, countPromptRows, computeCursorPosition

us.nineworlds.book.cli.tui.input/InputStateMachine.kt

Keyboard dispatch, scroll state, completion overlay, findActiveFileToken, updateCompletions

us.nineworlds.book.cli.tui.input/InputHistory.kt

Persistent input history (~/.bk/history.txt); Alt+Up/Down navigation

us.nineworlds.book.cli.tui.input/FileCompleter.kt

CWD traversal, prefix filter, dotfile + gitignore exclusion, directory-first sort, cap-at-8

us.nineworlds.book.cli.tui.input/GitIgnoreFilter.kt

Lazy .gitignore parser; four pattern forms: , *, /-anchored, dir/ suffix

us.nineworlds.book.cli.tui.commands/SlashCommandRouter.kt

11 built-in commands + extension dispatch; completions(partial) for tab-completion

us.nineworlds.book.cli.tui.commands/Completion.kt

Sealed Completion interface; CommandCompletion and FileCompletion data classes

us.nineworlds.book.cli.tui.navigation/ScreenNavigator.kt

Active screen state & modal transitions interface

us.nineworlds.book.cli.tui.navigation/DefaultScreenNavigator.kt

Default ScreenNavigator implementation managing active screen, controller references, and polymorphic key delegation

us.nineworlds.book.cli.tui.screens/ScreenController.kt

Screen controller interface contract for interactive modal screens

us.nineworlds.book.cli.session/SessionOrchestrator.kt

Full session lifecycle; persist, fork, auto-name, extension event dispatch

us.nineworlds.book.cli.screens/ModelSelectionScreen.kt

Model picker; load() companion factory

us.nineworlds.book.cli.screens/SessionSelectionScreen.kt

Session picker with type-to-filter; open() companion factory

us.nineworlds.book.cli.screens/EffortSelectionScreen.kt

Modal reasoning effort selector; applies session-scoped choice with hint bar mentioning /effort-default

us.nineworlds.book.cli.screens/ForkScreen.kt

Fork-point selector โ€” spawns a new session file from the chosen message index

us.nineworlds.book.cli.screens/TreeScreen.kt

In-place branch selector โ€” see TreeScreen data-flow below

us.nineworlds.book.cli.agent/AgentEventProcessor.kt

AgentEvent dispatch, skill detection, auto-name trigger

us.nineworlds.book.cli.agent/HeadlessRunner.kt

Headless -p execution; spinner, event collection, session persistence, session info print

โ€”

โ€”

us.nineworlds.book.cli.tui.navigation/DefaultScreenNavigatorTest.kt

TDD suite for ScreenNavigator screen transition state and Escape dismissal

us.nineworlds.book.cli.tui.screens/ScreenControllerTest.kt

Unit tests for ScreenController implementations and polymorphic contract

us.nineworlds.book.cli.tui.render/ToolResultDiffRendererTest.kt

Unit tests for ToolResultDiffRenderer verifying diff colorization, pass-through, and line truncation

us.nineworlds.book.cli.tui.render/MessageListRendererTest.kt

Unit tests for MessageListRenderer chat message grid formatting and tool result rendering

us.nineworlds.book.cli.tui.render/DiffSyntaxColorizerTest.kt

TDD test suite verifying diff syntax line colorization and truncation limits

us.nineworlds.book.cli.tui.render/DiffRendererTest.kt

Unit tests for DiffRenderer computing diff widgets for file modification tools

us.nineworlds.book.cli.tui.render/TuiRendererTest.kt

Character-wrap sync contract regression; renderCompletions polymorphic rendering tests

us.nineworlds.book.cli.tui.render/CursorPositionTest.kt

Full TDD suite for countPromptRows edge cases and computeCursorPosition scenarios

us.nineworlds.book.cli.tui.render/RenderFrameBuilderTest.kt

Screen routing, scroll update, overlay conditionals

us.nineworlds.book.cli.tui.render/TuiRenderCoordinatorTest.kt

Unit tests for TuiRenderCoordinator dirty state transitions and ActiveProgressRegistry

us.nineworlds.book.cli.tui.input/InputStateMachineTest.kt

Key-to-action mapping without TUI harness; file-token tests with @TempDir

us.nineworlds.book.cli.tui.commands/CompletionTypeTest.kt

CommandCompletion and FileCompletion display name / description logic

us.nineworlds.book.cli.tui.commands/SlashCommandRouterTest.kt

All 11 built-in commands + extension dispatch

us.nineworlds.book.cli.tui.input/GitIgnoreFilterTest.kt

Real-filesystem tests for all four gitignore pattern forms

us.nineworlds.book.cli.tui.input/FileCompleterTest.kt

Real-filesystem tests for traversal, filtering, sorting, and capping

us.nineworlds.book.cli.session/SessionOrchestratorTest.kt

Full session lifecycle with mock SessionManager

us.nineworlds.book.cli.agent/AgentEventProcessorTest.kt

AgentEvent dispatch, skill detection

us.nineworlds.book.domain.extensions/ExtensionUIProgressTest.kt

Domain unit tests for ExtensionUI.startProgress default implementation and NoOpProgressTaskHandle

us.nineworlds.book.cli.approval/MordantExtensionUIProgressTest.kt

CLI unit tests for MordantExtensionUI.startProgress routing in TUI and headless modes

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() returns Int? โ€” the selected message index on success, null on cancel or empty history.

  • The on-disk branch happens before Tui updates lastState, so a crash between the two leaves the JSONL consistent with the intended branch point.

  • BeforeTree is an interceptable event โ€” extensions can inspect the sessionFile and leafCount and set cancel = true to abort the operation before the selector is shown.

  • Empty message lists return null immediately without opening the selector.

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).