summaryrefslogtreecommitdiffstats
path: root/src/ui.rs
blob: 69e7aa967c8e33dbfd2a021f8f40062958819de0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use std::io::{IsTerminal, Write};
use std::sync::OnceLock;
use std::time::Duration;

use crate::provider::{Outcome, Sink};

pub fn stdout_is_tty() -> bool {
    std::io::stdout().is_terminal()
}

pub fn stdin_is_tty() -> bool {
    std::io::stdin().is_terminal()
}

fn color() -> bool {
    static COLOR: OnceLock<bool> = OnceLock::new();
    *COLOR.get_or_init(|| {
        stdout_is_tty()
            && std::env::var_os("NO_COLOR").is_none()
            && std::env::var("TERM")
                .map(|term| term != "dumb")
                .unwrap_or(true)
    })
}

fn paint(code: &str, text: &str) -> String {
    if color() {
        format!("\x1b[{code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

/// Streams to stdout. Colour is used only when stdout is a terminal, so piping
/// the output somewhere gives clean text.
pub struct Renderer {
    dimmed: bool,
    wrote_text: bool,
}

impl Renderer {
    pub fn new() -> Self {
        Self {
            dimmed: false,
            wrote_text: false,
        }
    }

    fn undim(&mut self) {
        if self.dimmed {
            print!("\x1b[0m");
            self.dimmed = false;
        }
    }
}

impl Sink for Renderer {
    fn text(&mut self, s: &str) {
        self.undim();
        print!("{s}");
        let _ = std::io::stdout().flush();
        self.wrote_text = true;
    }

    fn reasoning(&mut self, s: &str) {
        if !color() {
            return;
        }
        if !self.dimmed {
            print!("\x1b[2m");
            self.dimmed = true;
        }
        print!("{s}");
        let _ = std::io::stdout().flush();
    }

    fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) {
        self.undim();
        if self.wrote_text {
            println!();
            self.wrote_text = false;
        }
    }
}

pub fn tool_line(step: usize, name: &str, args: &serde_json::Value) {
    let detail = match name {
        "bash" => args
            .get("cmd")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "grep" => format!(
            "{} in {}",
            args.get("pattern").and_then(|v| v.as_str()).unwrap_or(""),
            args.get("path").and_then(|v| v.as_str()).unwrap_or(".")
        ),
        "glob" => args
            .get("pattern")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        _ => args
            .get("path")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
    };
    println!(
        "{} {}",
        paint("1;36", &format!("● [{step}] {name}")),
        detail
    );
    let _ = std::io::stdout().flush();
}

pub fn tool_result(summary: &str, aborted: bool) {
    let text = if aborted {
        "aborted".to_string()
    } else {
        crate::provider::truncate(summary.trim(), 100)
    };
    println!("  {} {}", paint("2", "└"), paint("2", &text));
    let _ = std::io::stdout().flush();
}

pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) {
    let mut parts = vec![
        if steps == 1 {
            "1 step".to_string()
        } else {
            format!("{steps} steps")
        },
        format!("{:.1}s", elapsed.as_secs_f64()),
    ];
    let (input, output) = outcome.tokens();
    if let (Some(i), Some(o)) = (input, output) {
        parts.push(format!("{i} in · {o} out"));
    }
    if let Some(allowance) = outcome.allowance() {
        if allowance > 0.0 {
            parts.push(format!("${allowance:.6}"));
        }
    }
    println!("{}", paint("2", &format!("─ {}", parts.join(" · "))));
    let _ = std::io::stdout().flush();
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Answer {
    No,
    Yes,
    Always,
}

pub struct Approver {
    yolo: bool,
    interactive: bool,
    edits_allowed: bool,
}

impl Approver {
    pub fn new(yolo: bool) -> Self {
        Self {
            yolo,
            interactive: stdin_is_tty(),
            edits_allowed: false,
        }
    }

    pub fn yolo(&self) -> bool {
        self.yolo
    }

    fn ask(&self, question: &str, allow_always: bool) -> Answer {
        if self.yolo {
            return Answer::Yes;
        }
        if !self.interactive {
            println!(
                "{}",
                paint("33", "  no terminal to ask; denied (use --yolo to allow)")
            );
            return Answer::No;
        }
        let hint = if allow_always { "[y/N/a]" } else { "[y/N]" };
        print!("\n{} {} ", question, paint("2", hint));
        let _ = std::io::stdout().flush();

        // Typeahead from before the prompt appeared must not answer it: a "y"
        // typed during streaming would otherwise approve a command unseen.
        unsafe {
            libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH);
        }

        let mut line = String::new();
        if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
            return Answer::No;
        }
        // Ctrl-C during the prompt arrives as a signal, not a keystroke.
        if crate::signal::CANCEL.load(std::sync::atomic::Ordering::Relaxed) {
            return Answer::No;
        }
        match line.trim().to_ascii_lowercase().as_str() {
            "y" | "yes" => Answer::Yes,
            "a" | "always" if allow_always => Answer::Always,
            _ => Answer::No,
        }
    }

    /// One prompt for the first edit of a session, then silent.
    pub fn allow_edit(&mut self, path: &str, preview: &str) -> bool {
        if self.yolo || self.edits_allowed {
            return true;
        }
        println!("{preview}");
        match self.ask(&format!("apply this change to {path}?"), true) {
            Answer::Yes => true,
            Answer::Always => {
                self.edits_allowed = true;
                true
            }
            Answer::No => false,
        }
    }

    /// Every call, no memory: the point is seeing the command.
    pub fn allow_bash(&mut self, cmd: &str) -> bool {
        if self.yolo {
            return true;
        }
        // Bash prompts every call by design, so "always" is not offered here.
        self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200)), false)
            == Answer::Yes
    }
}