TUI Internals: Render & Input
Deep-dive internals of the Book TUI: character-wrap rendering, cursor position arithmetic, the render/sync contract, and file-attachment completion. For day-to-day TUI usage see the User Guide; for the high-level component map see TUI Architecture.
Prompt Rendering: Character-Wrap Strategy
Why Not Word-Wrap?
Mordant offers several built-in whitespace modes, including Whitespace.PRE_WRAP (wraps at
word boundaries). However, the cursor arithmetic in computeCursorPosition uses
character-level column counting:
cursorColInPrompt = lastLine.length % terminalWidth
If Mordant wraps the prompt at a space instead of at exactly column terminalWidth, the
rendered line layout diverges from this arithmetic โ the cursor ends up pointing at a column
that does not exist on the rendered line, producing a visible cursor jump or overlap.
Solution: TuiRenderer.renderPrompt pre-processes the input text with charWrap() before
handing it to Mordant, then uses Whitespace.PRE (no further wrapping) so that Mordant
renders exactly what it receives.
fun renderPrompt(state: AgentState, inputBuffer: String, width: Int): Widget =
Text(
charWrap(brightBlue("bk") + gray(": ") + inputBuffer, width),
whitespace = Whitespace.PRE, // โ Mordant must NOT re-wrap
width = width
)
charWrap โ Implementation Detail
charWrap inserts a \n at every width-th visible character. It processes the text
character by character, maintaining a visibleCol counter that increments only for printable
characters (ANSI escape sequences are skipped transparently โ see below).
Input: "bk: the quick brown fox jumps" (width = 10) Output: "bk: bk: the \nquick brow\nn fox jump\ns"
Every non-terminal line in the output has exactly width visible characters โ the renderer
and the cursor arithmetic agree perfectly.
ANSI Escape Transparency
The prompt prefix ("bk: ") is rendered with Mordant colour helpers (brightBlue, gray),
which wrap characters in ANSI escape sequences like \u001B[94mq\u001B[0m. These sequences
must not be counted toward the visible column width, or the wrap point would be wrong.
charWrap detects escape sequences with the regex \u001B\[[0-9;]*[A-Za-z] and copies
them verbatim without incrementing visibleCol:
val ansiEscape = Regex("\u001B\\[[0-9;]*[A-Za-z]")
// ... inside the loop:
val match = ansiEscape.find(line, i)
if (match != null && match.range.first == i) {
result.append(match.value) // copy, no visibleCol++
i = match.range.last + 1
} else {
if (visibleCol == width) { result.append('\n'); visibleCol = 0 }
result.append(line[i])
visibleCol++
i++
}
Cursor Position Arithmetic
After rendering the full frame, RenderLoop emits a raw ANSI cursor-positioning escape
(\u001B[row;colH). The row and column are computed by computeCursorPosition in
us.nineworlds.book.cli.tui.render.CursorPosition.kt.
Key Types
// Input to the computation
internal data class CursorParams(
val promptText: String, // "bk: " + inputBuffer (after charWrap, plain text)
val terminalWidth: Int,
val terminalHeight: Int,
val footerHeight: Int = 2,
)
// Output โ 0-based row and column
internal data class CursorPosition(val row: Int, val col: Int)
Callers convert to 1-based ANSI coordinates:
\u001B[${pos.row + 1};${pos.col + 1}H.
countPromptRows
Returns the number of terminal rows the prompt text occupies, accounting for:
-
Explicit
\ncharacters (pasted multi-line text) -
Character-level wrap at
width -
The "overflow row" when a line’s length is an exact multiple of
width(the cursor sits at column 0 of the next row)
internal fun countPromptRows(text: String, width: Int): Int =
text.split('\n').sumOf { line ->
when {
line.isEmpty() -> 1
line.length % width == 0 -> line.length / width + 1 // overflow row
else -> (line.length + width - 1) / width
}
}
The Overflow Row
When the user types exactly width characters, the last character fills column width - 1.
The next keystroke begins on a new terminal row at column 0. countPromptRows accounts for
this by returning length / width + 1 (not just length / width), so the cursor arithmetic
places the cursor on the correct (currently empty) row.
| Input length | width |
Visual rows | countPromptRows |
|---|---|---|---|
79 |
80 |
1 |
1 |
80 |
80 |
1 (+overflow) |
2 |
81 |
80 |
2 |
2 |
160 |
80 |
2 (+overflow) |
3 |
computeCursorPosition
internal fun computeCursorPosition(params: CursorParams): CursorPosition {
val totalPromptRows = countPromptRows(params.promptText, params.terminalWidth)
val lastLine = params.promptText.split('\n').last()
val cursorRowInPrompt = totalPromptRows - 1
val cursorColInPrompt = lastLine.length % params.terminalWidth
val rowStart = (params.terminalHeight - params.footerHeight - totalPromptRows)
.coerceAtLeast(0)
val cursorRow = rowStart + cursorRowInPrompt
return CursorPosition(row = cursorRow, col = cursorColInPrompt)
}
Step-by-step for promptText = "bk: hello\nworld", width = 80, height = 24:
totalPromptRows = 2 // "bk: hello" (1 row) + "world" (1 row) lastLine = "world" // the last \n-delimited segment cursorRowInPrompt = 1 // 0-indexed within the prompt cursorColInPrompt = 5 // "world".length % 80 rowStart = 24 - 2 - 2 = 20 cursorRow = 20 + 1 = 21 โ CursorPosition(row = 21, col = 5)
Frame Anchoring from the Bottom
The Prompt is always anchored at the bottom of the terminal, above the Footer:
rowStart = terminalHeight - footerHeight - totalPromptRows
Widgets rendered above the Prompt (status, completions, approval prompt) do not change
rowStart โ they reduce the Viewport’s height instead. This invariant means the cursor
formula only needs footerHeight and totalPromptRows; it is independent of how many
messages are visible or how many overlay rows are showing.
This was a deliberate design choice made during the cursor-sync fix:
passing per-frame row counts (completionRows, approvalRows, statusHeight) into CursorParams
introduced fragile coupling. Anchoring from the bottom makes the formula robust to any
future overlay additions.
The Sync Contract
The correctness of the cursor position rests on three invariants:
| # | Invariant | Where enforced |
|---|---|---|
1 |
Every rendered prompt line has exactly |
|
2 |
|
|
3 |
|
|
Breaking any one of these three invariants desynchronises the rendered text from the cursor
position. The regression test renderPrompt character-wraps at exact width to match cursor
arithmetic in TuiRendererTest verifies all three together:
// Every non-terminal rendered line must be exactly `width` visible chars.
nonTerminalLines.forEach { line ->
assertThat(line.length).isEqualTo(width)
}
// Cursor arithmetic must agree with the rendered layout.
assertThat(pos.col).isEqualTo(fullPromptText.length % width)
File Attachment Completion
overlay infrastructure through a shared Completion sealed interface.
Trigger Detection โ findActiveFileToken
InputStateMachine.findActiveFileToken(buffer: String): Pair<Int, String>? is an internal pure
function that scans the input buffer for an active file token โ one that has been opened by
@ or # and has not yet been closed by a space.
internal fun findActiveFileToken(buffer: String): Pair<Int, String>? {
val triggerPos = maxOf(buffer.lastIndexOf('@'), buffer.lastIndexOf('#'))
if (triggerPos < 0) return null
val tokenText = buffer.substring(triggerPos + 1)
if (tokenText.contains(' ')) return null // space closes the token
return Pair(triggerPos, tokenText)
}
Rules:
| Scenario | Result |
|---|---|
No |
|
Trigger exists but a space follows it |
|
|
|
|
|
Multiple triggers โ |
Returns the rightmost trigger ( |
Trigger at end with nothing after โ |
|
Empty buffer |
|
The function is internal so that TuiTest can exercise it via the Tui.findActiveFileToken
delegate without standing up the full TUI machinery.
The Completion Sealed Interface
All completion suggestions โ both file paths and slash commands โ are represented by a single
sealed interface Completion defined in Completion.kt:
sealed interface Completion {
val displayName: String
val description: String
}
data class CommandCompletion(val name: String, override val description: String) : Completion {
override val displayName = "/$name"
}
data class FileCompletion(
val name: String,
val relativePath: String,
val isDirectory: Boolean
) : Completion {
override val displayName = if (isDirectory) "$name/" else name
override val description = if (isDirectory) "๐ directory" else "๐ file"
}
data class ArgumentCompletion(
val value: String,
val itemLabel: String?,
override val description: String
) : Completion {
override val displayName = itemLabel ?: value
}
| Subtype | displayName |
description |
|---|---|---|
|
|
caller-supplied |
|
|
|
|
|
|
|
|
caller-supplied |
TuiRenderer.renderCompletions and Tui.completionSuggestions both operate on
List<Completion> โ the renderer accesses only displayName and description, making it
fully polymorphic over all three subtypes.
FileCompleter โ Directory Traversal
FileCompleter lists filesystem entries matching a partial path token, applying several layers
of filtering before returning results.
class FileCompleter(
private val root: String,
private val gitIgnoreFilter: GitIgnoreFilter = GitIgnoreFilter("$root/.gitignore"),
val maxResults: Int = 8
) {
fun complete(partial: String): List<FileCompletion>
}
Behaviour pipeline (applied in order):
-
Root guard โ if
rootdoes not exist or is not a directory, returnemptyList(). -
Sub-path resolution โ if
partialcontains/, split on the last/intodirPathandfilePrefix; resolveFile(root, dirPath)as the listing target. Otherwise listrootdirectly. -
Prefix filter โ include only entries whose
name.startsWith(filePrefix)(case-sensitive). -
Dotfile exclusion โ exclude any entry whose
name.startsWith("."). -
Gitignore filter โ call
gitIgnoreFilter.isIgnored(relativePath, isDirectory)and exclude matching entries. -
Sort โ directories first (alphabetically), then files (alphabetically).
-
Cap โ
.take(maxResults)(default 8).
Constructor injection for tests: In production, InputStateMachine creates
FileCompleter(System.getProperty("user.dir")) lazily via private val defaultFileCompleter by lazy { โฆ }. Tests inject a FileCompleter pointed at a @TempDir via InputStateMachine’s optional
`fileCompleter constructor parameter (which propagates from `Tui’s constructor for integration
tests).
GitIgnoreFilter โ Pattern Parser
GitIgnoreFilter parses a .gitignore file on first use (lazy) and exposes one method:
fun isIgnored(relativePath: String, isDirectory: Boolean): Boolean
Four pattern forms are supported:
| Pattern form | Example | Matches |
|---|---|---|
Single-segment wildcard |
|
Any path segment ending in |
Multi-segment wildcard |
|
Any path whose first segment is |
|
|
Exactly |
Directory-only suffix |
|
Any directory named |
Explicitly out of scope (silently ignored): character classes ([abc]), backslash escapes,
and negation patterns (!). Lines starting with # are treated as comments; blank lines are
skipped.
If the .gitignore file does not exist, isIgnored always returns false โ the filter is
transparent and never crashes on a missing file.
updateCompletions โ Dispatch Logic
InputStateMachine.updateCompletions() is called after every keystroke that modifies the input
buffer. It determines which completion branch fires:
buffer contains active @/# token?
YES โ FileCompleter.complete(partial) โ completionSuggestions (FileCompletion list)
NO โ buffer starts with "/" (no space)?
YES โ SlashCommandRouter.completions(โฆ) โ completionSuggestions (CommandCompletion list)
NO โ completionSuggestions = emptyList()
In all branches: completionIndex = 0
The file-token branch takes priority: a buffer like compare @src/F triggers file completion
even though it does not start with /.
Arrow Key Overlay Intercept
When completionSuggestions is non-empty (overlay is visible), ArrowUp/ArrowDown navigate
the selection index instead of scrolling the chat viewport:
ArrowDown โ if overlay open: completionIndex = (completionIndex + 1).coerceAtMost(lastIndex)
else: scroll viewport down 1 line
ArrowUp โ if overlay open: completionIndex = (completionIndex - 1).coerceAtLeast(0)
else: scroll viewport up 1 line
The index is clamped at both ends โ it never wraps around. Escape dismisses the overlay
(clears completionSuggestions and resets completionIndex) without clearing the input buffer;
this behaviour is unchanged from the pre-file-completion implementation.
UX note: This is a deliberate break from the previous behaviour where
ArrowDownalways scrolled the viewport even when a slash-command overlay was visible. Users who previously used arrow keys to scroll while a completion overlay was open must now pressEscapefirst.
Tab & Enter Polymorphic Dispatch
Both Tab and Enter (when the overlay is open) call the same private
applySelectedCompletion() function, which dispatches on the runtime type of the selected
Completion:
FileCompletion โ directory
trigger char preserved โ replace token with "@dir/" (or "#dir/") call updateCompletions() โ overlay refreshes with directory's children overlay stays open
Example: buffer compare @src, Tab on src/ โ buffer becomes compare @src/, overlay now
shows main/, test/, etc.
FileCompletion โ file
replace token with `relativePath` (backtick-wrapped) overlay dismissed (completionSuggestions = emptyList())
Example: buffer compare @src/F, Tab on Foo.kt โ buffer becomes compare `src/Foo.kt`.
The backtick wrapping signals to the agent that this is a file reference.
CommandCompletion
clear buffer append "/name " (trailing space included) overlay dismissed
This is the pre-existing slash-command completion behaviour, unchanged.
Enter guard
When the overlay is open, Enter calls applySelectedCompletion() instead of submitting
the message. The message is only submitted when completionSuggestions is empty.
Extension UI Adoption & Delegation Architecture
The Book extension system adopts TuiExtensionUI across approval delegates, script receivers, and headless fallback components.
Implementation Matrix
| Class | Location | Role |
|---|---|---|
|
|
Interactive TUI-mode implementation. Backs owned methods like |
|
|
Interactive TUI approval interface handling tool call permission dialogs. |
|
|
Top-level delegating proxy implementing |
|
|
Production no-op implementation of |
The Delegate Switch
ToolApprovalController.currentUI (typed as TuiExtensionUI) acts as the dynamic switch for extension UI routing:
-
In interactive TUI mode,
currentUIpoints toTuiApprovalExtensionUIorMordantExtensionUI. -
When de-activated or in headless/ACP mode,
currentUIswitches toHeadlessTuiExtensionUI.
Every call through DelegatingExtensionUI forwards directly through ToolApprovalController.currentUI.
Script Surface Integration
.bk.kts scripts receive ui and tui properties via BookScriptReceiver, typed directly as TuiExtensionUI. If ctx.ui is not an instance of TuiExtensionUI (e.g. in custom non-TUI contexts), BookScriptReceiver safely falls back to a no-op TuiExtensionUI implementation. This enables scripts to invoke status, widget, slot, and theme APIs cast-free and without checking runtime types.
Extension UI Registries and Layout Integration
TUI rendering incorporates extension contributions through two thread-safe registries owned by presentation components: StatusBarRegistry and UiSlotRegistry.
StatusBarRegistry
StatusBarRegistry manages extension items rendered inside the status bar row.
-
Storage:
ConcurrentHashMap<String, StatusItem>where keys are unique string IDs. -
Item types:
StatusItem.Text(String),StatusItem.Widget(MordantWidget), andStatusItem.Flow(StateFlow<MordantWidget>). -
Lifecycle:
put(id, item)adds or replaces an item;remove(id)deletes it;snapshot()returns an immutableMap<String, StatusItem>. -
Rendering:
StatusBarRendererfetches core status items first (agent state, duration, working indicator), then appends active extension status items in snapshot order.
UiSlotRegistry
UiSlotRegistry manages slot widget contributions interleaved into the grid layout by RenderFrameBuilder.
-
Slots: Defined by
UiSlot(HEADER,ABOVE_PROMPT,BELOW_PROMPT,FOOTER). -
Storage and Insertion Order: Maintains a
ConcurrentHashMapof entries for eachUiSlot, backed by a synchronized list preserving insertion order for widget keys. -
Content Types:
SlotContent.Builder(invoked with terminal width(width: Int) → Widget) andSlotContent.Flow(reads currentStateFlow<Widget>value). -
Lifecycle:
put(slot, id, content)inserts or updates content while preserving first-seen insertion position;remove(slot, id)deletes the content and removes the key from the order list;snapshot(slot)returns an orderedMap<String, SlotContent>.
Viewport Math and Frame Layout
RenderFrameBuilder.build queries UiSlotRegistry.snapshot for all four slots and calculates total slot height:
-
headerSlotWidgetsrender directly belowheaderRenderer. -
abovePromptSlotWidgetsrender directly below the viewport divider line and abovestatusBarRenderer. -
belowPromptSlotWidgetsrender directly belowpromptBoxRenderer. -
footerSlotWidgetsrender directly belowfooterRenderer.
Total slot line count is added to chromeLines:
chromeLines = 2 + 2 + 1 + (if (hasStatus) 1 else 0) + promptRows + slotLines viewportHeight = (terminalHeight - chromeLines).coerceAtLeast(1)
Adding slot widgets shrinks viewportHeight accordingly without breaking bottom prompt anchoring (CursorParams calculation remains stable).
Empty-Registry Parity Guarantee
If StatusBarRegistry and UiSlotRegistry contain no items, RenderFrameBuilder renders zero slot rows and StatusBarRenderer appends no extension items. The resulting rendered frame string is byte-identical to the layout output produced before the registries were introduced.
RendererRegistry & Message List Rendering
RendererRegistry manages runtime lookups for custom tool, entry, and message renderers, as well as the ordered markdown transformer chain.
-
Lookups:
ConcurrentHashMapstoresToolRenderer,EntryRenderer, andMessageRenderermapped by tool name or customType.CopyOnWriteArrayListstoresMarkdownTransformerinstances in registration order. -
Resolution & Fallback:
MessageListRendererconsultsRendererRegistryduring row rendering. If a custom renderer is registered for a tool name or customType, it is invoked viaresolveAndRender. If no custom renderer is registered, or if the custom renderer throws an exception (failure containment per ADR ยง9.1), the row falls back to built-in rendering. -
Markdown Transformer Chain: Pre-widget execution runs all registered
MarkdownTransformerinstances sequentially before building MordantMarkdownwidgets. A throwing transformer is safely skipped (keeping output so far), and transformations are display-only (persisted message payloads remain untouched). '''
Custom Views, Overlays & Focus Routing Internals
Spec 5 introduces interactive custom views, modal overlays, focus capture, and overlay compositing to the Book TUI.
1. InputStateMachine Branch Order & Focus Routing
When a keyboard event arrives at InputStateMachine, event dispatch follows a strict branch order:
KeyboardEvent arrives
โโโ 1. Overlay Focus Check: Is OverlayManager.active != null?
โ YES โ Route event to active view's events flow (bypass input buffer)
โ NO โ Continue
โโโ 2. Shortcut Interception (Spec 6 planning)
โโโ 3. Default Input Buffer Handling (char insertion, movement, editing, completion triggers)
If a custom view or overlay is active (OverlayManager.active != null), input events are intercepted at the very top of InputStateMachine and emitted into the view’s events flow. The input buffer remains untouched.
2. Input Buffer Snapshot & Restore
To guarantee non-negotiable buffer preservation (ADR ยง3):
-
Before opening an overlay or custom view,
InputStateMachinetakes aBufferSnapshotcapturing the exact buffer text and cursor index. -
While active, the user can type freely inside the custom view without affecting the background session prompt.
-
Upon close, the snapshot is restored byte-identical, putting back the exact text and cursor position the user had before opening the view.
3. Nested-Overlay Queueing (OverlayManager)
OverlayManager acts as the single focus-owner authority:
-
Exclusive Focus: Only one overlay or custom view holds focus at any given time.
-
Queueing: If
customVieworoverlayis invoked while another view is already active, the new request is placed into a nested overlay queue. -
Promotion: When the active view finishes or cancels (closing its session and releasing focus),
OverlayManagerautomatically promotes the next queued overlay in FIFO order.
4. Overlay Compositor & RenderLoop Integration
Once the base TUI frame is fully assembled by RenderFrameBuilder, the compositing pass executes:
-
OverlayCompositor: InspectsOverlayManager.active. If null, it returns the base frame unchanged (byte-identical parity guarantee). -
Anchored Panels: If an active overlay is present,
OverlayCompositorcalculates the screen coordinates based onOverlayOptions.anchor(CENTER,TOP_CENTER,BOTTOM_CENTER,LEFT_CENTER,RIGHT_CENTER) and dimensions (widthPercent,heightPercent), drawing the panel and optional title header over the frame region. -
Dirty Flagging: Calling
OverlayHandle.hide(),show(),focus(),unfocus(), orclose()automatically triggersrequestRender(), marking the render coordinator dirty for the next frame tick.