diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index e7a2532820..79fe41b193 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -466,6 +466,10 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc) { sess.drain_code_mode_messages().await; + let writes = &sess.services.unified_exec_manager.launch_failure_writes; + writes.close(); + writes.wait().await; + crate::hook_runtime::run_session_end_hooks(sess).await; emit_thread_stop_lifecycle(sess).await; } diff --git a/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs b/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs index d896616d3c..66f6b717cc 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs @@ -1,6 +1,6 @@ //! Reports terminal process-creation failures as command attempts without a process handle. //! Approval rejections retain their own lifecycle, and sandbox denials remain retryable. -//! Once started, failure event publication survives caller cancellation. +//! Session shutdown drains failure publications that outlive the caller. use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; @@ -42,6 +42,16 @@ pub(super) async fn with_launch_failure_events( .plugin_attribution_for_command(&req.resolved.command, &cwd) }) }; + // Register before checking closure so shutdown waits for every admitted write. + let writes = &ctx + .session + .services + .unified_exec_manager + .launch_failure_writes; + let write = writes.token(); + if writes.is_closed() { + return result; + } let emitter = ToolEmitter::unified_exec( &req.resolved.command, req.cwd.clone(), @@ -71,6 +81,7 @@ pub(super) async fn with_launch_failure_events( ToolEventStage::Failure(ToolEventFailure::Message(message)), ) .await; + drop(write); }; if let Err(err) = tokio::spawn(publish.in_current_span()).await { tracing::warn!(%err, "failed to publish unified exec launch failure"); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index a276a69af4..318477f9cf 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -35,6 +35,7 @@ use rand::Rng; use rand::rng; use tokio::sync::Mutex; use tokio_util::sync::CancellationToken; +use tokio_util::task::TaskTracker; use crate::session::session::Session; use crate::session::step_context::StepContext; @@ -158,6 +159,7 @@ impl ProcessStore { } pub(crate) struct UnifiedExecProcessManager { + pub(crate) launch_failure_writes: TaskTracker, process_store: Mutex, max_write_stdin_yield_time_ms: u64, } @@ -165,6 +167,7 @@ pub(crate) struct UnifiedExecProcessManager { impl UnifiedExecProcessManager { pub(crate) fn new(max_write_stdin_yield_time_ms: u64) -> Self { Self { + launch_failure_writes: TaskTracker::new(), process_store: Mutex::new(ProcessStore::default()), max_write_stdin_yield_time_ms: max_write_stdin_yield_time_ms .max(MIN_EMPTY_YIELD_TIME_MS), diff --git a/codex-rs/core/tests/suite/unified_exec_launch_failure_tests.rs b/codex-rs/core/tests/suite/unified_exec_launch_failure_tests.rs index 0a8f52fe01..3d7b502734 100644 --- a/codex-rs/core/tests/suite/unified_exec_launch_failure_tests.rs +++ b/codex-rs/core/tests/suite/unified_exec_launch_failure_tests.rs @@ -220,3 +220,89 @@ async fn interrupted_one_shot_launch_failure_completes_and_persists() -> Result< request.single_request(); Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_during_launch_failure_preserves_the_failed_command() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let gate = Arc::new(PauseCommandCompletion::default()); + let mut extensions = ExtensionRegistryBuilder::::new(); + extensions.turn_lifecycle_contributor(gate.clone()); + let test = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_history_mode(ThreadHistoryMode::Paginated) + .with_config(|config| { + config + .features + .enable(Feature::UnifiedExec) + .expect("enable unified exec"); + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::Never); + config + .permissions + .set_permission_profile(PermissionProfile::Disabled) + .expect("disable sandboxing"); + }) + .build_with_auto_env(&server) + .await?; + let request = responses::mount_sse_once(&server, responses::sse(vec![ + responses::ev_response_created("launch"), + responses::ev_exec_command_call_with_args(CALL_ID, + &json!({"cmd": "echo unreachable", "workdir": "missing-work-directory", "login": false})), + responses::ev_completed("launch"), + ])).await; + test.codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "Run the command.".into(), + text_elements: Vec::new(), + }])) + .await?; + + gate.entered.notified().await; + test.codex.submit(Op::Interrupt).await?; + let EventMsg::TurnAborted(aborted) = wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await + else { + unreachable!() + }; + + // Try to close the writer while the command completion is paused before its append. + test.codex.submit(Op::Shutdown).await?; + let shutdown = timeout(Duration::from_secs(1), test.codex.wait_until_terminated()).await; + gate.release.notify_one(); + test.codex.wait_until_terminated().await; + + let path = test.codex.rollout_path().context("rollout path")?; + let (items, _, errors) = RolloutRecorder::load_rollout_items(&path).await?; + assert_eq!(errors, 0); + let mut history = ThreadHistoryBuilder::new(); + for item in &items { + history.handle_rollout_item(item); + } + let turn = history + .turn_snapshot(aborted.turn_id.as_deref().context("turn id")?) + .context("interrupted turn in persisted history")?; + assert_eq!(turn.status, TurnStatus::Interrupted); + let commands = turn + .item_payloads() + .filter_map(|item| match item { + ThreadItemPayload::CommandExecution { id, status, .. } => Some((id.as_str(), status)), + _ => None, + }) + .collect::>(); + assert_eq!( + commands, + vec![( + CALL_ID, + &codex_app_server_protocol::CommandExecutionStatus::Failed + )] + ); + assert!( + shutdown.is_err(), + "session closed while failure publication was paused" + ); + request.single_request(); + Ok(()) +}