zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc` with no arguments, in a terminal: a full-screen session over the
//! mesh, the account and this machine's sharing
//! (docs/superpowers/specs/2026-10-02-zc-session-design.md).
//!
//! The terminal is the alternate screen for the session's lifetime and is
//! restored on every way out: quit, Ctrl-C, or a panic (`ratatui::init`
//! installs the hook). One line goes to the normal scrollback afterwards
//! if anything was changed.

pub mod app;
pub mod clip;
pub mod command;
pub mod data;
pub mod model;
pub mod view;

use app::{update, App, Effect, Event, Key};
use crossterm::event::{self as ct, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::DefaultTerminal;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;

/// How long the loop waits for a key before it looks at data events again.
/// Data arrives on a channel the key poll cannot wake on, so this is also
/// the latency between a snapshot arriving and it being drawn.
const TICK: Duration = Duration::from_millis(25);

/// Bare `zc`, on a terminal, with nobody asking for plain output.
pub fn should_open(args_len: usize, stdout_tty: bool, plain: bool, term: Option<&str>) -> bool {
    args_len == 1 && stdout_tty && !plain && term != Some("dumb")
}

pub fn map_key(k: KeyEvent) -> Option<Key> {
    Some(match k.code {
        KeyCode::Char('c') if k.modifiers.contains(KeyModifiers::CONTROL) => Key::CtrlC,
        KeyCode::Char(c) => Key::Char(c),
        KeyCode::Enter => Key::Enter,
        KeyCode::Esc => Key::Esc,
        KeyCode::Tab => Key::Tab,
        KeyCode::BackTab => Key::BackTab,
        KeyCode::Up => Key::Up,
        KeyCode::Down => Key::Down,
        KeyCode::PageUp => Key::PageUp,
        KeyCode::PageDown => Key::PageDown,
        KeyCode::Home => Key::Home,
        KeyCode::End => Key::End,
        KeyCode::Left => Key::Left,
        KeyCode::Right => Key::Right,
        KeyCode::Backspace => Key::Backspace,
        _ => return None,
    })
}

pub fn run() -> i32 {
    let (tx, rx) = std::sync::mpsc::channel::<Event>();
    let dir = data::agent_dir();
    let pollers = data::spawn_pollers(tx.clone(), dir.clone());
    let mut app = App::new();
    let mut terminal = ratatui::init();
    let code = event_loop(&mut terminal, &mut app, &rx, &tx, &pollers, dir);
    ratatui::restore();
    if let Some(line) = app::exit_summary(&app) {
        println!("{line}");
    }
    code
}

fn event_loop(
    terminal: &mut DefaultTerminal,
    app: &mut App,
    rx: &Receiver<Event>,
    tx: &Sender<Event>,
    pollers: &data::Pollers,
    dir: Option<std::path::PathBuf>,
) -> i32 {
    loop {
        if terminal.draw(|f| view::draw(f, app)).is_err() {
            return 1;
        }
        while let Ok(ev) = rx.try_recv() {
            let effects = update(app, ev);
            run_effects(effects, terminal, tx, pollers, &dir);
        }
        if app.quit {
            return 0;
        }
        let ev = match ct::poll(TICK) {
            Ok(true) => match ct::read() {
                Ok(ct::Event::Key(k)) if k.kind == KeyEventKind::Press => {
                    map_key(k).map(Event::Key)
                }
                Ok(_) => None,
                Err(_) => return 1,
            },
            Ok(false) => Some(Event::Tick),
            Err(_) => return 1,
        };
        if let Some(ev) = ev {
            let effects = update(app, ev);
            run_effects(effects, terminal, tx, pollers, &dir);
        }
        if app.quit {
            return 0;
        }
    }
}

fn run_effects(
    effects: Vec<Effect>,
    terminal: &mut DefaultTerminal,
    tx: &Sender<Event>,
    pollers: &data::Pollers,
    dir: &Option<std::path::PathBuf>,
) {
    for e in effects {
        match e {
            Effect::Copy(text) => {
                let via = clip::copy(&text);
                let _ = tx.send(Event::Note(format!("copied {text} to the {via}")));
            }
            Effect::OpenUrl(url) => {
                let opener = if cfg!(target_os = "macos") {
                    "open"
                } else {
                    "xdg-open"
                };
                let ok = std::process::Command::new(opener)
                    .arg(&url)
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .spawn()
                    .is_ok();
                let note = if ok {
                    format!("opened {url}")
                } else {
                    format!("could not open {url}")
                };
                let _ = tx.send(Event::Note(note));
            }
            Effect::Suspend(args) => {
                suspend(terminal, &args);
                pollers.refresh_mesh();
                data::execute(Effect::RefreshAgent, tx, pollers, dir.clone());
            }
            other => data::execute(other, tx, pollers, dir.clone()),
        }
    }
}

/// Run `cmd` in the foreground while this process ignores SIGINT, so a
/// Ctrl-C at the child's prompt stops the child and not the session (what
/// a shell does for its foreground job). The handler is set after the
/// spawn: a child inheriting SIG_IGN could not be interrupted at all.
fn run_ignoring_sigint(
    mut cmd: std::process::Command,
) -> std::io::Result<std::process::ExitStatus> {
    let mut child = cmd.spawn()?;
    // SAFETY: swapping a signal disposition and restoring the previous one;
    // no handler code runs.
    let previous = unsafe { libc::signal(libc::SIGINT, libc::SIG_IGN) };
    let status = child.wait();
    unsafe { libc::signal(libc::SIGINT, previous) };
    status
}

/// Block until a key press, or until the terminal can no longer be read.
fn wait_for_key(mut read: impl FnMut() -> std::io::Result<ct::Event>) {
    loop {
        match read() {
            Ok(ct::Event::Key(k)) if k.kind == KeyEventKind::Press => return,
            Ok(_) => {}
            Err(_) => return,
        }
    }
}

/// Hand the terminal to `zc <args…>` (sudo prompts, progress output and
/// all), then take it back after a key.
fn suspend(terminal: &mut DefaultTerminal, args: &[String]) {
    ratatui::restore();
    println!("\n$ zc {}", args.join(" "));
    let status = std::env::current_exe()
        .map_err(|e| e.to_string())
        .and_then(|exe| {
            let mut cmd = std::process::Command::new(exe);
            cmd.args(args);
            run_ignoring_sigint(cmd).map_err(|e| e.to_string())
        });
    match status {
        Ok(s) if s.success() => println!("\n✓ done — press any key to return to zc"),
        Ok(s) => println!(
            "\n✗ exited {} — press any key to return to zc",
            s.code().unwrap_or(1)
        ),
        Err(e) => println!("\n✗ {e} — press any key to return to zc"),
    }
    let _ = crossterm::terminal::enable_raw_mode();
    wait_for_key(ct::read);
    let _ = crossterm::terminal::disable_raw_mode();
    *terminal = ratatui::init();
    // A fresh terminal assumes a blank screen and draws only non-blank
    // cells; clear it so nothing of the command's output shows through.
    let _ = terminal.clear();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    #[test]
    fn opens_only_for_bare_zc_on_a_real_terminal() {
        assert!(should_open(1, true, false, Some("xterm-256color")));
        assert!(should_open(1, true, false, None));
        assert!(
            !should_open(2, true, false, None),
            "any argument: a one-shot command"
        );
        assert!(!should_open(1, false, false, None), "piped: help");
        assert!(!should_open(1, true, true, None), "ZC_PLAIN");
        assert!(!should_open(1, true, false, Some("dumb")));
    }

    /// Ctrl-C at a prompt in a suspended command reaches the command, not
    /// the session: the parent ignores SIGINT while it waits.
    #[test]
    fn a_child_interrupting_its_parent_does_not_kill_the_session() {
        let mut cmd = std::process::Command::new("sh");
        cmd.args(["-c", "kill -INT $PPID; sleep 0.2; exit 3"]);
        let status = run_ignoring_sigint(cmd).unwrap();
        assert_eq!(status.code(), Some(3));
    }

    /// A terminal that errors or closes while we wait for a key ends the
    /// wait instead of spinning.
    #[test]
    fn waiting_for_a_key_stops_on_a_read_error() {
        let mut calls = 0;
        wait_for_key(|| {
            calls += 1;
            Err(std::io::Error::other("tty gone"))
        });
        assert_eq!(calls, 1);
    }

    #[test]
    fn keys_map_including_ctrl_c_and_backtab() {
        let k = |c, m| map_key(KeyEvent::new(c, m));
        assert_eq!(
            k(KeyCode::Char('c'), KeyModifiers::CONTROL),
            Some(app::Key::CtrlC)
        );
        assert_eq!(
            k(KeyCode::Char('c'), KeyModifiers::NONE),
            Some(app::Key::Char('c'))
        );
        assert_eq!(
            k(KeyCode::BackTab, KeyModifiers::SHIFT),
            Some(app::Key::BackTab)
        );
        assert_eq!(k(KeyCode::F(5), KeyModifiers::NONE), None);
    }
}