Skip to main content

rpi_cli/
extras.rs

1//! First-launch setup banner — thin host wrapper over the rpi-tui components.
2//!
3//! Kept out of the library crate so rpi-tui stays cli-free (project constraint).
4
5use std::sync::Arc;
6
7use rpi_tui::Container;
8
9use crate::config;
10
11/// Path of the "first-time setup done" sentinel, under the agent dir
12/// (`~/.rpi/agent/.setup_done`).
13pub fn setup_done_path() -> Option<std::path::PathBuf> {
14    config::agent_dir().ok().map(|d| d.join(".setup_done"))
15}
16
17/// Whether first-time setup has already been completed (sentinel present).
18pub fn setup_done() -> bool {
19    setup_done_path().map(|p| p.exists()).unwrap_or(false)
20}
21
22/// Mark first-time setup complete (write the sentinel). Best-effort.
23pub fn mark_setup_done() -> std::io::Result<()> {
24    let path = setup_done_path().ok_or_else(|| {
25        std::io::Error::new(std::io::ErrorKind::NotFound, "no home dir for .rpi/agent")
26    })?;
27    if let Some(parent) = path.parent() {
28        std::fs::create_dir_all(parent)?;
29    }
30    std::fs::write(&path, b"1")
31}
32
33/// If first-time setup hasn't run yet, show a brief setup note in the chat
34/// container. Returns `true` if anything was shown.
35pub fn maybe_first_time_setup(chat: &Arc<Container>) -> bool {
36    use rpi_tui::{DynamicBorder, Spacer, Text};
37    if setup_done() {
38        return false;
39    }
40    let accent = rpi_tui::theme().colors.accent;
41    let muted = rpi_tui::theme().colors.muted;
42    chat.add_child(Arc::new(DynamicBorder::with_color(accent)));
43    let lines = [
44        accent.fg(&bold("Welcome to rpi!")),
45        muted.fg("Pick a theme with /theme (dark/light/monochrome)."),
46        muted.fg("Type /help for commands."),
47    ];
48    for line in lines {
49        chat.add_child(Arc::new(Text::new(line, 1, 0)));
50    }
51    chat.add_child(Arc::new(DynamicBorder::with_color(accent)));
52    chat.add_child(Arc::new(Spacer::new(1)));
53    let _ = mark_setup_done();
54    true
55}
56
57fn bold(s: &str) -> String {
58    format!("\x1b[1m{s}\x1b[22m")
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use rpi_tui::{strip_ansi, visible_width, Component};
65
66    struct TempAgentDir {
67        _guard: std::sync::MutexGuard<'static, ()>,
68        tmp: tempfile::TempDir,
69        prev: Option<std::ffi::OsString>,
70    }
71
72    impl TempAgentDir {
73        fn new() -> Self {
74            let guard = crate::config::test_support::env_lock()
75                .lock()
76                .unwrap_or_else(|e| e.into_inner());
77            let prev = std::env::var_os(crate::config::CONFIG_DIR_ENV);
78            let tmp = tempfile::TempDir::new().unwrap();
79            std::env::set_var(crate::config::CONFIG_DIR_ENV, tmp.path());
80            Self {
81                _guard: guard,
82                tmp,
83                prev,
84            }
85        }
86
87        fn path(&self) -> &std::path::Path {
88            self.tmp.path()
89        }
90    }
91
92    impl Drop for TempAgentDir {
93        fn drop(&mut self) {
94            match self.prev.take() {
95                Some(v) => std::env::set_var(crate::config::CONFIG_DIR_ENV, v),
96                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
97            }
98        }
99    }
100
101    #[test]
102    fn test_sentinel_paths_under_agent_dir() {
103        // The sentinel lives directly under the resolved agent dir and honors
104        // the `RPI_CODING_AGENT_DIR` override (delegated to `config::agent_dir`).
105        let env = TempAgentDir::new();
106        let agent = crate::config::agent_dir().unwrap();
107        assert_eq!(agent.as_path(), env.path());
108        if let Some(p) = setup_done_path() {
109            assert!(p.ends_with(".setup_done"));
110            assert_eq!(p.parent().unwrap(), agent);
111        }
112    }
113
114    #[test]
115    fn test_first_time_setup_renders_cleanly_across_widths() {
116        let env = TempAgentDir::new();
117        let chat = Arc::new(Container::new());
118
119        assert!(maybe_first_time_setup(&chat));
120        assert!(env.path().join(".setup_done").exists());
121
122        for width in [60, 80, 120] {
123            let rendered = chat.render(width);
124            assert_eq!(
125                rendered.len(),
126                6,
127                "expected top border + 3 text lines + bottom border + 1 spacer at width {width}"
128            );
129
130            for (idx, line) in rendered.iter().enumerate() {
131                let w = visible_width(line);
132                assert!(
133                    w <= width,
134                    "line {idx} exceeded width {width} (visible_width={w}): {line:?}"
135                );
136            }
137
138            let expected_border = "─".repeat(width);
139            assert_eq!(strip_ansi(&rendered[0]), expected_border);
140            assert_eq!(strip_ansi(&rendered[4]), expected_border);
141
142            let plain_lines: Vec<String> = rendered.iter().map(|l| strip_ansi(l)).collect();
143            let plain = plain_lines.join("\n");
144            assert_eq!(plain.matches("Welcome to rpi!").count(), 1);
145            assert_eq!(plain.matches("Pick a theme with /theme").count(), 1);
146            assert_eq!(
147                plain
148                    .matches("Pick a theme with /theme (dark/light/monochrome).")
149                    .count(),
150                1
151            );
152            assert_eq!(plain.matches("Type /help for commands.").count(), 1);
153            assert!(rendered[1].contains("\x1b[1m"));
154        }
155    }
156
157    #[test]
158    fn test_first_time_setup_skips_when_sentinel_exists() {
159        let env = TempAgentDir::new();
160        std::fs::write(env.path().join(".setup_done"), b"1").unwrap();
161
162        let chat = Arc::new(Container::new());
163        assert!(!maybe_first_time_setup(&chat));
164        assert_eq!(chat.child_count(), 0);
165        assert!(chat.render(80).is_empty());
166    }
167}