summaryrefslogtreecommitdiffstats
path: root/src/ui.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/ui.rs171
1 files changed, 155 insertions, 16 deletions
diff --git a/src/ui.rs b/src/ui.rs
index 13440b2..2ec0821 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -1,4 +1,5 @@
1use std::io::{IsTerminal, Write}; 1use std::io::{IsTerminal, Write};
2use std::sync::OnceLock;
2use std::time::Duration; 3use std::time::Duration;
3 4
4use crate::provider::{Outcome, Sink}; 5use crate::provider::{Outcome, Sink};
@@ -7,18 +8,33 @@ pub fn stdout_is_tty() -> bool {
7 std::io::stdout().is_terminal() 8 std::io::stdout().is_terminal()
8} 9}
9 10
11pub fn stdin_is_tty() -> bool {
12 std::io::stdin().is_terminal()
13}
14
15fn color() -> bool {
16 static COLOR: OnceLock<bool> = OnceLock::new();
17 *COLOR.get_or_init(stdout_is_tty)
18}
19
20fn paint(code: &str, text: &str) -> String {
21 if color() {
22 format!("\x1b[{code}m{text}\x1b[0m")
23 } else {
24 text.to_string()
25 }
26}
27
10/// Streams to stdout. Colour is used only when stdout is a terminal, so piping 28/// Streams to stdout. Colour is used only when stdout is a terminal, so piping
11/// the output somewhere gives clean text. 29/// the output somewhere gives clean text.
12pub struct Renderer { 30pub struct Renderer {
13 color: bool,
14 dimmed: bool, 31 dimmed: bool,
15 wrote_text: bool, 32 wrote_text: bool,
16} 33}
17 34
18impl Renderer { 35impl Renderer {
19 pub fn new(color: bool) -> Self { 36 pub fn new() -> Self {
20 Self { 37 Self {
21 color,
22 dimmed: false, 38 dimmed: false,
23 wrote_text: false, 39 wrote_text: false,
24 } 40 }
@@ -41,7 +57,7 @@ impl Sink for Renderer {
41 } 57 }
42 58
43 fn reasoning(&mut self, s: &str) { 59 fn reasoning(&mut self, s: &str) {
44 if !self.color { 60 if !color() {
45 return; 61 return;
46 } 62 }
47 if !self.dimmed { 63 if !self.dimmed {
@@ -52,24 +68,147 @@ impl Sink for Renderer {
52 let _ = std::io::stdout().flush(); 68 let _ = std::io::stdout().flush();
53 } 69 }
54 70
55 fn done(&mut self, outcome: &Outcome, elapsed: Duration) { 71 fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) {
56 self.undim(); 72 self.undim();
57 if self.wrote_text { 73 if self.wrote_text {
58 println!(); 74 println!();
75 self.wrote_text = false;
76 }
77 }
78}
79
80pub fn tool_line(name: &str, args: &serde_json::Value) {
81 let detail = match name {
82 "bash" => args
83 .get("cmd")
84 .and_then(|v| v.as_str())
85 .unwrap_or("")
86 .to_string(),
87 "grep" => format!(
88 "{} in {}",
89 args.get("pattern").and_then(|v| v.as_str()).unwrap_or(""),
90 args.get("path").and_then(|v| v.as_str()).unwrap_or(".")
91 ),
92 "glob" => args
93 .get("pattern")
94 .and_then(|v| v.as_str())
95 .unwrap_or("")
96 .to_string(),
97 _ => args
98 .get("path")
99 .and_then(|v| v.as_str())
100 .unwrap_or("")
101 .to_string(),
102 };
103 println!("{} {}", paint("1;36", &format!("● {name}")), detail);
104 let _ = std::io::stdout().flush();
105}
106
107pub fn tool_result(result: &Result<String, String>) {
108 let text = match result {
109 Ok(output) => output,
110 Err(error) => error,
111 };
112 let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
113 let summary = crate::provider::truncate(first.trim(), 100);
114 println!(" {} {}", paint("2", "└"), paint("2", &summary));
115 let _ = std::io::stdout().flush();
116}
117
118pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) {
119 let mut parts = vec![
120 if steps == 1 {
121 "1 step".to_string()
122 } else {
123 format!("{steps} steps")
124 },
125 format!("{:.1}s", elapsed.as_secs_f64()),
126 ];
127 let (input, output) = outcome.tokens();
128 if let (Some(i), Some(o)) = (input, output) {
129 parts.push(format!("{i} in · {o} out"));
130 }
131 if let Some(allowance) = outcome.allowance() {
132 if allowance > 0.0 {
133 parts.push(format!("${allowance:.6}"));
134 }
135 }
136 println!("{}", paint("2", &format!("─ {}", parts.join(" · "))));
137 let _ = std::io::stdout().flush();
138}
139
140#[derive(Debug, PartialEq, Eq, Clone, Copy)]
141pub enum Answer {
142 No,
143 Yes,
144 Always,
145}
146
147pub struct Approver {
148 yolo: bool,
149 interactive: bool,
150 edits_allowed: bool,
151}
152
153impl Approver {
154 pub fn new(yolo: bool) -> Self {
155 Self {
156 yolo,
157 interactive: stdin_is_tty(),
158 edits_allowed: false,
159 }
160 }
161
162 pub fn yolo(&self) -> bool {
163 self.yolo
164 }
165
166 fn ask(&self, question: &str) -> Answer {
167 if self.yolo {
168 return Answer::Yes;
169 }
170 if !self.interactive {
171 println!(
172 "{}",
173 paint("33", " no terminal to ask; denied (use --yolo to allow)")
174 );
175 return Answer::No;
59 } 176 }
60 let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; 177 print!("\n{} {} ", question, paint("2", "[y/N/a]"));
61 if let Some(usage) = &outcome.usage { 178 let _ = std::io::stdout().flush();
62 let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); 179
63 let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); 180 let mut line = String::new();
64 if let (Some(i), Some(o)) = (input, output) { 181 if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
65 parts.push(format!("{i} in · {o} out")); 182 return Answer::No;
183 }
184 match line.trim().to_ascii_lowercase().as_str() {
185 "y" | "yes" => Answer::Yes,
186 "a" | "always" => Answer::Always,
187 _ => Answer::No,
188 }
189 }
190
191 /// One prompt for the first edit of a session, then silent.
192 pub fn allow_edit(&mut self, path: &str, preview: &str) -> bool {
193 if self.yolo || self.edits_allowed {
194 return true;
195 }
196 println!("{preview}");
197 match self.ask(&format!("apply this change to {path}?")) {
198 Answer::Yes => true,
199 Answer::Always => {
200 self.edits_allowed = true;
201 true
66 } 202 }
203 Answer::No => false,
67 } 204 }
68 let line = format!("─ {}", parts.join(" · ")); 205 }
69 if self.color { 206
70 println!("\x1b[2m{line}\x1b[0m"); 207 /// Every call, no memory: the point is seeing the command.
71 } else { 208 pub fn allow_bash(&mut self, cmd: &str) -> bool {
72 println!("{line}"); 209 if self.yolo {
210 return true;
73 } 211 }
212 self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes
74 } 213 }
75} 214}