Skip to main content

nmbrs_tui/
repl_state.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! REPL visibility state machine.
5//!
6//! The interactive REPL — the command prompt at the bottom of
7//! the terminal that accepts `set`, `controls`, `metrics …`,
8//! and other inspector commands — has three visibility states:
9//!
10//! - **Hidden** (default): no prompt rendered, no input
11//!   accepted, the status block fills the bottom region.
12//!   This is the baseline for non-interactive runs.
13//! - **Bar**: a single-row prompt at the bottom of the
14//!   terminal, accepting commands. The status block remains
15//!   visible above it.
16//! - **Window**: a full-screen REPL — most of the terminal is
17//!   turned over to the command interface with command history
18//!   visible. The status block is suppressed in this mode.
19//!
20//! ## Keys
21//!
22//! - `~`: cycle Hidden ↔ Bar. From Window, returns to Hidden.
23//!   Tilde is the universal "toggle off" key — pressing it
24//!   from any visible state collapses to Hidden.
25//! - `` ` `` (backtick): open or close Window. From Hidden or
26//!   Bar, opens to Window; from Window, returns to Hidden.
27//!   Picked over the originally-spec'd `Ctrl-~` because
28//!   terminals deliver the bare chord more reliably than the
29//!   Ctrl-modified one.
30//!
31//! ## Coordination
32//!
33//! State lives in a process-global atomic (`AtomicU8`). The
34//! key watcher (which sees `~` presses) stamps the state; the
35//! LogOnlySink reads it on every render tick to decide whether
36//! to draw the prompt. No locks — every reader picks up the
37//! latest write within one render frame.
38
39use std::collections::VecDeque;
40use std::sync::Mutex;
41use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
42use std::time::{Duration, Instant};
43
44/// Discriminant values stored in the global atomic. `u8` so the
45/// load/store is single-instruction on every platform we care
46/// about, and so the value can be mapped directly to the enum
47/// without unsafe transmutes.
48const STATE_HIDDEN: u8 = 0;
49const STATE_BAR: u8 = 1;
50const STATE_WINDOW: u8 = 2;
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum ReplVisibility {
54    /// No REPL surface drawn. The default for non-interactive
55    /// runs and the implicit state at session start until the
56    /// operator hits `~`.
57    Hidden,
58    /// Single-row prompt at the bottom of the terminal. Status
59    /// block continues to render above.
60    Bar,
61    /// Full-screen REPL — most of the terminal is the REPL
62    /// surface. Status block is suppressed (or compressed into
63    /// a single header line, TBD when the renderer lands).
64    Window,
65}
66
67impl ReplVisibility {
68    fn to_u8(self) -> u8 {
69        match self {
70            Self::Hidden => STATE_HIDDEN,
71            Self::Bar => STATE_BAR,
72            Self::Window => STATE_WINDOW,
73        }
74    }
75
76    fn from_u8(v: u8) -> Self {
77        match v {
78            STATE_BAR => Self::Bar,
79            STATE_WINDOW => Self::Window,
80            _ => Self::Hidden,
81        }
82    }
83}
84
85static STATE: AtomicU8 = AtomicU8::new(STATE_HIDDEN);
86
87/// Wall-clock nanos of the most recent toggle (either kind).
88/// Auto-repeat coming through stdin in raw mode sends a stream
89/// of keystrokes while a key is held; without this debounce
90/// the operator's single press would strobe Hidden ↔ Bar at
91/// 30 Hz. The debounce window is held long enough to absorb
92/// the auto-repeat cadence but short enough that a deliberate
93/// second tap registers — see `TOGGLE_DEBOUNCE`.
94static LAST_TOGGLE_NS: AtomicU64 = AtomicU64::new(0);
95
96/// Minimum interval between honored toggles. Tuned to swallow
97/// the typical auto-repeat cadence (30 Hz ≈ 33 ms inter-arrival)
98/// plus headroom, while still feeling responsive to a second
99/// deliberate press.
100const TOGGLE_DEBOUNCE: Duration = Duration::from_millis(250);
101
102fn now_nanos() -> u64 {
103    use std::sync::OnceLock;
104    static ORIGIN: OnceLock<Instant> = OnceLock::new();
105    let origin = *ORIGIN.get_or_init(Instant::now);
106    origin.elapsed().as_nanos() as u64
107}
108
109fn debounce_ok() -> bool {
110    let now = now_nanos();
111    let last = LAST_TOGGLE_NS.load(Ordering::Acquire);
112    if last != 0 && now.saturating_sub(last) < TOGGLE_DEBOUNCE.as_nanos() as u64 {
113        return false;
114    }
115    LAST_TOGGLE_NS.store(now, Ordering::Release);
116    true
117}
118
119/// Current REPL visibility. Read on every render tick by the
120/// LogOnlySink to decide whether to draw the prompt and how
121/// to lay out the bottom region.
122pub fn current() -> ReplVisibility {
123    ReplVisibility::from_u8(STATE.load(Ordering::Acquire))
124}
125
126/// Apply the `~` keystroke transition:
127///
128/// - Hidden → Bar
129/// - Bar → Hidden
130/// - Window → Hidden (tilde collapses anything visible)
131///
132/// Idempotent against rapid auto-repeat — the operator
133/// holding `~` shouldn't strobe between states. Returns the
134/// new state.
135pub fn toggle_bar() -> ReplVisibility {
136    if !debounce_ok() {
137        return current();
138    }
139    let next = match current() {
140        ReplVisibility::Hidden => ReplVisibility::Bar,
141        ReplVisibility::Bar | ReplVisibility::Window => ReplVisibility::Hidden,
142    };
143    STATE.store(next.to_u8(), Ordering::Release);
144    next
145}
146
147/// Apply the `Ctrl-~` keystroke transition:
148///
149/// - Hidden, Bar → Window (opens the full-screen REPL)
150/// - Window → Hidden (toggle off)
151pub fn toggle_window() -> ReplVisibility {
152    if !debounce_ok() {
153        return current();
154    }
155    let next = match current() {
156        ReplVisibility::Hidden | ReplVisibility::Bar => ReplVisibility::Window,
157        ReplVisibility::Window => ReplVisibility::Hidden,
158    };
159    STATE.store(next.to_u8(), Ordering::Release);
160    next
161}
162
163/// Capacity of the transcript ring. Caps the in-memory cost of
164/// keeping a session-long REPL history; 200 entries is enough
165/// to scroll through ~3 screens of typical responses while
166/// being a flat ~50 KB at the upper bound.
167const TRANSCRIPT_CAPACITY: usize = 200;
168
169/// Per-line REPL transcript. Lines are pre-rendered (the
170/// command echo `> cmd` is one entry, each response line is
171/// another) so the Window-mode renderer can pick the last N
172/// entries directly without re-splitting per tick.
173///
174/// Mutex (not RwLock): writes (dispatch push) and reads (every
175/// render frame) are infrequent relative to the lock-acquire
176/// cost; the simpler primitive is the right pick.
177static TRANSCRIPT: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
178
179/// Push the operator's command echo + the dispatcher's response
180/// onto the transcript ring. Each line lands as its own entry
181/// so the renderer's "last N rows" slice maps directly to
182/// display rows. Older entries fall off the front when the
183/// ring is full.
184pub fn push_transcript(command: &str, response: &str) {
185    let Ok(mut t) = TRANSCRIPT.lock() else {
186        return;
187    };
188    t.push_back(format!("> {command}"));
189    for line in response.split('\n') {
190        t.push_back(line.to_string());
191    }
192    while t.len() > TRANSCRIPT_CAPACITY {
193        t.pop_front();
194    }
195}
196
197/// Push a single pre-rendered line to the transcript ring — e.g.
198/// a completion-suggestion row — with no `> ` command echo.
199/// Same ring and capacity discipline as [`push_transcript`]. Used
200/// to keep ephemeral console output inside the frame instead of
201/// scrolling it through the terminal.
202pub fn push_transcript_line(line: &str) {
203    let Ok(mut t) = TRANSCRIPT.lock() else {
204        return;
205    };
206    t.push_back(line.to_string());
207    while t.len() > TRANSCRIPT_CAPACITY {
208        t.pop_front();
209    }
210}
211
212/// Current number of lines in the transcript ring. Cheap change
213/// detector for the console renderer — when it differs from the
214/// last paint, the console (on the alternate screen) repaints to
215/// show new output, regardless of which source pushed it.
216pub fn transcript_len() -> usize {
217    TRANSCRIPT.lock().map(|t| t.len()).unwrap_or(0)
218}
219
220/// Snapshot the most recent `n` transcript lines in display
221/// order (oldest first). Returns `<= n` strings — fewer when
222/// the transcript is shorter than `n`.
223pub fn transcript_tail(n: usize) -> Vec<String> {
224    let Ok(t) = TRANSCRIPT.lock() else {
225        return Vec::new();
226    };
227    let start = t.len().saturating_sub(n);
228    t.iter().skip(start).cloned().collect()
229}
230
231/// Test-only reset to the default state. Avoids cross-test
232/// state leakage where one test's `toggle_*` call affects the
233/// next test's view of `current()`. Also clears the
234/// transcript so transcript-targeted tests see a clean ring.
235#[cfg(test)]
236pub fn reset() {
237    STATE.store(STATE_HIDDEN, Ordering::Release);
238    LAST_TOGGLE_NS.store(0, Ordering::Release);
239    if let Ok(mut t) = TRANSCRIPT.lock() {
240        t.clear();
241    }
242}
243
244/// Test-only: apply a toggle bypassing the auto-repeat
245/// debounce so tests can exercise consecutive toggles without
246/// sleeping. Production callers always use the debounced
247/// `toggle_*` entry points.
248#[cfg(test)]
249pub fn toggle_bar_undebounced() -> ReplVisibility {
250    LAST_TOGGLE_NS.store(0, Ordering::Release);
251    toggle_bar()
252}
253
254#[cfg(test)]
255pub fn toggle_window_undebounced() -> ReplVisibility {
256    LAST_TOGGLE_NS.store(0, Ordering::Release);
257    toggle_window()
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use std::sync::Mutex;
264
265    /// All tests touching the global STATE serialize through
266    /// this lock — otherwise parallel test execution causes
267    /// transitions to interfere across cases.
268    static LOCK: Mutex<()> = Mutex::new(());
269
270    #[test]
271    fn tilde_cycles_hidden_to_bar_and_back() {
272        let _g = LOCK.lock().unwrap();
273        reset();
274        assert_eq!(current(), ReplVisibility::Hidden);
275        assert_eq!(toggle_bar_undebounced(), ReplVisibility::Bar);
276        assert_eq!(current(), ReplVisibility::Bar);
277        assert_eq!(toggle_bar_undebounced(), ReplVisibility::Hidden);
278        assert_eq!(current(), ReplVisibility::Hidden);
279    }
280
281    #[test]
282    fn ctrl_tilde_opens_and_closes_window() {
283        let _g = LOCK.lock().unwrap();
284        reset();
285        assert_eq!(toggle_window_undebounced(), ReplVisibility::Window);
286        assert_eq!(current(), ReplVisibility::Window);
287        assert_eq!(toggle_window_undebounced(), ReplVisibility::Hidden);
288    }
289
290    #[test]
291    fn ctrl_tilde_from_bar_promotes_to_window() {
292        let _g = LOCK.lock().unwrap();
293        reset();
294        toggle_bar_undebounced();
295        assert_eq!(current(), ReplVisibility::Bar);
296        assert_eq!(toggle_window_undebounced(), ReplVisibility::Window);
297    }
298
299    #[test]
300    fn tilde_from_window_collapses_to_hidden() {
301        let _g = LOCK.lock().unwrap();
302        reset();
303        toggle_window_undebounced();
304        assert_eq!(current(), ReplVisibility::Window);
305        // "tilde also closes it completely" — from any visible
306        // state, `~` collapses to Hidden.
307        assert_eq!(toggle_bar_undebounced(), ReplVisibility::Hidden);
308    }
309
310    /// The debounce swallows the second toggle when it lands
311    /// inside the auto-repeat window. The state stays where the
312    /// first toggle left it. This is the auto-repeat-hold
313    /// safeguard: a single deliberate press of `~` doesn't
314    /// strobe through Hidden ↔ Bar at the 30 Hz repeat rate.
315    #[test]
316    fn debounce_swallows_rapid_toggles() {
317        let _g = LOCK.lock().unwrap();
318        reset();
319        // First call lands.
320        assert_eq!(toggle_bar(), ReplVisibility::Bar);
321        // Second call within 250ms is swallowed — state stays Bar.
322        assert_eq!(toggle_bar(), ReplVisibility::Bar);
323        assert_eq!(toggle_bar(), ReplVisibility::Bar);
324    }
325
326    /// Transcript stores command + response as separate lines
327    /// (per-line entries are what the Window-mode renderer
328    /// directly maps to display rows). `transcript_tail` returns
329    /// the most-recent slice in chronological order.
330    #[test]
331    fn transcript_push_and_tail_round_trip() {
332        let _g = LOCK.lock().unwrap();
333        reset();
334        push_transcript("set foo 1", "OK");
335        push_transcript("controls", "foo=1\nbar=0");
336        let tail = transcript_tail(10);
337        assert_eq!(
338            tail,
339            vec![
340                "> set foo 1".to_string(),
341                "OK".to_string(),
342                "> controls".to_string(),
343                "foo=1".to_string(),
344                "bar=0".to_string(),
345            ]
346        );
347    }
348
349    /// `push_transcript_line` appends a single raw line (no `> `
350    /// echo prefix) — the path console completions / contained
351    /// output take into the frame.
352    #[test]
353    fn push_transcript_line_appends_raw() {
354        let _g = LOCK.lock().unwrap();
355        reset();
356        push_transcript("cmd", "resp");
357        push_transcript_line("a  b  c"); // e.g. a completion row
358        let tail = transcript_tail(10);
359        assert_eq!(
360            tail,
361            vec![
362                "> cmd".to_string(),
363                "resp".to_string(),
364                "a  b  c".to_string(),
365            ]
366        );
367    }
368
369    /// Tail bounded by request — `transcript_tail(2)` on a
370    /// 5-line transcript returns the LAST two entries.
371    #[test]
372    fn transcript_tail_caps_at_requested_count() {
373        let _g = LOCK.lock().unwrap();
374        reset();
375        push_transcript("a", "1");
376        push_transcript("b", "2");
377        let tail = transcript_tail(2);
378        assert_eq!(tail, vec!["> b".to_string(), "2".to_string()]);
379    }
380
381    /// Ring overflow drops the oldest entries first.
382    #[test]
383    fn transcript_ring_drops_oldest_on_overflow() {
384        let _g = LOCK.lock().unwrap();
385        reset();
386        for i in 0..(TRANSCRIPT_CAPACITY + 5) {
387            push_transcript(&format!("c{i}"), "");
388        }
389        let tail = transcript_tail(usize::MAX);
390        // Each `push_transcript` adds 2 entries: `> cmd` + ""
391        // (the empty response splits into one empty line).
392        // The ring keeps the most recent TRANSCRIPT_CAPACITY.
393        assert_eq!(tail.len(), TRANSCRIPT_CAPACITY);
394        // The very first command's echo (`> c0`) MUST have
395        // fallen off; the most recent one (`> c{N+4}`) MUST
396        // still be present.
397        assert!(
398            !tail.iter().any(|l| l == "> c0"),
399            "oldest entry MUST be evicted: {tail:?}"
400        );
401        assert!(
402            tail.iter()
403                .any(|l| l == &format!("> c{}", TRANSCRIPT_CAPACITY + 4)),
404            "newest entry MUST be retained: {tail:?}"
405        );
406    }
407}