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 requests = Requests::new(Arc::clone(&api), answers);
81        let ended = drive(
82            terminal,
83            &client::base(&config.url),
84            theme,
85            &mut Keyboard,
86            &inbox,
87            &mut |effects: Vec<Effect>| requests.send(effects),
88            &OffsetDateTime::now_utc,
89        );
90        // Before the process exits, every request's thread has ended and
91        // dropped its clone of the client: a thread still ending while the
92        // process exits can crash it.
93        requests.finish();
94        ended.map(|_| ())
95    })?
96}
97
98/// Runs `body` with this process's terminal taken for a UI (keys one at a
99/// time and not echoed, the alternate screen), and puts the terminal back
100/// when `body` returns and when it panics (through the hook
101/// `ratatui::try_init` installs, which runs before the panic's message is
102/// written). Returns what `body` returned.
103///
104/// It is the one place the terminal is taken and put back, apart from the
105/// UI's loop, so that a test can put a body of its own on a terminal
106/// (`tests/tui_terminal.rs`).
107///
108/// # Errors
109///
110/// A sentence with the terminal's error when it cannot be taken; `body`
111/// has then not run.
112pub fn with_terminal<T>(
113    body: impl FnOnce(&mut ratatui::DefaultTerminal) -> T,
114) -> Result<T, String> {
115    let mut terminal = ratatui::try_init().map_err(|e| format!("the terminal: {e}"))?;
116    let value = body(&mut terminal);
117    ratatui::restore();
118    Ok(value)
119}
120
121/// Whether the UI can start: it reads keys from standard input and draws
122/// on standard output, so each must be a terminal. `input` and `output`
123/// say whether they are.
124///
125/// # Errors
126///
127/// A sentence that says a terminal is required, which of the two is not
128/// one, and what to do.
129pub fn require_terminal(input: bool, output: bool) -> Result<(), String> {
130    let what = match (input, output) {
131        (true, true) => return Ok(()),
132        (false, true) => "standard input is not one",
133        (true, false) => "standard output is not one",
134        (false, false) => "standard input and standard output are not one",
135    };
136    Err(format!(
137        "a terminal is required: {what}; run it in a terminal, not through a pipe, a redirect or a job without one"
138    ))
139}
140
141/// Where the terminal's events come from: the keyboard in [`run`], a
142/// script in tests.
143pub trait Inputs {
144    /// The next event, or `None` when none arrives within `wait`.
145    ///
146    /// # Errors
147    ///
148    /// The terminal's error when it cannot be read.
149    fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>>;
150}
151
152/// This process's terminal.
153struct Keyboard;
154
155impl Inputs for Keyboard {
156    fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>> {
157        if event::poll(wait)? {
158            event::read().map(Some)
159        } else {
160            Ok(None)
161        }
162    }
163}
164
165/// The loop: applies every answer in `inbox`, draws, waits one tick for an
166/// event and applies it, until the state says quit. Each request the state
167/// asks for goes to `dispatch`, whose answer comes back through `inbox`;
168/// `now` is the clock. Returns the state at the end.
169///
170/// # Errors
171///
172/// A sentence with the terminal's error when it cannot be drawn or read.
173pub fn drive<B: Backend>(
174    terminal: &mut Terminal<B>,
175    server: &str,
176    theme: Theme,
177    inputs: &mut dyn Inputs,
178    inbox: &Receiver<Event>,
179    dispatch: &mut dyn FnMut(Vec<Effect>),
180    now: &dyn Fn() -> OffsetDateTime,
181) -> Result<State, String> {
182    let size = terminal.size().map_err(|e| format!("the terminal: {e}"))?;
183    let (mut state, first) = State::new(server, (size.width, size.height));
184    dispatch(first);
185    while !state.quit {
186        while let Ok(event) = inbox.try_recv() {
187            dispatch(state.step(event, now()));
188        }
189        terminal
190            .draw(|frame| view::draw(frame, &state, theme))
191            .map_err(|e| format!("the terminal: {e}"))?;
192        let input = inputs
193            .next(TICK)
194            .map_err(|e| format!("the terminal: {e}"))?;
195        if let Some(event) = input.as_ref().and_then(translate) {
196            dispatch(state.step(event, now()));
197        }
198    }
199    Ok(state)
200}
201
202/// The UI's requests, each on a thread of its own that sends its answer to
203/// the UI's inbox.
204struct Requests {
205    api: Arc<dyn Api>,
206    answers: Sender<Event>,
207    running: Vec<std::thread::JoinHandle<()>>,
208}
209
210impl Requests {
211    fn new(api: Arc<dyn Api>, answers: Sender<Event>) -> Self {
212        Self {
213            api,
214            answers,
215            running: Vec::new(),
216        }
217    }
218
219    /// Starts each request on a thread that sends its answer to the inbox,
220    /// and joins the threads of the requests that have ended, so a long
221    /// session keeps only the handles of those under way.
222    fn send(&mut self, effects: Vec<Effect>) {
223        let (ended, running): (Vec<_>, Vec<_>) = std::mem::take(&mut self.running)
224            .into_iter()
225            .partition(std::thread::JoinHandle::is_finished);
226        self.running = running;
227        for handle in ended {
228            // A request's thread only sends its answer; a panic in it has
229            // already been reported on stderr, and the UI goes on.
230            drop(handle.join());
231        }
232        for effect in effects {
233            let api = Arc::clone(&self.api);
234            let answers = self.answers.clone();
235            self.running.push(std::thread::spawn(move || {
236                // The receiver is gone only when the UI has quit; the answer
237                // then has no reader.
238                drop(answers.send(client::perform(api.as_ref(), &effect)));
239            }));
240        }
241    }
242
243    /// The UI's exit: ends every request under way ([`Api::close`]) and
244    /// joins every request's thread, so that none still holds the client
245    /// when the process exits.
246    fn finish(self) {
247        self.api.close();
248        for handle in self.running {
249            drop(handle.join());
250        }
251    }
252
253    #[cfg(test)]
254    fn under_way(&self) -> usize {
255        self.running.len()
256    }
257
258    #[cfg(test)]
259    fn all_ended(&self) -> bool {
260        self.running
261            .iter()
262            .all(std::thread::JoinHandle::is_finished)
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use ratatui::crossterm::event::{
269        Event as Input, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
270    };
271
272    use std::collections::VecDeque;
273    use std::sync::mpsc;
274    use std::time::Duration;
275
276    use ratatui::Terminal;
277    use ratatui::backend::TestBackend;
278    use time::OffsetDateTime;
279    use time::macros::datetime;
280
281    use super::client::{self, Api};
282    use super::state::{Action, ApiError, Effect, Event, KeyInfo, Page, Row, State, View};
283    use super::view::Theme;
284    use super::{Inputs, drive, translate};
285
286    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
287
288    fn row(n: u8) -> Row {
289        Row {
290            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
291            stored_at: "2026-10-25T12:00:00Z".to_owned(),
292            updated_at: "2026-10-25T12:30:00Z".to_owned(),
293            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
294        }
295    }
296
297    /// A server with a reader key and two vCons.
298    struct TwoVcons;
299
300    impl Api for TwoVcons {
301        fn key(&self) -> Result<KeyInfo, ApiError> {
302            Ok(KeyInfo {
303                id: "0123456789abcdef".to_owned(),
304                tenant: Some("t_example".to_owned()),
305                scopes: vec!["read".to_owned()],
306            })
307        }
308
309        fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
310            Ok(Page {
311                vcons: vec![row(0), row(1)],
312                next: None,
313            })
314        }
315
316        fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
317            Ok(vec!["Masked view".to_owned()])
318        }
319
320        fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
321            Ok("{}".to_owned())
322        }
323    }
324
325    /// Keys from a list. When the list ends the input fails, so a loop that
326    /// does not end on quit fails its test instead of hanging.
327    struct Script(VecDeque<KeyCode>);
328
329    impl Inputs for Script {
330        fn next(&mut self, _wait: Duration) -> std::io::Result<Option<Input>> {
331            let code = self
332                .0
333                .pop_front()
334                .ok_or_else(|| std::io::Error::other("the script ended"))?;
335            Ok(Some(key(code, KeyEventKind::Press)))
336        }
337    }
338
339    /// Runs the loop on a test terminal with `keys`, each request answered
340    /// at once by [`TwoVcons`], and returns the result and the last frame.
341    fn driven(keys: &[KeyCode]) -> (Result<State, String>, String) {
342        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("a terminal");
343        let (answers, inbox) = mpsc::channel();
344        let mut dispatch = |effects: Vec<Effect>| {
345            for effect in effects {
346                answers
347                    .send(client::perform(&TwoVcons, &effect))
348                    .expect("the loop holds the receiver");
349            }
350        };
351        let result = drive(
352            &mut terminal,
353            "https://vcon.example.com:8443",
354            Theme { color: false },
355            &mut Script(keys.iter().copied().collect()),
356            &inbox,
357            &mut dispatch,
358            &|| NOW,
359        );
360        let buffer = terminal.backend().buffer();
361        let frame = buffer
362            .content()
363            .iter()
364            .map(ratatui::buffer::Cell::symbol)
365            .collect();
366        (result, frame)
367    }
368
369    #[test]
370    fn the_loop_applies_answers_and_keys_in_order_and_ends_on_quit() {
371        let (result, frame) = driven(&[KeyCode::Down, KeyCode::Enter, KeyCode::Char('q')]);
372        let state = result.expect("the loop ends on q");
373        assert_eq!(state.view, View::Detail, "Enter opened the detail view");
374        assert_eq!(
375            state.detail,
376            Some(row(1).uuid),
377            "both answers were applied before Down, so Down moved to the second vCon"
378        );
379        assert!(
380            frame.contains(&format!("vCon {}", row(1).uuid)),
381            "the last frame drawn is the detail view: {frame}"
382        );
383    }
384
385    fn key(code: KeyCode, kind: KeyEventKind) -> Input {
386        Input::Key(KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind))
387    }
388
389    #[test]
390    fn the_loop_stops_with_the_terminals_error_when_input_fails() {
391        let (result, _) = driven(&[KeyCode::Down]);
392        assert_eq!(
393            result,
394            Err("the terminal: the script ended".to_owned()),
395            "the error is returned, with what it is about"
396        );
397    }
398
399    #[test]
400    fn the_loop_stamps_answers_with_the_clock_it_is_given() {
401        let (result, _) = driven(&[KeyCode::Char('q')]);
402        assert_eq!(
403            result.expect("the loop ends on q").as_of,
404            Some(NOW),
405            "the list was read at the time the clock said"
406        );
407    }
408
409    #[test]
410    fn a_bound_key_going_down_is_its_action() {
411        assert_eq!(
412            translate(&key(KeyCode::Char('q'), KeyEventKind::Press)),
413            Some(Event::Action(Action::Quit)),
414            "q quits"
415        );
416    }
417
418    #[test]
419    fn a_held_key_repeats_its_action() {
420        assert_eq!(
421            translate(&key(KeyCode::Down, KeyEventKind::Repeat)),
422            Some(Event::Action(Action::Down)),
423            "holding Down keeps moving"
424        );
425    }
426
427    #[test]
428    fn a_key_coming_up_is_nothing() {
429        assert_eq!(
430            translate(&key(KeyCode::Char('q'), KeyEventKind::Release)),
431            None,
432            "a terminal that reports releases must not act twice"
433        );
434    }
435
436    #[test]
437    fn an_unbound_key_is_nothing() {
438        assert_eq!(
439            translate(&key(KeyCode::Char('x'), KeyEventKind::Press)),
440            None,
441            "x is not bound"
442        );
443    }
444
445    #[test]
446    fn a_resize_carries_the_new_size() {
447        assert_eq!(
448            translate(&Input::Resize(132, 43)),
449            Some(Event::Resize(132, 43)),
450            "columns, then lines"
451        );
452    }
453
454    #[test]
455    fn focus_and_paste_are_nothing() {
456        assert_eq!(
457            translate(&Input::FocusGained),
458            None,
459            "focus changes nothing"
460        );
461        assert_eq!(
462            translate(&Input::Paste("q".to_owned())),
463            None,
464            "pasted text is not typed keys"
465        );
466    }
467
468    // The threads of the UI's requests: the exit ends and joins each.
469
470    use std::sync::{Arc, Condvar, Mutex};
471    use std::time::Instant;
472
473    use super::Requests;
474
475    /// How long a [`Held`] request waits for [`Api::close`] before it gives
476    /// up by itself, so that a test whose exit never closes it still ends.
477    const HELD_AT_MOST: Duration = Duration::from_secs(20);
478
479    /// A server whose key request answers only once the client is closed;
480    /// its other requests answer at once. It counts the requests begun.
481    #[derive(Default)]
482    struct Held {
483        state: Mutex<(bool, usize)>,
484        changed: Condvar,
485    }
486
487    impl Held {
488        fn begun(&self) -> usize {
489            self.state.lock().expect("the state").1
490        }
491
492        fn closed(&self) -> bool {
493            self.state.lock().expect("the state").0
494        }
495
496        fn begin(&self) {
497            self.state.lock().expect("the state").1 += 1;
498            self.changed.notify_all();
499        }
500
501        /// Waits until `n` requests have begun, at most 10 s.
502        fn wait_begun(&self, n: usize) {
503            let guard = self.state.lock().expect("the state");
504            let (guard, _) = self
505                .changed
506                .wait_timeout_while(guard, Duration::from_secs(10), |s| s.1 < n)
507                .expect("the state");
508            assert!(guard.1 >= n, "{n} requests began: {}", guard.1);
509        }
510    }
511
512    impl Api for Held {
513        fn key(&self) -> Result<KeyInfo, ApiError> {
514            self.begin();
515            let guard = self.state.lock().expect("the state");
516            let (guard, _) = self
517                .changed
518                .wait_timeout_while(guard, HELD_AT_MOST, |s| !s.0)
519                .expect("the state");
520            drop(guard);
521            Err(ApiError::Unreachable("closed".to_owned()))
522        }
523
524        fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
525            self.begin();
526            TwoVcons.page(None)
527        }
528
529        fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
530            self.begin();
531            Ok(Vec::new())
532        }
533
534        fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
535            self.begin();
536            Ok(String::new())
537        }
538
539        fn close(&self) {
540            self.state.lock().expect("the state").0 = true;
541            self.changed.notify_all();
542        }
543    }
544
545    /// Requests on `held`, with the inbox their answers reach.
546    fn requests(held: &Arc<Held>) -> (Requests, mpsc::Receiver<Event>) {
547        let (answers, inbox) = mpsc::channel();
548        let api: Arc<dyn Api> = held.clone();
549        (Requests::new(api, answers), inbox)
550    }
551
552    // Success.
553
554    #[test]
555    fn finish_ends_a_request_under_way_and_joins_its_thread() {
556        let held = Arc::new(Held::default());
557        let (mut running, _inbox) = requests(&held);
558        running.send(vec![Effect::FetchKey]);
559        held.wait_begun(1);
560        let began = Instant::now();
561        running.finish();
562        assert!(held.closed(), "the exit closed the client");
563        assert!(
564            began.elapsed() < Duration::from_secs(10),
565            "the request ended when the client closed: {:?}",
566            began.elapsed()
567        );
568        assert_eq!(
569            Arc::strong_count(&held),
570            1,
571            "every request's thread has ended and dropped its clone of the client"
572        );
573    }
574
575    #[test]
576    fn finish_joins_requests_that_have_answered() {
577        let held = Arc::new(Held::default());
578        let (mut running, inbox) = requests(&held);
579        running.send(vec![Effect::FetchPage(None), Effect::FetchPage(None)]);
580        for _ in 0..2 {
581            let answer = inbox
582                .recv_timeout(Duration::from_secs(10))
583                .expect("an answer");
584            assert!(matches!(answer, Event::Page(Ok(_))), "a page: {answer:?}");
585        }
586        running.finish();
587        assert_eq!(
588            Arc::strong_count(&held),
589            1,
590            "no request's thread holds the client"
591        );
592    }
593
594    #[test]
595    fn each_request_answers_to_the_inbox() {
596        let held = Arc::new(Held::default());
597        let (mut running, inbox) = requests(&held);
598        running.send(vec![Effect::FetchPage(None)]);
599        let answer = inbox
600            .recv_timeout(Duration::from_secs(10))
601            .expect("an answer");
602        assert!(matches!(answer, Event::Page(Ok(_))), "a page: {answer:?}");
603        running.finish();
604    }
605
606    // Failure.
607
608    #[test]
609    fn finish_ends_requests_whose_inbox_is_gone() {
610        // The UI has quit and dropped its inbox: the answers have no reader.
611        let held = Arc::new(Held::default());
612        let (mut running, inbox) = requests(&held);
613        drop(inbox);
614        running.send(vec![Effect::FetchKey, Effect::FetchPage(None)]);
615        held.wait_begun(2);
616        running.finish();
617        assert_eq!(
618            Arc::strong_count(&held),
619            1,
620            "every thread ended though no one read its answer"
621        );
622    }
623
624    #[test]
625    fn finish_ends_several_requests_under_way_together() {
626        let held = Arc::new(Held::default());
627        let (mut running, _inbox) = requests(&held);
628        running.send(vec![Effect::FetchKey, Effect::FetchKey, Effect::FetchKey]);
629        held.wait_begun(3);
630        let began = Instant::now();
631        running.finish();
632        assert!(
633            began.elapsed() < Duration::from_secs(10),
634            "one close ended them all: {:?}",
635            began.elapsed()
636        );
637        assert_eq!(Arc::strong_count(&held), 1, "all three threads ended");
638    }
639
640    // Edge.
641
642    #[test]
643    fn finish_with_no_request_closes_the_client() {
644        let held = Arc::new(Held::default());
645        let (running, _inbox) = requests(&held);
646        running.finish();
647        assert!(held.closed(), "closed");
648        assert_eq!(Arc::strong_count(&held), 1, "nothing holds the client");
649    }
650
651    #[test]
652    fn send_joins_the_threads_of_requests_that_have_ended() {
653        // A long session sends many requests: the ended ones are joined as
654        // it goes, so their handles do not pile up until the exit.
655        let held = Arc::new(Held::default());
656        let (mut running, inbox) = requests(&held);
657        running.send(vec![Effect::FetchPage(None); 3]);
658        for _ in 0..3 {
659            inbox
660                .recv_timeout(Duration::from_secs(10))
661                .expect("an answer");
662        }
663        let deadline = Instant::now() + Duration::from_secs(10);
664        while !running.all_ended() {
665            assert!(Instant::now() < deadline, "the three threads end");
666            std::thread::yield_now();
667        }
668        running.send(vec![Effect::FetchPage(None)]);
669        assert!(
670            running.under_way() <= 1,
671            "the three ended threads were joined: {} kept",
672            running.under_way()
673        );
674        running.finish();
675    }
676
677    #[test]
678    fn an_empty_send_starts_no_thread() {
679        let held = Arc::new(Held::default());
680        let (mut running, _inbox) = requests(&held);
681        running.send(Vec::new());
682        assert_eq!(running.under_way(), 0, "no thread");
683        assert_eq!(held.begun(), 0, "no request");
684        running.finish();
685    }
686}