Part VII · The Terminal UI Engine
Chapter 21
The Interactive REPL: Screens, Input, Keybindings, and Vim Mode
Layer: Layer 7 (The Terminal UI Engine)
Prerequisites: Chapter 01, Chapter 03, Chapter 07, Chapter 11, Chapter 20
Primary Source Files:
- replLauncher.tsx — lazy dynamic import boundary that mounts
<App>+<REPL>after setup dialogs finish- interactiveHelpers.tsx — sequential setup-screen runner (
showSetupScreens), workspace trust boundary, Ink-safe exit helpers, and frame-telemetry wiring- components/App.tsx — top-level provider stack (
FpsMetricsProvider→StatsProvider→AppStateProvider)- screens/REPL.tsx — the interactive orchestrator bridging
query(), streaming deltas, modal dialogs, permission queues, andPromptInput- utils/QueryGuard.ts — synchronous 3-state generation-numbered lifecycle guard exposed via
useSyncExternalStore- utils/handlePromptSubmit.ts — unified submission, mid-turn queueing, immediate
local-jsxdispatch, andprocessUserInput()driver- utils/messageQueueManager.ts & hooks/useQueueProcessor.ts — priority command queue (
now > next > later) and idle auto-drain loop- hooks/useMergedCommands.ts, hooks/useMergedTools.ts, & utils/toolPool.ts — live merging of built-in, plugin, and MCP capabilities with cache-safe tool partitioning
- components/Messages.tsx, components/VirtualMessageList.tsx, & hooks/useVirtualScroll.ts — memoized transcript pipeline, fullscreen height-cached virtualization, and main-screen UUID-anchored render cap
- components/PromptInput/PromptInput.tsx, inputModes.ts, & inputPaste.ts — prompt editor shell, paste/image pills, undo, stash, history, and queue pop-to-edit
- keybindings/schema.ts, defaultBindings.ts, resolver.ts, match.ts, KeybindingContext.tsx, KeybindingProviderSetup.tsx, useKeybinding.ts, loadUserBindings.ts, & reservedShortcuts.ts — context-aware chorded keybinding engine with hot-reload
- vim/types.ts, vim/motions.ts, vim/textObjects.ts, vim/operators.ts, vim/transitions.ts, hooks/useVimInput.ts, & components/VimTextInput.tsx — pure-functional Vim state machine bridged into the terminal prompt editor
Snapshot boundaries & compiled
.tsxoutput: Three type-only modules imported by this layer—types/message.ts,types/messageQueueTypes.ts, andkeybindings/types.ts—are absent from this source snapshot; their shapes are observed directly at call sites and in companion runtime schemas (keybindings/schema.ts, keybindings/validate.ts, utils/messageQueueManager.ts). Additionally,.tsxfiles in this checkout contain React Compiler memoization transforms (const $ = _c(N)) and inline base64 source maps; all descriptions and excerpts below refer strictly to the underlying application logic, never compiler-emitted cache arrays.
Why This Layer Exists
By the end of Chapter 20, we have a custom 60 FPS terminal React renderer (ink/) with Yoga flexbox layout, mouse hit-testing, synchronized output, and Kitty keyboard parsing. From Layers 0–6, we have a pull-based query() async generator (Chapter 07), a multi-mode permission engine (Chapter 11), dynamic MCP/plugin discovery (Chapters 15–16), and background tasks/swarms (Chapters 17–19).
Gluing an asynchronous, streaming agent engine to a reactive terminal UI is where clean abstractions collide with human timing:
- Startup trust vs. bundle weight. Before the workspace is trusted, the harness cannot apply repo environment variables, start OTel helpers, or pay the parse cost of the 5,000-line
REPL.tsxmodule graph—yet it still needs interactive dialogs rendered through the same Ink root. - React batching vs. synchronous concurrency. React
useStateupdates asynchronously;query(), permission prompts,Esccancellations, and rapid follow-up submits happen synchronously across microtask boundaries. One desynced loading boolean produces duplicate turns, stalefinallycleanups, or a 56-year elapsed timer. - Unbounded transcript growth vs. terminal memory. Mounting one React/Yoga subtree per message costs ~250 KB RSS each. Without virtualization (fullscreen) or a stable render-window cap (main screen), long sessions enter a GC death spiral.
- Overlapping keybindings, chords, and modal Vim editing. Eighteen UI contexts share
Escape,Enter,Tab, and arrow keys; multi-key chords likectrl+x ctrl+kmust stop their second key from landing in the text box; and Vim commands like2d3worci"must run faster than React re-renders without corrupting inline[Image #N]pills or wrapped terminal lines.
This chapter dissects the five subsystems that make the interactive REPL hold together under real terminal workloads.
1. Mounting the Workspace: Setup Screens, Lazy REPL Launch, and Live Capability Merging
The Problem
When main.tsx enters interactive mode, it allocates a single Ink Root, runs up to half a dozen sequential consent/onboarding screens (theme onboarding, workspace trust, .mcp.json server approval, external CLAUDE.md includes, custom API key approval, bypass-permissions/auto-mode consent, dev channels), and only then mounts the REPL. If any of those screens statically imported screens/REPL.tsx, users sitting at a first-run trust dialog would pay the entire REPL + prompt-input + markdown + tool-UI import cost upfront—and if a fatal error occurred after createRoot(), calling console.error() would vanish silently because Ink's patchConsole intercepts stdout/stderr.
Once <REPL> does mount, MCP servers and plugins finish connecting asynchronously in the background. The UI must merge newly discovered tools and slash commands into the active session without reordering built-in tools (which would invalidate the Anthropic prompt cache prefix established in Chapter 02 and Chapter 04).
The Real Implementation
Interactive bootstrapping is split cleanly across three small files: interactiveHelpers.tsx, replLauncher.tsx, and components/App.tsx.
First, getRenderContext(exitOnCtrlC) in interactiveHelpers.tsx:299-365 wires Ink's onFrame hook to three observers before createRoot() runs: FpsTracker, a process-wide StatsStore, an optional JSONL frame-timing benchmark sink gated by CLAUDE_CODE_FRAME_TIMING_LOG, and a flicker telemetry detector that skips DEC 2026 synchronized-output terminals (isSynchronizedOutputSupported()) and only logs tengu_flicker when two non-resize flickers land within 1,000 ms.
Second, showSetupScreens() (interactiveHelpers.tsx:104-298) drives every pre-REPL modal sequentially over that same Ink Root via showDialog() and showSetupDialog():
// interactiveHelpers.tsx:39-44, 86-92
export function showDialog<T = void>(
root: Root,
renderer: (done: (result: T) => void) => React.ReactNode,
): Promise<T> {
return new Promise<T>(resolve => {
const done = (result: T): void => void resolve(result)
root.render(renderer(done))
})
}
export function showSetupDialog<T = void>(
root: Root,
renderer: (done: (result: T) => void) => React.ReactNode,
options?: { onChangeAppState?: typeof onChangeAppState },
): Promise<T> {
return showDialog<T>(root, done => (
<AppStateProvider onChangeAppState={options?.onChangeAppState}>
<KeybindingSetup>{renderer(done)}</KeybindingSetup>
</AppStateProvider>
))
}
Wrapping each dialog in a temporary <AppStateProvider> + <KeybindingSetup> means confirmation keys (Enter, Esc, Up/Down) work identically before <App> exists. For fatal exits after createRoot(), exitWithError() / exitWithMessage() (interactiveHelpers.tsx:52-80) dynamically import <Text>, render the final line through Ink, call root.unmount(), await optional cleanup, and then process.exit(exitCode).
Only after showSetupScreens() resolves does main.tsx call launchRepl() in replLauncher.tsx:12-22:
// replLauncher.tsx:12-22
export async function launchRepl(
root: Root,
appProps: AppWrapperProps,
replProps: REPLProps,
renderAndRun: (root: Root, element: React.ReactNode) => Promise<void>,
): Promise<void> {
const { App } = await import('./components/App.js')
const { REPL } = await import('./screens/REPL.js')
await renderAndRun(
root,
<App {...appProps}>
<REPL {...replProps} />
</App>,
)
}
<App> (components/App.tsx:19-55) is a thin three-provider shell: FpsMetricsProvider → StatsProvider → AppStateProvider (wired to onChangeAppState). renderAndRun() (interactiveHelpers.tsx:98-103) calls root.render(element), triggers startDeferredPrefetches() in main.tsx, awaits root.waitUntilExit(), and runs gracefulShutdown(0).
Inside screens/REPL.tsx:811-835, live capability merging uses two specialized hooks:
- Commands (hooks/useMergedCommands.ts:5-15):
REPL.tsxchainsuseMergedCommandstwice—first merginglocalCommands+plugins.commands, then mergingmcp.commandson top withuniqBy([...initialCommands, ...mcpCommands], 'name'), short-circuiting to the original array reference when the dynamic list is empty. - Tools (hooks/useMergedTools.ts:20-44 + utils/toolPool.ts:55-79):
useMergedToolsruns insideuseMemo, delegating toassembleToolPool(toolPermissionContext, mcpTools)and thenmergeAndFilterTools(initialTools, assembled, toolPermissionContext.mode).mergeAndFilterTools()deduplicates byname, partitions MCP tools from built-in tools, sorts each partition alphabetically ([...builtIn.sort(byName), ...mcp.sort(byName)]) so built-ins remain a stable contiguous prompt-cache prefix, and—whenfeature('COORDINATOR_MODE')is enabled and coordinator mode is active—filters the pool throughapplyCoordinatorToolFilter(). Finally,REPL.tsx:814-829appliesresolveAgentTools()if--agent(mainThreadAgentDefinition) is set.
Hidden Invariants & Failure Modes
- Trust boundary ordering in
showSetupScreens()(interactiveHelpers.tsx:131-190): Workspace trust is enforced even inbypassPermissionsmode (skipped only underprocess.env.CLAUBBIT). OnceTrustDialogresolves (or fast-paths viacheckHasTrustDialogAccepted()), the runner executes a strict sequence:setSessionTrustAccepted(true)→resetGrowthBook()+initializeGrowthBook()(so GrowthBook picks up authenticated headers after trust/login) →getSystemContext()prefetch →handleMcpjsonServerApprovals()→ClaudeMdExternalIncludesDialog→updateGithubRepoPathMapping()(post-trust so untrusted repos cannot poison teleport mappings) →applyConfigEnvironmentVariables()(applies untrusted repo env vars only after consent) →setImmediate(() => initializeTelemetryAfterTrust()). Deferring OTel tosetImmediatekeeps its dynamic import out of the pre-render microtask queue. - Feature-gated setup screens:
AutoModeOptInDialogis gated behindfeature('TRANSCRIPT_CLASSIFIER')and only runs whenpermissionMode === 'auto'actually resolved (interactiveHelpers.tsx:224-235).DevChannelsDialogis gated behindfeature('KAIROS') || feature('KAIROS_CHANNELS')and awaitscheckGate_CACHED_OR_BLOCKING('tengu_harbor')first so a cold disk cache does not silently drop channel notifications (interactiveHelpers.tsx:241-288). - Turn-1 MCP race avoidance (screens/REPL.tsx:2746-2755): Even though
useMergedToolskeeps React state fresh,onQueryImplintentionally extractsfreshToolsandfreshMcpClientsfromgetToolUseContext(...)(which readsstore.getState()directly) rather than trusting the closure-capturedtoolsprop—ensuring MCP connections that flushed between render andonQueryappear on turn 1.
2. Bridging query() Into React: QueryGuard, Stream Dispatch, Queued Prompts, and Modal Arbitration
The Problem
A single interactive turn spans at least four asynchronous stages: (1) processUserInput() expanding slash commands, shell ! commands, images, and attachments; (2) onBeforeQuery hooks and system-prompt construction; (3) for await (const event of query(...)) streaming hundreds of SSE chunks and executing tools; and (4) finally cleanup + queue draining.
Originally, REPL.tsx tracked "is a turn running?" with two values: a React isLoading state (asynchronously batched) and an isQueryRunning ref (synchronous). Those two regularly drifted apart, opening four severe failure modes:
- A second submission arriving during
processUserInput()'sawaitstarted a concurrent turn instead of queueing. - Pressing
Esc(onCancel) and immediately submitting a new prompt let the cancelled turn's microtaskfinallyblock clear the new turn's loading state. - A spinner rendered in the gap between reserving a turn and resetting
loadingStartTimeRefcomputedDate.now() - 0 ≈ 56 years(INC-4549). - Nineteen competing overlays (permission prompts, sandbox network approvals, MCP elicitations, rewind selector, cost warnings, onboarding callouts) could fight over focus and steal keystrokes while the user was mid-sentence.
The Real Implementation
1. QueryGuard: Synchronous Generation-Numbered Turn Ownership
utils/QueryGuard.ts replaces the dual-state pattern with a 3-state machine (idle → dispatching → running → idle) subscribed to by React via useSyncExternalStore:
// utils/QueryGuard.ts:29-93 (abridged)
export class QueryGuard {
private _status: 'idle' | 'dispatching' | 'running' = 'idle'
private _generation = 0
private _changed = createSignal()
reserve(): boolean {
if (this._status !== 'idle') return false
this._status = 'dispatching'
this._notify()
return true
}
tryStart(): number | null {
if (this._status === 'running') return null
this._status = 'running'
++this._generation
this._notify()
return this._generation
}
end(generation: number): boolean {
if (this._generation !== generation) return false
if (this._status !== 'running') return false
this._status = 'idle'
this._notify()
return true
}
forceEnd(): void {
if (this._status === 'idle') return
this._status = 'idle'
++this._generation
this._notify()
}
}
In screens/REPL.tsx:900-916, REPL allocates one queryGuard ref and derives read-only isLoading = isQueryActive || isExternalLoading (where isExternalLoading covers remote CCR sessions and foregrounded background tasks that bypass onQuery).
2. Submission, Priority Queueing, and Idle Auto-Drain
Every prompt submission flows through onSubmit (screens/REPL.tsx:3170-3545) into handlePromptSubmit() (utils/handlePromptSubmit.ts:120-387):
- Immediate
local-jsxescape hatch (screens/REPL.tsx:3184-3281, utils/handlePromptSubmit.ts:229-311): Slash commands markedimmediate: true(e.g.,/config,/model,/btw) or invoked via a keybinding (fromKeybinding) execute whilequeryGuard.isActiveis true, mounting their UI viasetToolJSX({ isLocalJSXCommand: true, isImmediate: true })without queueing or clobbering the user's draft text. - Mid-turn queueing vs. interruptible tools (utils/handlePromptSubmit.ts:313-351): If
queryGuard.isActive || isExternalLoading,handlePromptSubmitfilters orphaned image entries, expands pasted text refs early (expandPastedTextRefs), and pushes aQueuedCommandonto the module-level priority queue in utils/messageQueueManager.ts:53-193 (PRIORITY_ORDER:'now' (0) > 'next' (1, user input) > 'later' (2, task notifications)). If every currently running tool declaresinterruptBehavior: 'cancel'(such asSleepTool),handlePromptSubmitalso callsabortController.abort('interrupt')so the queued prompt preempts the sleep immediately. - Reservation &
AsyncLocalStorageworkload scoping (utils/handlePromptSubmit.ts:396-610): When idle,executeUserInput()callsqueryGuard.reserve()synchronously before the firstawait, wraps the turn inrunWithWorkload(turnWorkload, ...)so detached subagents inherit the turn's workload tag viaAsyncLocalStorage, iteratescommandsthroughprocessUserInput()(only command0attaches IDE selection, attachments, andpastedContents), snapshotsfileHistory, and callsonQuery(). Itsfinallyblock callsqueryGuard.cancelReservation(), which is a no-op ifonQueryalready promoteddispatching → runningand later ranend(). - Reactive queue drain (hooks/useCommandQueue.ts + hooks/useQueueProcessor.ts): Both
useCommandQueueanduseQueueProcessorsubscribe to the module-level queue viauseSyncExternalStore(avoiding React context lag in Ink). Whenever!isQueryActive && !hasActiveLocalJsxUI && queueSnapshot.length > 0,useQueueProcessorcallsprocessQueueIfReady({ executeInput: executeQueuedInput }), whose synchronous chain immediately callsqueryGuard.reserve()before React re-runs the effect on the dequeue snapshot update.
3. Pumping query() Events Into React State
Inside onQuery (screens/REPL.tsx:2855-2960), queryGuard.tryStart() atomically claims the next thisGeneration (if a race still occurs and returns null, non-meta user messages are salvaged by re-enqueueing them onto the command queue instead of dropping them). It appends newMessages, reads messagesRef.current synchronously, and calls onQueryImpl() (screens/REPL.tsx:2661-2854), which builds systemPrompt/userContext/systemContext in parallel and drives the generator:
// screens/REPL.tsx:2793-2803
for await (const event of query({
messages: messagesIncludingNewMessages,
systemPrompt,
userContext,
systemContext,
canUseTool,
toolUseContext,
querySource: getQuerySourceForREPL(),
})) {
onQueryEvent(event)
}
Each yielded item goes to onQueryEvent → handleMessageFromStream() (utils/messages.ts:2930-3090), which fans out five distinct streams:
| Generator Event | Target State / Callback | Purpose |
|---|---|---|
stream_request_start |
setStreamMode('requesting') |
Spinner transitions to waiting-for-TTFT state |
message_start |
apiMetricsRef.current.push(...) |
Captures ttftMs and response-length baseline |
content_block_start (thinking/text/tool_use) |
setStreamMode(...), setStreamingToolUses(...) |
Updates spinner verb; registers live tool stub before full JSON arrives |
content_block_delta (text_delta/input_json_delta/thinking_delta) |
setResponseLength, onStreamingText, setStreamingToolUses |
Feeds live token counter, streaming markdown preview, and partial tool args (signature_delta explicitly excluded from length/OTPS!) |
message_stop |
setStreamMode('tool-use'), setStreamingToolUses([]) |
Clears transient tool stubs as execution begins |
tombstone |
setMessages(filter), removeTranscriptMessage(uuid) |
Deletes rolled-back/superseded messages from UI and JSONL |
Completed Message (assistant, user, progress, system, attachment) |
onStreamingText(() => null), setMessages(...) |
Atomically swaps streaming preview for final message |
Notice the streaming-text polish at screens/REPL.tsx:1461-1473: streamingText updates on every text_delta (coalesced by Ink's 16 ms render throttle), but visibleStreamingText slices to streamingText.lastIndexOf('\n') + 1 so Markdown streams line-by-line instead of jittering character-by-character, and disables itself entirely when prefersReducedMotion or hasCursorUpViewportYankBug() is true.
4. Permission Prompts and getFocusedInputDialog() Arbitration
Tool permissions (Chapter 11) enter REPL through useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) (screens/REPL.tsx:2382), which pushes a ToolUseConfirm onto toolUseConfirmQueue and returns a Promise that blocks runToolUse() until <PermissionRequest> calls onDone.
Because nineteen different interactive overlays can become ready at the same moment, getFocusedInputDialog() (screens/REPL.tsx:2017-2065) resolves focus with a single deterministic priority ladder:
- Exit flow (
isExiting || exitFlow) → returnsundefined(nothing steals exit). - High-priority explicit overlay:
isMessageSelectorVisible→'message-selector'(always wins). - Typing guard:
if (isPromptInputActive) return undefined— if the user is mid-keystroke inPromptInput, incoming permission modals are suppressed rather than eating the user's nextyorEnter!hasSuppressedDialogs(screens/REPL.tsx:2068) flagsPromptInputto show a dim"Waiting for permission…"banner until the prompt clears. - Blocking security & tool queues:
sandbox-permission→ (gated byallowDialogsWithAnimation = !toolJSX || toolJSX.shouldContinueAnimationso background tool hints never deadlock a permission prompt) →tool-permission→prompt→worker-sandbox-permission→elicitation. - Turn-end & advisory dialogs:
cost→idle-return→ultraplan-choice/ultraplan-launch(feature('ULTRAPLAN')) →ide-onboarding→ ant-only callouts (model-switch,undercover-callout, dead-code-eliminated in external builds via"external" === 'ant') →effort-callout→remote-callout→lsp-recommendation→plugin-hint→desktop-upsell.
Hidden Invariants & Failure Modes
INC-4549 (The 56-Year Elapsed Timer):
queryGuard.reserve()flipsisQueryActivetotruebeforeprocessUserInput()awaits, whereasonQuery()resetsloadingStartTimeRefafterprocessUserInput()finishes. During that window, the spinner readloadingStartTimeRef.current === 0and displayedDate.now() - 0 ≈ 56 years. screens/REPL.tsx:949-953 fixes this with an inline render-phase edge check (if (isQueryActive && !wasQueryActiveRef.current) resetTimingRefs()), andsetIsExternalLoadingperforms the same reset for remote sessions.
- Ephemeral progress coalescing prevents 120 MB transcripts (screens/REPL.tsx:2608-2627):
SleepToolandBashToolemit a progress tick every second. WhenisEphemeralToolProgress(newMessage.data.type)is true and the last message shares the sameparentToolUseIDand progress type,onQueryEventreplaces the last array element in place instead of appending. Appending previously grewmessagespast 13,000 entries and bloated JSONL logs to 120 MB; same-length replacement also keepsuseLogMessagesfrom writing redundant lines to disk. Conversely,agent_progress,hook_progress, andskill_progressare not ephemeral because the UI renders their full subagent/hook trail. - Cancel preserves partial text and bumps generation (screens/REPL.tsx:2106-2163):
onCancel()callsqueryGuard.forceEnd()(invalidating any pendingfinallyvia++_generation), commits any non-emptystreamingTextintomessagesbeforeresetLoadingState()clears it (ensuring transcript order[user, partial-assistant, [Request interrupted by user]]), aborts the active controller or permission queue, and clearsabortControllertonullso subsequentEscpresses don't see a stale aborted signal. - Synchronous
messagesRef&streamModeRefprevent latency spikes and heap leaks (screens/REPL.tsx:838-848, 2901-2906, 3538-3545): UpdatingmessagesRef.currentsynchronously inside thesetMessageswrapper letsonQuerypasslatestMessagesimmediately without awaiting React's scheduler (eliminating a 20–56 ms per-prompt stall). ReadingmessagesRef.currentandstreamModeRef.currentinsideonSubmitkeepsonSubmitreferentially stable across ~30setMessagesand ~10streamModeflips per turn—preventing downstream closures from pinning ~9–15 historical 1,776-byte REPL scopes and message arrays on the heap. - Config lock-storm guard (GH #3117) (screens/REPL.tsx:3840-3857): Counting prompt-queue usage via
saveGlobalConfiguses an edge-triggeredhasCountedQueueUseRef(firing only on0 → ≥1), because writing on every queue length mutation causedELOCKEDwrite storms and~/.claude.jsoncorruption across concurrent sessions.
3. Rendering Thousands of Messages Without a GC Death Spiral: Messages.tsx, VirtualMessageList, and PromptInput
The Problem
Once messages is in React state, rendering it at 60 FPS inside a terminal hits two scaling walls:
- Memory & O(n) scroll stalls: Every mounted
MessageRowallocates React fibers, memo caches, and Yoga nodes (~250 KB RSS per message). At ~2,000 messages, main-screen Ink held ~500 MB of fibers and 3,000-line screen buffers—triggering observed 59 GB RSS / 14kmmap/munmap/sec GC death spirals. Even in fullscreen virtual scroll, rebuilding grouping/collapse Maps on every scroll range change burned ~50 ms of allocations per scroll over 27k messages, causing 100–173 ms stop-the-world GC pauses. - Rich terminal editing in a single box:
PromptInputhas to handle multi-line text,!bash mode, 50 KB pastes, clipboard images, inline[Image #N]pills, undo history, prompt stashing, external$EDITOR, queued-command recall, and floating notifications—without causing Ink to repaint the whole terminal or unmounting stateful background hooks.
The Real Implementation
1. The Split Memo Pipeline in Messages.tsx
components/Messages.tsx:379-543 splits transcript preparation into two strictly separated useMemo stages so scrolling never recomputes O(n) message transforms:
- Transform stage (
collapsed_0,lookups_0):normalizeMessages(messages).filter(isNotEmptyMessage)splits multi-block API messages into one renderable row per block with deterministic derived UUIDs.syntheticStreamingToolUseMessagesconverts in-flightstreamingToolUsesinto synthetic rows whose UUID isderiveUUID(streamingToolUse.contentBlock.id, 0)—neverrandomUUID(), which would remount rows on everyinput_json_deltachunk and corrupt Ink's DOM (components/Messages.tsx:447-458).- Main-screen mode slices at the latest compact boundary (
getMessagesAfterCompactBoundary(..., { includeSnipped: true })); fullscreen keeps pre-compact scrollback (capped to one compact interval inonQueryEventat screens/REPL.tsx:2594-2600). - Drops
progressrows andisNullRenderingAttachment(msg)rows (hook_success, etc.) before counting or slicing (CC-724), reorders tool results next to their tool calls (reorderMessagesInUI), applies optionalBRIEFfiltering (feature('KAIROS') || feature('KAIROS_BRIEF')), and runs the grouping/collapsing chain:applyGrouping→collapseReadSearchGroups→collapseTeammateShutdowns→collapseHookSummaries→collapseBackgroundBashNotifications→buildMessageLookups.
- Cheap slice stage (
renderableMessages):- In fullscreen mode (
virtualScrollRuntimeGate = scrollRef != null && !CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),Messagesmounts<VirtualMessageList>(components/VirtualMessageList.tsx), powered byuseVirtualScroll()(hooks/useVirtualScroll.ts:19-130). Instead of mounting all items,useVirtualScrollmounts only viewport +OVERSCAN_ROWS = 80rows flanked by top/bottom Yoga spacer<Box>nodes. It caches measured Yoga heights per item key (invalidated whenevercolumnschanges), quantizesscrollToptoSCROLL_QUANTUM = 40rows foruseSyncExternalStoreso wheel ticks bypass React completely via Ink'sScrollBox.forceRender, caps newly mounted rows atSLIDE_STEP = 25per commit (preventing 290 ms synchronous Markdown-lexing stalls), and enforces a hard ceiling ofMAX_MOUNTED_ITEMS = 300. - In main-screen mode (no fullscreen
scrollRef),Messagescaps mounted rows viacomputeSliceStart()(components/Messages.tsx:307-340):
- In fullscreen mode (
// components/Messages.tsx:307-340
const MAX_MESSAGES_WITHOUT_VIRTUALIZATION = 200
const MESSAGE_CAP_STEP = 50
export function computeSliceStart(
collapsed: ReadonlyArray<{ uuid: string }>,
anchorRef: { current: SliceAnchor },
cap = MAX_MESSAGES_WITHOUT_VIRTUALIZATION,
step = MESSAGE_CAP_STEP,
): number {
const anchor = anchorRef.current
const anchorIdx = anchor
? collapsed.findIndex(m => m.uuid === anchor.uuid)
: -1
let start =
anchorIdx >= 0
? anchorIdx
: anchor
? Math.min(anchor.idx, Math.max(0, collapsed.length - cap))
: 0
if (collapsed.length - start > cap + step) {
start = collapsed.length - cap
}
const msgAtStart = collapsed[start]
if (msgAtStart && (anchor?.uuid !== msgAtStart.uuid || anchor.idx !== start)) {
anchorRef.current = { uuid: msgAtStart.uuid, idx: start }
} else if (!msgAtStart && anchor) {
anchorRef.current = null
}
return start
}
Why a { uuid, idx } anchor instead of collapsed.slice(-200)? Naive slice(-200) drops one row on every append, shifting scrollback and triggering a full terminal reset every turn (CC-941). Quantizing to 50-row steps (CC-1154) still jittered whenever compaction or regrouping changed collapsed.length. The UUID anchor advances only when rendered count exceeds cap + step (CC-1174), and the fallback idx heals cases where collapseHookSummaries + reorderMessagesInUI changes the first UUID in a merged group.
Each visible row renders through <MessageRow> (components/MessageRow.tsx) → <Message> (components/Message.tsx:58-180), which dispatches across ~30 specialized renderers in components/messages/ (AssistantTextMessage, AssistantToolUseMessage, AssistantThinkingMessage, UserTextMessage, UserToolResultMessage, CollapsedReadSearchContent, GroupedToolUseContent, AttachmentMessage, SystemTextMessage, CompactBoundaryMessage, etc.). Live streaming text renders as a sibling <StreamingMarkdown> directly below the list (components/Messages.tsx:703-712), so when the final assistant message arrives and streamingText clears in the same React batch, the transition is positionally seamless.
2. PromptInput: Pills, Pastes, Stash, and Queue Editing
components/PromptInput/PromptInput.tsx coordinates every input concern around a single inner editor (<VimTextInput> when isVimModeEnabled(), otherwise <TextInput>, at line 2243):
- Mode prefixing (components/PromptInput/inputModes.ts:4-33): Typing or pasting a leading
!into an empty prompt flipsmodeto'bash', strips!from the displayed value, and swaps the border tobashBorder; history serialization prepends!back viaprependModeCharacterToInput(). - Paste & image pill lifecycle (components/PromptInput/PromptInput.tsx:1151-1246, inputPaste.ts:4-90):
onTextPaste()strips ANSI codes, normalizes\rand tabs, and collapses any paste longer thanPASTE_THRESHOLD(800chars inutils/imagePaste.ts:30) or taller thanMath.min(rows - 10, 2)lines into a compact[Pasted text #N]ref backed bypastedContents[pasteId]—keeping Ink's input box from growing tall enough to force a full terminal repaint. Separately,maybeTruncateInput()ininputPaste.tstruncates huge programmatic inputs over10,000chars into[...Truncated text #N +M lines...].onImagePaste()caches the image path synchronously, persists the base64 payload to disk asynchronously, inserts[Image #N], and armspendingSpaceAfterPillRef.current = truesolazySpaceInputFilterauto-inserts a single space before the next printable character. A companionuseEffect(PromptInput.tsx:1189-1200) prunes anypastedContentsimage whose[Image #N]token was deleted from the text.
- Stash, external editor, undo, and queue recall (PromptInput.tsx:1257-1383):
ctrl+s(handleStash) snapshots{ text, cursorOffset, pastedContents }intostashedPrompt(and pops it back on empty input, or automatically after a submitted prompt/slash command completes—deferred pasthandlePromptSubmitwhen submitting a slash command or queueing mid-turn so the restored draft isn't clobbered, screens/REPL.tsx:3328-3357, 3521-3532).ctrl+g/ctrl+x ctrl+e(handleExternalEditor) expands collapsed paste refs, opens$EDITOR, and pushes the previous state onto the undo buffer (ctrl+_/ctrl+shift+-) before writing edits back.- Pressing Up when editable commands are waiting in the queue calls
popAllCommandsFromQueue(), restoring both queued prompt text and any attached images back into the active input box.
Hidden Invariants & Failure Modes
- React Compiler
memoCachepinning trap (components/Messages.tsx:695-698, components/MessageRow.tsx:45-48):Messagesintentionally precomputesisUserContinuationandhasContentAfteras booleans instead of passingrenderableMessagesto eachMessageRow. Because the React Compiler caches previous prop values inside each fiber'smemoCache, passing the array prop pinned every historical version ofrenderableMessages(~1–2 MB leaked over just 7 turns). LogoHeaderblit-cache protection (components/Messages.tsx:55, and source comment): BecauseLogoHeaderis the first sibling before allMessageRows in main-screen mode, letting it become dirty on every message append tripped Ink'sseenDirtyChildcascade (Chapter 20), disabling prev-screen blitting for all 2,800 subsequent rows and pegging CPU at 100%. Wrapping it inReact.memo+<OffscreenFreeze>keeps it permanently clean.- Custom
MessagesReact.memocomparator (components/Messages.tsx:741-778): Ignores stable refs/callbacks, comparesstreamingToolUsesbycontentBlockobject identity (soinput_json_deltachunks don't re-render the whole transcript), comparesinProgressToolUseIDsby set equality, and comparestoolsby tool names. Notificationsusesheight={0}, never unmount (components/PromptInput/PromptInput.tsx:2276-2295): In fullscreen mode, floating notifications sit in anabsolutezero-layout-height box above the prompt border. When slash autocomplete opens, the box collapses viaheight={0}instead of unmounting—because unmounting<Notifications>re-firedAutoUpdater's initial check effect on every slash-completion toggle (PR #22413).- Multiline arrow-key ownership (components/PromptInput/PromptInput.tsx:1656-1659, 2177-2182):
history:previousandhistory:nextare intentionally not bound viauseKeybindingsinPromptInput; they are passed asonHistoryUp/onHistoryDownprops toTextInput/VimTextInputsouseTextInputattempts intra-prompt cursor movement first and falls through to history only at the top/bottom boundary.
4. The Keybindings Subsystem: Stacked Contexts, Chords, and Terminal Quirks
The Problem
An interactive coding terminal layers up to 18 UI contexts (keybindings/schema.ts:12-32): Global, Chat, Autocomplete, Confirmation, Help, Transcript, HistorySearch, Task, ThemePicker, Settings, Tabs, Attachments, Footer, MessageSelector, DiffDialog, ModelPicker, Select, and Plugin (plus Scroll and feature-gated MessageActions in defaultBindings.ts).
The same physical key means completely different things depending on what is open:
Ctrl+Ttoggles todos inGlobal, but toggles syntax highlighting insideThemePicker.Escapecancels a running query inChat, dismisses autocomplete inAutocomplete, rejects a permission prompt inConfirmation, closes/helpinHelp, and exitsTranscript.- Multi-keystroke chords like
ctrl+x ctrl+k(kill background agents) orctrl+x ctrl+e(open$EDITOR) must swallow the first key (ctrl+x), wait up to 1 second, and intercept the second key (kore) beforePromptInputinserts a literal'k'into the prompt—and if the user aborts mid-chord withctrl+x ctrl+c, that second key must cancel the chord without triggeringapp:interrupt.
The Real Implementation
1. Declarative Bindings, Platform Defaults, and Pure Chord Resolution
keybindings/defaultBindings.ts defines DEFAULT_BINDINGS as an ordered array of { context, bindings } blocks. Platform quirks are resolved at module load:
IMAGE_PASTE_KEY:'alt+v'on Windows (ctrl+vis system paste),'ctrl+v'elsewhere.MODE_CYCLE_KEY:'shift+tab'when the terminal supports VT mode (getPlatform() !== 'windows', or Bun>=1.2.23/ Node>=22.17.0 <23 || >=24.2.0), otherwise'meta+m'.chat:undobinds both'ctrl+_'(legacy terminals sending0x1f) and'ctrl+shift+-'(Kitty protocol sending physical key + modifiers).- Feature-gated defaults (
feature('QUICK_SEARCH'),feature('TERMINAL_PANEL'),feature('MESSAGE_ACTIONS'),feature('VOICE_MODE'),feature('KAIROS')) spread conditionally intoDEFAULT_BINDINGSso dead code elimination strips them cleanly.
keybindings/parser.ts normalizes modifier aliases (opt/option → alt, cmd/command/win → super) and splits space-separated chords (preserving a lone ' ' as the Space key!). keybindings/match.ts maps Ink's Key flags to canonical names and collapses alt and meta into one logical modifier (because legacy terminals cannot distinguish them) while keeping super (cmd/win) distinct for Kitty-protocol terminals.
The heart of the resolver is the pure function resolveKeyWithChordState() in keybindings/resolver.ts:166-244:
// keybindings/resolver.ts:192-236
const ctxSet = new Set(activeContexts)
const contextBindings = bindings.filter(b => ctxSet.has(b.context))
// Check if this could be a prefix for longer chords. Group by chord
// string so a later null-override shadows the default it unbinds —
// otherwise null-unbinding `ctrl+x ctrl+k` still makes `ctrl+x` enter
// chord-wait and the single-key binding on the prefix never fires.
const chordWinners = new Map<string, string | null>()
for (const binding of contextBindings) {
if (
binding.chord.length > testChord.length &&
chordPrefixMatches(testChord, binding)
) {
chordWinners.set(chordToString(binding.chord), binding.action)
}
}
let hasLongerChords = false
for (const action of chordWinners.values()) {
if (action !== null) {
hasLongerChords = true
break
}
}
if (hasLongerChords) {
return { type: 'chord_started', pending: testChord }
}
let exactMatch: ParsedBinding | undefined
for (const binding of contextBindings) {
if (chordExactlyMatches(testChord, binding)) {
exactMatch = binding
}
}
if (exactMatch) {
return exactMatch.action === null
? { type: 'unbound' }
: { type: 'match', action: exactMatch.action }
}
2. Two-Phase Dispatch: ChordInterceptor + useKeybinding / useKeybindings
keybindings/KeybindingProviderSetup.tsx:119-307 mounts <KeybindingProvider> and immediately renders <ChordInterceptor> as its first child before {children}:
// keybindings/KeybindingProviderSetup.tsx:205-208 (logical structure)
<KeybindingProvider bindings={bindings} pendingChordRef={pendingChordRef} ...>
<ChordInterceptor ... />
{children}
</KeybindingProvider>
Because Ink dispatches useInput listeners in mount order, ChordInterceptor sees every keystroke first:
- Synchronous ref + React state duality:
pendingChordRefandactiveContextsRef(aSetmutated synchronously inuseLayoutEffectbyuseRegisterKeybindingContext(), KeybindingContext.tsx:215-242) letresolve()observe rapid consecutive chord keystrokes and newly mounted modals without waiting for a React render flush.setPendingChord()updates both the ref and React state and resets aCHORD_TIMEOUT_MS = 1000cancellation timer. - Fast wheel skip:
if ((key.wheelUp || key.wheelDown) && pendingChordRef.current === null) returnavoids scanninghandlerRegistryRefon every mouse-wheel event, while still letting a wheel tick mid-chord cancel the pending chord. - Why
ChordInterceptoronly invokes handlers on chord completion (wasInChord === true): Onchord_started,chord_cancelled,unbound, or a completed multi-key chord (matchwithwasInChord === true),ChordInterceptorcallsevent.stopImmediatePropagation()(invoking the matching registered handler fromhandlerRegistryRefon chord completion). On a single-keystrokematch, it intentionally does not invoke handlers or stop propagation—it clearspendingChordand lets the event flow down to per-componentuseKeybinding()/useKeybindings()hooks (keybindings/useKeybinding.ts:33-196) so component mount order and ordering-sensitive handlers likeuseTypeahead(Enter accepting autocomplete before submit) remain intact. - Fall-through convention: In
useKeybinding/useKeybindings, if a handler returns literalfalse,event.stopImmediatePropagation()is not called—allowing fall-through (for instance,ScrollKeybindingHandlerreturnsfalseonscroll:lineUp/lineDownwhen theScrollBoxcontent already fits, letting a child list handle the wheel event instead).
3. User Customization, Validation, and Hot-Reload
keybindings/loadUserBindings.ts loads ~/.claude/keybindings.json synchronously on mount (loadKeybindingsSyncWithWarnings) and watches it with chokidar (awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 200 }, atomic: true) for live hot-reload. User customization is currently runtime-gated behind GrowthBook tengu_keybinding_customization_release (isKeybindingCustomizationEnabled() at lines 41-46); external users without that flag get DEFAULT_BINDINGS only.
User blocks are appended after defaults ([...defaultBindings, ...userParsed]) and validated by keybindings/validate.ts and keybindings/reservedShortcuts.ts:
checkDuplicateKeysInJson(rawJson)scans the raw JSON text with regex before relying onJSON.parse, becauseJSON.parsesilently overwrites earlier duplicate keys inside the same block.- Reserved shortcut checks flag
NON_REBINDABLE(ctrl+c,ctrl+d, andctrl+m—which sends identical CR bytes to Enter in terminals),TERMINAL_RESERVED(ctrl+zSIGTSTP,ctrl+\SIGQUIT—explicitly omittingctrl+s/ctrl+qbecausectrl+sis prompt stash), andMACOS_RESERVED(cmd+c/v/x/q/w/tab/space).normalizeKeyForComparison()splits chords on whitespace before splitting steps on+so multi-key chords aren't mangled. - Validation issues surface via a 60-second notification pointing to
/doctor(KeybindingProviderSetup.tsx:59-112).
Hidden Invariants & Failure Modes
How context precedence actually works: Although comments in
useKeybinding.ts:59suggest deduplicatedactiveContextsorder determines priority, keybindings/resolver.ts:193-229 convertsactiveContextsinto an unorderedSet(ctxSet) and scansbindingslinearly, keeping the last matching entry. Context precedence therefore comes from the array order inDEFAULT_BINDINGS(Globalat index 0, specific overlays likeConfirmation,ThemePicker, andHelplater) plus user overrides appended at the end.
- Ink's Escape-sets-Meta quirk (keybindings/match.ts:96-102, resolver.ts:86-89): Legacy VT escape parsing causes Ink to set
key.meta = truewhenever bare Escape is pressed. BothmatchesKeystrokeandbuildKeystrokeexplicitly forcemeta = falsewhenkey.escapeis true—otherwise"escape"bindings and chord cancellations would never match. - Direct
chat:submitregistration bypass (components/PromptInput/PromptInput.tsx:1637-1653):PromptInputregisterschat:submitdirectly viakeybindingContext.registerHandler(...)instead ofuseKeybindings. That letsChordInterceptorinvoke submit if a user binds a custom chord (e.g.,ctrl+e s), while preventinguseKeybindingsfrom callingstopImmediatePropagation()on bareEnterbeforeuseTypeaheadaccepts autocomplete. - The
voice:pushToTalknull-unbind trap (keybindings/defaultBindings.ts:91-96): Underfeature('VOICE_MODE'),spaceis registered asvoice:pushToTalkso help displays can find it. If a user tries to disable it by setting"space": nullinkeybindings.json,resolveKeyWithChordStatereturns{ type: 'unbound' }andChordInterceptor/useKeybindingcallsevent.stopImmediatePropagation()—making the spacebar completely dead for typing! - Handler mount-order contract in
REPL.tsx(screens/REPL.tsx:4550-4563): Inside<KeybindingSetup>,<ScrollKeybindingHandler>is deliberately mounted before<CancelRequestHandler>soCtrl+Cwith an active terminal text selection copies the selection and stops propagation, whereasCtrl+Cwithout a selection falls through to cancel the running query.
5. Pure-Functional Vim Mode Inside the Prompt Editor
The Problem
When a user enables Vim mode, PromptInput swaps <TextInput> for <VimTextInput> (components/PromptInput/PromptInput.tsx:2243). Implementing Vim inside a React terminal input is deceptively hard:
- Multi-keystroke commands outrun React renders. Typing
2d3worci"delivers 3–4 keypress events faster than React commits state; if intermediate operator/count states lived inuseState, fast bursts would read stale closures. - Wrapped rows vs. logical lines. A long prompt wraps across multiple terminal columns.
j/kandddoperate on logical\n-delimited lines, whereasgj/gkmove across visual wrapped rows (and per:help gj,dgjis characterwise exclusive, not linewise!). - Grapheme clusters and inline pills. Emoji and combining sequences span multiple UTF-16 code units, and
[Image #1]is an atomic UI pill embedded inside plain text. Naiveoffset + 1splits surrogate pairs, anddwlanding inside[Image #1]would leave broken[Imagedebris.
The Real Implementation
The Vim engine separates a pure, React-free TypeScript state machine under vim/ from a thin React hook adapter in hooks/useVimInput.ts.
1. Discriminated State Machine (vim/types.ts + vim/transitions.ts)
vim/types.ts:49-120 encodes every legal mode and partial-command state as discriminated unions:
VimState: either{ mode: 'INSERT'; insertedText: string }(accumulating typed text for.repeat) or{ mode: 'NORMAL'; command: CommandState }.CommandState: 11 exhaustive variants—idle,count,operator,operatorCount,operatorFind,operatorTextObj,find,g,operatorG,replace, andindent.PersistentState: survives across commands (lastChange: RecordedChange | null,lastFind,register,registerIsLinewise).MAX_VIM_COUNT = 10000: clamps numeric prefixes (999999999xcannot hang the event loop).
vim/transitions.ts:59-460 is a pure transition table dispatching on state.type and returning { next?: CommandState; execute?: () => void }:
// vim/transitions.ts:283-332 (operator + multiplicative operatorCount)
function fromOperator(
state: { type: 'operator'; op: Operator; count: number },
input: string,
ctx: TransitionContext,
): TransitionResult {
// dd, cc, yy = line operation
if (input === state.op[0]) {
return { execute: () => executeLineOp(state.op, state.count, ctx) }
}
if (/[0-9]/.test(input)) {
return {
next: { type: 'operatorCount', op: state.op, count: state.count, digits: input },
}
}
return handleOperatorInput(state.op, state.count, input, ctx) ?? { next: { type: 'idle' } }
}
function fromOperatorCount(
state: { type: 'operatorCount'; op: Operator; count: number; digits: string },
input: string,
ctx: TransitionContext,
): TransitionResult {
if (/[0-9]/.test(input)) {
const parsedDigits = Math.min(parseInt(state.digits + input, 10), MAX_VIM_COUNT)
return { next: { ...state, digits: String(parsedDigits) } }
}
const effectiveCount = state.count * parseInt(state.digits, 10)
return handleOperatorInput(state.op, effectiveCount, input, ctx) ?? { next: { type: 'idle' } }
}
Thus 2d3w walks idle → count("2") → operator('delete', 2) → operatorCount('delete', 2, "3") → executes executeOperatorMotion('delete', 'w', 6, ctx). Notice also how 0 is start-of-logical-line in fromIdle (transitions.ts:253-257) but appends as a digit inside fromCount and fromOperatorCount.
2. Motions, Text Objects, and Operators (vim/motions.ts, textObjects.ts, operators.ts)
- Motions (vim/motions.ts:13-82):
resolveMotion(key, cursor, count)iterates up tocountsteps over immutableCursormethods (nextVimWord,downLogicalLine,downforgj, etc.) and breaks early as soon asnext.equals(result)(no wasted work at buffer boundaries).isInclusiveMotionmarkse,E,$;isLinewiseMotionmarksj,k,G,gg(explicitly excludinggj/gk). - Text objects (vim/textObjects.ts:38-186):
findTextObject()supportsw/W(pre-segmenting the buffer viaIntl.SegmenterfromgetGraphemeSegmenter()so emoji and accented characters never split), line-scoped quote objects (",',`) paired strictly0-1, 2-3, ..., and nested depth-counting bracket objects ((),[],{},<>,b,B) spanning multiple lines. - Operators (vim/operators.ts:42-556):
getOperatorRange()handles three subtle Vim/harness rules in one place:cw/cWchanges to the end of the word (matching Vim's classicceexception) instead of deleting trailing whitespace up to the next word.- Linewise motions (
dj,dk,dG,dgg, andddinexecuteLineOp) expand to full\n-bounded lines, absorbing the preceding newline when deleting the last line so no stray blank line remains, and normalize the yanked register to end with\nfor linewisep/P. - Image-pill protection (vim/operators.ts:469-473):
// vim/operators.ts:469-473 // Word motions can land inside an [Image #N] chip; extend the range to // cover the whole chip so dw/cw/yw never leave a partial placeholder. from = cursor.snapOutOfImageRef(from, 'start') to = cursor.snapOutOfImageRef(to, 'end')
3. Bridging Into React (hooks/useVimInput.ts + components/VimTextInput.tsx)
hooks/useVimInput.ts:34-316 wraps useTextInput and intercepts its onInput handler:
- Ref-backed machine, state-backed badge:
vimStateRefandpersistentRefmutate synchronously on every keypress; onlymode('INSERT' | 'NORMAL') triggers ReactsetModeso the footer badge updates without re-rendering ond→i→". - Dot-repeat without recursion: Exiting INSERT mode snapshots
insertedTextintopersistentRef.current.lastChange = { type: 'insert', text }(grapheme-safe on Backspace vialastGrapheme). Pressing.callsreplayLastChange(), which constructs anOperatorContextwithisReplay = truesorecordChangebecomes a no-op and replaying never overwriteslastChange. - Shared rendering:
<VimTextInput>(components/VimTextInput.tsx:13-136) passes the returnedvimInputStatestraight into<BaseTextInput>alongsideuseTerminalFocus()(inverting the cursor cell only when the terminal window is focused) anduseClipboardImageHint().
Hidden Invariants & Failure Modes
- Why
inputFilteris stripped fromuseTextInputand invoked manually (hooks/useVimInput.ts:42-46, 177-181):useVimInputpassesinputFilter: undefinedtouseTextInputand runsinputFilter(rawInput, key)itself at the top ofhandleVimInputin both modes—but only feeds the filtered string forward inINSERTmode (const input = state.mode === 'INSERT' ? filtered : rawInput). Otherwise, pasting an image pill (which armslazySpaceInputFilter), hittingEscto enter NORMAL mode, and returning to INSERT mode would leave the filter stale and prepend a surprise space—whereas applying the filtered string in NORMAL mode would turn'w'into' w'and break command dispatch. - Escape intentionally bypasses
keybindings/(hooks/useVimInput.ts:189-201):Escin INSERT always callsswitchToNormalMode()(stepping the cursor left by 1 unless at offset 0 or after\n), andEscin NORMAL resetscommandto{ type: 'idle' }. Leaving it out ofkeybindings.jsonguarantees a user config can never trap them in INSERT mode. - Guarding Backspace/Delete in literal-character states (hooks/useVimInput.ts:251-271, vim/transitions.ts:438-448): Backspace maps to
hand Delete maps toxonly whenexpectsMotionis true (idle,count,operator,operatorCount—with Delete also excluded fromcountso5<Del>doesn't become a destructive5x). Inreplace,find, andoperatorFind, mapping them would turnr<BS>into "replace withh" anddf<Del>into "delete tox". MeanwhilefromReplaceexplicitly checksif (input === '') return { next: { type: 'idle' } }sor<BS>cancels cleanly instead of deleting the character under the cursor. - Logical vs. wrapped line asymmetry in
vim/operators.ts: Notice an instructive detail in the snapshot:executeLineOp(vim/operators.ts:109-111) carefully counts\nviacountCharInStringbecausecursor.getPosition()returns the wrapped visual row, whereasexecuteJoin(line 261),executePaste(line 308),executeIndent(line 355), andexecuteOpenLine(line 403) still indextext.split('\n')usingcursor.getPosition().line—a real subtle boundary where long wrapped prompts behave differently across operators.
Putting the Layer Together
Here is how a keystroke travels from Ink's input pipeline through keybinding interception, Vim/prompt editing, QueryGuard + queue orchestration, query(), and back into bounded terminal frames:
flowchart TD
MAIN["main.tsx (createRoot + showSetupScreens)"] --> LAUNCH["replLauncher.tsx (lazy import App + REPL)"]
LAUNCH --> APP["components/App.tsx (FPS + Stats + AppState)"]
APP --> REPL["screens/REPL.tsx"]
REPL --> KB["KeybindingSetup (KeybindingProvider + ChordInterceptor)"]
KB -->|"1st: chord / unbound / stopImmediatePropagation"| HANDLERS["Global / Scroll / CancelRequest / useKeybindings"]
KB -->|"2nd: fall-through"| PI["PromptInput (pills, paste, stash, undo, history)"]
PI -->|"vim enabled"| VIM["VimTextInput -> useVimInput -> vim/ transitions"]
PI -->|"standard"| TI["TextInput -> useTextInput"]
PI -->|"onSubmit"| HPS["handlePromptSubmit.ts"]
HPS -->|"queryGuard.isActive"| Q["messageQueueManager (now > next > later)"]
Q -->|"idle auto-drain (useQueueProcessor)"| HPS
HPS -->|"queryGuard.reserve() -> processUserInput()"| ONQ["REPL.onQuery (queryGuard.tryStart)"]
ONQ -->|"for await"| QGEN["query() AsyncGenerator (Chapter 07)"]
QGEN -->|"StreamEvent / Message / Tombstone"| HMS["handleMessageFromStream()"]
HMS --> STATE["messages + streamingText + streamingToolUses + streamMode"]
QGEN -->|"canUseTool"| PERM["toolUseConfirmQueue -> getFocusedInputDialog()"]
STATE --> MSG["Messages.tsx (split memo pipeline)"]
MSG -->|"fullscreen"| VML["VirtualMessageList + useVirtualScroll (quantized 40-row bins)"]
MSG -->|"main screen"| CAP["computeSliceStart (200+50 UUID SliceAnchor)"]
PERM -->|"suppressed if isPromptInputActive"| OVERLAY["PermissionRequest / FullscreenLayout overlay"]
And underneath that loop sit two load-bearing state/dispatch invariants that keep concurrent input from tearing:
1. QueryGuard lifecycle (utils/QueryGuard.ts - sync + useSyncExternalStore)
+------+ reserve() +-------------+ tryStart() [++gen] +---------+
| idle | -------------> | dispatching | -------------------> | running |
+--+---+ <------------- +-------------+ +----+----+
| cancelReservation() |
| |
| tryStart() [++gen] (direct submit) |
+--------------------------------------------------------------+
^ |
+---------- end(gen) [if gen matches] / forceEnd() [++gen] ----+
2. Two-phase Keybinding dispatch (KeybindingProviderSetup + useKeybinding)
Ink useInput
+-> [1] ChordInterceptor (mounted FIRST inside KeybindingProvider)
| +- chord_started / chord_cancelled / unbound -> stopProp
| +- match (wasInChord=true) -> invoke registry + stopProp
| +- match (wasInChord=false) -> clear pending, FALL THROUGH
+-> [2] ScrollKeybindingHandler (mounted before CancelRequestHandler)
| +- Ctrl+C w/ selection copies + stops; no-op wheel -> false
+-> [3] CancelRequestHandler / per-context useKeybindings
+-> [4] PromptInput -> VimTextInput (Esc hardcoded) / TextInput
How This Snaps Into the Next Layer
With Chapter 21 complete, we have rebuilt the entire agent harness from Layer 0 atoms (Chapter 01) all the way to the interactive terminal workspace. Look at how the top of this chapter connects directly into main.tsx:
- main.tsx:2218-2242 calls
getRenderContext(false)from interactiveHelpers.tsx, dynamically importscreateRootfrom ink.ts, logs thestartuptimer before any blocking dialog renders (so p99 startup metrics aren't skewed by users sitting on trust dialogs), and awaitsshowSetupScreens(...). - After resolving sessions,
--resumepickers, bridge checks, and initial hook messages, main.tsx:3798-3806 handsroot,{ getFpsMetrics, stats, initialState },sessionConfig, andrenderAndRunstraight tolaunchRepl()in replLauncher.tsx.
In Chapter 22, we step into Layer 8 and trace the cold-start funnel from the very first byte executed in entrypoints/cli.tsx, through entrypoints/init.ts (TLS/CA setup, preconnects, safe env vars), into setup.ts and main.tsx—seeing how Claude Code decides in milliseconds whether to branch into a zero-import fast path, headless -p / SDK mode, or the full interactive REPL we just dissected.
Reading Exercises & Code Checkpoints
- Trace the context-precedence mechanics. Open keybindings/resolver.ts:187-236 alongside keybindings/defaultBindings.ts:32-194. Suppose
ThemePickermounts and callsuseRegisterKeybindingContext('ThemePicker'), and the user pressesCtrl+T. Trace whytheme:toggleSyntaxHighlightingwins overGlobal'sapp:toggleTodos—and predict what would happen if a user'skeybindings.jsonput aGlobaloverride forctrl+tafter aThemePickerblock. - Audit every
QueryGuardtransition site. Run:Verify howrg -n "queryGuard\.(reserve|cancelReservation|tryStart|end|forceEnd|isActive)" screens/ utils/ hooks/executeUserInput()'stry/finallycooperates withonQuery()'stry/finallyandonCancel()'sforceEnd()when a user hitsEscduringprocessUserInput()vs. mid-stream insidequery(). - Inspect all
Messages.tsxmemory and scrollback defenses. Read components/Messages.tsx:278-340 and hooks/useVirtualScroll.ts:13-58. Why isDEFAULT_ESTIMATE = 3intentionally biased low whilePESSIMISTIC_HEIGHT = 1is used for viewport coverage, and what specific bug doesSLIDE_STEP = 25prevent during rapid scrolling? - Trace a compound Vim edit across
useVimInputandvim/. Walk the exact state sequence of typing2d3wfollowed by.(dot-repeat) and thenr<Backspace>starting fromuseVimInput.ts:175throughvim/transitions.tsandvim/operators.ts. Where is the[Image #N]boundary protected during2d3w, and why doesn'tr<Backspace>delete the character under the cursor?
Manuscript chapters/21-the-interactive-repl-screens-keybindings-and-vim.md from AtlantisPleb/cc at 5aa286a, synced Nov 24, 2026.