diff --git a/codex-rs/core/src/session/extension_interruption.rs b/codex-rs/core/src/session/extension_interruption.rs index 70f2d46df2..b2fe353e61 100644 --- a/codex-rs/core/src/session/extension_interruption.rs +++ b/codex-rs/core/src/session/extension_interruption.rs @@ -91,6 +91,7 @@ impl Session { active_turn, TurnAbortReason::Interrupted, /*error*/ None, + std::future::ready(()), ) .await; } diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 24a6a79dcb..808d950295 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -195,22 +195,26 @@ impl Session { return; }; let decision = pending.validate(decision); - pending.resolve_command(&decision).await; if decision == ReviewDecision::Abort { let turn_id = if pending.kind == ExecApprovalKind::HumanCommand { - Some(&pending.turn_id) + Some(pending.turn_id.clone()) } else { - active_turn_id.as_ref() + active_turn_id }; if let Some(turn_id) = turn_id { - self.abort_turn_if_active( - turn_id, + self.abort_turn_if_active_with_publication( + &turn_id, TurnAbortReason::Interrupted, /*error*/ None, + pending.resolve_command(&decision), ) .await; + pending.reply(decision); + return; } - } else if let ReviewDecision::ApprovedExecpolicyAmendment { + } + pending.resolve_command(&decision).await; + if let ReviewDecision::ApprovedExecpolicyAmendment { proposed_execpolicy_amendment, } = &decision && let Err(err) = self diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index ca955a3cae..fc17507eaa 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -699,6 +699,7 @@ impl Session { reason.clone(), &active_turn.turn_state, /*error*/ None, + std::future::ready(()), ) .await; } @@ -722,13 +723,28 @@ impl Session { turn_id: &str, reason: TurnAbortReason, error: Option, + ) -> bool { + self.abort_turn_if_active_with_publication(turn_id, reason, error, std::future::ready(())) + .await + } + + /// Signal the matching task before waiting for an item that must precede TurnAborted. + /// Publish the item even if its turn has already finished. + pub(crate) async fn abort_turn_if_active_with_publication( + self: &Arc, + turn_id: &str, + reason: TurnAbortReason, + error: Option, + publication: impl Future, ) -> bool { let active_turn = self.take_named_active_turn(turn_id, &reason).await; let Some(active_turn) = active_turn else { + publication.await; return false; }; - self.finish_turn_abort(active_turn, reason, error).await; + self.finish_turn_abort(active_turn, reason, error, publication) + .await; true } @@ -756,11 +772,20 @@ impl Session { mut active_turn: ActiveTurn, reason: TurnAbortReason, error: Option, + publication: impl Future, ) { let task = active_turn.task.take(); if let Some(task) = task { - self.handle_task_abort(task, reason.clone(), &active_turn.turn_state, error) - .await; + self.handle_task_abort( + task, + reason.clone(), + &active_turn.turn_state, + error, + publication, + ) + .await; + } else { + publication.await; } // Let interrupted tasks observe cancellation before dropping pending approvals, or an // in-flight approval wait can surface as a model-visible rejection before TurnAborted. @@ -1193,9 +1218,11 @@ impl Session { reason: TurnAbortReason, turn_state: &Mutex, error: Option, + publication: impl Future, ) { let sub_id = task.turn_context.sub_id.clone(); if task.cancellation_token.is_cancelled() { + publication.await; self.emit_turn_abort_lifecycle(reason, task.turn_context.extension_data.as_ref()) .await; return; @@ -1203,23 +1230,26 @@ impl Session { trace!(task_kind = ?task.kind, sub_id, "aborting running task"); task.cancellation_token.cancel(); - if reason == TurnAbortReason::Interrupted - && task - .turn_context - .config - .features - .enabled(Feature::CodeModeInterrupt) - { - self.services - .code_mode_service - .interrupt_active_cells() - .await; - } - task.turn_context - .turn_metadata_state - .cancel_git_enrichment_task(); - let session_task = task.task; - + let interrupt = async { + if reason == TurnAbortReason::Interrupted + && task + .turn_context + .config + .features + .enabled(Feature::CodeModeInterrupt) + { + self.services + .code_mode_service + .interrupt_active_cells() + .await; + } + task.turn_context + .turn_metadata_state + .cancel_git_enrichment_task(); + }; + // Publication can hold the writer the task needs to drain completed tool results. + // Give the task its full grace period once that writer is available. + tokio::join!(interrupt, publication); let mut handle = task.handle; let grace = Duration::from_millis(GRACEFULL_INTERRUPTION_TIMEOUT_MS); let joined = match tokio::time::timeout(grace, &mut handle).await { @@ -1229,6 +1259,7 @@ impl Session { handle.await } }; + let session_task = task.task; // A task may finish normally between the deadline and the abort. if let Err(error) = joined { warn!(%error, "task {sub_id} did not finish gracefully"); 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 3d7b502734..73e4a2d406 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 @@ -1,4 +1,4 @@ -//! Failed one-shot launches must finish publishing their lifecycle after interruption. +//! Exercises interruption while a one-shot command's completion is waiting to reach history. use std::sync::Arc; use std::time::Duration; @@ -12,18 +12,25 @@ use codex_config::Constrained; use codex_config::test_support::CloudConfigBundleFixture; use codex_core::TurnInputRequest; use codex_core::config::Config; +use codex_extension_api::CommandStartInput; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::ToolCallOutcome; +use codex_extension_api::ToolFinishInput; +use codex_extension_api::ToolLifecycleContributor; +use codex_extension_api::ToolLifecycleFuture; use codex_extension_api::TurnLifecycleContributor; use codex_features::Feature; use codex_history::RolloutItem; +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::items::CommandExecutionStatus; use codex_protocol::items::TurnItem; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::user_input::UserInput; use codex_rollout::RolloutRecorder; @@ -36,7 +43,7 @@ use serde_json::json; use tokio::sync::Notify; use tokio::time::timeout; -const CALL_ID: &str = "interrupted-launch-failure"; +const CALL_ID: &str = "gated-command"; #[derive(Default)] struct PauseCommandCompletion { @@ -63,6 +70,153 @@ impl TurnLifecycleContributor for PauseCommandCompletion { } } +#[tokio::test] +async fn cancelling_approval_stops_running_sibling_and_preserves_completed_output() -> Result<()> { + skip_if_no_network!(Ok(())); + core_test_support::skip_if_target_windows!(Ok(()), "runs a POSIX sleep command"); + + #[derive(Default)] + struct SiblingResults { + completed: Notify, + release_first: Notify, + } + + impl ToolLifecycleContributor for SiblingResults { + fn on_command_start<'a>(&'a self, input: CommandStartInput<'a>) -> ToolLifecycleFuture<'a> { + Box::pin(async move { + if input.call_id == CALL_ID { + self.completed.notified().await; + } + }) + } + + fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> { + Box::pin(async move { + match input.call_id { + "sibling" => self.release_first.notified().await, + "finished" => { + assert_eq!(input.outcome, ToolCallOutcome::Completed { success: true }); + self.completed.notify_one(); + } + _ => {} + } + }) + } + } + + let server = responses::start_mock_server().await; + let gate = Arc::new(PauseCommandCompletion::default()); + let results = Arc::new(SiblingResults::default()); + let mut extensions = ExtensionRegistryBuilder::::new(); + extensions.turn_lifecycle_contributor(gate.clone()); + extensions.tool_lifecycle_contributor(results.clone()); + let test = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_cloud_config_bundle( + CloudConfigBundleFixture::loader_with_enterprise_requirement( + "[features]\nunified_exec = false\nshell_tool = true\n", + ), + ) + .with_config(|config| config.approvals_reviewer = ApprovalsReviewer::User) + .build_with_auto_env(&server) + .await?; + let requests = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_response_created("parallel"), + responses::ev_exec_command_call_with_args( + "sibling", + &json!({"cmd": "sleep 120", "timeout_ms": 120_000}), + ), + responses::ev_exec_command_call_with_args( + "finished", + &json!({"cmd": "echo sibling-output", "login": false}), + ), + responses::ev_exec_command_call_with_args( + CALL_ID, + &json!({"cmd": "echo pending", "sandbox_permissions": "require_escalated", + "justification": "Run outside the sandbox?"}), + ), + responses::ev_completed("parallel"), + ]), + responses::sse(vec![responses::ev_completed("follow-up")]), + ], + ) + .await; + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: "run the commands".to_string(), + text_elements: Vec::new(), + }]) + .with_thread_settings( + codex_protocol::protocol::ThreadSettingsOverrides { + approval_policy: Some(AskForApproval::OnRequest), + permission_profile: Some(PermissionProfile::workspace_write()), + ..Default::default() + }, + ), + ) + .await?; + let mut started = false; + let mut prompt = None; + while !started || prompt.is_none() { + match test.codex.next_event().await?.msg { + EventMsg::ExecCommandBegin(event) if event.call_id == "sibling" => { + assert!(event.process_id.is_some()); + started = true; + } + EventMsg::ExecApprovalRequest(event) if event.call_id == CALL_ID => { + prompt = Some(event) + } + _ => {} + } + } + let prompt = prompt.unwrap(); + test.codex + .submit(Op::ExecApproval { + id: prompt.effective_approval_id(), + turn_id: Some(prompt.turn_id), + decision: ReviewDecision::Abort, + }) + .await?; + + gate.entered.notified().await; + // The sibling should stop even while history is waiting to record the decline. + wait_for_event( + &test.codex, + |event| matches!(event, EventMsg::ExecCommandEnd(end) if end.call_id == "sibling"), + ) + .await; + // Results drain in call order. Hold the first result and the decline beyond + // the abort grace period, with the successful second result queued behind it. + tokio::time::pause(); + tokio::time::sleep(Duration::from_secs(1)).await; + tokio::time::resume(); + results.release_first.notify_one(); + gate.release.notify_one(); + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::ItemCompleted(completed) + if matches!(&completed.item, TurnItem::CommandExecution(command) + if command.id == CALL_ID && command.status == CommandExecutionStatus::Declined)) + }) + .await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await; + test.submit_text_turn("What did the finished command print?") + .await?; + let requests = requests.requests(); + assert_eq!(requests.len(), 2); + let output = requests[1] + .function_call_output_text("finished") + .context("finished command output")?; + assert!(output.contains("sibling-output"), "{output}"); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn interrupted_one_shot_launch_failure_completes_and_persists() -> Result<()> { skip_if_no_network!(Ok(()));