From 6bf1e3e68765e1c91e031f692e2b918dcd10365c Mon Sep 17 00:00:00 2001 From: jif Date: Fri, 27 Nov 2026 15:16:55 +0000 Subject: [PATCH] Persist command completions when approval is declined or fails (#64341) ## Why The app server completed command items for rejected approval responses directly in the live stream. That bypassed core's history recording, so clients could see a completed command live and lose it when reloading the turn. ## What changed Keep top-level command items with their pending approvals in core. Record and emit the command completion before unblocking the turn. Declines and cancellations produce a `declined` item, while invalid responses and approval request failures produce a `failed` item. ## Testing App-server integration tests cover cancellation, decline, and malformed responses. They check that `item/completed` precedes `turn/completed` and that paginated history returns the same command item after restart. GitOrigin-RevId: d3d95272c8a6af2fa65fa980f312260313cc5e32 --- .../app-server/src/bespoke_event_handling.rs | 151 +++++------------- .../app-server/tests/suite/v2/turn_start.rs | 103 +++++++++--- codex-rs/core/src/codex_thread.rs | 5 + codex-rs/core/src/session/command_approval.rs | 108 +++++++++++++ .../src/session/elicitation_holders_tests.rs | 2 +- codex-rs/core/src/session/handlers.rs | 3 +- codex-rs/core/src/session/mod.rs | 151 ++++++++++-------- codex-rs/core/src/state/turn.rs | 15 +- codex-rs/protocol/src/approvals.rs | 7 + codex-rs/protocol/src/protocol.rs | 6 +- 10 files changed, 332 insertions(+), 219 deletions(-) create mode 100644 codex-rs/core/src/session/command_approval.rs diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 079152a28d..f11d63f241 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -44,7 +44,6 @@ use codex_app_server_protocol::ModelSafetyBufferingUpdatedNotification; use codex_app_server_protocol::ModelVerificationNotification; use codex_app_server_protocol::NetworkApprovalContext as V2NetworkApprovalContext; use codex_app_server_protocol::NetworkPolicyAmendment as V2NetworkPolicyAmendment; -use codex_app_server_protocol::NetworkPolicyRuleAction as V2NetworkPolicyRuleAction; use codex_app_server_protocol::PermissionsRequestApprovalParams; use codex_app_server_protocol::PermissionsRequestApprovalResponse; use codex_app_server_protocol::RawResponseCompletedNotification; @@ -847,15 +846,11 @@ pub(crate) async fn apply_bespoke_event_handling( tokio::spawn(async move { on_command_execution_request_approval_response( event_turn_id, - conversation_id, - approval_id, - call_id, - completion_item, - opened_command_item, + approval_id.unwrap_or(call_id), + completion_item.filter(|_| opened_command_item), pending_request_id, rx, conversation, - outgoing, thread_state, permission_guard, ) @@ -2076,15 +2071,11 @@ async fn on_file_change_request_approval_response( #[allow(clippy::too_many_arguments)] async fn on_command_execution_request_approval_response( event_turn_id: String, - conversation_id: ThreadId, - approval_id: Option, - item_id: String, - completion_item: Option, - opened_command_item: bool, + approval_id: String, + opened_command: Option, pending_request_id: RequestId, receiver: oneshot::Receiver, conversation: Arc, - outgoing: ThreadScopedOutgoingMessageSender, thread_state: Arc>, permission_guard: Option, ) { @@ -2098,70 +2089,23 @@ async fn on_command_execution_request_approval_response( .lock() .await .network_approvals - .contains_key(approval_id.as_ref().unwrap_or(&item_id)) + .contains_key(&approval_id) { return; } - let (decision, completion_status) = match response { - Ok(Ok(value)) => { - match serde_json::from_value::(value) { - Ok(response) => match response.decision { - CommandExecutionApprovalDecision::Accept => (ReviewDecision::Approved, None), - CommandExecutionApprovalDecision::AcceptForSession => { - (ReviewDecision::ApprovedForSession, None) - } - CommandExecutionApprovalDecision::AcceptWithExecpolicyAmendment { - execpolicy_amendment, - } => ( - ReviewDecision::ApprovedExecpolicyAmendment { - proposed_execpolicy_amendment: execpolicy_amendment.into_core(), - }, - None, - ), - CommandExecutionApprovalDecision::ApplyNetworkPolicyAmendment { - network_policy_amendment, - } => { - let completion_status = match network_policy_amendment.action { - V2NetworkPolicyRuleAction::Allow => None, - V2NetworkPolicyRuleAction::Deny => { - Some(CommandExecutionStatus::Declined) - } - }; - ( - ReviewDecision::NetworkPolicyAmendment { - network_policy_amendment: network_policy_amendment.into_core(), - }, - completion_status, - ) - } - CommandExecutionApprovalDecision::Decline => ( - ReviewDecision::denied("rejected by user"), - Some(CommandExecutionStatus::Declined), - ), - CommandExecutionApprovalDecision::Cancel => ( - ReviewDecision::Abort, - Some(CommandExecutionStatus::Declined), - ), - }, - Err(err) => { - error!("failed to deserialize CommandExecutionRequestApprovalResponse: {err}"); - ( - ReviewDecision::denied("approval request failed"), - Some(CommandExecutionStatus::Failed), - ) - } - } - } + let response = match response { + Ok(Ok(value)) => serde_json::from_value::(value) + .map_err(|_| "invalid approval response"), Ok(Err(err)) if is_turn_transition_server_request_error(&err) => { // A late approval can open an item after its turn has already cleaned up. - if opened_command_item && let Some(completion_item) = completion_item { + if let Some(completion_item) = opened_command { let state = thread_state.lock().await; if !state.turn_summaries.contains_key(&event_turn_id) && let Some(sender) = state.listener_command_tx() && sender .send(ThreadListenerCommand::CompleteLateCommandApproval { turn_id: event_turn_id, - item_id, + item_id: approval_id, completion_item: Box::new(completion_item), }) .is_err() @@ -2171,57 +2115,40 @@ async fn on_command_execution_request_approval_response( } return; } - Ok(Err(err)) => { - error!("request failed with client error: {err:?}"); - ( - ReviewDecision::denied("approval request failed"), - Some(CommandExecutionStatus::Failed), - ) - } - Err(err) => { - error!("request failed: {err:?}"); - ( - ReviewDecision::denied("approval request failed"), - Some(CommandExecutionStatus::Failed), - ) + Ok(Err(_)) => Err("client approval request failed"), + Err(_) => Err("approval response channel closed"), + }; + let decision = match response { + Ok(response) => match response.decision { + CommandExecutionApprovalDecision::Accept => ReviewDecision::Approved, + CommandExecutionApprovalDecision::AcceptForSession => { + ReviewDecision::ApprovedForSession + } + CommandExecutionApprovalDecision::AcceptWithExecpolicyAmendment { + execpolicy_amendment, + } => ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: execpolicy_amendment.into_core(), + }, + CommandExecutionApprovalDecision::ApplyNetworkPolicyAmendment { + network_policy_amendment, + } => ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: network_policy_amendment.into_core(), + }, + CommandExecutionApprovalDecision::Decline => ReviewDecision::denied("rejected by user"), + CommandExecutionApprovalDecision::Cancel => ReviewDecision::Abort, + }, + Err(message) => { + error!("{message}"); + conversation + .fail_exec_approval(&approval_id, &event_turn_id) + .await; + return; } }; - let suppress_subcommand_completion_item = { - // For regular shell/unified_exec approvals, approval_id is null. - // For zsh-fork subcommand approvals, approval_id is present and - // item_id points to the parent command item. - if approval_id.is_some() { - let state = thread_state.lock().await; - state - .command_start_times - .get(&event_turn_id) - .is_some_and(|starts| starts.contains_key(&item_id)) - } else { - false - } - }; - - if let Some(status) = completion_status - && !suppress_subcommand_completion_item - && let Some(completion_item) = completion_item - { - complete_command_execution_item( - &conversation_id, - event_turn_id.clone(), - item_id.clone(), - completion_item, - status, - /*completed_at_ms*/ None, - &outgoing, - &thread_state, - ) - .await; - } - if let Err(err) = conversation .submit(Op::ExecApproval { - id: approval_id.unwrap_or_else(|| item_id.clone()), + id: approval_id, turn_id: Some(event_turn_id), decision, }) diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 175dcfc8db..e1a8c7a301 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -64,6 +64,8 @@ use codex_app_server_protocol::ThreadShellCommandParams; use codex_app_server_protocol::ThreadSource; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::ThreadTurnsListParams; +use codex_app_server_protocol::ThreadTurnsListResponse; use codex_app_server_protocol::TokenUsageBreakdown; use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnEnvironmentParams; @@ -3275,6 +3277,18 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { Ok(()) } +#[tokio::test] +async fn turn_start_exec_approval_cancel_completes_command_before_turn_v2() -> Result<()> { + run_turn_start_exec_approval_rejection_v2( + serde_json::to_value(CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Cancel, + })?, + CommandExecutionStatus::Declined, + /*expected_rejection*/ None, + ) + .await +} + #[tokio::test] async fn turn_start_exec_approval_decline_v2() -> Result<()> { run_turn_start_exec_approval_rejection_v2( @@ -3282,7 +3296,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> { decision: CommandExecutionApprovalDecision::Decline, })?, CommandExecutionStatus::Declined, - "rejected by user", + Some("rejected by user"), ) .await } @@ -3292,7 +3306,7 @@ async fn turn_start_exec_approval_invalid_response_v2() -> Result<()> { run_turn_start_exec_approval_rejection_v2( json!({ "unexpected": "response" }), CommandExecutionStatus::Failed, - "approval request failed", + Some("approval request failed"), ) .await } @@ -3300,7 +3314,7 @@ async fn turn_start_exec_approval_invalid_response_v2() -> Result<()> { async fn run_turn_start_exec_approval_rejection_v2( approval_response: Value, expected_status: CommandExecutionStatus, - expected_rejection: &str, + expected_rejection: Option<&str>, ) -> Result<()> { // TODO(anp): Remove after command approval routing accepts target-native Windows cwd. skip_if_wine_exec!( @@ -3324,15 +3338,15 @@ async fn run_turn_start_exec_approval_rejection_v2( let expected_display_command = expected_approval_command.replace(bearer_token, "[REDACTED_SECRET]"); - let responses = vec![ - create_escalated_command_execution_sse_response( - shell_command, - /*workdir*/ None, - Some(5000), - "call-decline", - )?, - create_final_assistant_message_sse_response("done")?, - ]; + let mut responses = vec![create_escalated_command_execution_sse_response( + shell_command, + /*workdir*/ None, + Some(5000), + "call-decline", + )?]; + if expected_rejection.is_some() { + responses.push(create_final_assistant_message_sse_response("done")?); + } let server = create_mock_responses_server_sequence(responses).await; MockResponsesConfig::new(&server.uri()) .with_approval_policy("on-request") @@ -3346,6 +3360,7 @@ async fn run_turn_start_exec_approval_rejection_v2( let ThreadStartResponse { thread, .. } = mcp .start_thread(ThreadStartParams { model: Some("mock-model".to_string()), + history_mode: Some(ThreadHistoryMode::Paginated), ..Default::default() }) .await?; @@ -3416,7 +3431,7 @@ async fn run_turn_start_exec_approval_rejection_v2( let completed: ItemCompletedNotification = mcp.read_notification("item/completed").await?; if let ThreadItemPayload::CommandExecution { .. } = completed.item.payload { - return Ok::(completed.item.payload); + return Ok::<_, anyhow::Error>(completed.item); } } }) @@ -3429,7 +3444,7 @@ async fn run_turn_start_exec_approval_rejection_v2( exit_code, aggregated_output, .. - } = completed_command_execution + } = completed_command_execution.payload.clone() else { unreachable!("loop ensures we break on command execution items"); }; @@ -3442,22 +3457,58 @@ async fn run_turn_start_exec_approval_rejection_v2( assert!(exit_code.is_none()); assert!(aggregated_output.is_none()); - timeout( + // read_notification buffers anything it skips while looking for item/completed. + assert!( + !mcp.pending_notification_methods() + .iter() + .any(|method| method == "turn/completed"), + "turn/completed arrived before the command's item/completed" + ); + let completed: TurnCompletedNotification = timeout( DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), + mcp.read_notification("turn/completed"), ) .await??; + assert_eq!(completed.turn.id, turn.id); + if let Some(expected_rejection) = expected_rejection { + let requests = server + .received_requests() + .await + .context("failed to fetch received requests")?; + assert!( + requests.iter().any(|request| { + request.url.path().ends_with("/responses") + && body_contains(request, expected_rejection) + }), + "model request should include approval rejection: {expected_rejection}" + ); + } else { + assert_eq!(completed.turn.status, TurnStatus::Interrupted); + } - let requests = server - .received_requests() - .await - .context("failed to fetch received requests")?; - assert!( - requests.iter().any(|request| { - request.url.path().ends_with("/responses") && body_contains(request, expected_rejection) - }), - "model request should include approval rejection: {expected_rejection}" - ); + assert!(mcp.shutdown_gracefully().await?.success()); + let mut mcp = TestAppServer::builder() + .with_codex_home(codex_home.as_path()) + .build_initialized() + .await?; + let page_id = mcp + .send_thread_turns_list_request(ThreadTurnsListParams { + thread_id: thread.id, + cursor: None, + limit: None, + sort_direction: None, + items_view: Some(TurnItemsView::Full), + }) + .await?; + let page: ThreadTurnsListResponse = mcp.read_response(page_id).await?; + assert_eq!(page.data.len(), 1); + assert_eq!(page.data[0].id, turn.id); + let commands = page.data[0] + .items + .iter() + .filter(|item| matches!(item.payload, ThreadItemPayload::CommandExecution { .. })) + .collect::>(); + assert_eq!(commands, vec![&completed_command_execution]); Ok(()) } diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 6f8391d0f4..c7752fa0ac 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -1537,6 +1537,11 @@ impl CodexThread { self.session.resume_config_snapshot().await } + /// Fail a pending command prompt when the client could not provide a decision. + pub async fn fail_exec_approval(&self, approval_id: &str, turn_id: &str) { + self.session.fail_exec_approval(approval_id, turn_id).await; + } + /// Returns the active turn's reviewer, including live updates, or the thread default. pub async fn approvals_reviewer_for_turn(&self, turn_id: &str) -> ApprovalsReviewer { if let Some((turn, settings, _, _)) = self diff --git a/codex-rs/core/src/session/command_approval.rs b/codex-rs/core/src/session/command_approval.rs new file mode 100644 index 0000000000..6fcc1a5f21 --- /dev/null +++ b/codex-rs/core/src/session/command_approval.rs @@ -0,0 +1,108 @@ +//! The pending approval owns the proposed command until the client replies. + +use super::Session; +use super::TurnContext; +use crate::state::PendingApproval; +use codex_protocol::approvals::NetworkPolicyRuleAction; +use codex_protocol::items::CommandExecutionItem; +use codex_protocol::items::CommandExecutionStatus; +use codex_protocol::items::TurnItem; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ReviewDecision; +use codex_utils_path_uri::PathUri; +use std::sync::Arc; + +pub(crate) struct ProposedCommand { + turn: Arc, + item: CommandExecutionItem, +} + +impl ProposedCommand { + pub(super) fn from_request( + turn: &Arc, + request: &ExecApprovalRequestEvent, + cwd: PathUri, + ) -> Option> { + if !request.starts_command() { + return None; + } + let item = CommandExecutionItem { + id: request.call_id.clone(), + model_context: request.model_context.clone(), + sandbox_type: None, + plugin_id: request.plugin_id.clone(), + script_path: request.script_path.clone(), + command: request.command.clone(), + cwd, + parsed_cmd: request.parsed_cmd.clone(), + process_id: None, + source: ExecCommandSource::Agent, + interaction_input: None, + status: CommandExecutionStatus::InProgress, + aggregated_output: None, + exit_code: None, + duration: None, + }; + Some(Box::new(Self { + turn: Arc::clone(turn), + item, + })) + } + + async fn complete(mut self, session: &Session, status: CommandExecutionStatus) { + self.item.status = status; + let event = session + .prepare_item_completed( + &self.turn, + TurnItem::CommandExecution(self.item), + /*content_token_count*/ None, + /*user_input_extension_data*/ None, + ) + .await; + // No process launched, so there is no legacy ExecCommandEnd to emit. + session + .send_event_raw(Event { + id: self.turn.sub_id.clone(), + msg: EventMsg::ItemCompleted(event), + }) + .await; + } +} + +impl PendingApproval { + pub(super) async fn resolve_command(&mut self, session: &Session, decision: &ReviewDecision) { + let status = match decision { + ReviewDecision::Approved + | ReviewDecision::ApprovedForSession + | ReviewDecision::ApprovedExecpolicyAmendment { .. } => return, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment, + } if network_policy_amendment.action == NetworkPolicyRuleAction::Allow => return, + ReviewDecision::NetworkPolicyAmendment { .. } + | ReviewDecision::Denied { .. } + | ReviewDecision::Abort => CommandExecutionStatus::Declined, + ReviewDecision::TimedOut | ReviewDecision::ApprovedMcpPolicyAmendment => { + CommandExecutionStatus::Failed + } + }; + if let Some(command) = self.command.take() { + command.complete(session, status).await; + } + } +} + +impl Session { + pub(crate) async fn fail_exec_approval(&self, approval_id: &str, turn_id: &str) { + if let Some((pending, _)) = self.take_pending_approval(approval_id, Some(turn_id)).await { + if let Some(command) = pending.command { + command.complete(self, CommandExecutionStatus::Failed).await; + } + let _ = pending + .sender + .send(ReviewDecision::denied("approval request failed")); + } + } +} diff --git a/codex-rs/core/src/session/elicitation_holders_tests.rs b/codex-rs/core/src/session/elicitation_holders_tests.rs index 00cbdad48b..0492b09128 100644 --- a/codex-rs/core/src/session/elicitation_holders_tests.rs +++ b/codex-rs/core/src/session/elicitation_holders_tests.rs @@ -91,7 +91,7 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro async move { session .request_command_approval( - turn_context.as_ref(), + &turn_context, ExecApprovalKind::Command, crate::guardian::GuardianReviewContext::from(turn_context.clone()) .model_context(), diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index d6f2d1211e..e7a2532820 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -188,13 +188,14 @@ impl Session { turn_id: Option, decision: ReviewDecision, ) { - let Some((pending, active_turn_id)) = self + let Some((mut pending, active_turn_id)) = self .take_pending_approval(&approval_id, turn_id.as_deref()) .await else { return; }; let decision = pending.validate(decision); + pending.resolve_command(self, &decision).await; if decision == ReviewDecision::Abort { let turn_id = if pending.kind == ExecApprovalKind::HumanCommand { Some(&pending.turn_id) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 6b4794dc98..5ce21a21ad 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -291,6 +291,7 @@ mod rollout_budget; mod rollout_reconstruction; mod sampling_interrupt; pub(crate) use sampling_interrupt::SamplingInterrupt; +pub(crate) mod command_approval; #[allow(clippy::module_inception)] pub(crate) mod session; pub(crate) mod startup_prewarm; @@ -3200,6 +3201,25 @@ impl Session { content_token_count: Option, user_input_extension_data: Option<&BTreeMap>, ) { + let event = self + .prepare_item_completed( + turn_context, + item, + content_token_count, + user_input_extension_data, + ) + .await; + self.send_event(turn_context, EventMsg::ItemCompleted(event)) + .await; + } + + async fn prepare_item_completed( + &self, + turn_context: &TurnContext, + item: TurnItem, + content_token_count: Option, + user_input_extension_data: Option<&BTreeMap>, + ) -> ItemCompletedEvent { record_turn_ttfm_metric(turn_context, &item).await; for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor @@ -3226,18 +3246,14 @@ impl Session { ); completed_at_ms }); - self.send_event( - turn_context, - EventMsg::ItemCompleted(ItemCompletedEvent { - thread_id: self.thread_id, - turn_id: turn_context.sub_id.clone(), - item, - content_token_count, - started_at_ms: Some(started_at_ms), - completed_at_ms, - }), - ) - .await; + ItemCompletedEvent { + thread_id: self.thread_id, + turn_id: turn_context.sub_id.clone(), + item, + content_token_count, + started_at_ms: Some(started_at_ms), + completed_at_ms, + } } /// Adds an execpolicy amendment to both the in-memory and on-disk policies so future @@ -3415,9 +3431,9 @@ impl Session { clippy::await_holding_invalid_type, reason = "active turn checks and turn state updates must remain atomic" )] - pub async fn request_command_approval( + pub(crate) async fn request_command_approval( &self, - turn_context: &TurnContext, + turn_context: &Arc, kind: ExecApprovalKind, model_context: ModelInvocationContext, call_id: String, @@ -3439,48 +3455,6 @@ impl Session { // command-level approvals use `call_id`. // `approval_id` identifies subcommand callbacks and stdin writes. 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, _network_prompt) = { - let mut active = self.active_turn.lock().await; - // The proxy reviews with the active turn's settings. A sandbox retry - // keeps its originating step's settings even after a background cell yields. - if let Some(binding) = turn_binding - && active - .as_ref() - .and_then(|turn| turn.task.as_ref()) - .is_none_or(|task| { - binding == NetworkApprovalTurn::Originating - && task.turn_context.sub_id != turn_context.sub_id - }) - { - return ReviewDecision::Abort; - } - match active.as_mut() { - Some(at) => { - let mut ts = at.turn_state.lock().await; - let prev = ts.insert_pending_approval( - effective_approval_id.clone(), - tx_approve, - kind, - turn_context.sub_id.clone(), - ); - let prompt = network_approval_context.as_ref().map(|_| { - ts.track_network_prompt( - &self.tx_event, - &turn_context.sub_id, - &effective_approval_id, - ) - }); - (prev, prompt) - } - None => (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![ @@ -3511,7 +3485,7 @@ impl Session { .as_ref() .map(PluginCommandAttribution::serialized_fields) .unzip(); - let event = EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { + let request = ExecApprovalRequestEvent { model_context: Some(model_context), kind, call_id, @@ -3522,7 +3496,7 @@ impl Session { environment_id, started_at_ms: now_unix_timestamp_ms(), command, - cwd: cwd.into(), + cwd: cwd.clone().into(), reason, network_approval_context, proposed_execpolicy_amendment, @@ -3530,9 +3504,57 @@ impl Session { additional_permissions, available_decisions: Some(available_decisions), parsed_cmd, - }); + }; + let command = command_approval::ProposedCommand::from_request(turn_context, &request, cwd); + // Add the tx_approve callback to the map before sending the request. + let (tx_approve, rx_approve) = oneshot::channel(); + let (prev_entry, _network_prompt) = { + let mut active = self.active_turn.lock().await; + // The proxy reviews with the active turn's settings. A sandbox retry + // keeps its originating step's settings even after a background cell yields. + if let Some(binding) = turn_binding + && active + .as_ref() + .and_then(|turn| turn.task.as_ref()) + .is_none_or(|task| { + binding == NetworkApprovalTurn::Originating + && task.turn_context.sub_id != turn_context.sub_id + }) + { + return ReviewDecision::Abort; + } + match active.as_mut() { + Some(at) => { + let mut ts = at.turn_state.lock().await; + let prev = ts.insert_pending_approval( + effective_approval_id.clone(), + PendingApproval { + sender: tx_approve, + kind, + turn_id: turn_context.sub_id.clone(), + command, + }, + ); + let prompt = request.network_approval_context.as_ref().map(|_| { + ts.track_network_prompt( + &self.tx_event, + &turn_context.sub_id, + &effective_approval_id, + ) + }); + (prev, prompt) + } + // Without an active turn there is no owner to receive a reply. + None => return ReviewDecision::Abort, + } + }; + if prev_entry.is_some() { + warn!("Overwriting existing pending approval for call_id: {effective_approval_id}"); + } + let _user_wait = self.start_user_wait_timing(turn_context, user_wait_owner.as_deref()); - self.send_event(turn_context, event).await; + self.send_event(turn_context, EventMsg::ExecApprovalRequest(request)) + .await; rx_approve.await.unwrap_or(ReviewDecision::Abort) } @@ -3560,9 +3582,12 @@ impl Session { let mut ts = at.turn_state.lock().await; ts.insert_pending_approval( approval_id.clone(), - tx_approve, - ExecApprovalKind::Command, - turn_context.sub_id.clone(), + PendingApproval { + sender: tx_approve, + kind: ExecApprovalKind::Command, + turn_id: turn_context.sub_id.clone(), + command: None, + }, ) } None => None, diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index 39b587c96b..261d036dce 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -24,6 +24,7 @@ use crate::agent::types::AgentExecutionGuard; use crate::session::PendingUserInput; use crate::session::SamplingInterrupt; use crate::session::TurnInputQueue; +use crate::session::command_approval::ProposedCommand; use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnEnvironment; @@ -124,6 +125,7 @@ pub(crate) struct TurnState { } pub(crate) struct PendingApproval { + pub(crate) command: Option>, pub(crate) sender: oneshot::Sender, pub(crate) kind: codex_protocol::approvals::ExecApprovalKind, // A yielded cell can emit a prompt for its original turn while a later turn services it. @@ -199,21 +201,12 @@ impl TurnState { pub(crate) fn insert_pending_approval( &mut self, key: String, - tx: oneshot::Sender, - kind: codex_protocol::approvals::ExecApprovalKind, - turn_id: String, + pending: PendingApproval, ) -> Option { self.pending_approvals .lock() .unwrap_or_else(PoisonError::into_inner) - .insert( - key, - PendingApproval { - sender: tx, - kind, - turn_id, - }, - ) + .insert(key, pending) } pub(crate) fn remove_pending_approval( diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 6b1f0ef34e..6762bbfe99 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -356,6 +356,13 @@ pub struct ExecApprovalRequestEvent { } impl ExecApprovalRequestEvent { + /// Only a top-level command prompt opens a new execution item. + pub fn starts_command(&self) -> bool { + self.kind == ExecApprovalKind::Command + && self.approval_id.is_none() + && self.network_approval_context.is_none() + } + pub fn effective_approval_id(&self) -> String { self.approval_id .clone() diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 689f679999..2b9b6ce177 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1780,11 +1780,7 @@ impl EventMsg { /// Stdin and network reviews have their own prompts for an existing operation. pub fn command_approval_start(&self) -> Option<(&str, i64)> { match self { - Self::ExecApprovalRequest(request) - if request.kind == crate::approvals::ExecApprovalKind::Command - && request.approval_id.is_none() - && request.network_approval_context.is_none() => - { + Self::ExecApprovalRequest(request) if request.starts_command() => { Some((&request.call_id, request.started_at_ms)) } Self::GuardianAssessment(assessment)