pub mod client;
pub mod keys;
pub mod state;
pub mod view;
#[cfg(test)]
mod page_tests;
#[cfg(test)]
mod screens;
use std::io::IsTerminal;
use std::sync::Arc;
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::Duration;
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::crossterm::event::{self, Event as Input, KeyEventKind};
use time::OffsetDateTime;
use crate::mcp::stdio::ClientConfig;
use client::{Api, HttpApi};
use state::{Effect, Event, State};
use view::Theme;
const TICK: Duration = Duration::from_millis(100);
#[must_use]
pub fn translate(input: &Input) -> Option<Event> {
match input {
Input::Key(key) if key.kind != KeyEventKind::Release => {
keys::action(key.code, key.modifiers).map(Event::Action)
}
Input::Resize(columns, lines) => Some(Event::Resize(*columns, *lines)),
_ => None,
}
}
pub fn run(config: &ClientConfig) -> Result<(), String> {
require_terminal(
std::io::stdin().is_terminal(),
std::io::stdout().is_terminal(),
)?;
let api: Arc<dyn Api> = Arc::new(HttpApi::new(config)?);
let theme = view::theme(
std::env::var("NO_COLOR").ok().as_deref(),
std::env::var("TERM").ok().as_deref(),
);
with_terminal(|terminal| {
let (answers, inbox) = mpsc::channel();
let mut requests = Requests::new(Arc::clone(&api), answers);
let ended = drive(
terminal,
&client::base(&config.url),
theme,
&mut Keyboard,
&inbox,
&mut |effects: Vec<Effect>| requests.send(effects),
&OffsetDateTime::now_utc,
);
requests.finish();
ended.map(|_| ())
})?
}
pub fn with_terminal<T>(
body: impl FnOnce(&mut ratatui::DefaultTerminal) -> T,
) -> Result<T, String> {
let mut terminal = ratatui::try_init().map_err(|e| format!("the terminal: {e}"))?;
let value = body(&mut terminal);
ratatui::restore();
Ok(value)
}
pub fn require_terminal(input: bool, output: bool) -> Result<(), String> {
let what = match (input, output) {
(true, true) => return Ok(()),
(false, true) => "standard input is not one",
(true, false) => "standard output is not one",
(false, false) => "standard input and standard output are not one",
};
Err(format!(
"a terminal is required: {what}; run it in a terminal, not through a pipe, a redirect or a job without one"
))
}
pub trait Inputs {
fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>>;
}
struct Keyboard;
impl Inputs for Keyboard {
fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>> {
if event::poll(wait)? {
event::read().map(Some)
} else {
Ok(None)
}
}
}
pub fn drive<B: Backend>(
terminal: &mut Terminal<B>,
server: &str,
theme: Theme,
inputs: &mut dyn Inputs,
inbox: &Receiver<Event>,
dispatch: &mut dyn FnMut(Vec<Effect>),
now: &dyn Fn() -> OffsetDateTime,
) -> Result<State, String> {
let size = terminal.size().map_err(|e| format!("the terminal: {e}"))?;
let (mut state, first) = State::new(server, (size.width, size.height));
dispatch(first);
while !state.quit {
while let Ok(event) = inbox.try_recv() {
dispatch(state.step(event, now()));
}
terminal
.draw(|frame| view::draw(frame, &state, theme))
.map_err(|e| format!("the terminal: {e}"))?;
let input = inputs
.next(TICK)
.map_err(|e| format!("the terminal: {e}"))?;
if let Some(event) = input.as_ref().and_then(translate) {
dispatch(state.step(event, now()));
}
}
Ok(state)
}
struct Requests {
api: Arc<dyn Api>,
answers: Sender<Event>,
running: Vec<std::thread::JoinHandle<()>>,
}
impl Requests {
fn new(api: Arc<dyn Api>, answers: Sender<Event>) -> Self {
Self {
api,
answers,
running: Vec::new(),
}
}
fn send(&mut self, effects: Vec<Effect>) {
let (ended, running): (Vec<_>, Vec<_>) = std::mem::take(&mut self.running)
.into_iter()
.partition(std::thread::JoinHandle::is_finished);
self.running = running;
for handle in ended {
drop(handle.join());
}
for effect in effects {
let api = Arc::clone(&self.api);
let answers = self.answers.clone();
self.running.push(std::thread::spawn(move || {
drop(answers.send(client::perform(api.as_ref(), &effect)));
}));
}
}
fn finish(self) {
self.api.close();
for handle in self.running {
drop(handle.join());
}
}
#[cfg(test)]
fn under_way(&self) -> usize {
self.running.len()
}
#[cfg(test)]
fn all_ended(&self) -> bool {
self.running
.iter()
.all(std::thread::JoinHandle::is_finished)
}
}
#[cfg(test)]
mod tests {
use ratatui::crossterm::event::{
Event as Input, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
};
use std::collections::VecDeque;
use std::sync::mpsc;
use std::time::Duration;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use time::OffsetDateTime;
use time::macros::datetime;
use super::client::{self, Api};
use super::state::{Action, ApiError, Effect, Event, KeyInfo, Page, Row, State, View};
use super::view::Theme;
use super::{Inputs, drive, translate};
const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
fn row(n: u8) -> Row {
Row {
uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
stored_at: "2026-10-25T12:00:00Z".to_owned(),
updated_at: "2026-10-25T12:30:00Z".to_owned(),
version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
}
}
struct TwoVcons;
impl Api for TwoVcons {
fn key(&self) -> Result<KeyInfo, ApiError> {
Ok(KeyInfo {
id: "0123456789abcdef".to_owned(),
tenant: Some("t_example".to_owned()),
scopes: vec!["read".to_owned()],
})
}
fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
Ok(Page {
vcons: vec![row(0), row(1)],
next: None,
})
}
fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
Ok(vec!["Masked view".to_owned()])
}
fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
Ok("{}".to_owned())
}
}
struct Script(VecDeque<KeyCode>);
impl Inputs for Script {
fn next(&mut self, _wait: Duration) -> std::io::Result<Option<Input>> {
let code = self
.0
.pop_front()
.ok_or_else(|| std::io::Error::other("the script ended"))?;
Ok(Some(key(code, KeyEventKind::Press)))
}
}
fn driven(keys: &[KeyCode]) -> (Result<State, String>, String) {
let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("a terminal");
let (answers, inbox) = mpsc::channel();
let mut dispatch = |effects: Vec<Effect>| {
for effect in effects {
answers
.send(client::perform(&TwoVcons, &effect))
.expect("the loop holds the receiver");
}
};
let result = drive(
&mut terminal,
"https://vcon.example.com:8443",
Theme { color: false },
&mut Script(keys.iter().copied().collect()),
&inbox,
&mut dispatch,
&|| NOW,
);
let buffer = terminal.backend().buffer();
let frame = buffer
.content()
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect();
(result, frame)
}
#[test]
fn the_loop_applies_answers_and_keys_in_order_and_ends_on_quit() {
let (result, frame) = driven(&[KeyCode::Down, KeyCode::Enter, KeyCode::Char('q')]);
let state = result.expect("the loop ends on q");
assert_eq!(state.view, View::Detail, "Enter opened the detail view");
assert_eq!(
state.detail,
Some(row(1).uuid),
"both answers were applied before Down, so Down moved to the second vCon"
);
assert!(
frame.contains(&format!("vCon {}", row(1).uuid)),
"the last frame drawn is the detail view: {frame}"
);
}
fn key(code: KeyCode, kind: KeyEventKind) -> Input {
Input::Key(KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind))
}
#[test]
fn the_loop_stops_with_the_terminals_error_when_input_fails() {
let (result, _) = driven(&[KeyCode::Down]);
assert_eq!(
result,
Err("the terminal: the script ended".to_owned()),
"the error is returned, with what it is about"
);
}
#[test]
fn the_loop_stamps_answers_with_the_clock_it_is_given() {
let (result, _) = driven(&[KeyCode::Char('q')]);
assert_eq!(
result.expect("the loop ends on q").as_of,
Some(NOW),
"the list was read at the time the clock said"
);
}
#[test]
fn a_bound_key_going_down_is_its_action() {
assert_eq!(
translate(&key(KeyCode::Char('q'), KeyEventKind::Press)),
Some(Event::Action(Action::Quit)),
"q quits"
);
}
#[test]
fn a_held_key_repeats_its_action() {
assert_eq!(
translate(&key(KeyCode::Down, KeyEventKind::Repeat)),
Some(Event::Action(Action::Down)),
"holding Down keeps moving"
);
}
#[test]
fn a_key_coming_up_is_nothing() {
assert_eq!(
translate(&key(KeyCode::Char('q'), KeyEventKind::Release)),
None,
"a terminal that reports releases must not act twice"
);
}
#[test]
fn an_unbound_key_is_nothing() {
assert_eq!(
translate(&key(KeyCode::Char('x'), KeyEventKind::Press)),
None,
"x is not bound"
);
}
#[test]
fn a_resize_carries_the_new_size() {
assert_eq!(
translate(&Input::Resize(132, 43)),
Some(Event::Resize(132, 43)),
"columns, then lines"
);
}
#[test]
fn focus_and_paste_are_nothing() {
assert_eq!(
translate(&Input::FocusGained),
None,
"focus changes nothing"
);
assert_eq!(
translate(&Input::Paste("q".to_owned())),
None,
"pasted text is not typed keys"
);
}
use std::sync::{Arc, Condvar, Mutex};
use std::time::Instant;
use super::Requests;
const HELD_AT_MOST: Duration = Duration::from_secs(20);
#[derive(Default)]
struct Held {
state: Mutex<(bool, usize)>,
changed: Condvar,
}
impl Held {
fn begun(&self) -> usize {
self.state.lock().expect("the state").1
}
fn closed(&self) -> bool {
self.state.lock().expect("the state").0
}
fn begin(&self) {
self.state.lock().expect("the state").1 += 1;
self.changed.notify_all();
}
fn wait_begun(&self, n: usize) {
let guard = self.state.lock().expect("the state");
let (guard, _) = self
.changed
.wait_timeout_while(guard, Duration::from_secs(10), |s| s.1 < n)
.expect("the state");
assert!(guard.1 >= n, "{n} requests began: {}", guard.1);
}
}
impl Api for Held {
fn key(&self) -> Result<KeyInfo, ApiError> {
self.begin();
let guard = self.state.lock().expect("the state");
let (guard, _) = self
.changed
.wait_timeout_while(guard, HELD_AT_MOST, |s| !s.0)
.expect("the state");
drop(guard);
Err(ApiError::Unreachable("closed".to_owned()))
}
fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
self.begin();
TwoVcons.page(None)
}
fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
self.begin();
Ok(Vec::new())
}
fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
self.begin();
Ok(String::new())
}
fn close(&self) {
self.state.lock().expect("the state").0 = true;
self.changed.notify_all();
}
}
fn requests(held: &Arc<Held>) -> (Requests, mpsc::Receiver<Event>) {
let (answers, inbox) = mpsc::channel();
let api: Arc<dyn Api> = held.clone();
(Requests::new(api, answers), inbox)
}
#[test]
fn finish_ends_a_request_under_way_and_joins_its_thread() {
let held = Arc::new(Held::default());
let (mut running, _inbox) = requests(&held);
running.send(vec![Effect::FetchKey]);
held.wait_begun(1);
let began = Instant::now();
running.finish();
assert!(held.closed(), "the exit closed the client");
assert!(
began.elapsed() < Duration::from_secs(10),
"the request ended when the client closed: {:?}",
began.elapsed()
);
assert_eq!(
Arc::strong_count(&held),
1,
"every request's thread has ended and dropped its clone of the client"
);
}
#[test]
fn finish_joins_requests_that_have_answered() {
let held = Arc::new(Held::default());
let (mut running, inbox) = requests(&held);
running.send(vec![Effect::FetchPage(None), Effect::FetchPage(None)]);
for _ in 0..2 {
let answer = inbox
.recv_timeout(Duration::from_secs(10))
.expect("an answer");
assert!(matches!(answer, Event::Page(Ok(_))), "a page: {answer:?}");
}
running.finish();
assert_eq!(
Arc::strong_count(&held),
1,
"no request's thread holds the client"
);
}
#[test]
fn each_request_answers_to_the_inbox() {
let held = Arc::new(Held::default());
let (mut running, inbox) = requests(&held);
running.send(vec![Effect::FetchPage(None)]);
let answer = inbox
.recv_timeout(Duration::from_secs(10))
.expect("an answer");
assert!(matches!(answer, Event::Page(Ok(_))), "a page: {answer:?}");
running.finish();
}
#[test]
fn finish_ends_requests_whose_inbox_is_gone() {
let held = Arc::new(Held::default());
let (mut running, inbox) = requests(&held);
drop(inbox);
running.send(vec![Effect::FetchKey, Effect::FetchPage(None)]);
held.wait_begun(2);
running.finish();
assert_eq!(
Arc::strong_count(&held),
1,
"every thread ended though no one read its answer"
);
}
#[test]
fn finish_ends_several_requests_under_way_together() {
let held = Arc::new(Held::default());
let (mut running, _inbox) = requests(&held);
running.send(vec![Effect::FetchKey, Effect::FetchKey, Effect::FetchKey]);
held.wait_begun(3);
let began = Instant::now();
running.finish();
assert!(
began.elapsed() < Duration::from_secs(10),
"one close ended them all: {:?}",
began.elapsed()
);
assert_eq!(Arc::strong_count(&held), 1, "all three threads ended");
}
#[test]
fn finish_with_no_request_closes_the_client() {
let held = Arc::new(Held::default());
let (running, _inbox) = requests(&held);
running.finish();
assert!(held.closed(), "closed");
assert_eq!(Arc::strong_count(&held), 1, "nothing holds the client");
}
#[test]
fn send_joins_the_threads_of_requests_that_have_ended() {
let held = Arc::new(Held::default());
let (mut running, inbox) = requests(&held);
running.send(vec![Effect::FetchPage(None); 3]);
for _ in 0..3 {
inbox
.recv_timeout(Duration::from_secs(10))
.expect("an answer");
}
let deadline = Instant::now() + Duration::from_secs(10);
while !running.all_ended() {
assert!(Instant::now() < deadline, "the three threads end");
std::thread::yield_now();
}
running.send(vec![Effect::FetchPage(None)]);
assert!(
running.under_way() <= 1,
"the three ended threads were joined: {} kept",
running.under_way()
);
running.finish();
}
#[test]
fn an_empty_send_starts_no_thread() {
let held = Arc::new(Held::default());
let (mut running, _inbox) = requests(&held);
running.send(Vec::new());
assert_eq!(running.under_way(), 0, "no thread");
assert_eq!(held.begun(), 0, "no request");
running.finish();
}
}