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 \n characters (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 width visible characters (except the last)

charWrap in TuiRenderer

2

countPromptRows uses the same character-wrap arithmetic as charWrap

CursorPosition.kt

3

renderPrompt uses Whitespace.PRE so Mordant never re-wraps

TuiRenderer.renderPrompt

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 @ or # in buffer

null

Trigger exists but a space follows it

null (token is resolved/closed)

@src/F at position 8

Pair(8, "src/F")

#README at position 4

Pair(4, "README")

Multiple triggers โ€” @resolved.kt #partial

Returns the rightmost trigger (#partial)

Trigger at end with nothing after โ€” open @

Pair(5, "") (empty partial, all files listed)

Empty buffer

null

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

CommandCompletion("help", โ€ฆ)

/help

caller-supplied

FileCompletion("src", โ€ฆ, isDirectory = true)

src/

๐Ÿ“ directory

FileCompletion("Foo.kt", โ€ฆ, isDirectory = false)

Foo.kt

๐Ÿ“„ file

ArgumentCompletion("opt1", "Option 1", "Desc")

Option 1

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

  1. Root guard โ€” if root does not exist or is not a directory, return emptyList().

  2. Sub-path resolution โ€” if partial contains /, split on the last / into dirPath and filePrefix; resolve File(root, dirPath) as the listing target. Otherwise list root directly.

  3. Prefix filter โ€” include only entries whose name.startsWith(filePrefix) (case-sensitive).

  4. Dotfile exclusion โ€” exclude any entry whose name.startsWith(".").

  5. Gitignore filter โ€” call gitIgnoreFilter.isIgnored(relativePath, isDirectory) and exclude matching entries.

  6. Sort โ€” directories first (alphabetically), then files (alphabetically).

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

*.class

Any path segment ending in .class at any depth

Multi-segment wildcard

build/**

Any path whose first segment is build

/-anchored literal

/build

Exactly build at the repository root

Directory-only suffix

node_modules/

Any directory named node_modules; ignores a file with the same name

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 ArrowDown always 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 press Escape first.


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

MordantExtensionUI

jvm/cli/…​/approval

Interactive TUI-mode implementation. Backs owned methods like theme (ShepherdTheme), in-memory status items, and editor text buffer.

TuiApprovalExtensionUI

jvm/cli/…​/approval

Interactive TUI approval interface handling tool call permission dialogs.

DelegatingExtensionUI

jvm/cli/…​/approval

Top-level delegating proxy implementing TuiExtensionUI that forwards every method to ToolApprovalController.currentUI.

HeadlessTuiExtensionUI

jvm/cli/…​/approval

Production no-op implementation of TuiExtensionUI used in headless CLI mode and ACP server mode.

The Delegate Switch

ToolApprovalController.currentUI (typed as TuiExtensionUI) acts as the dynamic switch for extension UI routing:

  • In interactive TUI mode, currentUI points to TuiApprovalExtensionUI or MordantExtensionUI.

  • When de-activated or in headless/ACP mode, currentUI switches to HeadlessTuiExtensionUI.

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), and StatusItem.Flow(StateFlow<MordantWidget>).

  • Lifecycle: put(id, item) adds or replaces an item; remove(id) deletes it; snapshot() returns an immutable Map<String, StatusItem>.

  • Rendering: StatusBarRenderer fetches 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 ConcurrentHashMap of entries for each UiSlot, backed by a synchronized list preserving insertion order for widget keys.

  • Content Types: SlotContent.Builder (invoked with terminal width (width: Int) → Widget) and SlotContent.Flow (reads current StateFlow<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 ordered Map<String, SlotContent>.

Viewport Math and Frame Layout

RenderFrameBuilder.build queries UiSlotRegistry.snapshot for all four slots and calculates total slot height:

  1. headerSlotWidgets render directly below headerRenderer.

  2. abovePromptSlotWidgets render directly below the viewport divider line and above statusBarRenderer.

  3. belowPromptSlotWidgets render directly below promptBoxRenderer.

  4. footerSlotWidgets render directly below footerRenderer.

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: ConcurrentHashMap stores ToolRenderer, EntryRenderer, and MessageRenderer mapped by tool name or customType. CopyOnWriteArrayList stores MarkdownTransformer instances in registration order.

  • Resolution & Fallback: MessageListRenderer consults RendererRegistry during row rendering. If a custom renderer is registered for a tool name or customType, it is invoked via resolveAndRender. 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 MarkdownTransformer instances sequentially before building Mordant Markdown widgets. 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, InputStateMachine takes a BufferSnapshot capturing 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 customView or overlay is 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), OverlayManager automatically 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: Inspects OverlayManager.active. If null, it returns the base frame unchanged (byte-identical parity guarantee).

  • Anchored Panels: If an active overlay is present, OverlayCompositor calculates the screen coordinates based on OverlayOptions.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(), or close() automatically triggers requestRender(), marking the render coordinator dirty for the next frame tick.