diff --git a/crates/goose-cli/src/session/elicitation.rs b/crates/goose-cli/src/session/elicitation.rs index 8ddaa496f..91add67ef 100644 --- a/crates/goose-cli/src/session/elicitation.rs +++ b/crates/goose-cli/src/session/elicitation.rs @@ -3,6 +3,11 @@ use rmcp::model::ElicitationAction; use serde_json::Value; use std::collections::HashMap; use std::io::{self, BufRead, IsTerminal, Write}; +use tokio_util::sync::CancellationToken; + +#[cfg(all(test, unix))] +#[path = "../../tests/support/elicitation_signals.rs"] +mod signal_tests; pub struct ElicitationInput { pub action: ElicitationAction, @@ -22,7 +27,33 @@ struct SingleSelect<'a> { initial_value: Option, } -pub fn collect_elicitation_input(message: &str, schema: &Value) -> io::Result { +pub fn collect_elicitation_input( + message: &str, + schema: &Value, + cancel_token: &CancellationToken, +) -> io::Result { + if cancel_token.is_cancelled() { + return Ok(cancelled_input()); + } + let input = collect_elicitation_input_inner(message, schema, cancel_token)?; + if cancel_token.is_cancelled() { + return Ok(cancelled_input()); + } + Ok(input) +} + +fn cancelled_input() -> ElicitationInput { + ElicitationInput { + action: ElicitationAction::Cancel, + user_data: HashMap::new(), + } +} + +fn collect_elicitation_input_inner( + message: &str, + schema: &Value, + cancel_token: &CancellationToken, +) -> io::Result { if !message.is_empty() { println!("\n{}", style(message).cyan()); } @@ -70,6 +101,12 @@ pub fn collect_elicitation_input(message: &str, schema: &Value) -> io::Result = HashMap::new(); for (name, field_schema) in properties { + if cancel_token.is_cancelled() { + return Ok(ElicitationInput { + action: ElicitationAction::Cancel, + user_data: HashMap::new(), + }); + } let is_required = required.contains(&name.as_str()); let field_type = field_schema .get("type") @@ -122,7 +159,7 @@ pub fn collect_elicitation_input(message: &str, schema: &Value) -> io::Result) -> io::Result io::Result> { - if !std::io::stdin().is_terminal() { - let mut line = String::new(); - io::stdin().lock().read_line(&mut line)?; - return Ok(Some(line.trim().to_string())); +#[cfg(unix)] +fn read_line(cancel_token: &CancellationToken) -> io::Result> { + let mut reader = cancellable_stdin::Input::new(io::stdin().lock(), cancel_token)?; + let result = read_line_from(&mut reader); + if cancel_token.is_cancelled() || matches!(result, Ok(None)) { + if matches!(result, Ok(None)) { + reader.discard_terminal_input()?; + } + return Ok(None); + } + result +} + +#[cfg(not(unix))] +fn read_line(cancel_token: &CancellationToken) -> io::Result> { + if cancel_token.is_cancelled() { + return Ok(None); + } + let result = read_line_from(&mut io::stdin().lock()); + if cancel_token.is_cancelled() { + return Ok(None); + } + result +} + +#[cfg(unix)] +mod cancellable_stdin { + use super::*; + use std::io::Read; + use std::os::fd::AsRawFd; + + pub(super) struct Input<'a> { + stdin: io::StdinLock<'a>, + original_flags: libc::c_int, + cancel_token: &'a CancellationToken, } - let mut line = String::new(); - match io::stdin().lock().read_line(&mut line) { - Ok(0) => Ok(None), - Ok(_) => Ok(Some(line.trim().to_string())), - Err(e) if e.kind() == io::ErrorKind::Interrupted => Ok(None), - Err(e) => Err(e), + impl<'a> Input<'a> { + pub(super) fn new( + stdin: io::StdinLock<'a>, + cancel_token: &'a CancellationToken, + ) -> io::Result { + // Nonblocking reads close the race between readiness and a signal flushing stdin. + let original_flags = unsafe { libc::fcntl(stdin.as_raw_fd(), libc::F_GETFL) }; + if original_flags < 0 + || unsafe { + libc::fcntl( + stdin.as_raw_fd(), + libc::F_SETFL, + original_flags | libc::O_NONBLOCK, + ) + } < 0 + { + return Err(io::Error::last_os_error()); + } + Ok(Self { + stdin, + original_flags, + cancel_token, + }) + } + + pub(super) fn discard_terminal_input(&self) -> io::Result<()> { + // A programmatic SIGINT need not flush the terminal's unfinished line. + if self.stdin.is_terminal() + && unsafe { libc::tcflush(self.stdin.as_raw_fd(), libc::TCIFLUSH) } < 0 + { + return Err(io::Error::last_os_error()); + } + Ok(()) + } } + + impl Read for Input<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let available = self.fill_buf()?; + let count = buffer.len().min(available.len()); + buffer[..count].copy_from_slice(&available[..count]); + self.consume(count); + Ok(count) + } + } + + impl BufRead for Input<'_> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + loop { + if self.cancel_token.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + // Rustyline's nonterminal input may already have buffered the next answer. + match self.stdin.fill_buf() { + Ok(_) => return self.stdin.fill_buf(), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} + Err(error) => return Err(error), + } + let mut descriptor = libc::pollfd { + fd: self.stdin.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + // StdinLock keeps input exclusively owned until the read returns. + if unsafe { libc::poll(&mut descriptor, 1, 50) } < 0 { + return Err(io::Error::last_os_error()); + } + } + } + + fn consume(&mut self, amount: usize) { + self.stdin.consume(amount); + } + } + + impl Drop for Input<'_> { + fn drop(&mut self) { + // Restore the shared stdin description before handing input back to the CLI. + unsafe { libc::fcntl(self.stdin.as_raw_fd(), libc::F_SETFL, self.original_flags) }; + } + } +} + +fn read_line_from(reader: &mut impl BufRead) -> io::Result> { + let mut line = Vec::new(); + loop { + // BufRead::read_line retries Interrupted instead of allowing cancellation. + let available = match reader.fill_buf() { + Ok(available) => available, + Err(error) if error.kind() == io::ErrorKind::Interrupted => return Ok(None), + Err(error) => return Err(error), + }; + if available.is_empty() { + break; + } + let newline = available.iter().position(|byte| *byte == b'\n'); + let consumed = newline.map_or(available.len(), |index| index + 1); + line.extend_from_slice(&available[..consumed]); + reader.consume(consumed); + if newline.is_some() { + break; + } + } + + let line = String::from_utf8(line).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "stream did not contain valid UTF-8", + ) + })?; + Ok(line.ends_with('\n').then(|| line.trim().to_string())) } fn format_default(value: &Value) -> String { @@ -319,8 +490,128 @@ fn parse_value(input: &str, field_type: &str, enum_values: Option<&Vec>) mod tests { use super::*; use serde_json::json; + use std::io::{BufReader, Cursor, Read}; use test_case::test_case; + #[test_case(json!({}); "confirmation")] + #[test_case(json!({"properties": {"answer": {"type": "boolean"}}}); "boolean")] + #[test_case(json!({"properties": {"answer": {"enum": ["yes", "no"]}}}); "selection")] + #[test_case(json!({"properties": {"answer": {"type": "string"}}}); "freeform")] + fn cancelled_token_never_collects_answers(schema: Value) { + let token = CancellationToken::new(); + token.cancel(); + let result = collect_elicitation_input("", &schema, &token).unwrap(); + assert_eq!(result.action, ElicitationAction::Cancel); + assert!(result.user_data.is_empty()); + } + + struct ScriptedReader { + prefix: Cursor<&'static [u8]>, + error: Option, + suffix: Cursor<&'static [u8]>, + } + + impl Read for ScriptedReader { + fn read(&mut self, output: &mut [u8]) -> io::Result { + let input = self.fill_buf()?; + let count = input.len().min(output.len()); + output[..count].copy_from_slice(&input[..count]); + self.consume(count); + Ok(count) + } + } + + impl BufRead for ScriptedReader { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + if self.prefix.position() < self.prefix.get_ref().len() as u64 { + return self.prefix.fill_buf(); + } + if let Some(error) = self.error.take() { + return Err(error.into()); + } + self.suffix.fill_buf() + } + + fn consume(&mut self, amount: usize) { + if self.prefix.position() < self.prefix.get_ref().len() as u64 { + self.prefix.consume(amount); + } else { + self.suffix.consume(amount); + } + } + } + + #[test] + fn nonterminal_eof_cancels_elicitation_input() { + assert_eq!(read_line_from(&mut Cursor::new([])).unwrap(), None); + } + + #[test] + fn blank_line_accepts_the_field_default() { + assert_eq!( + read_line_from(&mut Cursor::new(b"\n")).unwrap(), + Some(String::new()) + ); + } + + #[test] + fn partial_line_at_eof_cancels_elicitation_input() { + assert_eq!(read_line_from(&mut Cursor::new(b"partial")).unwrap(), None); + } + + #[test_case(""; "before any input")] + #[test_case("partial"; "after partial input")] + fn interrupted_read_cancels_elicitation_input(prefix: &'static str) { + let mut reader = ScriptedReader { + prefix: Cursor::new(prefix.as_bytes()), + error: Some(io::ErrorKind::Interrupted), + suffix: Cursor::new(b"later input\n"), + }; + + assert_eq!(read_line_from(&mut reader).unwrap(), None); + assert_eq!( + read_line_from(&mut reader).unwrap(), + Some("later input".to_string()) + ); + } + + #[test_case(1; "split unicode")] + #[test_case(64; "multiple lines in one buffer")] + fn buffered_read_preserves_unicode_and_the_next_line(capacity: usize) { + let mut reader = BufReader::with_capacity(capacity, Cursor::new(" café \r\nnext\n")); + + assert_eq!(read_line_from(&mut reader).unwrap(), Some("café".into())); + assert_eq!(read_line_from(&mut reader).unwrap(), Some("next".into())); + assert_eq!(read_line_from(&mut reader).unwrap(), None); + } + + #[test_case(b"\xff\n"; "complete line")] + #[test_case(b"\xff"; "partial line at eof")] + fn invalid_utf8_returns_an_error(input: &[u8]) { + assert_eq!( + read_line_from(&mut Cursor::new(input)).unwrap_err().kind(), + io::ErrorKind::InvalidData + ); + } + + #[test] + fn non_interruption_errors_are_propagated_without_reading_more() { + let mut reader = ScriptedReader { + prefix: Cursor::new(b"partial"), + error: Some(io::ErrorKind::PermissionDenied), + suffix: Cursor::new(b"later input\n"), + }; + + assert_eq!( + read_line_from(&mut reader).unwrap_err().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!( + read_line_from(&mut reader).unwrap(), + Some("later input".to_string()) + ); + } + #[test] fn builds_required_enum_select_with_default() { let schema = json!({ diff --git a/crates/goose-cli/src/session/mod.rs b/crates/goose-cli/src/session/mod.rs index 381ca1a24..bf2f1548f 100644 --- a/crates/goose-cli/src/session/mod.rs +++ b/crates/goose-cli/src/session/mod.rs @@ -1426,7 +1426,7 @@ impl CliSession { output::hide_thinking(); let _ = progress_bars.hide(); - match elicitation::collect_elicitation_input(&elicitation_message, &schema) { + match elicitation::collect_elicitation_input(&elicitation_message, &schema, &cancel_token_clone) { Ok(input) => { match &input.action { ElicitationAction::Decline => { diff --git a/crates/goose-cli/tests/support/elicitation_signals.rs b/crates/goose-cli/tests/support/elicitation_signals.rs new file mode 100644 index 000000000..fef7cbe04 --- /dev/null +++ b/crates/goose-cli/tests/support/elicitation_signals.rs @@ -0,0 +1,261 @@ +#![cfg(unix)] + +use super::*; +use std::fs::File; +use std::future::{poll_fn, Future}; +use std::io::Read; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::process::CommandExt; +use std::process::{Child, Command, Stdio}; +use std::task::Poll; +use std::time::{Duration, Instant}; +use test_case::test_case; +use tokio_util::sync::CancellationToken; + +const CHILD_MODE: &str = "GOOSE_ELICITATION_SIGNAL_TEST"; + +struct ChildGuard(Child); + +impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +fn wait_for(output: &mut impl ReadFd, expected: &str) { + let deadline = Instant::now() + Duration::from_secs(5); + let mut received = String::new(); + while !received.contains(expected) { + assert!( + Instant::now() < deadline, + "waiting for {expected:?}, got {received:?}" + ); + let mut descriptor = libc::pollfd { + fd: output.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + // The descriptor is owned by output and remains open throughout poll. + let ready = unsafe { libc::poll(&mut descriptor, 1, 50) }; + assert!(ready >= 0); + if ready > 0 { + let mut byte = [0]; + assert_eq!( + output.read(&mut byte).unwrap(), + 1, + "child closed output: {received}" + ); + received.push(char::from(byte[0])); + } + } +} + +trait ReadFd: Read + AsRawFd {} +impl ReadFd for T {} + +fn own_descriptor(fd: libc::c_int) -> File { + // Only descriptors returned by successful openpty/pipe calls reach this helper. + let file = unsafe { File::from_raw_fd(fd) }; + assert_eq!( + unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }, + 0 + ); + file +} + +#[test_case(false, false, Some(false); "pipe sigint")] +#[test_case(true, false, Some(false); "pty sigint")] +#[test_case(false, true, Some(false); "pipe partial and earlier field")] +#[test_case(true, true, Some(false); "pty partial and earlier field")] +#[test_case(true, true, Some(true); "pty keyboard ctrl c")] +#[test_case(false, false, None; "pipe completed lines")] +#[test_case(true, false, None; "pty completed lines")] +fn freeform_input_preserves_cancellation_and_ownership( + terminal: bool, + partial: bool, + keyboard: Option, +) { + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "session::elicitation::signal_tests::signal_child", + "--nocapture", + ]) + .env( + CHILD_MODE, + if keyboard.is_none() { + "complete" + } else if partial { + "partial" + } else { + "empty" + }, + ) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + + let mut pipe_input = None; + let input = if terminal { + let mut master = -1; + let mut slave = -1; + // openpty initializes both descriptors; File takes ownership after success. + assert_eq!( + unsafe { + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }, + 0 + ); + let master = own_descriptor(master); + let slave = own_descriptor(slave); + command.stdin(Stdio::from(slave)); + // Only async-signal-safe syscalls run between fork and exec. + unsafe { + command.pre_exec(|| { + if libc::setsid() < 0 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 { + return Err(io::Error::last_os_error()); + } + // Closing the test's PTY master must not kill the child during shutdown. + libc::signal(libc::SIGHUP, libc::SIG_IGN); + Ok(()) + }); + } + master + } else { + let mut descriptors = [-1; 2]; + // Keep a read descriptor to observe when the child consumed the partial line. + assert_eq!(unsafe { libc::pipe(descriptors.as_mut_ptr()) }, 0); + let reader = own_descriptor(descriptors[0]); + let writer = own_descriptor(descriptors[1]); + command.stdin(Stdio::from(reader.try_clone().unwrap())); + pipe_input = Some(reader); + writer + }; + + let mut child = ChildGuard(command.spawn().unwrap()); + // Close the PTY master before waiting for the child, including on assertion failure. + let mut input = input; + let mut output = child.0.stdout.take().unwrap(); + if keyboard.is_none() { + wait_for(&mut output, "PREFETCH_INPUT"); + input.write_all("\ncafé\nnext chat\n".as_bytes()).unwrap(); + wait_for(&mut output, "ACCEPTED_COMPLETE_ANSWERS"); + } else { + if partial { + wait_for(&mut output, "a_previous: "); + input.write_all(b"prior private answer\n").unwrap(); + } + wait_for(&mut output, "z_answer: "); + if partial { + input.write_all(b"unfinished").unwrap(); + if let Some(pipe) = pipe_input { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let mut pending: libc::c_int = 0; + assert_eq!( + unsafe { libc::ioctl(pipe.as_raw_fd(), libc::FIONREAD as _, &mut pending) }, + 0 + ); + if pending == 0 { + break; + } + assert!( + Instant::now() < deadline, + "child did not consume partial input" + ); + std::thread::sleep(Duration::from_millis(10)); + } + } + } + if keyboard == Some(true) { + input.write_all(&[3]).unwrap(); + } else { + // Signal only the isolated child, never the test runner's process group. + assert_eq!( + unsafe { libc::kill(child.0.id() as libc::pid_t, libc::SIGINT) }, + 0 + ); + } + wait_for(&mut output, "CANCELLED_WITHOUT_ANSWERS"); + input.write_all(b"next chat\n").unwrap(); + } + wait_for(&mut output, "NEXT_INPUT_PRESERVED"); + drop(input); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if let Some(status) = child.0.try_wait().unwrap() { + assert!(status.success()); + break; + } + assert!( + Instant::now() < deadline, + "child did not exit after cancellation" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn signal_child() { + let Ok(mode) = std::env::var(CHILD_MODE) else { + return; + }; + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let token = CancellationToken::new(); + let cancelled = token.clone(); + let mut signal = Box::pin(tokio::signal::ctrl_c()); + poll_fn(|cx| { + assert!(signal.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + tokio::spawn(async move { + signal.await.unwrap(); + cancelled.cancel(); + }); + let properties = if mode == "complete" { + serde_json::json!({"a_previous": {"type": "string", "default": "default"}, "z_answer": {"type": "string"}}) + } else if mode == "partial" { + serde_json::json!({"a_previous": {"type": "string"}, "z_answer": {"type": "string"}}) + } else { + serde_json::json!({"z_answer": {"type": "string"}}) + }; + let schema = serde_json::json!({"type": "object", "properties": properties}); + if mode == "complete" { + println!("PREFETCH_INPUT"); + io::stdout().flush().unwrap(); + assert!(!io::stdin().lock().fill_buf().unwrap().is_empty()); + } + let flags = unsafe { libc::fcntl(0, libc::F_GETFL) }; + let result = collect_elicitation_input("", &schema, &token).unwrap(); + assert_eq!(unsafe { libc::fcntl(0, libc::F_GETFL) }, flags); + if mode == "complete" { + assert_eq!(result.action, ElicitationAction::Accept); + assert_eq!(result.user_data["a_previous"], "default"); + assert_eq!(result.user_data["z_answer"], "café"); + println!("ACCEPTED_COMPLETE_ANSWERS"); + } else { + assert_eq!(result.action, ElicitationAction::Cancel); + assert!(result.user_data.is_empty()); + println!("CANCELLED_WITHOUT_ANSWERS"); + } + io::stdout().flush().unwrap(); + assert_eq!( + read_line_from(&mut io::stdin().lock()).unwrap().as_deref(), + Some("next chat") + ); + println!("NEXT_INPUT_PRESERVED"); + }); +}