1use std::time::Duration;
14
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde_json::json;
19
20use crate::server::browser_actions::{note, How, Kind};
21use crate::server::browser_attention::{self as attention, Answer};
22use crate::server::browser_bypass as bypass;
23use crate::server::browser_terminal::{
24 check_target, credential_line, let_screen_catch_up, look, output_fields, rows_of, settle, step_for_key, KeyStep, Refusal, CHUNK,
25};
26use crate::server::ui_handlers::{err_response, proxy_value};
27use crate::server::AppState;
28
29const ANSWER_WAIT: Duration = Duration::from_secs(3 * 60);
31pub(crate) const MAX_SHOWN: usize = 4_000;
33const BANNER_ROWS: usize = 5;
35const BANNER_ROW_CHARS: usize = 200;
37const MAX_WRAP_ROWS: usize = 12;
39const READBACK_WAIT: Duration = Duration::from_secs(5);
42const READBACK_POLL: Duration = Duration::from_millis(500);
44
45pub(crate) struct Call<'a> {
47 pub state: &'a AppState,
48 pub block_id: &'a str,
49 pub pane: &'a str,
50 pub agent: &'a str,
51 pub grant: &'a bypass::Grant,
52 pub origin: &'a str,
53 pub steps: Vec<KeyStep>,
55 pub typed: &'a str,
56 pub reason: &'a str,
57 pub what: String,
59 pub wait: Duration,
60 pub until: Option<&'a str>,
61 pub rows_before: Vec<String>,
63 pub owner: Option<String>,
66}
67
68fn is_hidden(c: char) -> bool {
71 c.is_control()
72 || matches!(
73 c,
74 '\u{00a0}' | '\u{00ad}' | '\u{034f}' | '\u{061c}' | '\u{115f}' | '\u{1160}' | '\u{17b4}' | '\u{17b5}' | '\u{180e}'
75 | '\u{2000}'..='\u{200f}' | '\u{2028}'..='\u{202f}' | '\u{205f}'..='\u{206f}' | '\u{3000}' | '\u{3164}'
76 | '\u{feff}' | '\u{ffa0}' | '\u{0600}'..='\u{0605}' | '\u{06dd}' | '\u{070f}' | '\u{08e2}' | '\u{1bca0}'..='\u{1bca3}'
77 | '\u{1d173}'..='\u{1d17a}' | '\u{2800}' | '\u{fe00}'..='\u{fe0f}' | '\u{fff9}'..='\u{fffc}'
78 | '\u{e0000}'..='\u{e007f}' | '\u{e0100}'..='\u{e01ef}'
79 )
80}
81
82pub(crate) fn visible(s: &str) -> String {
85 s.chars().map(|c| if is_hidden(c) { c.escape_unicode().to_string() } else { c.to_string() }).collect()
86}
87
88fn tail_row(rows: &[String]) -> String {
90 rows.iter().rev().find(|r| !r.trim().is_empty()).map(|r| r.trim_end().to_string()).unwrap_or_default()
91}
92
93pub(crate) fn read_back(rows: &[String], typed: &str) -> Option<String> {
98 let end = rows.iter().rposition(|r| !r.trim().is_empty())?;
99 let tail = &rows[..=end];
100 if typed.trim().is_empty() {
101 return Some(tail_row(rows));
102 }
103 let want = typed.trim_end();
104 (1..=tail.len().min(MAX_WRAP_ROWS)).find_map(|k| {
105 let joined = tail[tail.len() - k..].concat();
106 joined.trim_end().ends_with(want).then(|| joined.trim_end().to_string())
107 })
108}
109
110pub(crate) fn rows_for_banner(rows: &[String]) -> Vec<String> {
114 let Some(end) = rows.iter().rposition(|r| !r.trim().is_empty()) else { return Vec::new() };
115 let from = (end + 1).saturating_sub(BANNER_ROWS);
116 rows[from..=end]
117 .iter()
118 .map(|r| {
119 let masked = agentmux_common::redact::redact_token_shapes(r.trim_end());
120 visible(&masked).chars().take(BANNER_ROW_CHARS).collect()
121 })
122 .collect()
123}
124
125pub(crate) fn split_line(mut steps: Vec<KeyStep>, typed: &str) -> Result<(Vec<KeyStep>, bool), String> {
128 if typed.contains('\t') {
129 return Err("a tab completes in the terminal, so the line can't be confirmed: type the line without tabs".to_string());
130 }
131 if typed.chars().count() > MAX_SHOWN {
132 return Err(format!("this site's grant shows the person each line, and a line over {MAX_SHOWN} characters is too long to show: send a shorter one"));
133 }
134 let enters = steps.iter().filter(|k| k.key == "Enter").count();
135 match enters {
136 0 => Ok((steps, false)),
137 1 if steps.last().is_some_and(|k| k.key == "Enter") => {
138 steps.pop();
139 Ok((steps, true))
140 }
141 1 => Err("Enter must be the last key: the person answers for the line before it runs".to_string()),
142 _ => Err("this site's grant shows the person each line: send one line per call".to_string()),
143 }
144}
145
146fn brake(c: &Call<'_>) -> Option<String> {
149 if crate::server::browser_actions::not_paused(c.block_id).is_err() {
150 return Some("the user paused this pane, so nothing more was typed".to_string());
151 }
152 if !bypass::active_for(c.pane, c.agent).is_some_and(|g| g.id == c.grant.id) {
153 return Some("the person ended the grant".to_string());
154 }
155 None
156}
157
158async fn send(c: &Call<'_>, keys: &[KeyStep]) -> Result<(), String> {
160 for chunk in keys.chunks(CHUNK) {
161 let body = json!({ "block_id": c.block_id, "keys": chunk, "allowed_origins": c.grant.origins });
162 proxy_value(c.state, "terminal_keys", body, Duration::from_secs(20)).await.map_err(|(_, e)| e)?;
163 }
164 Ok(())
165}
166
167async fn type_pre(c: &Call<'_>, pre: &[KeyStep]) -> (usize, Option<String>) {
170 let mut sent = 0;
171 for chunk in pre.chunks(CHUNK) {
172 if let Some(why) = brake(c) {
173 return (sent, Some(why));
174 }
175 if let Err(e) = send(c, chunk).await {
176 return (sent, Some(e));
177 }
178 sent += chunk.len();
179 }
180 (sent, None)
181}
182
183async fn erase(c: &Call<'_>, typed: &[KeyStep]) {
190 let count = typed.iter().filter(|k| k.text.is_some()).count();
191 let baseline = tail_row(&c.rows_before);
192 if count > 0 {
193 let Ok(back) = step_for_key("Backspace") else { return };
194 let keys = vec![back; count];
195 if send(c, &keys).await.is_err() {
196 return;
197 }
198 }
199 let_screen_catch_up(c.state, c.block_id).await;
200 if crate::server::browser_owner::owner_of(c.pane) != c.owner {
201 return;
202 }
203 let now = look(c.state, c.block_id).await.ok().and_then(|v| rows_of(&v)).unwrap_or_default();
204 if tail_row(&now) != baseline {
205 if let Ok(ctrl_c) = step_for_key("Ctrl+C") {
206 let _ = send(c, &[ctrl_c]).await;
207 }
208 }
209}
210
211async fn finish(c: &Call<'_>, sent: usize, stopped: Option<String>, how: How, answer: Option<&str>) -> Response {
213 let (rows, screen_reader) = if sent == 0 { (None, true) } else { settle(c.state, c.block_id, c.wait, c.until).await };
214 note(c.pane, c.agent, Kind::Terminal).detail(&c.what).how(how).record(c.state);
215 let mut data = json!({ "sent": sent, "of": c.steps.len() });
216 if let Some(a) = answer {
217 data["answer"] = json!(a);
218 }
219 if let Some(why) = stopped {
220 data["stopped"] = json!(why);
221 }
222 output_fields(&mut data, rows, screen_reader, sent);
223 (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
224}
225
226fn refuse(c: &Call<'_>, code: StatusCode, why: String) -> Response {
228 note(c.pane, c.agent, Kind::Terminal).detail(&c.what).how(How::Refused(why.clone())).record(c.state);
229 err_response(code, why)
230}
231
232async fn ask_person(c: &Call<'_>, line: &str, rows: &[String]) -> Result<(Answer, attention::Waiting), String> {
235 let reason: String = c.reason.trim().chars().take(300).collect();
236 let payload = json!({
237 "reason": reason,
238 "line": visible(line),
239 "long": line.chars().count() > 300,
240 "rows": rows_for_banner(rows),
241 "origin": c.origin,
242 });
243 attention::ask(c.state, c.pane, c.agent, attention::Kind::Line, payload, ANSWER_WAIT).await.map_err(|e| e.to_string())
244}
245
246async fn rows_showing(c: &Call<'_>) -> Result<(Vec<String>, Option<String>), (StatusCode, String)> {
249 let start = std::time::Instant::now();
250 loop {
251 let rows = rows_of(&look(c.state, c.block_id).await?).unwrap_or_default();
252 let line = read_back(&rows, c.typed);
253 if line.is_some() || start.elapsed() >= READBACK_WAIT {
254 return Ok((rows, line));
255 }
256 tokio::time::sleep(READBACK_POLL).await;
257 }
258}
259
260async fn still_the_line(c: &Call<'_>, shown: &str) -> Result<(), String> {
263 check_target(c.state, c.block_id, c.grant).await.map_err(|r| match r {
264 Refusal::Plain(_, why) | Refusal::Secret(why) => why,
265 })?;
266 let rows = look(c.state, c.block_id).await.map_err(|(_, e)| e)?;
267 match read_back(&rows_of(&rows).unwrap_or_default(), c.typed) {
268 Some(now) if now == shown => Ok(()),
269 _ => Err("the line in the terminal changed after the person was shown it, so it was not run".to_string()),
270 }
271}
272
273pub(crate) async fn run(c: Call<'_>) -> Response {
275 let (pre, wants_enter) = match split_line(c.steps.clone(), c.typed) {
276 Ok(x) => x,
277 Err(e) => return refuse(&c, StatusCode::BAD_REQUEST, e),
278 };
279 let (sent, stopped) = type_pre(&c, &pre).await;
280 if let Some(why) = stopped {
281 erase(&c, &pre[..sent]).await;
282 return finish(&c, 0, Some(why), How::Refused("stopped".to_string()), None).await;
283 }
284 if !wants_enter {
285 return finish(&c, sent, None, How::Approved, None).await;
286 }
287 let_screen_catch_up(c.state, c.block_id).await;
288 let (rows, found) = match rows_showing(&c).await {
289 Ok(x) => x,
290 Err((code, e)) => {
291 erase(&c, &pre).await;
292 return refuse(&c, code, e);
293 }
294 };
295 let line = match (check_target(c.state, c.block_id, c.grant).await, found) {
296 (Err(Refusal::Plain(code, why)), _) => {
297 erase(&c, &pre).await;
298 return refuse(&c, code, why);
299 }
300 (Err(Refusal::Secret(why)), _) => {
301 erase(&c, &pre).await;
302 return refuse(&c, StatusCode::FORBIDDEN, why);
303 }
304 (Ok(_), Some(line)) if !credential_line(&line) => line,
305 (Ok(_), Some(_)) => {
306 erase(&c, &pre).await;
307 return refuse(&c, StatusCode::FORBIDDEN, "the line at the prompt looks like a credential, so it is not run: ask the person to type it".to_string());
308 }
309 (Ok(_), None) => {
310 erase(&c, &pre).await;
311 return refuse(&c, StatusCode::CONFLICT, "I can't confirm what would run: the terminal doesn't show what you typed. Hand off the pane".to_string());
312 }
313 };
314 let (answer, _holding) = match ask_person(&c, &line, &rows).await {
315 Ok(a) => a,
316 Err(e) => {
317 erase(&c, &pre).await;
318 return refuse(&c, StatusCode::CONFLICT, e);
319 }
320 };
321 if !matches!(answer, Answer::Yes | Answer::YesAlways | Answer::YesAsking) {
322 erase(&c, &pre).await;
323 let (how, said) = if answer == Answer::TimedOut { (How::TimedOut, "timed_out") } else { (How::Declined, "declined") };
324 return finish(&c, 0, None, how, Some(said)).await;
325 }
326 let late = if crate::server::browser_owner::owner_of(c.pane) != c.owner {
327 Some("the person took over this pane, so the line was not run".to_string())
328 } else {
329 match brake(&c) {
330 Some(why) => Some(why),
331 None => still_the_line(&c, &line).await.err(),
332 }
333 };
334 if let Some(why) = late {
335 erase(&c, &pre).await;
336 return refuse(&c, StatusCode::CONFLICT, why);
337 }
338 let Ok(enter) = step_for_key("Enter") else { return refuse(&c, StatusCode::INTERNAL_SERVER_ERROR, "no Enter key".to_string()) };
339 if let Err(e) = send(&c, &[enter]).await {
340 return refuse(&c, StatusCode::BAD_GATEWAY, e);
341 }
342 tracing::info!(agent_id = %c.agent, pane = %c.pane, origin = %c.origin, "[browser-terminal] ran a line the person approved");
343 finish(&c, sent + 1, None, How::Approved, Some("approved")).await
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 fn rows(v: &[&str]) -> Vec<String> {
351 v.iter().map(|s| s.to_string()).collect()
352 }
353
354 fn key(name: &str) -> KeyStep {
355 step_for_key(name).unwrap()
356 }
357
358 #[test]
359 fn hidden_characters_are_written_out() {
360 assert_eq!(visible("ls -la"), "ls -la");
361 assert_eq!(visible("a\u{200b}b"), "a\\u{200b}b");
362 assert_eq!(visible("rm\u{00a0}-rf"), "rm\\u{a0}-rf", "a look-alike space is not a space");
363 assert_eq!(visible("echo \u{1b}[2J"), "echo \\u{1b}[2J");
364 assert_eq!(visible("\u{202e}txt.sh"), "\\u{202e}txt.sh", "a direction mark is shown");
365 }
366
367 #[test]
368 fn tag_characters_selectors_annotations_and_blank_braille_are_shown_too() {
369 for c in ['\u{e0041}', '\u{e007f}', '\u{fe0f}', '\u{e0100}', '\u{fff9}', '\u{fffb}', '\u{2800}', '\u{200b}'] {
370 let shown = visible(&format!("a{c}b"));
371 assert!(shown.contains("\\u{") && !shown.contains(c), "U+{:04X} was left as it is: {shown:?}", c as u32);
372 }
373 assert_eq!(visible("café ✓ 日本語"), "café ✓ 日本語", "ordinary non-ASCII text is left readable");
374 }
375
376 #[test]
377 fn the_line_is_read_back_from_the_prompt_row() {
378 let r = rows(&["user@host:~$ ls", "a b c", "user@host:~$ echo hi", "", ""]);
379 assert_eq!(read_back(&r, "echo hi").as_deref(), Some("user@host:~$ echo hi"));
380 assert_eq!(read_back(&r, "ls"), None, "the typed text is not at the prompt");
381 }
382
383 #[test]
384 fn what_was_already_at_the_prompt_is_part_of_the_line() {
385 let r = rows(&["$ rm -rf build && echo hi"]);
386 assert_eq!(read_back(&r, "echo hi").as_deref(), Some("$ rm -rf build && echo hi"));
387 }
388
389 #[test]
390 fn a_line_that_wrapped_is_read_over_its_rows() {
391 let r = rows(&["$ echo aaaaaaaaaa", "bbbbbbbbbb", ""]);
392 assert_eq!(read_back(&r, "echo aaaaaaaaaabbbbbbbbbb").as_deref(), Some("$ echo aaaaaaaaaabbbbbbbbbb"));
393 }
394
395 #[test]
396 fn keys_alone_read_the_last_row() {
397 let r = rows(&["$ ls", "$ make test", ""]);
398 assert_eq!(read_back(&r, "").as_deref(), Some("$ make test"));
399 assert_eq!(read_back(&rows(&["", ""]), ""), None, "a blank terminal shows no line");
400 }
401
402 #[test]
403 fn the_banner_rows_are_the_last_few_escaped_and_masked() {
404 let r = rows(&["one", "two", "three", "four", "five", "six\u{1b}[0m", "", ""]);
405 let shown = rows_for_banner(&r);
406 assert_eq!(shown.len(), BANNER_ROWS);
407 assert_eq!(shown.last().map(String::as_str), Some("six\\u{1b}[0m"));
408 assert_eq!(shown.first().map(String::as_str), Some("two"));
409 let secret = rows(&[concat!("token ghp", "_abcdefghijklmnopqrstuvwxyz0123456789")]);
410 assert!(!rows_for_banner(&secret)[0].contains("abcdefghijklmnop"), "{:?}", rows_for_banner(&secret));
411 let long = rows(&[&"x".repeat(500)]);
412 assert_eq!(rows_for_banner(&long)[0].chars().count(), BANNER_ROW_CHARS);
413 }
414
415 #[test]
416 fn a_call_is_one_line_with_its_enter_last() {
417 let line = vec![key("Tab"), key("Enter")];
418 let (pre, enter) = split_line(line, "ls").unwrap();
419 assert_eq!((pre.len(), enter), (1, true));
420 let (pre, enter) = split_line(vec![key("Ctrl+C")], "").unwrap();
421 assert_eq!((pre.len(), enter), (1, false), "no Enter, nothing to answer");
422 assert!(split_line(vec![key("Enter"), key("Tab")], "").unwrap_err().contains("last"));
423 assert!(split_line(vec![key("Enter"), key("Enter")], "").unwrap_err().contains("one line"));
424 }
425
426 #[test]
427 fn a_tab_or_a_line_too_long_to_show_is_refused() {
428 assert!(split_line(Vec::new(), "ls\t").unwrap_err().contains("tab"));
429 let long = "x".repeat(MAX_SHOWN + 1);
430 assert!(split_line(Vec::new(), &long).unwrap_err().contains("too long"));
431 }
432}