summaryrefslogtreecommitdiffstats
path: root/src/ui.rs
blob: 3148df9de3414c994a84afc7607fd8acbcb4b517 (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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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.
///
/// Generic over the writer so the line-break rules can be tested without a
/// terminal: a reasoning stream does not always end with a newline, and the
/// answer must not be appended to the same line as the thinking.
pub struct Renderer<W: Write> {
    out: W,
    color: bool,
    dimmed: bool,
    line_dirty: bool,
}

impl Renderer<std::io::Stdout> {
    pub fn new() -> Self {
        Self {
            out: std::io::stdout(),
            color: color(),
            dimmed: false,
            line_dirty: false,
        }
    }
}

impl<W: Write> Renderer<W> {
    pub fn with_color(out: W, color: bool) -> Self {
        Self {
            out,
            color,
            dimmed: false,
            line_dirty: false,
        }
    }

    fn close_reasoning(&mut self) {
        if !self.dimmed {
            return;
        }
        let _ = write!(self.out, "\x1b[0m");
        if self.line_dirty {
            let _ = writeln!(self.out);
            self.line_dirty = false;
        }
        self.dimmed = false;
    }
}

impl<W: Write> Sink for Renderer<W> {
    fn text(&mut self, s: &str) {
        self.close_reasoning();
        let _ = write!(self.out, "{s}");
        let _ = self.out.flush();
        self.line_dirty = !s.ends_with('\n');
    }

    fn reasoning(&mut self, s: &str) {
        if !self.color {
            return;
        }
        if !self.dimmed {
            let _ = write!(self.out, "\x1b[2m");
            self.dimmed = true;
        }
        let _ = write!(self.out, "{s}");
        let _ = self.out.flush();
        self.line_dirty = !s.ends_with('\n');
    }

    fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) {
        self.close_reasoning();
        if self.line_dirty {
            let _ = writeln!(self.out);
            self.line_dirty = false;
        }
        let _ = self.out.flush();
    }
}

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
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rendered(color: bool, run: impl FnOnce(&mut Renderer<Vec<u8>>)) -> String {
        let mut renderer = Renderer::with_color(Vec::new(), color);
        run(&mut renderer);
        String::from_utf8(renderer.out).unwrap()
    }

    #[test]
    fn the_answer_starts_on_its_own_line_after_reasoning() {
        let text = rendered(true, |renderer| {
            renderer.reasoning("thinking without a newline");
            renderer.text("the answer");
            renderer.done(&Outcome::default(), Duration::ZERO);
        });
        assert_eq!(
            text,
            "\u{1b}[2mthinking without a newline\u{1b}[0m\nthe answer\n"
        );
    }

    #[test]
    fn reasoning_that_already_ended_with_a_newline_gets_no_blank_line() {
        let text = rendered(true, |renderer| {
            renderer.reasoning("thinking\n");
            renderer.text("answer");
            renderer.done(&Outcome::default(), Duration::ZERO);
        });
        assert_eq!(text, "\u{1b}[2mthinking\n\u{1b}[0manswer\n");
    }

    #[test]
    fn reasoning_alone_still_ends_the_line() {
        let text = rendered(true, |renderer| {
            renderer.reasoning("only thinking");
            renderer.done(&Outcome::default(), Duration::ZERO);
        });
        assert_eq!(text, "\u{1b}[2monly thinking\u{1b}[0m\n");
    }

    #[test]
    fn reasoning_is_dropped_when_colour_is_off() {
        let text = rendered(false, |renderer| {
            renderer.reasoning("invisible");
            renderer.text("answer");
            renderer.done(&Outcome::default(), Duration::ZERO);
        });
        assert_eq!(text, "answer\n");
    }
}