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

            
10
use cli_core::render::{
11
    ErrorReply, RenderError, WireValue, parse_wire, reparse_list, value_to_rows,
12
};
13
use rpc::{ErrorCode, Response, ResponsePayload, parse_response};
14
use scripting::nomiscript::{Reader, Value, format_value, list_to_vec};
15

            
16
use crate::pane::{PaneId, PaneSet};
17
use crate::widgets::Editor;
18
use 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.
23
pub 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.
28
pub const MAX_HISTORY_ENTRIES: usize = 1000;
29

            
30
/// Pure state for the Console tab.
31
#[derive(Debug)]
32
pub 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

            
55
impl Default for ConsoleState {
56
    fn default() -> Self {
57
        Self::new()
58
    }
59
}
60

            
61
impl ConsoleState {
62
    const PANES: &'static [PaneId] = &[PaneId::Prompt, PaneId::Scrollback];
63

            
64
    #[must_use]
65
2129
    pub fn new() -> Self {
66
2129
        Self {
67
2129
            input: Editor::default(),
68
2129
            pending: String::new(),
69
2129
            scrollback: Vec::new(),
70
2129
            history: Vec::new(),
71
2129
            history_cursor: None,
72
2129
            panes: PaneSet::new(Self::PANES, PaneId::Prompt),
73
2129
            scroll: 0,
74
2129
            stream: None,
75
2129
            focused: false,
76
2129
        }
77
2129
    }
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
1030
    pub fn take_complete_form(&mut self) -> Option<String> {
87
1030
        let line = self.input.buffer().to_string();
88
1030
        self.input = Editor::default();
89

            
90
1030
        let candidate = match self.pending.is_empty() {
91
1029
            true => line,
92
1
            false => format!("{}\n{}", self.pending, line),
93
        };
94

            
95
1030
        if candidate.trim().is_empty() {
96
2
            return None;
97
1028
        }
98

            
99
1028
        match Reader::is_incomplete(&candidate) {
100
            true => {
101
5
                self.pending = candidate;
102
5
                None
103
            }
104
            false => {
105
1023
                self.pending.clear();
106
1023
                self.push_history(candidate.clone());
107
1023
                self.history_cursor = None;
108
1023
                Some(candidate)
109
            }
110
        }
111
1030
    }
112

            
113
    /// Record a submitted form, dropping the oldest entries once the
114
    /// retained count would exceed [`MAX_HISTORY_ENTRIES`].
115
1023
    fn push_history(&mut self, form: String) {
116
1023
        self.history.push(form);
117
1023
        let overflow = self.history.len().saturating_sub(MAX_HISTORY_ENTRIES);
118
1023
        if overflow > 0 {
119
5
            self.history.drain(0..overflow);
120
1018
        }
121
1023
    }
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
12
    pub fn history_prev(&mut self) {
127
12
        if self.history.is_empty() {
128
1
            return;
129
11
        }
130
11
        let next = match self.history_cursor {
131
5
            None => self.history.len() - 1,
132
1
            Some(0) => 0,
133
5
            Some(i) => i - 1,
134
        };
135
11
        self.history_cursor = Some(next);
136
11
        self.load_history_entry();
137
12
    }
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
6
    pub fn history_next(&mut self) {
143
6
        let Some(cursor) = self.history_cursor else {
144
2
            return;
145
        };
146
4
        match cursor + 1 < self.history.len() {
147
            true => {
148
3
                self.history_cursor = Some(cursor + 1);
149
3
                self.load_history_entry();
150
            }
151
            false => {
152
1
                self.history_cursor = None;
153
1
                self.input = Editor::default();
154
            }
155
        }
156
6
    }
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
14
    fn load_history_entry(&mut self) {
161
14
        if let Some(entry) = self.history_cursor.and_then(|i| self.history.get(i)) {
162
14
            self.input = Editor::with_buffer(entry.clone());
163
        }
164
14
    }
165

            
166
    /// Append a line to the scrollback, dropping the oldest lines once
167
    /// the retained count would exceed [`MAX_SCROLLBACK_LINES`].
168
1394
    pub fn push_scrollback(&mut self, line: impl Into<String>) {
169
1394
        self.scrollback.push(line.into());
170
1394
        let overflow = self.scrollback.len().saturating_sub(MAX_SCROLLBACK_LINES);
171
1394
        if overflow > 0 {
172
5
            self.scrollback.drain(0..overflow);
173
1389
        }
174
1394
    }
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
18
    pub fn scroll_up(&mut self, n: usize) {
179
18
        self.scroll = (self.scroll + n).min(self.scrollback.len());
180
18
    }
181

            
182
    /// Scroll down by `n` lines (toward newer content). Saturates at 0.
183
9
    pub fn scroll_down(&mut self, n: usize) {
184
9
        self.scroll = self.scroll.saturating_sub(n);
185
9
    }
186

            
187
    /// Reset the scroll offset to the bottom (newest line visible).
188
47
    pub fn reset_scroll(&mut self) {
189
47
        self.scroll = 0;
190
47
    }
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
155
    pub fn visible_scrollback(&self, height: usize) -> &[String] {
198
155
        let len = self.scrollback.len();
199
155
        let max_scroll = RowWindow::last_top(len, height);
200
155
        let scroll = self.scroll.min(max_scroll);
201
155
        let end = len - scroll;
202
155
        let start = end.saturating_sub(height);
203
155
        &self.scrollback[start..end]
204
155
    }
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]
215
10
pub fn align_rows(rows: &[Vec<String>]) -> Vec<String> {
216
10
    if rows.is_empty() {
217
1
        return vec![];
218
9
    }
219
15
    let col_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
220
9
    let widths: Vec<usize> = (0..col_count)
221
17
        .map(|c| {
222
17
            rows.iter()
223
28
                .map(|r| r.get(c).map_or(0, |s| s.chars().count()))
224
                .max()
225
17
                .unwrap_or(0)
226
17
        })
227
        .collect();
228
9
    rows.iter()
229
15
        .map(|row| {
230
15
            row.iter()
231
15
                .enumerate()
232
26
                .map(|(c, cell)| {
233
26
                    let w = widths.get(c).copied().unwrap_or(0);
234
26
                    format!("{cell:<w$}", w = w)
235
26
                })
236
                .collect::<Vec<_>>()
237
15
                .join("  ")
238
                .trim_end()
239
                .to_string()
240
15
        })
241
        .collect()
242
10
}
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.
250
27
fn render_list_value(value: &Value) -> Option<Vec<String>> {
251
27
    if list_to_vec(value).is_none_or(|els| els.is_empty()) {
252
22
        return None;
253
5
    }
254
5
    let rows = value_to_rows(value);
255
5
    if rows.is_empty() {
256
        return None;
257
5
    }
258
5
    Some(align_rows(&rows))
259
27
}
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.
263
6
fn render_string_value(s: &str) -> Vec<String> {
264
6
    let trimmed = s.trim_start();
265
6
    trimmed
266
6
        .starts_with('(')
267
2
        .then(|| reparse_list(trimmed).ok())
268
        .flatten()
269
2
        .and_then(|value| render_list_value(&value))
270
4
        .unwrap_or_else(|| vec![s.to_string()])
271
6
}
272

            
273
27
fn is_stream_refusal(envelope: &str) -> bool {
274
27
    matches!(
275
27
        parse_response(envelope),
276
        Ok(Response { payload: ResponsePayload::Error { code, .. }, .. })
277
8
            if code.as_symbol().eq_ignore_ascii_case(ErrorCode::TOO_MANY_STREAMS)
278
    )
279
27
}
280

            
281
/// [`format_result`] plus, for a refused stream, the way out.
282
#[must_use]
283
27
pub fn console_lines(envelope: &str) -> Vec<String> {
284
27
    let mut lines = format_result(envelope);
285
27
    if is_stream_refusal(envelope) {
286
2
        lines.push("close a console window to free a stream".to_string());
287
25
    }
288
27
    lines
289
27
}
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]
298
46
pub fn format_result(envelope: &str) -> Vec<String> {
299
46
    match parse_wire(envelope) {
300
6
        Ok(WireValue::Value(Value::String(ref s))) => render_string_value(s),
301
        Ok(WireValue::Value(ref v)) => {
302
25
            render_list_value(v).unwrap_or_else(|| vec![format_value(v)])
303
        }
304
        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
305
11
            vec![format!("[error] {code}: {message}")]
306
        }
307
4
        Err(_) => envelope.lines().map(str::to_string).collect(),
308
    }
309
46
}
310

            
311
#[cfg(test)]
312
mod tests;