Skip to main content

vcon_server/
tui.rs

1//! `vcon-server tui`: a terminal UI for a running server (cargo feature
2//! `tui`, on by default).
3//!
4//! It is a client of the server's HTTP API with one API key, as any other
5//! client is: it opens no data directory, catalog or master key, so the
6//! server's scopes, tenant bounds and audit log apply to everything it
7//! shows. It reads only: the key's tenant's vCons as the API lists them
8//! (uuid, version and times), one vCon's masked view (`?view=masked`,
9//! no content), and a part of it when a reveal key asks for it
10//! (`?reveal=<part>`, recorded in the audit log).
11//!
12//! The parts: [`state`] is the state machine, [`view`] draws a state,
13//! [`keys`] is the one table of bindings, and [`client`] is the API behind
14//! a trait. This module joins them to a real terminal.
15
16pub mod client;
17pub mod keys;
18pub mod state;
19pub mod view;
20
21#[cfg(test)]
22mod page_tests;
23#[cfg(test)]
24mod screens;
25
26use std::io::IsTerminal;
27use std::sync::Arc;
28use std::sync::mpsc::{self, Receiver, Sender};
29use std::time::Duration;
30
31use ratatui::Terminal;
32use ratatui::backend::Backend;
33use ratatui::crossterm::event::{self, Event as Input, KeyEventKind};
34use time::OffsetDateTime;
35
36use crate::mcp::stdio::ClientConfig;
37use client::{Api, HttpApi};
38use state::{Effect, Event, State};
39use view::Theme;
40
41/// How long the loop waits for a key before it looks for an answer.
42const TICK: Duration = Duration::from_millis(100);
43
44/// What a terminal event asks of the state: a bound key's action when the
45/// key goes down, or the new size. Releases, repeats of a release, the
46/// mouse, focus and paste are nothing.
47#[must_use]
48pub fn translate(input: &Input) -> Option<Event> {
49    match input {
50        Input::Key(key) if key.kind != KeyEventKind::Release => {
51            keys::action(key.code, key.modifiers).map(Event::Action)
52        }
53        Input::Resize(columns, lines) => Some(Event::Resize(*columns, *lines)),
54        _ => None,
55    }
56}
57
58/// Runs the UI on this process's terminal until the user quits.
59///
60/// The terminal is put back on every way out: a normal quit, an error, and
61/// a panic (through the hook `ratatui::try_init` installs).
62///
63/// # Errors
64///
65/// A sentence naming what failed: no terminal ([`require_terminal`]), the
66/// key file, the CA file, or the terminal. It never holds the token.
67pub fn run(config: &ClientConfig) -> Result<(), String> {
68    // First, so that no key is read for a run that cannot start.
69    require_terminal(
70        std::io::stdin().is_terminal(),
71        std::io::stdout().is_terminal(),
72    )?;
73    let api: Arc<dyn Api> = Arc::new(HttpApi::new(config)?);
74    let theme = view::theme(
75        std::env::var("NO_COLOR").ok().as_deref(),
76        std::env::var("TERM").ok().as_deref(),
77    );
78    with_terminal(|terminal| {
79        let (answers, inbox) = mpsc::channel();
80        let mut dispatch = |effects: Vec<Effect>| send(&api, effects, &answers);
81        drive(
82            terminal,
83            &client::base(&config.url),
84            theme,
85            &mut Keyboard,
86            &inbox,
87            &mut dispatch,
88            &OffsetDateTime::now_utc,
89        )
90        .map(|_| ())
91    })?
92}
93
94/// Runs `body` with this process's terminal taken for a UI (keys one at a
95/// time and not echoed, the alternate screen), and puts the terminal back
96/// when `body` returns and when it panics (through the hook
97/// `ratatui::try_init` installs, which runs before the panic's message is
98/// written). Returns what `body` returned.
99///
100/// It is the one place the terminal is taken and put back, apart from the
101/// UI's loop, so that a test can put a body of its own on a terminal
102/// (`tests/tui_terminal.rs`).
103///
104/// # Errors
105///
106/// A sentence with the terminal's error when it cannot be taken; `body`
107/// has then not run.
108pub fn with_terminal<T>(
109    body: impl FnOnce(&mut ratatui::DefaultTerminal) -> T,
110) -> Result<T, String> {
111    let mut terminal = ratatui::try_init().map_err(|e| format!("the terminal: {e}"))?;
112    let value = body(&mut terminal);
113    ratatui::restore();
114    Ok(value)
115}
116
117/// Whether the UI can start: it reads keys from standard input and draws
118/// on standard output, so each must be a terminal. `input` and `output`
119/// say whether they are.
120///
121/// # Errors
122///
123/// A sentence that says a terminal is required, which of the two is not
124/// one, and what to do.
125pub fn require_terminal(input: bool, output: bool) -> Result<(), String> {
126    let what = match (input, output) {
127        (true, true) => return Ok(()),
128        (false, true) => "standard input is not one",
129        (true, false) => "standard output is not one",
130        (false, false) => "standard input and standard output are not one",
131    };
132    Err(format!(
133        "a terminal is required: {what}; run it in a terminal, not through a pipe, a redirect or a job without one"
134    ))
135}
136
137/// Where the terminal's events come from: the keyboard in [`run`], a
138/// script in tests.
139pub trait Inputs {
140    /// The next event, or `None` when none arrives within `wait`.
141    ///
142    /// # Errors
143    ///
144    /// The terminal's error when it cannot be read.
145    fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>>;
146}
147
148/// This process's terminal.
149struct Keyboard;
150
151impl Inputs for Keyboard {
152    fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>> {
153        if event::poll(wait)? {
154            event::read().map(Some)
155        } else {
156            Ok(None)
157        }
158    }
159}
160
161/// The loop: applies every answer in `inbox`, draws, waits one tick for an
162/// event and applies it, until the state says quit. Each request the state
163/// asks for goes to `dispatch`, whose answer comes back through `inbox`;
164/// `now` is the clock. Returns the state at the end.
165///
166/// # Errors
167///
168/// A sentence with the terminal's error when it cannot be drawn or read.
169pub fn drive<B: Backend>(
170    terminal: &mut Terminal<B>,
171    server: &str,
172    theme: Theme,
173    inputs: &mut dyn Inputs,
174    inbox: &Receiver<Event>,
175    dispatch: &mut dyn FnMut(Vec<Effect>),
176    now: &dyn Fn() -> OffsetDateTime,
177) -> Result<State, String> {
178    let size = terminal.size().map_err(|e| format!("the terminal: {e}"))?;
179    let (mut state, first) = State::new(server, (size.width, size.height));
180    dispatch(first);
181    while !state.quit {
182        while let Ok(event) = inbox.try_recv() {
183            dispatch(state.step(event, now()));
184        }
185        terminal
186            .draw(|frame| view::draw(frame, &state, theme))
187            .map_err(|e| format!("the terminal: {e}"))?;
188        let input = inputs
189            .next(TICK)
190            .map_err(|e| format!("the terminal: {e}"))?;
191        if let Some(event) = input.as_ref().and_then(translate) {
192            dispatch(state.step(event, now()));
193        }
194    }
195    Ok(state)
196}
197
198/// Starts each request on a thread that sends its answer to `answers`.
199fn send(api: &Arc<dyn Api>, effects: Vec<Effect>, answers: &Sender<Event>) {
200    for effect in effects {
201        let api = Arc::clone(api);
202        let answers = answers.clone();
203        std::thread::spawn(move || {
204            // The receiver is gone only when the UI has quit; the answer
205            // then has no reader.
206            drop(answers.send(client::perform(api.as_ref(), &effect)));
207        });
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use ratatui::crossterm::event::{
214        Event as Input, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
215    };
216
217    use std::collections::VecDeque;
218    use std::sync::mpsc;
219    use std::time::Duration;
220
221    use ratatui::Terminal;
222    use ratatui::backend::TestBackend;
223    use time::OffsetDateTime;
224    use time::macros::datetime;
225
226    use super::client::{self, Api};
227    use super::state::{Action, ApiError, Effect, Event, KeyInfo, Page, Row, State, View};
228    use super::view::Theme;
229    use super::{Inputs, drive, translate};
230
231    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
232
233    fn row(n: u8) -> Row {
234        Row {
235            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
236            stored_at: "2026-10-25T12:00:00Z".to_owned(),
237            updated_at: "2026-10-25T12:30:00Z".to_owned(),
238            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
239        }
240    }
241
242    /// A server with a reader key and two vCons.
243    struct TwoVcons;
244
245    impl Api for TwoVcons {
246        fn key(&self) -> Result<KeyInfo, ApiError> {
247            Ok(KeyInfo {
248                id: "0123456789abcdef".to_owned(),
249                tenant: Some("t_example".to_owned()),
250                scopes: vec!["read".to_owned()],
251            })
252        }
253
254        fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
255            Ok(Page {
256                vcons: vec![row(0), row(1)],
257                next: None,
258            })
259        }
260
261        fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
262            Ok(vec!["Masked view".to_owned()])
263        }
264
265        fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
266            Ok("{}".to_owned())
267        }
268    }
269
270    /// Keys from a list. When the list ends the input fails, so a loop that
271    /// does not end on quit fails its test instead of hanging.
272    struct Script(VecDeque<KeyCode>);
273
274    impl Inputs for Script {
275        fn next(&mut self, _wait: Duration) -> std::io::Result<Option<Input>> {
276            let code = self
277                .0
278                .pop_front()
279                .ok_or_else(|| std::io::Error::other("the script ended"))?;
280            Ok(Some(key(code, KeyEventKind::Press)))
281        }
282    }
283
284    /// Runs the loop on a test terminal with `keys`, each request answered
285    /// at once by [`TwoVcons`], and returns the result and the last frame.
286    fn driven(keys: &[KeyCode]) -> (Result<State, String>, String) {
287        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("a terminal");
288        let (answers, inbox) = mpsc::channel();
289        let mut dispatch = |effects: Vec<Effect>| {
290            for effect in effects {
291                answers
292                    .send(client::perform(&TwoVcons, &effect))
293                    .expect("the loop holds the receiver");
294            }
295        };
296        let result = drive(
297            &mut terminal,
298            "https://vcon.example.com:8443",
299            Theme { color: false },
300            &mut Script(keys.iter().copied().collect()),
301            &inbox,
302            &mut dispatch,
303            &|| NOW,
304        );
305        let buffer = terminal.backend().buffer();
306        let frame = buffer
307            .content()
308            .iter()
309            .map(ratatui::buffer::Cell::symbol)
310            .collect();
311        (result, frame)
312    }
313
314    #[test]
315    fn the_loop_applies_answers_and_keys_in_order_and_ends_on_quit() {
316        let (result, frame) = driven(&[KeyCode::Down, KeyCode::Enter, KeyCode::Char('q')]);
317        let state = result.expect("the loop ends on q");
318        assert_eq!(state.view, View::Detail, "Enter opened the detail view");
319        assert_eq!(
320            state.detail,
321            Some(row(1).uuid),
322            "both answers were applied before Down, so Down moved to the second vCon"
323        );
324        assert!(
325            frame.contains(&format!("vCon {}", row(1).uuid)),
326            "the last frame drawn is the detail view: {frame}"
327        );
328    }
329
330    fn key(code: KeyCode, kind: KeyEventKind) -> Input {
331        Input::Key(KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind))
332    }
333
334    #[test]
335    fn the_loop_stops_with_the_terminals_error_when_input_fails() {
336        let (result, _) = driven(&[KeyCode::Down]);
337        assert_eq!(
338            result,
339            Err("the terminal: the script ended".to_owned()),
340            "the error is returned, with what it is about"
341        );
342    }
343
344    #[test]
345    fn the_loop_stamps_answers_with_the_clock_it_is_given() {
346        let (result, _) = driven(&[KeyCode::Char('q')]);
347        assert_eq!(
348            result.expect("the loop ends on q").as_of,
349            Some(NOW),
350            "the list was read at the time the clock said"
351        );
352    }
353
354    #[test]
355    fn a_bound_key_going_down_is_its_action() {
356        assert_eq!(
357            translate(&key(KeyCode::Char('q'), KeyEventKind::Press)),
358            Some(Event::Action(Action::Quit)),
359            "q quits"
360        );
361    }
362
363    #[test]
364    fn a_held_key_repeats_its_action() {
365        assert_eq!(
366            translate(&key(KeyCode::Down, KeyEventKind::Repeat)),
367            Some(Event::Action(Action::Down)),
368            "holding Down keeps moving"
369        );
370    }
371
372    #[test]
373    fn a_key_coming_up_is_nothing() {
374        assert_eq!(
375            translate(&key(KeyCode::Char('q'), KeyEventKind::Release)),
376            None,
377            "a terminal that reports releases must not act twice"
378        );
379    }
380
381    #[test]
382    fn an_unbound_key_is_nothing() {
383        assert_eq!(
384            translate(&key(KeyCode::Char('x'), KeyEventKind::Press)),
385            None,
386            "x is not bound"
387        );
388    }
389
390    #[test]
391    fn a_resize_carries_the_new_size() {
392        assert_eq!(
393            translate(&Input::Resize(132, 43)),
394            Some(Event::Resize(132, 43)),
395            "columns, then lines"
396        );
397    }
398
399    #[test]
400    fn focus_and_paste_are_nothing() {
401        assert_eq!(
402            translate(&Input::FocusGained),
403            None,
404            "focus changes nothing"
405        );
406        assert_eq!(
407            translate(&Input::Paste("q".to_owned())),
408            None,
409            "pasted text is not typed keys"
410        );
411    }
412}