diff --git a/codex-rs/exec/src/event_processor.rs b/codex-rs/exec/src/event_processor.rs index 6d2b6edb02..373e9534c2 100644 --- a/codex-rs/exec/src/event_processor.rs +++ b/codex-rs/exec/src/event_processor.rs @@ -14,6 +14,8 @@ pub enum CodexStatus { } pub(crate) trait EventProcessor { + fn output(&mut self) -> &mut ExecOutput; + /// Print summary of effective configuration and user prompt. fn print_config_summary( &mut self, @@ -34,18 +36,185 @@ pub(crate) trait EventProcessor { fn print_final_output(&mut self, output: Option) -> anyhow::Result<()>; } -pub(crate) fn handle_last_message( - last_agent_message: Option<&str>, - path: &Path, - file: BoundOutput, -) -> anyhow::Result<()> { - file.write(last_agent_message.unwrap_or_default().as_bytes()) - .with_context(|| format!("Failed to write last message file {path:?}"))?; - if last_agent_message.is_none() { - eprintln!( - "Warning: no last agent message; wrote empty content to {}", - path.display() - ); - } - Ok(()) +/// Local Unix runs keep blocking stream writes off the turn loop. Remote +/// clients and other platforms continue to use the standard print macros. +#[derive(Default)] +pub(crate) struct ExecOutput { + #[cfg(unix)] + writer: Option, +} + +impl ExecOutput { + pub(crate) fn handle_last_message( + &mut self, + last_agent_message: Option<&str>, + path: &Path, + file: BoundOutput, + ) -> anyhow::Result<()> { + let message = last_agent_message.unwrap_or_default(); + #[cfg(unix)] + let result = if let Some(writer) = &mut self.writer { + writer.write(OutputWrite::LastMessage(file, message.to_owned())) + } else { + file.write(message.as_bytes()) + }; + #[cfg(not(unix))] + let result = file.write(message.as_bytes()); + result.with_context(|| format!("Failed to write last message file {path:?}"))?; + if last_agent_message.is_none() { + self.stderr(format_args!( + "Warning: no last agent message; wrote empty content to {}", + path.display() + )); + } + Ok(()) + } + + #[cfg(unix)] + pub(crate) fn enable_interrupts( + &mut self, + ) -> std::io::Result> { + use std::io::Write; + use std::os::fd::AsFd; + use std::sync::mpsc::channel; + + // A full pipe can stay blocked until process exit. Avoid Tokio's + // blocking pool (which shutdown joins) and the global stdio locks. + let mut stdout = std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?); + let mut stderr = std::fs::File::from(std::io::stderr().as_fd().try_clone_to_owned()?); + let (writes, rx) = channel::(); + let (wake, status) = channel(); + let written = wake.clone(); + std::thread::Builder::new() + .name("exec-output".to_string()) + .spawn(move || { + for write in rx { + let result = match write { + OutputWrite::Stdout(mut line) => { + line.push('\n'); + stdout.write_all(line.as_bytes()) + } + OutputWrite::Stderr(mut line) => { + line.push('\n'); + stderr.write_all(line.as_bytes()) + } + // Keep the bound file's path checks and exact bytes, including + // for inherited descriptors such as shell process substitution. + OutputWrite::LastMessage(file, message) => file.write(message.as_bytes()), + }; + if written.send(WriteStatus::Written(result)).is_err() { + break; + } + } + })?; + self.writer = Some(StreamWriter { + writes, + status, + drain_budget: None, + truncated: false, + }); + Ok(wake) + } + + #[allow(clippy::print_stdout)] + pub(crate) fn stdout(&mut self, line: String) { + #[cfg(unix)] + if let Some(writer) = &mut self.writer { + writer + .write(OutputWrite::Stdout(line)) + .unwrap_or_else(|err| panic!("failed to write exec stdout: {err}")); + return; + } + println!("{line}"); + } + + pub(crate) fn stderr(&mut self, args: std::fmt::Arguments<'_>) { + #[cfg(unix)] + if let Some(writer) = &mut self.writer { + writer + .write(OutputWrite::Stderr(args.to_string())) + .unwrap_or_else(|err| panic!("failed to write exec stderr: {err}")); + return; + } + eprintln!("{args}"); + } + + pub(crate) fn truncated(&self) -> bool { + #[cfg(unix)] + { + self.writer.as_ref().is_some_and(|writer| writer.truncated) + } + #[cfg(not(unix))] + false + } +} + +#[cfg(unix)] +enum OutputWrite { + Stdout(String), + Stderr(String), + LastMessage(BoundOutput, String), +} + +#[cfg(unix)] +pub(crate) enum WriteStatus { + Written(std::io::Result<()>), + Interrupted, +} + +#[cfg(unix)] +struct StreamWriter { + writes: std::sync::mpsc::Sender, + status: std::sync::mpsc::Receiver, + drain_budget: Option, + truncated: bool, +} + +#[cfg(unix)] +impl StreamWriter { + fn write(&mut self, write: OutputWrite) -> std::io::Result<()> { + use std::sync::mpsc::RecvTimeoutError; + use std::time::Duration; + use std::time::Instant; + + if self.truncated { + return Ok(()); + } + // Wait for each write before accepting more output. A signal can + // release this wait even when the reader never drains the pipe. + if self.writes.send(write).is_err() { + panic!("exec output writer exited"); + } + loop { + let status = if let Some(budget) = &mut self.drain_budget { + let start = Instant::now(); + let status = self.status.recv_timeout(*budget); + *budget = budget.saturating_sub(start.elapsed()); + status + } else { + self.status + .recv() + .map_err(|_| RecvTimeoutError::Disconnected) + }; + match status { + // A cancelling reader may close the pipe during the drain. + // Let the turn interrupt run even when that write fails. + Ok(WriteStatus::Written(Err(_))) if self.drain_budget.is_some() => { + self.truncated = true; + return Ok(()); + } + Ok(WriteStatus::Written(result)) => return result, + // Keep delivering final events to a live reader. Bound the + // total time spent waiting for output across all of them. + Ok(WriteStatus::Interrupted) => { + self.drain_budget = Some(Duration::from_millis(100)) + } + Err(RecvTimeoutError::Timeout) => { + self.truncated = true; + return Ok(()); + } + Err(RecvTimeoutError::Disconnected) => panic!("exec output writer exited"), + } + } + } } diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 238e8a808a..035477e038 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -20,9 +20,9 @@ use owo_colors::Style; use crate::event_processor::CodexStatus; use crate::event_processor::EventProcessor; -use crate::event_processor::handle_last_message; pub(crate) struct EventProcessorWithHumanOutput { + output: crate::event_processor::ExecOutput, bold: Style, cyan: Style, dimmed: Style, @@ -49,6 +49,7 @@ impl EventProcessorWithHumanOutput { ) -> Self { let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain }; Self { + output: Default::default(), bold: style(Style::new().bold(), Style::new()), cyan: style(Style::new().cyan(), Style::new()), dimmed: style(Style::new().dimmed(), Style::new()), @@ -68,31 +69,37 @@ impl EventProcessorWithHumanOutput { } } - fn render_item_started(&self, item: &ThreadItemPayload) { + fn render_item_started(&mut self, item: &ThreadItemPayload) { match item { ThreadItemPayload::CommandExecution { command, cwd, .. } => { - eprintln!( + self.output.stderr(format_args!( "{}\n{} in {cwd}", "exec".style(self.italic).style(self.magenta), command.style(self.bold), - ); + )); } ThreadItemPayload::McpToolCall { server, tool, .. } => { - eprintln!( + self.output.stderr(format_args!( "{} {} {}", "mcp:".style(self.bold), format!("{server}/{tool}").style(self.cyan), "started".style(self.dimmed) - ); + )); } ThreadItemPayload::WebSearch(item) => { - eprintln!("{} {}", "web search:".style(self.bold), item.query); + self.output.stderr(format_args!( + "{} {}", + "web search:".style(self.bold), + item.query + )); } ThreadItemPayload::FileChange { .. } => { - eprintln!("{}", "apply patch".style(self.bold)); + self.output + .stderr(format_args!("{}", "apply patch".style(self.bold))); } ThreadItemPayload::CollabAgentToolCall { tool, .. } => { - eprintln!("{} {:?}", "collab:".style(self.bold), tool); + self.output + .stderr(format_args!("{} {:?}", "collab:".style(self.bold), tool)); } _ => {} } @@ -101,11 +108,11 @@ impl EventProcessorWithHumanOutput { fn render_item_completed(&mut self, item: ThreadItemPayload) { match item { ThreadItemPayload::AgentMessage { text, .. } => { - eprintln!( + self.output.stderr(format_args!( "{}\n{}", "codex".style(self.italic).style(self.magenta), text - ); + )); self.final_message = Some(text); self.final_message_rendered = true; } @@ -117,7 +124,8 @@ impl EventProcessorWithHumanOutput { reasoning_text(&summary, &content, self.show_raw_agent_reasoning) && !text.trim().is_empty() { - eprintln!("{}", text.style(self.dimmed)); + self.output + .stderr(format_args!("{}", text.style(self.dimmed))); } } ThreadItemPayload::CommandExecution { @@ -133,35 +141,35 @@ impl EventProcessorWithHumanOutput { .unwrap_or_default(); match status { CommandExecutionStatus::Completed => { - eprintln!( + self.output.stderr(format_args!( "{}", format!(" succeeded{duration_suffix}:").style(self.green) - ); + )); } CommandExecutionStatus::Failed => { let exit_code = exit_code.unwrap_or(1); - eprintln!( + self.output.stderr(format_args!( "{}", format!(" exited {exit_code}{duration_suffix}:").style(self.red) - ); + )); } CommandExecutionStatus::Declined => { - eprintln!( + self.output.stderr(format_args!( "{}", format!(" declined{duration_suffix}:").style(self.yellow) - ); + )); } CommandExecutionStatus::InProgress => { - eprintln!( + self.output.stderr(format_args!( "{}", format!(" in progress{duration_suffix}:").style(self.dimmed) - ); + )); } } if let Some(output) = aggregated_output && !output.trim().is_empty() { - eprintln!("{output}"); + self.output.stderr(format_args!("{output}")); } } ThreadItemPayload::FileChange { @@ -173,9 +181,14 @@ impl EventProcessorWithHumanOutput { PatchApplyStatus::Declined => "declined", PatchApplyStatus::InProgress => "in_progress", }; - eprintln!("{} {}", "patch:".style(self.bold), status_text); + self.output.stderr(format_args!( + "{} {}", + "patch:".style(self.bold), + status_text + )); for change in changes { - eprintln!("{}", change.path.style(self.dimmed)); + self.output + .stderr(format_args!("{}", change.path.style(self.dimmed))); } } ThreadItemPayload::McpToolCall { @@ -190,21 +203,27 @@ impl EventProcessorWithHumanOutput { McpToolCallStatus::Failed => "failed".style(self.red), McpToolCallStatus::InProgress => "in_progress".style(self.dimmed), }; - eprintln!( + self.output.stderr(format_args!( "{} {} {}", "mcp:".style(self.bold), format!("{server}/{tool}").style(self.cyan), format!("({status_text})").style(self.dimmed) - ); + )); if let Some(error) = error { - eprintln!("{}", error.message.style(self.red)); + self.output + .stderr(format_args!("{}", error.message.style(self.red))); } } ThreadItemPayload::WebSearch(item) => { - eprintln!("{} {}", "web search:".style(self.bold), item.query); + self.output.stderr(format_args!( + "{} {}", + "web search:".style(self.bold), + item.query + )); } ThreadItemPayload::ContextCompaction { .. } => { - eprintln!("{}", "context compacted".style(self.dimmed)); + self.output + .stderr(format_args!("{}", "context compacted".style(self.dimmed))); } _ => {} } @@ -212,6 +231,10 @@ impl EventProcessorWithHumanOutput { } impl EventProcessor for EventProcessorWithHumanOutput { + fn output(&mut self) -> &mut crate::event_processor::ExecOutput { + &mut self.output + } + fn print_config_summary( &mut self, config: &Config, @@ -220,18 +243,24 @@ impl EventProcessor for EventProcessorWithHumanOutput { workspace_roots: &[PathUri], ) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - eprintln!("OpenAI Codex v{VERSION}\n--------"); + self.output + .stderr(format_args!("OpenAI Codex v{VERSION}\n--------")); for (key, value) in config_summary_entries(config, session_configured_event, workspace_roots) { - eprintln!("{} {}", format!("{key}:").style(self.bold), value); + self.output.stderr(format_args!( + "{} {}", + format!("{key}:").style(self.bold), + value + )); } - eprintln!("--------"); - eprintln!("{}\n{}", "user".style(self.cyan), prompt); + self.output.stderr(format_args!("--------")); + self.output + .stderr(format_args!("{}\n{}", "user".style(self.cyan), prompt)); } fn print_thread_started(&mut self, thread_id: &str) { - eprintln!("thread id: {thread_id}"); + self.output.stderr(format_args!("thread id: {thread_id}")); } fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus { @@ -241,57 +270,59 @@ impl EventProcessor for EventProcessorWithHumanOutput { .details .map(|details| format!(" ({details})")) .unwrap_or_default(); - eprintln!( + self.output.stderr(format_args!( "{} {}{}", "warning:".style(self.yellow).style(self.bold), notification.summary, details - ); + )); CodexStatus::Running } ServerNotification::Warning(notification) => self.process_warning(notification.message), ServerNotification::AuthRecoveryStarted(notification) => { - eprintln!("{}", notification.message); + self.output.stderr(format_args!("{}", notification.message)); CodexStatus::Running } ServerNotification::AuthRecoveryCompleted(notification) => { - eprintln!("{}", notification.message.style(self.green)); + self.output + .stderr(format_args!("{}", notification.message.style(self.green))); CodexStatus::Running } ServerNotification::Error(notification) => { - eprintln!( + self.output.stderr(format_args!( "{} {}", "ERROR:".style(self.red).style(self.bold), notification.error - ); + )); CodexStatus::Running } ServerNotification::DeprecationNotice(notification) => { - eprintln!( + self.output.stderr(format_args!( "{} {}", "deprecated:".style(self.yellow).style(self.bold), notification.summary - ); + )); if let Some(details) = notification.details { - eprintln!("{}", details.style(self.dimmed)); + self.output + .stderr(format_args!("{}", details.style(self.dimmed))); } CodexStatus::Running } ServerNotification::HookStarted(notification) => { - eprintln!( + self.output.stderr(format_args!( "{} {}", "hook:".style(self.bold), format!("{:?}", notification.run.event_name).style(self.dimmed) - ); + )); CodexStatus::Running } ServerNotification::HookCompleted(notification) => { - eprintln!( + self.output.stderr(format_args!( "{} {} {:?}", "hook:".style(self.bold), format!("{:?}", notification.run.event_name).style(self.dimmed), notification.run.status - ); + )); CodexStatus::Running } ServerNotification::ItemStarted(notification) => { @@ -303,12 +334,12 @@ impl EventProcessor for EventProcessorWithHumanOutput { CodexStatus::Running } ServerNotification::ModelRerouted(notification) => { - eprintln!( + self.output.stderr(format_args!( "{} {} -> {}", "model rerouted:".style(self.yellow).style(self.bold), notification.from_model, notification.to_model - ); + )); CodexStatus::Running } ServerNotification::ModelVerification(_) => CodexStatus::Running, @@ -337,7 +368,11 @@ impl EventProcessor for EventProcessorWithHumanOutput { self.final_message_rendered = false; self.emit_final_message_on_shutdown = false; if let Some(error) = notification.turn.error { - eprintln!("{} {}", "ERROR:".style(self.red).style(self.bold), error); + self.output.stderr(format_args!( + "{} {}", + "ERROR:".style(self.red).style(self.bold), + error + )); } CodexStatus::InitiateShutdown } @@ -345,7 +380,8 @@ impl EventProcessor for EventProcessorWithHumanOutput { self.final_message = None; self.final_message_rendered = false; self.emit_final_message_on_shutdown = false; - eprintln!("{}", "turn interrupted".style(self.dimmed)); + self.output + .stderr(format_args!("{}", "turn interrupted".style(self.dimmed))); CodexStatus::InitiateShutdown } TurnStatus::InProgress => CodexStatus::Running, @@ -353,7 +389,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { ServerNotification::TurnDiffUpdated(notification) => { if notification.diff != self.last_turn_diff && !notification.diff.trim().is_empty() { - eprintln!("{}", notification.diff); + self.output.stderr(format_args!("{}", notification.diff)); } // Remember empty updates too, so a restored diff is rendered again. self.last_turn_diff = notification.diff; @@ -361,22 +397,31 @@ impl EventProcessor for EventProcessorWithHumanOutput { } ServerNotification::TurnPlanUpdated(notification) => { if let Some(explanation) = notification.explanation { - eprintln!("{}", explanation.style(self.italic)); + self.output + .stderr(format_args!("{}", explanation.style(self.italic))); } for step in notification.plan { match step.status { codex_app_server_protocol::TurnPlanStepStatus::Completed => { - eprintln!(" {} {}", "✓".style(self.green), step.step); + self.output.stderr(format_args!( + " {} {}", + "✓".style(self.green), + step.step + )); } codex_app_server_protocol::TurnPlanStepStatus::InProgress => { - eprintln!(" {} {}", "→".style(self.cyan), step.step); + self.output.stderr(format_args!( + " {} {}", + "→".style(self.cyan), + step.step + )); } codex_app_server_protocol::TurnPlanStepStatus::Pending => { - eprintln!( + self.output.stderr(format_args!( " {} {}", "•".style(self.dimmed), step.step.style(self.dimmed) - ); + )); } } } @@ -391,10 +436,10 @@ impl EventProcessor for EventProcessorWithHumanOutput { } fn process_warning(&mut self, message: String) -> CodexStatus { - eprintln!( + self.output.stderr(format_args!( "{} {message}", "warning:".style(self.yellow).style(self.bold) - ); + )); CodexStatus::Running } @@ -410,22 +455,22 @@ impl EventProcessor for EventProcessorWithHumanOutput { && let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output) && !(print_to_stdout && file.is_stdout()) { - handle_last_message(self.final_message.as_deref(), path, file) + self.output + .handle_last_message(self.final_message.as_deref(), path, file) } else { Ok(()) }; if let Some(usage) = &self.last_total_token_usage { - eprintln!( + self.output.stderr(format_args!( "{}\n{}", "tokens used".style(self.dimmed), format_with_separators(blended_total(usage)) - ); + )); } - #[allow(clippy::print_stdout)] if print_to_stdout && let Some(message) = self.final_message.as_deref() { - println!("{message}"); + self.output.stdout(message.to_owned()); } else if should_print_final_message_to_tty( self.emit_final_message_on_shutdown .then_some(self.final_message.as_deref()) @@ -435,11 +480,11 @@ impl EventProcessor for EventProcessorWithHumanOutput { std::io::stderr().is_terminal(), ) && let Some(message) = self.final_message.as_deref() { - eprintln!( + self.output.stderr(format_args!( "{}\n{}", "codex".style(self.italic).style(self.magenta), message - ); + )); } output_result } diff --git a/codex-rs/exec/src/event_processor_with_human_output_tests.rs b/codex-rs/exec/src/event_processor_with_human_output_tests.rs index fad13d64cd..ca87df9f73 100644 --- a/codex-rs/exec/src/event_processor_with_human_output_tests.rs +++ b/codex-rs/exec/src/event_processor_with_human_output_tests.rs @@ -70,6 +70,7 @@ fn turn_diff_notifications_render_only_changes() -> anyhow::Result<()> { } let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), @@ -405,6 +406,7 @@ fn final_message_from_turn_items_falls_back_to_latest_plan() { #[test] fn turn_completed_recovers_final_message_from_turn_items() { let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), @@ -458,6 +460,7 @@ fn turn_completed_recovers_final_message_from_turn_items() { #[test] fn turn_completed_overwrites_stale_final_message_from_turn_items() { let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), @@ -512,6 +515,7 @@ fn turn_completed_overwrites_stale_final_message_from_turn_items() { #[test] fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() { let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), @@ -558,6 +562,7 @@ fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() { #[test] fn turn_failed_clears_stale_final_message() { let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), @@ -605,6 +610,7 @@ fn turn_failed_clears_stale_final_message() { #[test] fn turn_interrupted_clears_stale_final_message() { let mut processor = EventProcessorWithHumanOutput { + output: Default::default(), bold: Style::new(), cyan: Style::new(), dimmed: Style::new(), diff --git a/codex-rs/exec/src/event_processor_with_jsonl_output.rs b/codex-rs/exec/src/event_processor_with_jsonl_output.rs index 77b3781beb..f6b75678be 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output.rs @@ -23,7 +23,6 @@ use serde_json::json; pub use crate::event_processor::CodexStatus; use crate::event_processor::EventProcessor; -use crate::event_processor::handle_last_message; use crate::exec_events::AgentMessageItem; use crate::exec_events::CollabAgentState; use crate::exec_events::CollabAgentStatus; @@ -59,6 +58,7 @@ use crate::exec_events::Usage; use crate::exec_events::WebSearchItem; pub struct EventProcessorWithJsonOutput { + output: crate::event_processor::ExecOutput, last_message_path: Option, next_item_id: AtomicU64, raw_to_exec_item_id: HashMap, @@ -84,6 +84,7 @@ pub struct CollectedThreadEvents { impl EventProcessorWithJsonOutput { pub fn new(last_message_path: Option) -> Self { Self { + output: Default::default(), last_message_path, next_item_id: AtomicU64::new(0), raw_to_exec_item_id: HashMap::new(), @@ -103,18 +104,15 @@ impl EventProcessorWithJsonOutput { format!("item_{}", self.next_item_id.fetch_add(1, Ordering::SeqCst)) } - #[allow(clippy::print_stdout)] - fn emit(&self, event: ThreadEvent) { - println!( - "{}", - serde_json::to_string(&event).unwrap_or_else(|err| { - json!({ - "type": "error", - "message": format!("failed to serialize exec json event: {err}"), - }) - .to_string() + fn emit(&mut self, event: ThreadEvent) { + let line = serde_json::to_string(&event).unwrap_or_else(|err| { + json!({ + "type": "error", + "message": format!("failed to serialize exec json event: {err}"), }) - ); + .to_string() + }); + self.output.stdout(line); } fn usage_from_last_total(&self) -> Usage { @@ -607,6 +605,10 @@ impl EventProcessorWithJsonOutput { } impl EventProcessor for EventProcessorWithJsonOutput { + fn output(&mut self) -> &mut crate::event_processor::ExecOutput { + &mut self.output + } + fn print_config_summary( &mut self, _: &Config, @@ -643,7 +645,8 @@ impl EventProcessor for EventProcessorWithJsonOutput { if self.emit_final_message_on_shutdown && let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output) { - handle_last_message(self.final_message.as_deref(), path, file)?; + self.output + .handle_last_message(self.final_message.as_deref(), path, file)?; } Ok(()) } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 2d792b8c8a..45905205bd 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -928,12 +928,14 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { let mut event_processor: Box = match json_mode { true => Box::new(EventProcessorWithJsonOutput::new(last_message_file.clone())), - _ => Box::new(EventProcessorWithHumanOutput::create_with_ansi( + false => Box::new(EventProcessorWithHumanOutput::create_with_ansi( stderr_with_ansi, Some(&config), last_message_file.clone(), )), }; + #[cfg(unix)] + let interrupt_output = event_processor.output().enable_interrupts()?; if oss { // We're in the oss section, so provider_id should be Some // Let's handle None case gracefully though just in case @@ -1271,11 +1273,21 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { info!("Codex initialized with event: {session_configured:?}"); let (interrupt_tx, interrupt_rx) = mpsc::unbounded_channel::<()>(); + #[cfg(unix)] + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; tokio::spawn(async move { - if tokio::signal::ctrl_c().await.is_ok() { - tracing::debug!("Keyboard interrupt"); - let _ = interrupt_tx.send(()); + #[cfg(unix)] + tokio::select! { + Ok(()) = tokio::signal::ctrl_c() => {} + _ = terminate.recv() => {} } + #[cfg(not(unix))] + if tokio::signal::ctrl_c().await.is_err() { + return; + } + let _ = interrupt_tx.send(()); + #[cfg(unix)] + let _ = interrupt_output.send(event_processor::WriteStatus::Interrupted); }); let task_id = match initial_operation { @@ -1288,6 +1300,9 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { .await .map_err(|err| anyhow::anyhow!("in-process app-server shutdown failed: {err}"))?; event_processor.print_final_output(bound_output)?; + if event_processor.output().truncated() { + std::process::exit(1); + } return Ok(()); } InitialOperation::UserTurn { @@ -1454,7 +1469,12 @@ async fn finish_turn( request_id: request_ids.next(), params: TurnInterruptParams { thread_id: primary_thread_id_for_requests.clone(), - turn_id: task_id.clone(), + // Local exec owns the thread. An untargeted interrupt also + // works before the server announces the turn as active. + turn_id: match &client { + AppServerClient::InProcess(_) => String::new(), + AppServerClient::Cloud(_) | AppServerClient::Remote(_) => task_id.clone(), + }, }, }, "turn/interrupt", @@ -1550,8 +1570,12 @@ async fn finish_turn( if let Err(err) = client.shutdown().await { warn!("in-process app-server shutdown failed: {err}"); } - event_processor.print_final_output(bound_output)?; - if error_seen { + // An interrupt may have cut off a completed turn's last event. Do not + // report success or overwrite the last-message file in that case. + if !event_processor.output().truncated() { + event_processor.print_final_output(bound_output)?; + } + if error_seen || event_processor.output().truncated() { std::process::exit(1); } diff --git a/codex-rs/exec/tests/suite/output_last_message.rs b/codex-rs/exec/tests/suite/output_last_message.rs index 419d1f56d3..49091a86d0 100644 --- a/codex-rs/exec/tests/suite/output_last_message.rs +++ b/codex-rs/exec/tests/suite/output_last_message.rs @@ -108,3 +108,59 @@ async fn sandbox_link_cannot_redirect_this_or_the_next_invocation() -> anyhow::R } Ok(()) } + +#[tokio::test] +async fn sigterm_interrupts_a_blocked_last_message_pipe() -> anyhow::Result<()> { + use tokio::io::AsyncReadExt; + + core_test_support::skip_if_no_network!(Ok(())); + let test = test_codex_exec(); + let server = responses::start_mock_server().await; + let message = "z".repeat(2 * 1024 * 1024); + responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("r"), + responses::ev_assistant_message("m", &message), + responses::ev_completed("r"), + ]), + ) + .await; + let cmd = test.cmd_with_server(&server); + let mut cli = tokio::process::Command::new(cmd.get_program()) + .args(cmd.get_args()) + .envs(cmd.get_envs().filter_map(|(k, v)| v.map(|v| (k, v)))) + .env("RUST_LOG", "off") + .current_dir(test.cwd_path()) + .args([ + "--skip-git-repo-check", + "--json", + "-o", + "/dev/stderr", + "reply", + ]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn()?; + + // JSON events go to /dev/null. Only the last-message write fills stderr. + let mut prefix = [0; 8192]; + cli.stderr + .as_mut() + .expect("stderr is piped") + .read_exact(&mut prefix) + .await?; + assert!(prefix.ends_with(b"zzzz")); + let pid = cli.id().expect("exec is running").to_string(); + assert!( + std::process::Command::new("kill") + .args(["-TERM", &pid]) + .status()? + .success() + ); + let status = tokio::time::timeout(std::time::Duration::from_secs(10), cli.wait()).await??; + assert_eq!(status.code(), Some(1)); + Ok(()) +} diff --git a/codex-rs/exec/tests/suite/server_error_exit.rs b/codex-rs/exec/tests/suite/server_error_exit.rs index bd0fad6987..b8102a35da 100644 --- a/codex-rs/exec/tests/suite/server_error_exit.rs +++ b/codex-rs/exec/tests/suite/server_error_exit.rs @@ -4,6 +4,99 @@ use core_test_support::responses; use core_test_support::test_codex_exec::test_codex_exec; +#[cfg(unix)] +#[tokio::test] +async fn sigterm_stops_the_command_and_child_with_blocked_json_stdout() -> anyhow::Result<()> { + check_sigterm_cleanup(BlockedPipe::JsonStdout).await +} + +#[cfg(unix)] +#[tokio::test] +async fn sigterm_stops_the_command_and_child_with_blocked_human_stderr() -> anyhow::Result<()> { + check_sigterm_cleanup(BlockedPipe::HumanStderr).await +} + +#[cfg(unix)] +enum BlockedPipe { + JsonStdout, + HumanStderr, +} + +#[cfg(unix)] +async fn check_sigterm_cleanup(pipe: BlockedPipe) -> anyhow::Result<()> { + use pretty_assertions::assert_eq; + use std::process::Command; + use tokio::io::AsyncReadExt; + use tokio::time::timeout_at; + + core_test_support::skip_if_no_network!(Ok(())); + core_test_support::skip_if_sandbox!(Ok(())); + let test = test_codex_exec(); + let server = responses::start_mock_server().await; + let fifo = test.cwd_path().join("ready"); + assert!(Command::new("mkfifo").arg(&fifo).status()?.success()); + let mut ready = tokio::net::unix::pipe::OpenOptions::new().open_receiver(&fifo)?; + // The command appears in both the JSON start event and the human log. + // Keep it larger than a typical pipe but below Linux's 128 KiB argument limit. + // The FIFO byte signals that sleep has started. EOF requires both processes to exit. + let padding = "x".repeat(112 * 1024); + let args = serde_json::json!({ + "cmd": format!("exec > ready; sleep 60 & printf .; wait # {padding}"), + "shell": "/bin/sh", + "login": false, + "yield_time_ms": 60_000, + }); + responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_function_call("wait", "exec_command", &args.to_string()), + responses::ev_completed("r1"), + ]), + ) + .await; + + let mut cmd = test.cmd_with_server(&server); + #[cfg(target_os = "macos")] + cmd.args(["--sandbox", "workspace-write"]); + #[cfg(not(target_os = "macos"))] + cmd.arg("--dangerously-bypass-approvals-and-sandbox"); + let mut cli = tokio::process::Command::new(cmd.get_program()); + cli.args(cmd.get_args()) + .envs(cmd.get_envs().filter_map(|(k, v)| v.map(|v| (k, v)))) + // Only the event processor should fill the pipe in this test. + .env("RUST_LOG", "off") + .current_dir(test.cwd_path()) + .arg("--skip-git-repo-check") + .stdin(std::process::Stdio::null()) + .kill_on_drop(true); + match pipe { + BlockedPipe::JsonStdout => cli.arg("--json").stdout(std::process::Stdio::piped()), + BlockedPipe::HumanStderr => cli.stderr(std::process::Stdio::piped()), + }; + let mut cli = cli.arg("wait").spawn()?; + tokio::select! { + byte = ready.read_u8() => byte?, + status = cli.wait() => anyhow::bail!("exec exited before the command started: {status:?}"), + }; + // Read into the large event, then hold the pipe open without draining it. + let reader: &mut (dyn tokio::io::AsyncRead + Unpin) = match pipe { + BlockedPipe::JsonStdout => cli.stdout.as_mut().expect("stdout is piped"), + BlockedPipe::HumanStderr => cli.stderr.as_mut().expect("stderr is piped"), + }; + reader.read_exact(&mut [0; 8192]).await?; + let pid = cli.id().expect("exec is running").to_string(); + assert!( + Command::new("kill") + .args(["-TERM", &pid]) + .status()? + .success() + ); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30); + assert_eq!(timeout_at(deadline, cli.wait()).await??.code(), Some(1)); + assert_eq!(timeout_at(deadline, ready.read(&mut [0])).await??, 0); + Ok(()) +} + /// Verify that when the server reports an error, `codex-exec` exits with a /// non-zero status code so automation can detect failures. #[tokio::test(flavor = "multi_thread", worker_threads = 2)]