diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index a671f0dd74..8fc0ba0cab 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -538,6 +538,7 @@ async fn handle_exec_approval( &approval_id_for_op, cancel_token, Some(&review_cancel), + /*pending_approval_to_cancel*/ None, ) .await } else { @@ -559,6 +560,7 @@ async fn handle_exec_approval( &approval_id_for_op, cancel_token, /*review_cancel_token*/ None, + Some(PendingApprovalToCancel::Exec), ) .await }; @@ -647,6 +649,7 @@ async fn handle_patch_approval( &approval_id, cancel_token, Some(&review_cancel), + /*pending_approval_to_cancel*/ None, ) .await, ) @@ -665,6 +668,7 @@ async fn handle_patch_approval( &approval_id, cancel_token, /*review_cancel_token*/ None, + Some(PendingApprovalToCancel::Patch), ) .await }; @@ -763,6 +767,7 @@ async fn maybe_auto_review_mcp_request_user_input( &event.call_id, cancel_token, Some(&review_cancel), + /*pending_approval_to_cancel*/ None, ) .await; let selected_label = match decision { @@ -884,13 +889,21 @@ where } } -/// Await an approval decision, aborting on cancellation. +#[derive(Clone, Copy, Debug)] +enum PendingApprovalToCancel { + Exec, + Patch, +} + +/// Await an approval decision, aborting any matching parent approval waiter on +/// cancellation. Guardian-only reviews do not create such a waiter. async fn await_approval_with_cancel( fut: F, parent_session: &Session, approval_id: &str, cancel_token: &CancellationToken, review_cancel_token: Option<&CancellationToken>, + pending_approval_to_cancel: Option, ) -> codex_protocol::protocol::ReviewDecision where F: core::future::Future, @@ -901,9 +914,25 @@ where if let Some(review_cancel_token) = review_cancel_token { review_cancel_token.cancel(); } - parent_session - .notify_approval(approval_id, codex_protocol::protocol::ReviewDecision::Abort) - .await; + match pending_approval_to_cancel { + Some(PendingApprovalToCancel::Exec) => { + parent_session + .notify_exec_approval( + approval_id, + codex_protocol::protocol::ReviewDecision::Abort, + ) + .await; + } + Some(PendingApprovalToCancel::Patch) => { + parent_session + .notify_patch_approval( + approval_id, + codex_protocol::protocol::ReviewDecision::Abort, + ) + .await; + } + None => {} + } codex_protocol::protocol::ReviewDecision::Abort } decision = fut => { diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 9513dcc56c..565b7be388 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -396,6 +396,155 @@ async fn handle_exec_approval_uses_call_id_for_guardian_review_and_approval_id_f ); } +#[tokio::test] +async fn cancelling_delegated_exec_removes_retry_waiter_and_late_response_is_inert() { + let (parent_session, parent_ctx, rx_events) = + crate::session::tests::make_session_and_context_with_rx().await; + *parent_session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + let mut parent_ctx = Arc::try_unwrap(parent_ctx).expect("single turn context ref"); + let mut config = (*parent_ctx.config).clone(); + config.approvals_reviewer = ApprovalsReviewer::User; + parent_ctx.config = Arc::new(config); + let parent_ctx = Arc::new(parent_ctx); + + let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_tx_events, rx_events_child) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); + let codex = Arc::new(Codex { + tx_sub, + rx_event: rx_events_child, + agent_status, + session: Arc::clone(&parent_session), + session_loop_termination: completed_session_loop_termination(), + }); + + let cancel_token = CancellationToken::new(); + let handle = tokio::spawn({ + let codex = Arc::clone(&codex); + let parent_session = Arc::clone(&parent_session); + let parent_ctx = Arc::clone(&parent_ctx); + let cancel_token = cancel_token.clone(); + async move { + handle_exec_approval( + codex.as_ref(), + "child-turn-1".to_string(), + &parent_session, + &parent_ctx, + delegated_retry_exec_approval_event(), + &cancel_token, + ) + .await; + } + }); + + let request_event = timeout(Duration::from_secs(1), rx_events.recv()) + .await + .expect("exec approval event timed out") + .expect("exec approval event missing"); + let EventMsg::ExecApprovalRequest(request) = request_event.msg else { + panic!("expected ExecApprovalRequest event"); + }; + assert_eq!(request.call_id, "command-item-1"); + assert_eq!(request.approval_id.as_deref(), Some("retry-id")); + + cancel_token.cancel(); + timeout(Duration::from_secs(1), handle) + .await + .expect("handle_exec_approval hung") + .expect("handle_exec_approval join error"); + + let submission = timeout(Duration::from_secs(1), rx_sub.recv()) + .await + .expect("exec cancellation response timed out") + .expect("exec cancellation response missing"); + assert_eq!( + submission.op, + Op::ExecApproval { + id: "retry-id".to_string(), + turn_id: Some("child-turn-1".to_string()), + decision: ReviewDecision::Abort, + } + ); + assert!( + parent_session + .take_pending_exec_approval("retry-id") + .await + .is_none(), + "exec cancellation must remove the matching retry waiter" + ); + + parent_session + .notify_exec_approval("retry-id", ReviewDecision::Approved) + .await; + assert!( + parent_session + .take_pending_exec_approval("retry-id") + .await + .is_none(), + "a late response must not recreate or resolve a cancelled retry waiter" + ); + assert!( + rx_sub.try_recv().is_err(), + "a late response must not produce another child approval response" + ); +} + +fn delegated_retry_exec_approval_event() -> ExecApprovalRequestEvent { + ExecApprovalRequestEvent { + call_id: "command-item-1".to_string(), + approval_id: Some("retry-id".to_string()), + turn_id: "child-turn-1".to_string(), + environment_id: Some("remote".to_string()), + started_at_ms: 0, + command: vec!["rm".to_string(), "-rf".to_string(), "tmp".to_string()], + cwd: test_path_buf("/tmp").abs(), + reason: Some("unsafe subcommand".to_string()), + network_approval_context: None, + proposed_execpolicy_amendment: None, + proposed_network_policy_amendments: None, + additional_permissions: None, + available_decisions: Some(vec![ReviewDecision::Approved, ReviewDecision::Abort]), + parsed_cmd: Vec::new(), + } +} + +#[tokio::test] +async fn cancelling_delegated_patch_removes_the_patch_waiter() { + let (parent_session, parent_ctx, _rx_events) = + crate::session::tests::make_session_and_context_with_rx().await; + let approval_id = "delegated-patch-cancel"; + let decision_rx = parent_session + .request_patch_approval( + &parent_ctx, + approval_id.to_string(), + HashMap::new(), + /*reason*/ None, + /*grant_root*/ None, + ) + .await; + let cancel_token = CancellationToken::new(); + cancel_token.cancel(); + + let decision = await_approval_with_cancel( + async move { decision_rx.await.unwrap_or(ReviewDecision::Abort) }, + &parent_session, + approval_id, + &cancel_token, + /*review_cancel_token*/ None, + Some(PendingApprovalToCancel::Patch), + ) + .await; + + assert_eq!(decision, ReviewDecision::Abort); + assert!( + parent_session + .take_pending_patch_approval(approval_id) + .await + .is_none(), + "patch cancellation must remove the matching pending waiter" + ); +} + #[tokio::test] async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() { let (parent_session, parent_ctx, _rx_events) = diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index a483ce5e0f..e3fcc10b6b 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -366,6 +366,19 @@ pub async fn exec_approval( turn_id: Option, decision: ReviewDecision, ) { + let Some(pending_approval) = sess.take_pending_exec_approval(&approval_id).await else { + warn!("No pending exec approval found for call_id: {approval_id}"); + return; + }; + let decision = if pending_approval.accepts(&decision) { + decision + } else { + warn!( + approval_id, + "rejecting decision that was not offered for approval request" + ); + ReviewDecision::Denied + }; let event_turn_id = turn_id.unwrap_or_else(|| approval_id.clone()); if let ReviewDecision::ApprovedExecpolicyAmendment { proposed_execpolicy_amendment, @@ -398,16 +411,29 @@ pub async fn exec_approval( ReviewDecision::Abort => { sess.interrupt_task().await; } - other => sess.notify_approval(&approval_id, other).await, + other => pending_approval.send(other), } } pub async fn patch_approval(sess: &Arc, id: String, decision: ReviewDecision) { + let Some(pending_approval) = sess.take_pending_patch_approval(&id).await else { + warn!("No pending patch approval found for call_id: {id}"); + return; + }; + let decision = if pending_approval.accepts(&decision) { + decision + } else { + warn!( + approval_id = id, + "rejecting decision that was not offered for patch approval request" + ); + ReviewDecision::Denied + }; match decision { ReviewDecision::Abort => { sess.interrupt_task().await; } - other => sess.notify_approval(&id, other).await, + other => pending_approval.send(other), } } diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index d43724e5db..f77689498f 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -979,6 +979,28 @@ fn push_prompt_fragment( } } +fn accepted_command_approval_decisions( + mut available_decisions: Vec, + proposed_network_policy_amendments: Option<&[NetworkPolicyAmendment]>, +) -> Vec { + // Preserve the existing API path for a client to persist a restrictive + // network deny without advertising that hidden choice in normal UX. + // Only the exact server-proposed deny payload is accepted. + available_decisions.extend( + proposed_network_policy_amendments + .into_iter() + .flatten() + .filter(|amendment| amendment.action == NetworkPolicyRuleAction::Deny) + .cloned() + .map( + |network_policy_amendment| ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment, + }, + ), + ); + available_decisions +} + impl Session { pub(crate) async fn app_server_client_metadata(&self) -> AppServerClientMetadata { let state = self.state.lock().await; @@ -2134,23 +2156,6 @@ impl Session { // command-level approvals use `call_id`. // `approval_id` is only present for subcommand callbacks (execve intercept) let effective_approval_id = approval_id.clone().unwrap_or_else(|| call_id.clone()); - // Add the tx_approve callback to the map before sending the request. - let (tx_approve, rx_approve) = oneshot::channel(); - let prev_entry = { - let mut active = self.active_turn.lock().await; - match active.as_mut() { - Some(at) => { - let mut ts = at.turn_state.lock().await; - ts.insert_pending_approval(effective_approval_id.clone(), tx_approve) - } - None => None, - } - }; - if prev_entry.is_some() { - warn!("Overwriting existing pending approval for call_id: {effective_approval_id}"); - } - - let parsed_cmd = parse_command(&command); let proposed_network_policy_amendments = network_approval_context.as_ref().map(|context| { vec![ NetworkPolicyAmendment { @@ -2171,6 +2176,32 @@ impl Session { additional_permissions.as_ref(), ) }); + let accepted_decisions = accepted_command_approval_decisions( + available_decisions.clone(), + proposed_network_policy_amendments.as_deref(), + ); + // Add the tx_approve callback to the map before sending the request. + let (tx_approve, rx_approve) = oneshot::channel(); + let prev_entry = { + let mut active = self.active_turn.lock().await; + match active.as_mut() { + Some(at) => { + let mut ts = at.turn_state.lock().await; + ts.insert_pending_approval( + effective_approval_id.clone(), + tx_approve, + crate::state::PendingApprovalKind::Exec, + accepted_decisions, + ) + } + None => None, + } + }; + if prev_entry.is_some() { + warn!("Overwriting existing pending approval for call_id: {effective_approval_id}"); + } + + let parsed_cmd = parse_command(&command); let event = EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { call_id, approval_id, @@ -2211,7 +2242,12 @@ impl Session { match active.as_mut() { Some(at) => { let mut ts = at.turn_state.lock().await; - ts.insert_pending_approval(approval_id.clone(), tx_approve) + ts.insert_pending_approval( + approval_id.clone(), + tx_approve, + crate::state::PendingApprovalKind::Patch, + vec![ReviewDecision::Approved, ReviewDecision::ApprovedForSession], + ) } None => None, } @@ -2688,23 +2724,59 @@ impl Session { clippy::await_holding_invalid_type, reason = "active turn checks and turn state updates must remain atomic" )] - pub async fn notify_approval(&self, approval_id: &str, decision: ReviewDecision) { - let entry = { + async fn take_pending_approval( + &self, + approval_id: &str, + kind: crate::state::PendingApprovalKind, + ) -> Option { + { let mut active = self.active_turn.lock().await; match active.as_mut() { Some(at) => { let mut ts = at.turn_state.lock().await; - ts.remove_pending_approval(approval_id) + ts.remove_pending_approval(approval_id, kind) } None => None, } - }; + } + } + + pub(crate) async fn take_pending_exec_approval( + &self, + approval_id: &str, + ) -> Option { + self.take_pending_approval(approval_id, crate::state::PendingApprovalKind::Exec) + .await + } + + pub(crate) async fn take_pending_patch_approval( + &self, + approval_id: &str, + ) -> Option { + self.take_pending_approval(approval_id, crate::state::PendingApprovalKind::Patch) + .await + } + + pub async fn notify_exec_approval(&self, approval_id: &str, decision: ReviewDecision) { + let entry = self.take_pending_exec_approval(approval_id).await; match entry { - Some(tx_approve) => { - tx_approve.send(decision).ok(); + Some(pending_approval) => { + pending_approval.send(decision); } None => { - warn!("No pending approval found for call_id: {approval_id}"); + warn!("No pending exec approval found for call_id: {approval_id}"); + } + } + } + + pub async fn notify_patch_approval(&self, approval_id: &str, decision: ReviewDecision) { + let entry = self.take_pending_patch_approval(approval_id).await; + match entry { + Some(pending_approval) => { + pending_approval.send(decision); + } + None => { + warn!("No pending patch approval found for call_id: {approval_id}"); } } } diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ece9d446b5..ec4c45c05a 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -755,6 +755,44 @@ fn validated_network_policy_amendment_host_rejects_mismatch() { assert!(message.contains("does not match approved host")); } +#[test] +fn accepted_command_decisions_add_only_exact_proposed_network_denials() { + let offered_allow = NetworkPolicyAmendment { + host: "example.com".to_string(), + action: NetworkPolicyRuleAction::Allow, + }; + let proposed_deny = NetworkPolicyAmendment { + host: "example.com".to_string(), + action: NetworkPolicyRuleAction::Deny, + }; + let available = vec![ + ReviewDecision::Approved, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: offered_allow.clone(), + }, + ReviewDecision::Abort, + ]; + + let accepted = accepted_command_approval_decisions( + available.clone(), + Some(&[offered_allow, proposed_deny.clone()]), + ); + + assert_eq!(&accepted[..available.len()], available.as_slice()); + assert_eq!( + accepted.last(), + Some(&ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: proposed_deny, + }) + ); + assert!(!accepted.contains(&ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: NetworkPolicyAmendment { + host: "other.example.com".to_string(), + action: NetworkPolicyRuleAction::Deny, + }, + })); +} + #[tokio::test] async fn start_managed_network_proxy_applies_execpolicy_network_rules() -> anyhow::Result<()> { let permission_profile = PermissionProfile::workspace_write(); diff --git a/codex-rs/core/src/state/mod.rs b/codex-rs/core/src/state/mod.rs index 20ff78b54f..0375693da9 100644 --- a/codex-rs/core/src/state/mod.rs +++ b/codex-rs/core/src/state/mod.rs @@ -11,6 +11,8 @@ pub(crate) use service::SessionServices; pub(crate) use session::SessionState; pub(crate) use turn::ActiveTurn; pub(crate) use turn::MailboxDeliveryPhase; +pub(crate) use turn::PendingApproval; +pub(crate) use turn::PendingApprovalKind; pub(crate) use turn::PendingRequestPermissions; pub(crate) use turn::RunningTask; pub(crate) use turn::TaskKind; diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index d1e31b7994..a036d97591 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -85,7 +85,7 @@ pub(crate) struct RunningTask { /// Mutable state for a single turn. #[derive(Default)] pub(crate) struct TurnState { - pending_approvals: HashMap>, + pending_approvals: HashMap<(PendingApprovalKind, String), PendingApproval>, pending_request_permissions: HashMap, pending_user_input: HashMap>, pending_elicitations: HashMap<(String, RequestId), oneshot::Sender>, @@ -99,6 +99,33 @@ pub(crate) struct TurnState { pub(crate) token_usage_at_turn_start: TokenUsage, } +pub(crate) struct PendingApproval { + tx_approve: oneshot::Sender, + accepted_decisions: Vec, +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(crate) enum PendingApprovalKind { + Exec, + Patch, +} + +impl PendingApproval { + pub(crate) fn accepts(&self, decision: &ReviewDecision) -> bool { + matches!( + decision, + ReviewDecision::Denied | ReviewDecision::TimedOut | ReviewDecision::Abort + ) || self + .accepted_decisions + .iter() + .any(|available| available == decision) + } + + pub(crate) fn send(self, decision: ReviewDecision) { + self.tx_approve.send(decision).ok(); + } +} + pub(crate) struct PendingRequestPermissions { pub(crate) tx_response: oneshot::Sender, pub(crate) requested_permissions: RequestPermissionProfile, @@ -110,15 +137,24 @@ impl TurnState { &mut self, key: String, tx: oneshot::Sender, - ) -> Option> { - self.pending_approvals.insert(key, tx) + kind: PendingApprovalKind, + accepted_decisions: Vec, + ) -> Option { + self.pending_approvals.insert( + (kind, key), + PendingApproval { + tx_approve: tx, + accepted_decisions, + }, + ) } pub(crate) fn remove_pending_approval( &mut self, key: &str, - ) -> Option> { - self.pending_approvals.remove(key) + kind: PendingApprovalKind, + ) -> Option { + self.pending_approvals.remove(&(kind, key.to_string())) } pub(crate) fn clear_pending_waiters(&mut self) { @@ -239,3 +275,7 @@ impl TurnState { self.strict_auto_review_enabled } } + +#[cfg(test)] +#[path = "turn_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/state/turn_tests.rs b/codex-rs/core/src/state/turn_tests.rs new file mode 100644 index 0000000000..f3057018d3 --- /dev/null +++ b/codex-rs/core/src/state/turn_tests.rs @@ -0,0 +1,126 @@ +use super::*; +use codex_protocol::approvals::ExecPolicyAmendment; + +fn pending_approval(accepted_decisions: Vec) -> PendingApproval { + let (tx_approve, _rx_approve) = oneshot::channel(); + PendingApproval { + tx_approve, + accepted_decisions, + } +} + +#[test] +fn one_shot_pending_approval_rejects_unoffered_persistent_decisions() { + let pending = pending_approval(vec![ReviewDecision::Approved, ReviewDecision::Abort]); + let amendment = ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec!["echo".to_string()]), + }; + + assert!(pending.accepts(&ReviewDecision::Approved)); + assert!(pending.accepts(&ReviewDecision::Denied)); + assert!(!pending.accepts(&ReviewDecision::ApprovedForSession)); + assert!(!pending.accepts(&amendment)); +} + +#[test] +fn cacheable_pending_approval_keeps_session_decision_compatibility() { + let pending = pending_approval(vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::Abort, + ]); + + assert!(pending.accepts(&ReviewDecision::ApprovedForSession)); +} + +#[test] +fn pending_approval_requires_the_exact_offered_amendment() { + let offered = ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec!["echo".to_string()]), + }; + let substituted = ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec!["rm".to_string()]), + }; + let pending = pending_approval(vec![ + ReviewDecision::Approved, + offered.clone(), + ReviewDecision::Abort, + ]); + + assert!(pending.accepts(&offered)); + assert!(!pending.accepts(&substituted)); + assert!(!pending.accepts(&ReviewDecision::ApprovedForSession)); +} + +#[test] +fn pending_approvals_with_the_same_id_are_isolated_by_request_kind() { + let (tx_patch, _rx_patch) = oneshot::channel(); + let (tx_exec, _rx_exec) = oneshot::channel(); + let mut turn_state = TurnState::default(); + turn_state.insert_pending_approval( + "approval".to_string(), + tx_patch, + PendingApprovalKind::Patch, + vec![ReviewDecision::Approved], + ); + turn_state.insert_pending_approval( + "approval".to_string(), + tx_exec, + PendingApprovalKind::Exec, + vec![ReviewDecision::Approved], + ); + + assert!( + turn_state + .remove_pending_approval("approval", PendingApprovalKind::Exec) + .is_some() + ); + assert!( + turn_state + .remove_pending_approval("approval", PendingApprovalKind::Patch) + .is_some() + ); +} + +#[tokio::test] +async fn consumed_approval_id_cannot_resolve_a_later_generation() { + for stale_decision in [ + ReviewDecision::Approved, + ReviewDecision::Abort, + ReviewDecision::Denied, + ] { + let mut turn_state = TurnState::default(); + let (initial_tx, initial_rx) = oneshot::channel(); + turn_state.insert_pending_approval( + "call-id".to_string(), + initial_tx, + PendingApprovalKind::Exec, + vec![ReviewDecision::Approved], + ); + turn_state + .remove_pending_approval("call-id", PendingApprovalKind::Exec) + .expect("initial waiter") + .send(ReviewDecision::Approved); + assert_eq!(initial_rx.await, Ok(ReviewDecision::Approved)); + + let (retry_tx, retry_rx) = oneshot::channel(); + turn_state.insert_pending_approval( + "retry-id".to_string(), + retry_tx, + PendingApprovalKind::Exec, + vec![ReviewDecision::Approved], + ); + + assert!( + turn_state + .remove_pending_approval("call-id", PendingApprovalKind::Exec) + .is_none(), + "stale {stale_decision:?} must not consume the retry waiter" + ); + turn_state + .remove_pending_approval("retry-id", PendingApprovalKind::Exec) + .expect("retry waiter remains pending") + .send(ReviewDecision::Approved); + assert_eq!(retry_rx.await, Ok(ReviewDecision::Approved)); + } +} diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 54205f7e8b..cc33286f16 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -2124,6 +2124,149 @@ async fn approving_apply_patch_for_session_skips_future_prompts_for_same_file() Ok(()) } +#[tokio::test(flavor = "current_thread")] +#[cfg(unix)] +async fn exec_approval_cannot_resolve_patch_approval() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let approval_policy = AskForApproval::UnlessTrusted; + let sandbox_policy = SandboxPolicy::DangerFullAccess; + let sandbox_policy_for_config = sandbox_policy.clone(); + + let mut builder = test_codex() + .with_model("gpt-5.4") + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + config + .set_legacy_sandbox_policy(sandbox_policy_for_config) + .expect("set sandbox policy"); + config.approvals_reviewer = ApprovalsReviewer::User; + }); + let test = builder.build(&server).await?; + + let target = TargetPath::OutsideWorkspace("apply_patch_reject_exec_response.txt"); + let (path, patch_path) = target.resolve_for_patch(&test); + let _path_cleanup = tempfile::TempPath::try_from_path(path.clone())?; + let _ = fs::remove_file(&path); + let patch = build_add_file_patch(&patch_path, "approved by patch response"); + let call_id = "apply_patch_reject_exec_response"; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_id, &patch), + ev_completed("resp-1"), + ]), + ) + .await; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ) + .await; + + submit_turn( + &test, + "apply patch with typed approval", + approval_policy, + sandbox_policy, + ) + .await?; + let approval = expect_patch_approval(&test, call_id).await; + + test.codex + .submit(Op::ExecApproval { + id: approval.call_id.clone(), + turn_id: None, + decision: ReviewDecision::Approved, + }) + .await?; + test.codex + .submit(Op::PatchApproval { + id: approval.call_id, + decision: ReviewDecision::Approved, + }) + .await?; + + wait_for_completion(&test).await; + assert_eq!(fs::read_to_string(&path)?, "approved by patch response\n"); + + Ok(()) +} + +#[tokio::test(flavor = "current_thread")] +#[cfg(unix)] +async fn patch_approval_cannot_resolve_exec_approval() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let approval_policy = AskForApproval::OnRequest; + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let mut builder = test_codex(); + let test = builder.build(&server).await?; + let call_id = "exec_reject_patch_response"; + let target = test.config.cwd.join("exec_reject_patch_response.txt"); + let _target_cleanup = tempfile::TempPath::try_from_path(target.clone())?; + let command = "touch exec_reject_patch_response.txt"; + + let event = shell_event( + call_id, + command, + /*timeout_ms*/ 1_000, + SandboxPermissions::RequireEscalated, + )?; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + event, + ev_completed("resp-1"), + ]), + ) + .await; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ) + .await; + + submit_turn( + &test, + "run command with typed approval", + approval_policy, + sandbox_policy, + ) + .await?; + let approval = expect_exec_approval(&test, command).await; + + test.codex + .submit(Op::PatchApproval { + id: approval.effective_approval_id(), + decision: ReviewDecision::Approved, + }) + .await?; + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::Approved, + }) + .await?; + + wait_for_completion(&test).await; + assert!(target.exists()); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] #[cfg(unix)] async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts() -> Result<()> { diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index e3415d945b..018b0edbd9 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -1405,6 +1405,11 @@ async fn handle_shell_command_user_approved_for_session_records_tool_decision() let EventMsg::ExecApprovalRequest(approval) = approval_event else { panic!("expected ExecApprovalRequest event"); }; + assert!( + approval + .effective_available_decisions() + .contains(&ReviewDecision::ApprovedForSession) + ); codex .submit(Op::ExecApproval { @@ -1615,6 +1620,11 @@ async fn handle_sandbox_error_user_approves_for_session_records_tool_decision() let EventMsg::ExecApprovalRequest(approval) = approval_event else { panic!("expected ExecApprovalRequest event"); }; + assert!( + approval + .effective_available_decisions() + .contains(&ReviewDecision::ApprovedForSession) + ); codex .submit(Op::ExecApproval { diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 5cf4f27f18..a1fff871b5 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -320,7 +320,7 @@ impl ExecApprovalRequestEvent { return vec![ReviewDecision::Approved, ReviewDecision::Abort]; } - let mut decisions = vec![ReviewDecision::Approved]; + let mut decisions = vec![ReviewDecision::Approved, ReviewDecision::ApprovedForSession]; if let Some(prefix) = proposed_execpolicy_amendment { decisions.push(ReviewDecision::ApprovedExecpolicyAmendment { proposed_execpolicy_amendment: prefix.clone(), @@ -417,6 +417,61 @@ mod tests { use codex_utils_absolute_path::test_support::test_path_buf; use pretty_assertions::assert_eq; + #[test] + fn cacheable_command_defaults_offer_session_and_exact_execpolicy_amendment() { + let amendment = ExecPolicyAmendment::new(vec!["cargo".to_string(), "test".to_string()]); + + assert_eq!( + ExecApprovalRequestEvent::default_available_decisions( + /*network_approval_context*/ None, + Some(&amendment), + /*proposed_network_policy_amendments*/ None, + /*additional_permissions*/ None, + ), + vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: amendment, + }, + ReviewDecision::Abort, + ] + ); + } + + #[test] + fn network_defaults_keep_exact_deny_amendment_hidden() { + let context = NetworkApprovalContext { + host: "example.com".to_string(), + protocol: NetworkApprovalProtocol::Https, + }; + let allow = NetworkPolicyAmendment { + host: context.host.clone(), + action: NetworkPolicyRuleAction::Allow, + }; + let deny = NetworkPolicyAmendment { + host: context.host.clone(), + action: NetworkPolicyRuleAction::Deny, + }; + + assert_eq!( + ExecApprovalRequestEvent::default_available_decisions( + Some(&context), + /*proposed_execpolicy_amendment*/ None, + Some(&[allow.clone(), deny]), + /*additional_permissions*/ None, + ), + vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: allow, + }, + ReviewDecision::Abort, + ] + ); + } + #[test] fn guardian_assessment_action_deserializes_command_shape() { let action: GuardianAssessmentAction = serde_json::from_value(serde_json::json!({