From 7caec30d71274a454258e7cd8e24327225269e25 Mon Sep 17 00:00:00 2001 From: jif Date: Mon, 30 Nov 2026 14:25:19 +0000 Subject: [PATCH] Honor Stop while recording a declined command approval (#64740) ## Why Recording a declined command approval can delay a subsequent Stop request while other commands in the same turn are still running. ## What changed If Stop is next in the submission queue, interrupt the active turn while the decline is still being recorded. Consume Stop only if it interrupts that turn, and leave other submissions in order. ## Testing Extend the approval cancellation regression test to cover declining a command and then pressing Stop. The test checks that a running sibling command stops before the decline is recorded and that output from a completed sibling remains available in the next turn. GitOrigin-RevId: 9f08cb35f96e497d95eaa0aefb039ca9729761e7 --- codex-rs/core/src/session/handlers.rs | 54 +++++++++++++++++-- .../core/src/session/tests/guardian_tests.rs | 2 + .../core/src/tools/network_approval_tests.rs | 1 + .../unified_exec_launch_failure_tests.rs | 31 +++++++---- 4 files changed, 73 insertions(+), 15 deletions(-) diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 808d950295..6c3ee6d481 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -56,12 +56,17 @@ use codex_protocol::mcp::RequestId as ProtocolRequestId; use codex_protocol::protocol::AgentStatus; use codex_rmcp_client::ElicitationAction; use codex_rmcp_client::ElicitationResponse; +use futures::StreamExt; +use futures::stream::Peekable; use serde_json::Value; +use std::pin::Pin; use std::sync::Arc; use tracing::debug; use tracing::info; use tracing::warn; +type SubmissionQueue<'a> = Pin<&'a mut Peekable>>>; + pub async fn interrupt(sess: &Arc) { sess.interrupt_task(sess.active_turn.lock().await).await; } @@ -187,6 +192,7 @@ impl Session { approval_id: String, turn_id: Option, decision: ReviewDecision, + submissions: Option>, ) { let Some((mut pending, active_turn_id)) = self .take_pending_approval(&approval_id, turn_id.as_deref()) @@ -195,6 +201,42 @@ impl Session { return; }; let decision = pending.validate(decision); + if matches!(decision, ReviewDecision::Denied { .. }) + && let Some(active_turn_id) = active_turn_id.as_ref() + && let Some(mut submissions) = submissions + { + let publish = async move { + pending.resolve_command(&decision).await; + pending.reply(decision); + }; + tokio::pin!(publish); + // Only the next Stop can interrupt this publication. Keep all other + // submissions queued, including a Stop if its serving turn has finished. + let next = tokio::select! { + biased; + () = &mut publish => return, + () = self.services.local_agent_runtime.shutdown.cancelled() => None, + sub = submissions.as_mut().peek() => sub, + }; + let Some(stop) = next.filter(|sub| matches!(sub.op.as_protocol(), Some(Op::Interrupt))) + else { + return publish.await; + }; + let span = submission_dispatch_span(stop); + if self + .abort_turn_if_active_with_publication( + active_turn_id, + TurnAbortReason::Interrupted, + /*error*/ None, + publish, + ) + .instrument(span) + .await + { + submissions.next().await; + } + return; + } if decision == ReviewDecision::Abort { let turn_id = if pending.kind == ExecApprovalKind::HumanCommand { Some(pending.turn_id.clone()) @@ -588,6 +630,8 @@ pub(super) async fn submission_loop( config: Arc, rx_sub: Receiver>, ) { + let submissions = rx_sub.clone().peekable(); + tokio::pin!(submissions); // Session shutdown and tree shutdown both use the existing teardown handler. let mut shutdown_received = false; let mut admission_updates = sess.services.extensions.turn_start_admission_updates(); @@ -614,7 +658,7 @@ pub(super) async fn submission_loop( rx_sub.close(); }, async { - while let Ok(sub) = rx_sub.recv().await { + while let Some(sub) = submissions.next().await { if let SubmissionOp::Protocol(op) = sub.op && let Op::InterAgentCommunication { communication, start_options } = *op && sub.message_delivery.as_ref().is_some_and(crate::agent_communication::MessageDelivery::awaits_result_write) @@ -642,9 +686,9 @@ pub(super) async fn submission_loop( } continue; } - sub = rx_sub.recv() => match sub { - Ok(sub) => *sub, - Err(_) => break, + sub = submissions.next() => match sub { + Some(sub) => *sub, + None => break, }, _ = sess.input_queue.pending_work_wake.notified() => { sess.maybe_start_turn_for_pending_work().await; @@ -917,7 +961,7 @@ pub(super) async fn submission_loop( turn_id, decision, } => { - sess.resolve_exec_approval(approval_id, turn_id, decision) + sess.resolve_exec_approval(approval_id, turn_id, decision, Some(submissions.as_mut())) .await; false } diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index 802c7e8a33..299ce944c8 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -1107,6 +1107,7 @@ async fn sandbox_denied_retry_uses_the_action_policy_and_reviewer() { approval.call_id.clone(), Some(current_turn.sub_id.clone()), ReviewDecision::Abort, + /*submissions*/ None, ) .await; session @@ -1114,6 +1115,7 @@ async fn sandbox_denied_retry_uses_the_action_policy_and_reviewer() { approval.call_id, Some(approval.turn_id), ReviewDecision::Approved, + /*submissions*/ None, ) .await; }; diff --git a/codex-rs/core/src/tools/network_approval_tests.rs b/codex-rs/core/src/tools/network_approval_tests.rs index ce6d172c47..77a0259c55 100644 --- a/codex-rs/core/src/tools/network_approval_tests.rs +++ b/codex-rs/core/src/tools/network_approval_tests.rs @@ -296,6 +296,7 @@ async fn execution_cancellation_respects_network_approval_boundary( approval.effective_approval_id(), Some(approval.turn_id), ReviewDecision::Abort, + /*submissions*/ None, ) .await; assert!(session.active_turn.lock().await.is_some()); 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 73e4a2d406..fcabe0953f 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 @@ -70,8 +70,12 @@ impl TurnLifecycleContributor for PauseCommandCompletion { } } +#[test_case::test_case(ReviewDecision::Abort; "cancel_prompt")] +#[test_case::test_case(ReviewDecision::denied("declined"); "decline_then_stop")] #[tokio::test] -async fn cancelling_approval_stops_running_sibling_and_preserves_completed_output() -> Result<()> { +async fn interrupt_during_decline_stops_running_sibling_and_preserves_completed_output( + decision: ReviewDecision, +) -> Result<()> { skip_if_no_network!(Ok(())); core_test_support::skip_if_target_windows!(Ok(()), "runs a POSIX sleep command"); @@ -114,7 +118,14 @@ async fn cancelling_approval_stops_running_sibling_and_preserves_completed_outpu .with_extensions(Arc::new(extensions.build())) .with_cloud_config_bundle( CloudConfigBundleFixture::loader_with_enterprise_requirement( - "[features]\nunified_exec = false\nshell_tool = true\n", + r#" +[features] +unified_exec = false +shell_tool = true +[[rules.prefix_rules]] +pattern = [{ token = "echo" }, { token = "pending" }] +decision = "prompt" +"#, ), ) .with_config(|config| config.approvals_reviewer = ApprovalsReviewer::User) @@ -133,11 +144,7 @@ async fn cancelling_approval_stops_running_sibling_and_preserves_completed_outpu "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_exec_command_call_with_args(CALL_ID, &json!({"cmd": "echo pending"})), responses::ev_completed("parallel"), ]), responses::sse(vec![responses::ev_completed("follow-up")]), @@ -153,7 +160,7 @@ async fn cancelling_approval_stops_running_sibling_and_preserves_completed_outpu .with_thread_settings( codex_protocol::protocol::ThreadSettingsOverrides { approval_policy: Some(AskForApproval::OnRequest), - permission_profile: Some(PermissionProfile::workspace_write()), + permission_profile: Some(PermissionProfile::Disabled), ..Default::default() }, ), @@ -173,16 +180,20 @@ async fn cancelling_approval_stops_running_sibling_and_preserves_completed_outpu _ => {} } } - let prompt = prompt.unwrap(); + let prompt = prompt.context("pending command approval")?; + let stop_after_decline = matches!(decision, ReviewDecision::Denied { .. }); test.codex .submit(Op::ExecApproval { id: prompt.effective_approval_id(), turn_id: Some(prompt.turn_id), - decision: ReviewDecision::Abort, + decision, }) .await?; gate.entered.notified().await; + if stop_after_decline { + test.codex.submit(Op::Interrupt).await?; + } // The sibling should stop even while history is waiting to record the decline. wait_for_event( &test.codex,