zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Drawing the session. Every renderer reads `App` and nothing else.

mod account;
mod frame;
mod help;
mod mesh;
mod share;

use super::app::{App, Tab};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::Frame;

pub const MIN_W: u16 = 70;
pub const MIN_H: u16 = 18;
/// From this width the list and the detail sit side by side.
pub const SPLIT_W: u16 = 100;

/// zakuro-ai.com's tokens (`src/ui.rs` holds the CLI's copy of the same).
pub(crate) const SEED: Color = Color::Rgb(0xE0, 0x71, 0x8C);
pub(crate) const URI: Color = Color::Rgb(0x9B, 0xD4, 0x8F);
pub(crate) const NUM: Color = Color::Rgb(0xE8, 0xC4, 0x68);
pub(crate) const LIVE: Color = Color::Rgb(0x6F, 0xCF, 0x7F);
pub(crate) const WARN: Color = Color::Rgb(0xE8, 0xA8, 0x4F);
pub(crate) const INK3: Color = Color::Rgb(0x9A, 0x8E, 0x8B);
pub(crate) const LINE: Color = Color::Rgb(0x4A, 0x3E, 0x3C);

/// A foreground colour, or none under `NO_COLOR`.
pub(crate) fn fg(c: Color) -> Style {
    match std::env::var_os("NO_COLOR") {
        Some(_) => Style::default(),
        None => Style::default().fg(c),
    }
}

/// The selected row: a quiet band, or reverse video without colour.
pub(crate) fn selected() -> Style {
    match std::env::var_os("NO_COLOR") {
        Some(_) => Style::default().add_modifier(Modifier::REVERSED),
        None => Style::default().bg(LINE).add_modifier(Modifier::BOLD),
    }
}

pub(crate) const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

pub(crate) fn spinner(app: &App) -> &'static str {
    // One frame per four 25 ms ticks: the same 10 frames a second the
    // spinner always had.
    SPINNER[(app.ticks as usize / 4) % SPINNER.len()]
}

/// `r` centred in `area`, `w`×`h` at most.
pub(crate) fn centered(area: Rect, w: u16, h: u16) -> Rect {
    let w = w.min(area.width);
    let h = h.min(area.height);
    Rect::new(
        area.x + (area.width - w) / 2,
        area.y + (area.height - h) / 2,
        w,
        h,
    )
}

pub fn draw(f: &mut Frame, app: &App) {
    let area = f.area();
    if area.width < MIN_W || area.height < MIN_H {
        frame::too_small(f, area);
        return;
    }
    let [top, tabs, body, status, footer] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .areas(area);
    frame::top_bar(f, top, app);
    frame::tabs(f, tabs, app);
    match app.tab {
        Tab::Mesh => mesh::render(f, body, app),
        Tab::Account => account::render(f, body, app),
        Tab::Share => share::render(f, body, app),
    }
    frame::status_line(f, status, app);
    frame::footer(f, footer, app);
    if app.help {
        help::render(f, area);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::app::tests::{mesh, summary};
    use crate::session::app::{update, AgentState, App, Event, Key, Tab};
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn screen(app: &App, w: u16, h: u16) -> Vec<String> {
        let mut t = Terminal::new(TestBackend::new(w, h)).unwrap();
        t.draw(|f| draw(f, app)).unwrap();
        let b = t.backend().buffer().clone();
        (0..h)
            .map(|y| {
                (0..w)
                    .map(|x| b[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect()
    }
    fn has(lines: &[String], needle: &str) -> bool {
        lines.iter().any(|l| l.contains(needle))
    }
    fn loaded() -> App {
        let mut a = App::new();
        update(&mut a, Event::Mesh(mesh()));
        update(
            &mut a,
            Event::Agent(AgentState::Running(Box::new(summary()))),
        );
        a
    }

    #[test]
    fn too_small_terminal_shows_message() {
        let s = screen(&loaded(), 60, 16);
        assert!(has(&s, "terminal too small (70×18 needed)"), "{s:#?}");
    }

    #[test]
    fn the_frame_shows_status_tabs_and_footer() {
        let s = screen(&loaded(), 120, 30);
        assert!(has(&s, "● connected"), "{s:#?}");
        assert!(has(&s, "¥1,241"), "{s:#?}");
        assert!(has(&s, "1 Mesh") && has(&s, "2 Account") && has(&s, "3 Share"));
        assert!(has(&s, "c copy zc://"), "mesh footer: {s:#?}");
        assert!(
            has(&s, "uv is not installed — brew install uv"),
            "problems line: {s:#?}"
        );
    }

    #[test]
    fn the_mesh_list_shows_nodes_then_workers_when_expanded() {
        let mut a = loaded();
        update(&mut a, Event::Key(Key::Enter));
        let s = screen(&a, 120, 30);
        assert!(has(&s, "i9"), "{s:#?}");
        assert!(has(&s, "w0") && has(&s, "ready"), "{s:#?}");
        assert!(has(&s, "zc://node-aaaa"), "detail pane: {s:#?}");
    }

    /// At the 45% split the list still shows whole names and statuses;
    /// the address lives in the detail pane, where there is room for it.
    #[test]
    fn mesh_rows_keep_full_names_and_statuses_at_the_split() {
        use crate::session::model::{MeshNode, MeshSnapshot, MeshWorker};
        let w = MeshWorker::from_json(
            &serde_json::json!({"name": "worker-zc-worker-cloudcompute-1",
            "status": "healthy", "cpus_total": 8.0, "price_per_hour": 3.6}),
        );
        let mut a = App::new();
        update(
            &mut a,
            Event::Mesh(MeshSnapshot {
                nodes: vec![
                    MeshNode {
                        fp: "5ac52d6d47f53d47".into(),
                        name: Some("zc-worker-cloudcompute-1".into()),
                        is_self: false,
                        workers: vec![w],
                    },
                    MeshNode {
                        fp: "3156686e7666c088".into(),
                        name: Some("zc-broker-0".into()),
                        is_self: false,
                        workers: vec![],
                    },
                ],
                ..Default::default()
            }),
        );
        update(&mut a, Event::Key(Key::Enter));
        let s = screen(&a, 120, 30);
        assert!(has(&s, "▾ zc-worker-cloudcompute-1"), "{s:#?}");
        assert!(has(&s, "1 worker"), "{s:#?}");
        assert!(
            !has(&s, "zc-broker-0"),
            "a node without workers is listed: {s:#?}"
        );
        assert!(has(&s, "ready"), "{s:#?}");
    }

    #[test]
    fn narrow_mesh_has_no_detail_pane_until_asked() {
        let mut a = loaded();
        let s = screen(&a, 80, 24);
        assert!(!has(&s, "Address"), "{s:#?}");
        update(&mut a, Event::Key(Key::Enter));
        update(&mut a, Event::Key(Key::Down));
        update(&mut a, Event::Key(Key::Enter));
        let s = screen(&a, 80, 24);
        assert!(has(&s, "Address"), "overlay: {s:#?}");
    }

    #[test]
    fn share_shows_state_and_the_price_editor() {
        let mut a = loaded();
        a.tab = Tab::Share;
        let s = screen(&a, 120, 30);
        assert!(has(&s, "Sharing") && has(&s, "on"), "{s:#?}");
        assert!(has(&s, "2 of 5"), "workers desired of max: {s:#?}");
        update(&mut a, Event::Key(Key::Char('p')));
        let s = screen(&a, 120, 30);
        assert!(has(&s, "[ 18 ]") && has(&s, "1–120"), "{s:#?}");
    }

    #[test]
    fn a_pending_write_shows_applying() {
        let mut a = loaded();
        a.tab = Tab::Share;
        update(&mut a, Event::Key(Key::Char(' ')));
        assert!(has(&screen(&a, 120, 30), "applying"));
    }

    #[test]
    fn without_an_agent_account_says_how_to_start_it() {
        let mut a = App::new();
        update(&mut a, Event::Agent(AgentState::NotRunning(None)));
        a.tab = Tab::Account;
        let s = screen(&a, 120, 30);
        assert!(has(&s, "zc agent is not running"), "{s:#?}");
        assert!(has(&s, "press a"), "{s:#?}");
    }

    /// Every help row keeps a gap between the key and what it does.
    #[test]
    fn help_rows_never_run_the_key_into_its_description() {
        let mut a = loaded();
        update(&mut a, Event::Key(Key::Char('?')));
        let s = screen(&a, 120, 34);
        let row = s
            .iter()
            .find(|l| l.contains(":login"))
            .expect("external commands listed");
        assert!(row.contains(":login  "), "{row}");
        assert!(has(&s, "outside the session"), "{s:#?}");
    }

    #[test]
    fn the_command_bar_and_help_render() {
        let mut a = loaded();
        update(&mut a, Event::Key(Key::Char(':')));
        update(&mut a, Event::Key(Key::Char('p')));
        assert!(has(&screen(&a, 120, 30), "> p"));
        update(&mut a, Event::Key(Key::Esc));
        update(&mut a, Event::Key(Key::Char('?')));
        let s = screen(&a, 120, 30);
        assert!(has(&s, "Keys") && has(&s, ":price <n>"), "{s:#?}");
    }
}