Skip to main content

tui/tabs/
nms.rs

1//! Console tab state: an interactive nomiscript REPL.
2//!
3//! This module holds the *pure* console state — the input editor, a
4//! multi-line `pending` form buffer (filled until a balanced form is
5//! read), a bounded scrollback transcript, and a command history. The
6//! async eval bridge (`ConsoleEval`) lives in a sibling module; this
7//! file is intentionally I/O-free so it can be unit-tested without a
8//! runtime or a database.
9
10use cli_core::render::{
11    ErrorReply, RenderError, WireValue, parse_wire, reparse_list, value_to_rows,
12};
13use rpc::{ErrorCode, Response, ResponsePayload, parse_response};
14use scripting::nomiscript::{Reader, Value, format_value, list_to_vec};
15
16use crate::pane::{PaneId, PaneSet};
17use crate::widgets::Editor;
18use tvui::RowWindow;
19
20/// Maximum number of scrollback lines retained. A long-lived SSH
21/// session must not grow memory without bound, so older lines are
22/// dropped once this cap is reached.
23pub const MAX_SCROLLBACK_LINES: usize = 1000;
24
25/// Maximum number of submitted forms retained for history navigation.
26/// As with scrollback, a long-lived session must not retain unbounded
27/// submitted-form text, so the oldest entries are dropped past this cap.
28pub const MAX_HISTORY_ENTRIES: usize = 1000;
29
30/// Pure state for the Console tab.
31#[derive(Debug)]
32pub struct ConsoleState {
33    /// The single-line input editor for the current line.
34    pub input: Editor,
35    /// Lines of an in-progress multi-line form, joined with `\n` once a
36    /// balanced form is assembled. Empty when no form is pending.
37    pub pending: String,
38    /// The rendered transcript (prompts, inputs, and eval results).
39    pub scrollback: Vec<String>,
40    /// Previously submitted complete forms, oldest first.
41    pub history: Vec<String>,
42    /// Cursor into `history` for up/down navigation; `None` means the
43    /// cursor sits below the newest entry (i.e. on a fresh line).
44    pub history_cursor: Option<usize>,
45    /// Which sub-pane (Prompt or Scrollback) currently has focus.
46    pub panes: PaneSet,
47    /// Lines scrolled up from the bottom (0 = newest/tail).
48    pub scroll: usize,
49    /// The eval stream of this window; opened by its first submit.
50    pub stream: Option<u32>,
51    /// Whether the prompt has the keyboard; the window keeps it while others are in front.
52    pub focused: bool,
53}
54
55impl Default for ConsoleState {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl ConsoleState {
62    const PANES: &'static [PaneId] = &[PaneId::Prompt, PaneId::Scrollback];
63
64    #[must_use]
65    pub fn new() -> Self {
66        Self {
67            input: Editor::default(),
68            pending: String::new(),
69            scrollback: Vec::new(),
70            history: Vec::new(),
71            history_cursor: None,
72            panes: PaneSet::new(Self::PANES, PaneId::Prompt),
73            scroll: 0,
74            stream: None,
75            focused: false,
76        }
77    }
78
79    /// Consume the current input line. If, together with any pending
80    /// lines, it forms a balanced nomiscript form, return that complete
81    /// form string, clear the buffers, and record it in `history`. An
82    /// unbalanced (incomplete) form is appended to `pending` and `None`
83    /// is returned, so the caller keeps collecting lines. A blank /
84    /// whitespace-only candidate yields `None` without echoing or
85    /// recording history (a bare Enter must not submit an empty form).
86    pub fn take_complete_form(&mut self) -> Option<String> {
87        let line = self.input.buffer().to_string();
88        self.input = Editor::default();
89
90        let candidate = match self.pending.is_empty() {
91            true => line,
92            false => format!("{}\n{}", self.pending, line),
93        };
94
95        if candidate.trim().is_empty() {
96            return None;
97        }
98
99        match Reader::is_incomplete(&candidate) {
100            true => {
101                self.pending = candidate;
102                None
103            }
104            false => {
105                self.pending.clear();
106                self.push_history(candidate.clone());
107                self.history_cursor = None;
108                Some(candidate)
109            }
110        }
111    }
112
113    /// Record a submitted form, dropping the oldest entries once the
114    /// retained count would exceed [`MAX_HISTORY_ENTRIES`].
115    fn push_history(&mut self, form: String) {
116        self.history.push(form);
117        let overflow = self.history.len().saturating_sub(MAX_HISTORY_ENTRIES);
118        if overflow > 0 {
119            self.history.drain(0..overflow);
120        }
121    }
122
123    /// Move the history cursor toward older entries, loading the entry
124    /// at the new cursor into the input editor. A no-op on empty history;
125    /// once the cursor reaches the oldest entry it stays there.
126    pub fn history_prev(&mut self) {
127        if self.history.is_empty() {
128            return;
129        }
130        let next = match self.history_cursor {
131            None => self.history.len() - 1,
132            Some(0) => 0,
133            Some(i) => i - 1,
134        };
135        self.history_cursor = Some(next);
136        self.load_history_entry();
137    }
138
139    /// Move the history cursor toward newer entries, loading the entry
140    /// into the input editor. Stepping past the newest entry clears the
141    /// cursor and the input line (a fresh prompt).
142    pub fn history_next(&mut self) {
143        let Some(cursor) = self.history_cursor else {
144            return;
145        };
146        match cursor + 1 < self.history.len() {
147            true => {
148                self.history_cursor = Some(cursor + 1);
149                self.load_history_entry();
150            }
151            false => {
152                self.history_cursor = None;
153                self.input = Editor::default();
154            }
155        }
156    }
157
158    /// Replace the input editor with the history entry at the current
159    /// cursor. Caller guarantees the cursor points at a valid index.
160    fn load_history_entry(&mut self) {
161        if let Some(entry) = self.history_cursor.and_then(|i| self.history.get(i)) {
162            self.input = Editor::with_buffer(entry.clone());
163        }
164    }
165
166    /// Append a line to the scrollback, dropping the oldest lines once
167    /// the retained count would exceed [`MAX_SCROLLBACK_LINES`].
168    pub fn push_scrollback(&mut self, line: impl Into<String>) {
169        self.scrollback.push(line.into());
170        let overflow = self.scrollback.len().saturating_sub(MAX_SCROLLBACK_LINES);
171        if overflow > 0 {
172            self.scrollback.drain(0..overflow);
173        }
174    }
175
176    /// Scroll up by `n` lines (toward older content). Clamped to the
177    /// scrollback length so the offset can never exceed the buffer size.
178    pub fn scroll_up(&mut self, n: usize) {
179        self.scroll = (self.scroll + n).min(self.scrollback.len());
180    }
181
182    /// Scroll down by `n` lines (toward newer content). Saturates at 0.
183    pub fn scroll_down(&mut self, n: usize) {
184        self.scroll = self.scroll.saturating_sub(n);
185    }
186
187    /// Reset the scroll offset to the bottom (newest line visible).
188    pub fn reset_scroll(&mut self) {
189        self.scroll = 0;
190    }
191
192    /// The slice of scrollback lines that fit in a viewport of `height` rows,
193    /// respecting the current scroll offset. The effective offset is clamped
194    /// to the viewport (`len - height`) so the visible window is never emptied
195    /// past the oldest line, even when the stored offset exceeds that bound.
196    #[must_use]
197    pub fn visible_scrollback(&self, height: usize) -> &[String] {
198        let len = self.scrollback.len();
199        let max_scroll = RowWindow::last_top(len, height);
200        let scroll = self.scroll.min(max_scroll);
201        let end = len - scroll;
202        let start = end.saturating_sub(height);
203        &self.scrollback[start..end]
204    }
205}
206
207/// Pad each column in `rows` to the maximum width in that column and
208/// join cells with two spaces. Empty `rows` yields an empty `Vec`.
209///
210/// Width is measured in Unicode scalars (`chars().count()`); wide (CJK) or
211/// zero-width characters in account/commodity names can therefore misalign
212/// columns slightly. Acceptable for the Console scrollback — the dedicated
213/// data tabs render through ratatui's own width-aware `Table`.
214#[must_use]
215pub fn align_rows(rows: &[Vec<String>]) -> Vec<String> {
216    if rows.is_empty() {
217        return vec![];
218    }
219    let col_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
220    let widths: Vec<usize> = (0..col_count)
221        .map(|c| {
222            rows.iter()
223                .map(|r| r.get(c).map_or(0, |s| s.chars().count()))
224                .max()
225                .unwrap_or(0)
226        })
227        .collect();
228    rows.iter()
229        .map(|row| {
230            row.iter()
231                .enumerate()
232                .map(|(c, cell)| {
233                    let w = widths.get(c).copied().unwrap_or(0);
234                    format!("{cell:<w$}", w = w)
235                })
236                .collect::<Vec<_>>()
237                .join("  ")
238                .trim_end()
239                .to_string()
240        })
241        .collect()
242}
243
244/// Tabulate `value` when it is a non-empty proper list — the shape every list
245/// command returns, including `pair:string` results like `get-balances` whose
246/// elements are plist strings. The Console is typeless (unlike the CLI's
247/// per-command `RenderMode` and the dedicated data tabs), so this is
248/// best-effort: an empty list or a non-list renders verbatim. `value_to_rows`
249/// owns the per-element formatting, exactly as the CLI list renderers do.
250fn render_list_value(value: &Value) -> Option<Vec<String>> {
251    if list_to_vec(value).is_none_or(|els| els.is_empty()) {
252        return None;
253    }
254    let rows = value_to_rows(value);
255    if rows.is_empty() {
256        return None;
257    }
258    Some(align_rows(&rows))
259}
260
261/// A `string` native may print a list (`form-options`, transaction detail):
262/// a string that reads as a list is tabulated, any other string is verbatim.
263fn render_string_value(s: &str) -> Vec<String> {
264    let trimmed = s.trim_start();
265    trimmed
266        .starts_with('(')
267        .then(|| reparse_list(trimmed).ok())
268        .flatten()
269        .and_then(|value| render_list_value(&value))
270        .unwrap_or_else(|| vec![s.to_string()])
271}
272
273fn is_stream_refusal(envelope: &str) -> bool {
274    matches!(
275        parse_response(envelope),
276        Ok(Response { payload: ResponsePayload::Error { code, .. }, .. })
277            if code.as_symbol().eq_ignore_ascii_case(ErrorCode::TOO_MANY_STREAMS)
278    )
279}
280
281/// [`format_result`] plus, for a refused stream, the way out.
282#[must_use]
283pub fn console_lines(envelope: &str) -> Vec<String> {
284    let mut lines = format_result(envelope);
285    if is_stream_refusal(envelope) {
286        lines.push("close a console window to free a stream".to_string());
287    }
288    lines
289}
290
291/// Render an RPC response envelope into scrollback lines.
292///
293/// Structured responses: list payloads → aligned table, scalars → one
294/// line, server errors → `[error] code: message`. Anything that does
295/// not parse as a response envelope (request frames, plain notices)
296/// falls back to verbatim line split.
297#[must_use]
298pub fn format_result(envelope: &str) -> Vec<String> {
299    match parse_wire(envelope) {
300        Ok(WireValue::Value(Value::String(ref s))) => render_string_value(s),
301        Ok(WireValue::Value(ref v)) => {
302            render_list_value(v).unwrap_or_else(|| vec![format_value(v)])
303        }
304        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
305            vec![format!("[error] {code}: {message}")]
306        }
307        Err(_) => envelope.lines().map(str::to_string).collect(),
308    }
309}
310
311#[cfg(test)]
312mod tests;