rpi-cli 0.35.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
//! First-launch setup banner — thin host wrapper over the rpi-tui components.
//!
//! Kept out of the library crate so rpi-tui stays cli-free (project constraint).

use std::sync::Arc;

use rpi_tui::Container;

use crate::config;

/// Path of the "first-time setup done" sentinel, under the agent dir
/// (`~/.rpi/agent/.setup_done`).
pub fn setup_done_path() -> Option<std::path::PathBuf> {
    config::agent_dir().ok().map(|d| d.join(".setup_done"))
}

/// Whether first-time setup has already been completed (sentinel present).
pub fn setup_done() -> bool {
    setup_done_path().map(|p| p.exists()).unwrap_or(false)
}

/// Mark first-time setup complete (write the sentinel). Best-effort.
pub fn mark_setup_done() -> std::io::Result<()> {
    let path = setup_done_path().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotFound, "no home dir for .rpi/agent")
    })?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&path, b"1")
}

/// If first-time setup hasn't run yet, show a brief setup note in the chat
/// container. Returns `true` if anything was shown.
pub fn maybe_first_time_setup(chat: &Arc<Container>) -> bool {
    use rpi_tui::{DynamicBorder, Spacer, Text};
    if setup_done() {
        return false;
    }
    let accent = rpi_tui::theme().colors.accent;
    let muted = rpi_tui::theme().colors.muted;
    chat.add_child(Arc::new(DynamicBorder::with_color(accent)));
    let lines = [
        accent.fg(&bold("Welcome to rpi!")),
        muted.fg("Pick a theme with /theme (dark/light/monochrome)."),
        muted.fg("Type /help for commands."),
    ];
    for line in lines {
        chat.add_child(Arc::new(Text::new(line, 1, 0)));
    }
    chat.add_child(Arc::new(DynamicBorder::with_color(accent)));
    chat.add_child(Arc::new(Spacer::new(1)));
    let _ = mark_setup_done();
    true
}

fn bold(s: &str) -> String {
    format!("\x1b[1m{s}\x1b[22m")
}

#[cfg(test)]
mod tests {
    use super::*;
    use rpi_tui::{strip_ansi, visible_width, Component};

    struct TempAgentDir {
        _guard: std::sync::MutexGuard<'static, ()>,
        tmp: tempfile::TempDir,
        prev: Option<std::ffi::OsString>,
    }

    impl TempAgentDir {
        fn new() -> Self {
            let guard = crate::config::test_support::env_lock()
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let prev = std::env::var_os(crate::config::CONFIG_DIR_ENV);
            let tmp = tempfile::TempDir::new().unwrap();
            std::env::set_var(crate::config::CONFIG_DIR_ENV, tmp.path());
            Self {
                _guard: guard,
                tmp,
                prev,
            }
        }

        fn path(&self) -> &std::path::Path {
            self.tmp.path()
        }
    }

    impl Drop for TempAgentDir {
        fn drop(&mut self) {
            match self.prev.take() {
                Some(v) => std::env::set_var(crate::config::CONFIG_DIR_ENV, v),
                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
            }
        }
    }

    #[test]
    fn test_sentinel_paths_under_agent_dir() {
        // The sentinel lives directly under the resolved agent dir and honors
        // the `RPI_CODING_AGENT_DIR` override (delegated to `config::agent_dir`).
        let env = TempAgentDir::new();
        let agent = crate::config::agent_dir().unwrap();
        assert_eq!(agent.as_path(), env.path());
        if let Some(p) = setup_done_path() {
            assert!(p.ends_with(".setup_done"));
            assert_eq!(p.parent().unwrap(), agent);
        }
    }

    #[test]
    fn test_first_time_setup_renders_cleanly_across_widths() {
        let env = TempAgentDir::new();
        let chat = Arc::new(Container::new());

        assert!(maybe_first_time_setup(&chat));
        assert!(env.path().join(".setup_done").exists());

        for width in [60, 80, 120] {
            let rendered = chat.render(width);
            assert_eq!(
                rendered.len(),
                6,
                "expected top border + 3 text lines + bottom border + 1 spacer at width {width}"
            );

            for (idx, line) in rendered.iter().enumerate() {
                let w = visible_width(line);
                assert!(
                    w <= width,
                    "line {idx} exceeded width {width} (visible_width={w}): {line:?}"
                );
            }

            let expected_border = "─".repeat(width);
            assert_eq!(strip_ansi(&rendered[0]), expected_border);
            assert_eq!(strip_ansi(&rendered[4]), expected_border);

            let plain_lines: Vec<String> = rendered.iter().map(|l| strip_ansi(l)).collect();
            let plain = plain_lines.join("\n");
            assert_eq!(plain.matches("Welcome to rpi!").count(), 1);
            assert_eq!(plain.matches("Pick a theme with /theme").count(), 1);
            assert_eq!(
                plain
                    .matches("Pick a theme with /theme (dark/light/monochrome).")
                    .count(),
                1
            );
            assert_eq!(plain.matches("Type /help for commands.").count(), 1);
            assert!(rendered[1].contains("\x1b[1m"));
        }
    }

    #[test]
    fn test_first_time_setup_skips_when_sentinel_exists() {
        let env = TempAgentDir::new();
        std::fs::write(env.path().join(".setup_done"), b"1").unwrap();

        let chat = Arc::new(Container::new());
        assert!(!maybe_first_time_setup(&chat));
        assert_eq!(chat.child_count(), 0);
        assert!(chat.render(80).is_empty());
    }
}