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