Files
codex/codex-rs/exec/src/event_processor.rs
T
Eric Traut 6cc6cee6c5 Make local codex exec interruptible when output blocks (#65099)
## Why

On Unix, a caller that stops draining an output pipe can stall
`codex exec` in a write, preventing it from interrupting the turn
and cleaning up running commands.

## What changed

Move human-readable output, JSON events, and `--output-last-message`
writes to a dedicated thread for local Unix runs. Handle `SIGTERM`
alongside `SIGINT`, and bound the time spent waiting for output after
an interrupt. Allow local turn cancellation before the server marks
the turn active, and exit with status 1 if output is cut short.

## Testing

Add regression tests that send `SIGTERM` with JSON stdout or human
stderr blocked and check that the running command and its child exit.
Also cover interruption while writing the last message to a blocked pipe.

GitOrigin-RevId: fd9a3621d340cefc9af589c605596d2b178aaa9f
2026-12-01 22:49:30 +00:00

221 lines
7.4 KiB
Rust

use anyhow::Context;
use std::path::Path;
use codex_app_server_protocol::ServerNotification;
use codex_core::config::Config;
use codex_exec_server::BoundOutput;
use codex_protocol::protocol::SessionConfiguredEvent;
use codex_utils_path_uri::PathUri;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexStatus {
Running,
InitiateShutdown,
}
pub(crate) trait EventProcessor {
fn output(&mut self) -> &mut ExecOutput;
/// Print summary of effective configuration and user prompt.
fn print_config_summary(
&mut self,
config: &Config,
prompt: &str,
session_configured: &SessionConfiguredEvent,
workspace_roots: &[PathUri],
);
fn print_thread_started(&mut self, thread_id: &str);
/// Handle a single typed app-server notification emitted by the agent.
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus;
/// Handle a local exec warning that is not represented as an app-server notification.
fn process_warning(&mut self, message: String) -> CodexStatus;
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()>;
}
/// 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<StreamWriter>,
}
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<std::sync::mpsc::Sender<WriteStatus>> {
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::<OutputWrite>();
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<OutputWrite>,
status: std::sync::mpsc::Receiver<WriteStatus>,
drain_budget: Option<std::time::Duration>,
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"),
}
}
}
}