Live fat-prompt runtime.
This module owns the prompt/footer/editor/spinner side effects used while a turn is running. The turn controller calls these helpers directly and also registers them as API stream hooks. api.nim must not import this module.
Types
LiveMarkdownStream = object
- Incremental renderer for assistant content during provider streaming. It buffers input until markdown line/block boundaries, renders through the same MarkdownState used by replay, and keeps the token footer sliding below whatever rendered bytes are emitted.
Vars
activeCommandHook: proc (cmd: string) {....gcsafe.}
contentStreamedLive: bool = false
- Set by callModel when the assistant's text content has been streamed to stdout chunk-by-chunk during the SSE read; read (and reset) by runTurns so the same content isn't redrawn a second time at the end of the turn.
fatPromptState = initFatPromptState()
- Explicit state for the normal scrollback transcript's volatile footer. Rendering still happens in this module, but prompt/bar/ticker data now has one home instead of separate process-level globals.
followupStartsAfterReceipt: bool = false
inputEditor: ptr minline.LineEditor
inputMessages: ptr JsonNode
inputProfile: ptr Profile
inputSession: ptr Session
inputStateLock: Lock
inputThreadRunning = false
receiptTouchesNextResponse: bool = false
Procs
proc apiAfterCall() {....raises: [], tags: [], forbids: [].}
proc apiAfterLiveContent(baseLabel: string; slurped: int) {. ...raises: [IOError, ResourceExhaustedError, Exception], tags: [WriteIOEffect, TimeEffect, ReadEnvEffect, RootEffect], forbids: [].}
proc apiBeforeCall(lastPromptTokens, window: int): string {. ...raises: [IOError, ResourceExhaustedError, Exception], tags: [TimeEffect, ReadEnvEffect, WriteIOEffect, RootEffect], forbids: [].}
proc apiContentDelta(chunk, baseLabel: string; slurped: int): bool {. ...raises: [IOError, Exception, ResourceExhaustedError], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect, TimeEffect, RootEffect], forbids: [].}
proc apiContentFinished(fullContent, baseLabel: string; slurped: int): bool {. ...raises: [IOError, Exception, ResourceExhaustedError], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect, TimeEffect, RootEffect], forbids: [].}
proc apiFinalUsage(usage: Usage; window, elapsed: int; assistantContent: string; streamedLive: bool) {. ...raises: [IOError, Exception, IOError, IOError], tags: [ReadEnvEffect, WriteIOEffect, RootEffect, ReadIOEffect, TimeEffect, WriteDirEffect], forbids: [].}
proc apiNoUsage(elapsed: int) {....raises: [IOError, IOError, IOError, Exception], tags: [ ReadEnvEffect, ReadIOEffect, TimeEffect, WriteIOEffect, WriteDirEffect, RootEffect], forbids: [].}
proc apiProgress(baseLabel: string; slurped: int) {....raises: [], tags: [], forbids: [].}
proc apiProviderActivity() {....raises: [], tags: [TimeEffect], forbids: [].}
proc apiReasoningDelta(reasoning, baseLabel: string; slurped: int; contentStarted: bool) {....raises: [], tags: [ReadEnvEffect, TimeEffect], forbids: [].}
proc apiSetStatusLabel(label: string) {....raises: [], tags: [], forbids: [].}
proc apiTrimTrailingContent(fullContent, baseLabel: string; slurped: int) {. ...raises: [IOError, Exception], tags: [ReadEnvEffect, WriteIOEffect, RootEffect, TimeEffect], forbids: [].}
proc beginForegroundEditorRedraw(ed: var minline.LineEditor) {. ...raises: [IOError], tags: [ReadEnvEffect, WriteIOEffect], forbids: [].}
- Foreground readline must redraw through the same footer wrapper as the buffered editor whenever a token bar is visible; otherwise standalone editor redraws can leave a stale partial prompt above a later bar repaint.
proc beginTurn() {....raises: [ResourceExhaustedError, IOError], tags: [TimeEffect, WriteIOEffect], forbids: [].}
- Hide the physical terminal caret for the duration of the turn. The prompt glyph stays visible as the stable visual anchor.
proc clearBarPrompt() {....raises: [IOError, Exception], tags: [ReadEnvEffect, WriteIOEffect, RootEffect], forbids: [].}
- Erase the bar + prompt rows in place. Cursor parks at col 0 of the bar row so the caller can write content there (which then pushes the next repaintBarPrompt one row down).
proc commitTranscriptBytes(transcriptBytes: string; restoreEditor = true; beforeRepaint: proc () = nil; reserveFooter = true; transcriptOwnsSpacing = false) {. ...raises: [IOError, Exception, IOError, Exception], tags: [TimeEffect, WriteIOEffect, RootEffect, ReadEnvEffect], forbids: [].}
- Commit transcript output while preserving the volatile footer. The controller owns the transcript bytes and item spacing. This proc owns the terminal mechanics: clear the volatile footer, append the bytes as scrollback, then repaint whatever footer state remains. beforeRepaint runs after transcript bytes are known but before repaint bytes are computed, so a controller can convert a live bar into a receipt and clear it without fatprompt reintroducing stale chrome.
proc consumeQueuedCommand(line: var string; echoRows: var int): bool {. ...raises: [], tags: [], forbids: [].}
- Consume a colon command submitted while a turn was active. Commands are intentionally separate from autosend prompts so they never enter the model conversation by mistake.
proc consumeQueuedInput(line: var string; echoRows: var int; cmdWasQuit: var bool): bool {....raises: [], tags: [], forbids: [].}
-
Consume the next submitted editor line, regardless of whether it was entered while the controller was idle or while a turn was active.
Inherent-unpark: the idle input thread parks itself in getCh (returns
-1 -> EOFError) when `inputIdleSubmitted` is set. That park must bereleased by this controller thread. Rather than rely on every call site remembering releaseIdleSubmittedInput(), the release is folded into polling: if we found nothing to consume yet the flag is still set, the submitted line must already have been consumed on a prior pass (or was never real text) — clear the park so the input thread stops spinning in its EOFError busy-wait and resumes reading keystrokes. Missing this means a frozen prompt: both threads sleep-loop forever.
proc emitFatPromptEvent(ev: FatPromptEvent) {....raises: [], tags: [], forbids: [].}
- Single state transition entry point for the volatile footer model. Terminal bytes are still rendered by the helpers below, but all production state changes flow through this event reducer.
proc emitUserSubmit(line: string) {....raises: [IOError, Exception], tags: [ ReadEnvEffect, TimeEffect, WriteIOEffect, RootEffect], forbids: [].}
- Append the submitted prompt as transcript and clear the volatile editor area. The editor text itself is data; the on-screen prompt is chrome.
proc endTurn(repaintPrompt = true) {....raises: [IOError, Exception], tags: [ TimeEffect, WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
- Transition to typing-ready state: clear the bar at its current row, advance one row to leave a blank "gap" between the last content row and the bar, repaint bar+prompt, and show the terminal caret. The gap is one-shot — emitUserSubmit overwrites it with the receipt at next submit, so it never persists in scroll history.
proc endTurnAfterTranscriptAppend() {....raises: [IOError, Exception], tags: [ TimeEffect, WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
- Complete a turn after the controller has already appended the final assistant transcript item and repainted the live footer. Do not walk upward or repaint prompt chrome here; this proc only finalizes terminal mode/state so no transient prompt-only or duplicate-token frame appears.
proc ensureDraftFlusherStarted() {....raises: [ResourceExhaustedError], tags: [], forbids: [].}
- Start the background draft flusher once. Idempotent. Started alongside the persistent input thread so it is alive for the whole editing session.
proc ensureInputThreadStarted() {....raises: [ResourceExhaustedError], tags: [TimeEffect], forbids: [].}
proc enterPromptInput() {....raises: [IOError, Exception], tags: [WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
- Prepare the physical cursor for either immediate input or buffered input during a running turn. In bar mode, repaint the shared bar+prompt footer and park on the prompt row. In prompt-only mode, clear the prompt row in place. The line editor writes its own prompt glyph after this, so the prepainted glyph is only a stable visual placeholder.
proc feedContent(s: var LiveMarkdownStream; chunk: string; slurpedNow: int) {. ...raises: [IOError, Exception, ResourceExhaustedError], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect, TimeEffect, RootEffect], forbids: [].}
proc finishContent(s: var LiveMarkdownStream; slurpedNow: int) {. ...raises: [IOError, Exception, ResourceExhaustedError], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect, TimeEffect, RootEffect], forbids: [].}
proc finishForegroundEditorRedraw() {....raises: [IOError], tags: [ReadEnvEffect, WriteIOEffect], forbids: [].}
proc flushDraftNow() {....raises: [Exception], tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect], forbids: [].}
- Persist the current draft synchronously. Called from cleanup as the last reliable save before teardown. No-op when no session path exists yet; otherwise writes unconditionally — we are shutting down, so a redundant write is cheap insurance against losing the in-flight prompt.
proc hasQueuedAutosend(): bool {....raises: [], tags: [], forbids: [].}
- True once the background editor has accepted Enter and the text is waiting for the outer REPL to echo as transcript. At that point it must not be restored as live editor chrome after transcript appends.
proc initLiveMarkdownStream(baseLabel: string): LiveMarkdownStream {....raises: [], tags: [TimeEffect], forbids: [].}
proc installApiStreamHooks() {....raises: [], tags: [], forbids: [].}
proc liveLabel(base: string; slurped: int): string {....raises: [], tags: [], forbids: [].}
- Spinner label whose token slots match the per-call summary's shape: icon hugs value. ↑/↻ read as 0 until the final usage event closes the response; the spinner thread renders this in fgCyan + styleBright.
proc markProviderActivity() {....raises: [], tags: [TimeEffect], forbids: [].}
proc nextCommandSymbol(): string {....raises: [], tags: [], forbids: [].}
proc paintBarBelow(label: string) {....raises: [IOError, Exception], tags: [ ReadEnvEffect, WriteIOEffect, RootEffect], forbids: [].}
- Paint bar + prompt one and two rows below the cursor, restoring the cursor to its original (likely mid-line) position. Used during streaming to keep the bar visible while content is being accumulated in memory and the cursor stays put.
proc paintBarPrompt(label: string) {....raises: [IOError, Exception], tags: [ TimeEffect, WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
- Write bar + prompt at the cursor's current row, parking cursor at col 0 of the bar row. Caches label so a later repaintBarPrompt knows what to draw. Clears currentBarHasGap — during streaming the bar slides flush with content; only endTurn paints a gap.
proc paintInitialBar(p: Profile) {....raises: [IOError, Exception], tags: [ WriteIOEffect, TimeEffect, ReadEnvEffect, RootEffect], forbids: [].}
- Welcome-time paint: one blank gap row, then bar+prompt at zero values with a ○ 0% context indicator (the empty-circle glyph is the same one a populated bar carries — at startup we just haven't sent a request yet, so promptTokens is 0). Bright cyan prompt — typing-ready. Sets currentBarHasGap = true to match endTurn's shape between turns.
proc paintInitialPrompt(p: Profile) {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
- Welcome-time paint when starting fresh. The first prompt is intentionally prompt-only; the token bar appears after the first response has real usage to display.
proc paintPromptOnly() {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
proc releaseIdleSubmittedInput() {....raises: [], tags: [], forbids: [].}
- Let the persistent editor leave the submitted-line state after an idle controller path has consumed and committed the line. Model turns use beginTurn for the same acknowledgement.
proc repaintBarPrompt() {....raises: [IOError, Exception], tags: [ReadEnvEffect, WriteIOEffect, RootEffect], forbids: [].}
- Re-emit the bar+prompt at the cursor's current row using the cached currentBarLabel. Used by writeTranscriptWithFatPrompt to put the bar back after a content write.
proc resetPromptInputAfterEmpty(echoRows: int) {....raises: [IOError], tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}
- Empty submission should leave the prompt/footer at the same visual floor instead of drifting downward. echoRows is the editor's visual input height, including wraps.
proc restoreCancelTermios() {.noconv, ...gcsafe, raises: [], tags: [], forbids: [].}
proc restoreInputTermios() {.noconv, ...raises: [], tags: [], forbids: [].}
- Restore stdin's termios to the snapshot the input thread captured before putting it in raw mode. Safe to call from any thread and idempotent; a no-op when no snapshot exists.
proc setActiveCommandHook(hook: proc (cmd: string) {....gcsafe.}) {....raises: [], tags: [], forbids: [].}
proc setBarPromptState(label: string) {....raises: [], tags: [], forbids: [].}
- Update the logical bar label without painting immediately. Used when a completed response still needs to be committed to scrollback first; the subsequent transcript append repaints the footer with this final label.
proc setCommandStatusActive(active: bool) {....raises: [], tags: [], forbids: [].}
proc startBarTick(base: string) {....raises: [IOError, ResourceExhaustedError], tags: [TimeEffect, WriteIOEffect], forbids: [].}
proc startSpinner(label: string) {....raises: [IOError, ResourceExhaustedError, Exception], tags: [TimeEffect, WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
proc stopBarTick(): int {....raises: [IOError], tags: [TimeEffect, WriteIOEffect], forbids: [].}
- Stops the bar tick and returns elapsed seconds.
proc stopDraftFlusher() {....raises: [], tags: [], forbids: [].}
- Signal the flusher thread to stop (non-blocking; does not join). Safe to call from any thread, including the flusher thread itself, since it never waits on the thread. The loop checks the flag and exits within one sleep.
proc stopSpinner(clearLiveFooter = true) {....raises: [IOError, Exception], tags: [TimeEffect, WriteIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
proc stopTurnInputForFinalRender() {....raises: [], tags: [], forbids: [].}
- Mark the persistent input thread as idle before final assistant text is committed. The thread itself remains alive so idle and active prompt input keep the same editor path.
Templates
template captureStdoutWrites(body: untyped): string
- Run a transcript formatter against a temporary stdout target and return the produced bytes. writeTranscriptWithFatPrompt uses this to make formatter flushes invisible until the footer can be restored in the same render tick.
template currentBarHasGap(): untyped
- Whether there's a one-row blank "gap" between the bar and the row above it. Set by endTurn (typing-ready state — the gap sits between the last LLM line and the bar, breathing room while the user reads). Cleared by every paintBarPrompt / paintBarBelow (during streaming, the bar slides flush with content — no gap mid-turn). Read by emitUserSubmit so the receipt repaints the gap row in place — overwriting the blank, leaving the receipt flush below the LLM content with no permanent gap in scroll history.
template currentBarLabel(): untyped
- What's currently shown in the live bar. Updated by every paint (live during streaming, accurate after callModel parses usage, zero on first turn). Used by writeTranscriptWithFatPrompt to repaint the bar with the same label after a content write hides it.
template pendingHint(): untyped
-
Carries the latest iteration's accurate usage forward. Two roles:
- After each callModel iteration, used to repaint the token bar with accurate values (replacing the live rough ones).
- On user submit (next turn), the saved values become the token receipt — the dim repaint of the previous bar's row, leaving the receipt in scroll history while a fresh bar (at zeros) takes its place at the new bottom.
See ## Token UI in CLAUDE.md for the full lifecycle.
template writeTranscriptWithFatPrompt(body: untyped)
template writeTranscriptWithFatPromptRestore(restoreEditor: bool; body: untyped)
- Capture formatter writes and commit them through the fat-prompt terminal preservation primitive. This is compatibility glue for older call sites; controller-owned transcript paths should prefer commitTranscriptBytes.