1use std::collections::VecDeque;
2use std::io::{BufRead, Write};
3use std::sync::mpsc::{self, TryRecvError};
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use crate::session::{AnswerError, ApprovalAnswer, Entry, EntryBody, Session};
8
9const POLL_WAIT: Duration = Duration::from_millis(100);
10const APPROVAL_PROMPT: &str = "Approve once? [y/N] ";
11
12pub struct TerminalOptions {
13 pub input_is_terminal: bool,
14 pub settle: Duration,
15 pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
16 pub runs_working: Arc<dyn Fn() -> Result<usize, String> + Send + Sync>,
17}
18
19pub fn render_entry(entry: &Entry) -> Option<String> {
20 match &entry.body {
21 EntryBody::UserMessage { text, .. } => Some(format!("> {text}")),
22 EntryBody::Turn { text, .. } => {
23 if text.is_empty() {
24 None
25 } else {
26 Some(text.clone())
27 }
28 }
29 EntryBody::ToolStarted { name, input } => {
30 let first_line = input.lines().next().unwrap_or("");
31 let truncated: String = first_line.chars().take(100).collect();
32 Some(format!(" {name}: {truncated}"))
33 }
34 EntryBody::ToolFinished {
35 name,
36 summary,
37 is_error,
38 } => {
39 if *is_error {
40 Some(format!(" {name} failed: {summary}"))
41 } else {
42 None
43 }
44 }
45 EntryBody::Retry {
46 attempt,
47 max,
48 wait_ms,
49 reason,
50 } => Some(format!(" retry {attempt}/{max} in {wait_ms} ms: {reason}")),
51 EntryBody::Error { message } => Some(format!("error: {message}")),
52 EntryBody::Idle {
53 turns,
54 cost_usd,
55 seconds,
56 ..
57 } => {
58 let cost = match cost_usd {
59 Some(c) => format!("USD {c:.4}"),
60 None => "cost unknown".to_string(),
61 };
62 let time = match seconds {
63 Some(s) => format!("{s:.1} s"),
64 None => "time unknown".to_string(),
65 };
66 Some(format!("[{turns} turn(s), {cost}, {time}]"))
67 }
68 EntryBody::ModelChanged { model } => Some(format!("model: {model}")),
69 EntryBody::EffortChanged { effort } => match effort {
70 Some(e) => Some(format!("effort: {e}")),
71 None => Some("effort: default".to_string()),
72 },
73 EntryBody::Decision { run, action, note } => match note {
74 Some(n) if !n.is_empty() => Some(format!(" decision on {run}: {action} ({n})")),
75 _ => Some(format!(" decision on {run}: {action}")),
76 },
77 EntryBody::PeerMessage {
78 from_name,
79 from_repository,
80 text,
81 ..
82 } => Some(format!("[from {from_name} ({from_repository})] {text}")),
83 EntryBody::ApprovalRequested {
84 command, reason, ..
85 } => Some(format!("RUN OUTSIDE THE SANDBOX\n{command}\n{reason}")),
86 EntryBody::PublishApprovalRequested { publish, .. } => {
87 let short_commit: String = publish.commit.chars().take(12).collect();
88 Some(format!(
89 "OPEN PULL REQUEST\n{}\n{} -> {}, commit {}\n{}",
90 publish.title, publish.branch, publish.base, short_commit, publish.remote_url
91 ))
92 }
93 EntryBody::LandApprovalRequested { land, .. } => {
94 let short_commit: String = land.commit.chars().take(12).collect();
95 Some(format!(
96 "MERGE PULL REQUEST #{}\n{}\n{}\n{} -> {}, commit {}\nLanding check passed: {}",
97 land.number,
98 land.title,
99 land.pull_request_url,
100 land.branch,
101 land.base,
102 short_commit,
103 land.check_command
104 ))
105 }
106 EntryBody::ApprovalAnswered {
107 answer, command, ..
108 } => Some(format!("approval {answer}: {command}")),
109 EntryBody::ShellCommand {
110 command,
111 exit_code,
112 output,
113 timed_out,
114 ..
115 } => {
116 let status = if *timed_out {
117 format!("exit {exit_code}, timed out")
118 } else {
119 format!("exit {exit_code}")
120 };
121 if output.is_empty() {
122 Some(format!("$ {command} [{status}]"))
123 } else {
124 Some(format!("$ {command} [{status}]\n{output}"))
125 }
126 }
127 }
128}
129
130enum InputEvent {
131 Line(String),
132 Eof,
133 Error(std::io::Error),
134}
135
136fn spawn_input_reader(mut input: Box<dyn BufRead + Send>) -> mpsc::Receiver<InputEvent> {
137 let (tx, rx) = mpsc::channel();
138 std::thread::spawn(move || {
139 let mut buf = String::new();
140 loop {
141 buf.clear();
142 match input.read_line(&mut buf) {
143 Ok(0) => {
144 let _ = tx.send(InputEvent::Eof);
145 break;
146 }
147 Ok(_) => {
148 let without_lf = buf.strip_suffix('\n').unwrap_or(&buf);
149 let trimmed = without_lf.strip_suffix('\r').unwrap_or(without_lf);
150 if tx.send(InputEvent::Line(trimmed.to_string())).is_err() {
151 break;
152 }
153 }
154 Err(e) => {
155 let _ = tx.send(InputEvent::Error(e));
156 break;
157 }
158 }
159 }
160 });
161 rx
162}
163
164fn format_answer_error(err: AnswerError) -> &'static str {
165 match err {
166 AnswerError::NotFound => "not found",
167 AnswerError::AlreadyAnswered => "already answered",
168 }
169}
170
171fn parse_approval_answer(line: &str) -> ApprovalAnswer {
172 match line.trim().to_ascii_lowercase().as_str() {
173 "y" | "yes" => ApprovalAnswer::Yes,
174 _ => ApprovalAnswer::No,
175 }
176}
177
178fn approval_request_id(body: &EntryBody) -> Option<&str> {
179 match body {
180 EntryBody::ApprovalRequested { id, .. }
181 | EntryBody::PublishApprovalRequested { id, .. }
182 | EntryBody::LandApprovalRequested { id, .. } => Some(id.as_str()),
183 _ => None,
184 }
185}
186
187fn write_line_breaking_prompt(out: &mut dyn Write, prompt_shown: &mut bool, text: &str) {
188 if *prompt_shown {
189 let _ = writeln!(out);
190 *prompt_shown = false;
191 }
192 let _ = writeln!(out, "{text}");
193}
194
195fn show_approval_prompt(out: &mut dyn Write, prompt_shown: &mut bool) {
196 let _ = write!(out, "{APPROVAL_PROMPT}");
197 *prompt_shown = true;
198}
199
200pub fn run_terminal_front(
201 session: &Session,
202 input: Box<dyn BufRead + Send>,
203 out: &mut dyn Write,
204 options: TerminalOptions,
205) -> i32 {
206 let mut after = session.info().last_seq;
207 let rx = spawn_input_reader(input);
208 let mut waiting_approvals: VecDeque<String> = VecDeque::new();
209 let mut prompt_shown = false;
210 let mut saw_error = false;
211 let mut input_closed = false;
212 let mut quiet_since: Option<Instant> = None;
213
214 loop {
215 let entries = session.entries_after(after, POLL_WAIT);
216 if !entries.is_empty() {
217 quiet_since = None;
218 for entry in entries {
219 after = entry.seq;
220 if matches!(entry.body, EntryBody::Error { .. }) {
221 saw_error = true;
222 }
223 if let Some(rendered) = render_entry(&entry) {
224 write_line_breaking_prompt(out, &mut prompt_shown, &rendered);
225 }
226 if let Some(id) = approval_request_id(&entry.body) {
227 if options.input_is_terminal {
228 let was_empty = waiting_approvals.is_empty();
229 waiting_approvals.push_back(id.to_string());
230 if was_empty {
231 show_approval_prompt(out, &mut prompt_shown);
232 }
233 } else {
234 let _ = session.answer_approval(id, ApprovalAnswer::No);
235 write_line_breaking_prompt(
236 out,
237 &mut prompt_shown,
238 "approval needs a terminal: standard input is not one",
239 );
240 }
241 } else if let EntryBody::ApprovalAnswered { id, .. } = &entry.body {
242 if let Some(pos) = waiting_approvals.iter().position(|w| w == id) {
243 waiting_approvals.remove(pos);
244 write_line_breaking_prompt(out, &mut prompt_shown, "answered on the page");
245 if pos == 0 && !waiting_approvals.is_empty() {
246 show_approval_prompt(out, &mut prompt_shown);
247 }
248 }
249 }
250 }
251 let _ = out.flush();
252 }
253
254 loop {
255 match rx.try_recv() {
256 Ok(InputEvent::Line(line)) => {
257 quiet_since = None;
258 if let Some(id) = waiting_approvals.pop_front() {
259 prompt_shown = false;
260 let answer = parse_approval_answer(&line);
261 if let Err(err) = session.answer_approval(&id, answer) {
262 let _ = writeln!(
263 out,
264 "approval not recorded: {}",
265 format_answer_error(err)
266 );
267 }
268 if !waiting_approvals.is_empty() {
269 show_approval_prompt(out, &mut prompt_shown);
270 }
271 let _ = out.flush();
272 } else {
273 let trimmed = line.trim();
274 if trimmed.is_empty() {
275 continue;
276 }
277 if trimmed == "/exit" {
278 return 0;
279 }
280 if trimmed == "/help" {
281 let _ = writeln!(out, "/help show available commands");
282 let _ = writeln!(out, "/exit exit the terminal");
283 let _ = out.flush();
284 } else if trimmed.starts_with('/') {
285 let _ = writeln!(out, "unknown command: {trimmed} (try /help)");
286 let _ = out.flush();
287 } else if let Err(e) = session.submit(&line, Vec::new()) {
288 let _ = writeln!(out, "error: {e}");
289 let _ = out.flush();
290 }
291 }
292 }
293 Ok(InputEvent::Eof) => {
294 if options.input_is_terminal {
295 if session.info().busy {
296 session.stop_run();
297 }
298 return 0;
299 }
300 input_closed = true;
301 }
302 Ok(InputEvent::Error(e)) => {
303 write_line_breaking_prompt(
304 out,
305 &mut prompt_shown,
306 &format!("error: cannot read input: {e}"),
307 );
308 let _ = out.flush();
309 return 1;
310 }
311 Err(TryRecvError::Empty) => break,
312 Err(TryRecvError::Disconnected) => {
313 if !input_closed {
314 if options.input_is_terminal {
315 if session.info().busy {
316 session.stop_run();
317 }
318 return 0;
319 }
320 input_closed = true;
321 }
322 break;
323 }
324 }
325 }
326
327 if (options.take_interrupt)() {
328 if session.info().busy {
329 session.stop_run();
330 write_line_breaking_prompt(out, &mut prompt_shown, "stopping the current turn");
331 let _ = out.flush();
332 quiet_since = None;
333 } else {
334 return 0;
335 }
336 }
337
338 if input_closed {
339 let info = session.info();
340 if !info.busy && info.queued == 0 && info.last_seq <= after {
341 match (options.runs_working)() {
342 Ok(0) => {
343 let since = *quiet_since.get_or_insert_with(Instant::now);
344 if since.elapsed() >= options.settle {
345 return if saw_error { 1 } else { 0 };
346 }
347 }
348 Ok(_) => {
349 quiet_since = None;
350 }
351 Err(e) => {
352 write_line_breaking_prompt(
353 out,
354 &mut prompt_shown,
355 &format!("error: cannot tell whether runs are working: {e}"),
356 );
357 let _ = out.flush();
358 return 1;
359 }
360 }
361 } else {
362 quiet_since = None;
363 }
364 }
365 }
366}