diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index f11d63f241..3e34d44009 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -4,7 +4,6 @@ use crate::outgoing_message::ThreadScopedOutgoingMessageSender; use crate::request_processors::thread_settings_from_config_snapshot; use crate::server_request_error::is_turn_transition_server_request_error; use crate::thread_state::PendingNetworkApproval; -use crate::thread_state::ThreadListenerCommand; use crate::thread_state::ThreadState; use crate::thread_state::resolve_server_request_on_thread_listener; use crate::thread_status::ThreadWatchActiveGuard; @@ -15,7 +14,6 @@ use codex_app_server_protocol::AuthRecoveryNotification; use codex_app_server_protocol::CodexErrorInfo as V2CodexErrorInfo; use codex_app_server_protocol::CommandAction as V2ParsedCommand; use codex_app_server_protocol::CommandExecutionApprovalDecision; -use codex_app_server_protocol::CommandExecutionPresentation; use codex_app_server_protocol::CommandExecutionRequestApprovalParams; use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; use codex_app_server_protocol::CommandExecutionSource; @@ -129,13 +127,8 @@ use tokio::sync::Mutex; use tokio::sync::oneshot; use tracing::error; -enum CommandExecutionApprovalPresentation { - Network(V2NetworkApprovalContext), - Command(CommandExecutionCompletionItem), -} - #[derive(Debug, PartialEq)] -pub(crate) struct CommandExecutionCompletionItem { +struct CommandExecutionCompletionItem { model_context: Option, plugin_id: Option, script_path: Option, @@ -168,7 +161,7 @@ pub(crate) async fn apply_bespoke_event_handling( if finishes_latest_turn { outgoing.abort_pending_server_requests().await; } - let approval_starts_command = msg.command_approval_start().is_some(); + let assessment_starts_command = msg.guardian_command_start().is_some(); match msg { EventMsg::TurnStarted(payload) => { outgoing.abort_pending_server_requests().await; @@ -344,7 +337,7 @@ pub(crate) async fn apply_bespoke_event_handling( } else { assessment.turn_id.clone() }; - if approval_starts_command + if assessment_starts_command && let Some((target_item_id, completion_item)) = pending_command_execution.as_ref() { start_command_execution_item( @@ -701,11 +694,8 @@ pub(crate) async fn apply_bespoke_event_handling( .map(CommandExecutionApprovalDecision::from) .collect::>(); let ExecApprovalRequestEvent { - model_context, kind, call_id, - plugin_id, - script_path, approval_id, turn_id, environment_id, @@ -737,8 +727,6 @@ pub(crate) async fn apply_bespoke_event_handling( return; } }; - let command_presentation = - CommandExecutionPresentation::from_raw(&command, &parsed_cmd, &cwd_uri); // Approval requests retain the exact command; only history is redacted. let command_actions = match cwd_uri.to_abs_path() { Ok(native_cwd) => parsed_cmd @@ -750,50 +738,12 @@ pub(crate) async fn apply_bespoke_event_handling( command: shlex_join(&command), }], }; - let presentation = if let Some(network_approval_context) = - network_approval_context.map(V2NetworkApprovalContext::from) - { - CommandExecutionApprovalPresentation::Network(network_approval_context) + let network_approval_context = + network_approval_context.map(V2NetworkApprovalContext::from); + let (command, cwd, command_actions) = if network_approval_context.is_some() { + (None, None, None) } else { - let completion_item = CommandExecutionCompletionItem { - model_context, - plugin_id, - script_path, - command: command_presentation.command, - cwd: cwd.clone(), - command_actions: command_presentation.command_actions, - }; - CommandExecutionApprovalPresentation::Command(completion_item) - }; - let (network_approval_context, command, cwd, command_actions, completion_item) = - match presentation { - CommandExecutionApprovalPresentation::Network(network_approval_context) => { - (Some(network_approval_context), None, None, None, None) - } - CommandExecutionApprovalPresentation::Command(completion_item) => ( - None, - Some(shlex_join(&command)), - Some(completion_item.cwd.clone()), - Some(command_actions), - (kind != codex_protocol::approvals::ExecApprovalKind::HumanCommand) - .then_some(completion_item), - ), - }; - let opened_command_item = if approval_starts_command - && let Some(completion_item) = completion_item.as_ref() - { - start_command_execution_item( - &conversation_id, - event_turn_id.clone(), - call_id.clone(), - started_at_ms, - completion_item, - &outgoing, - &thread_state, - ) - .await - } else { - false + (Some(shlex_join(&command)), Some(cwd), Some(command_actions)) }; let proposed_execpolicy_amendment_v2 = proposed_execpolicy_amendment.map(V2ExecPolicyAmendment::from); @@ -847,7 +797,6 @@ pub(crate) async fn apply_bespoke_event_handling( on_command_execution_request_approval_response( event_turn_id, approval_id.unwrap_or(call_id), - completion_item.filter(|_| opened_command_item), pending_request_id, rx, conversation, @@ -1120,7 +1069,7 @@ pub(crate) async fn apply_bespoke_event_handling( EventMsg::ViewImageToolCall(_) => {} EventMsg::ItemStarted(event) => { let should_emit = match &event.item { - // Approval and guardian flows can emit the command start notification before core + // Guardian can emit the command start notification before core // emits the canonical item. Keep the first observed start and suppress that duplicate. CoreTurnItem::CommandExecution(item) => thread_state .lock() @@ -1537,7 +1486,7 @@ async fn start_command_execution_item( } #[allow(clippy::too_many_arguments)] -pub(crate) async fn complete_command_execution_item( +async fn complete_command_execution_item( conversation_id: &ThreadId, turn_id: String, item_id: String, @@ -1576,7 +1525,7 @@ pub(crate) async fn complete_command_execution_item( turn_id, item, Some(started_at_ms), - // Guardian supplies the decision time used on resume. Manual approvals are timed here. + // Guardian supplies the decision time used on resume. completed_at_ms.unwrap_or_else(now_unix_timestamp_ms), ); outgoing @@ -2068,11 +2017,9 @@ 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, approval_id: String, - opened_command: Option, pending_request_id: RequestId, receiver: oneshot::Receiver, conversation: Arc, @@ -2096,25 +2043,7 @@ async fn on_command_execution_request_approval_response( 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 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: approval_id, - completion_item: Box::new(completion_item), - }) - .is_err() - { - error!("failed to complete late command approval: thread listener closed"); - } - } - return; - } + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(_)) => Err("client approval request failed"), Err(_) => Err("approval response channel closed"), }; diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index ae46933957..ee7ecca8cb 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -1,10 +1,8 @@ use super::thread_processor::THREAD_ITEMS_MAX_LIMIT; use super::thread_processor::thread_turns_page_size; use super::*; -use crate::bespoke_event_handling::complete_command_execution_item; use crate::extensions::send_thread_warning; use crate::thread_state::ListenerStateCandidate; -use codex_app_server_protocol::CommandExecutionStatus; use codex_app_server_protocol::McpToolCallStatus; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadQueueChangedNotification; @@ -1069,31 +1067,6 @@ async fn handle_thread_listener_command( ThreadListenerCommand::EmitThreadGoalSnapshot { state_db } => { send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await; } - ThreadListenerCommand::CompleteLateCommandApproval { - turn_id, - item_id, - completion_item, - } => { - let subscribers = thread_state_manager - .subscribed_connection_ids(conversation_id) - .await; - let outgoing = ThreadScopedOutgoingMessageSender::new( - Arc::clone(outgoing), - subscribers, - conversation_id, - ); - complete_command_execution_item( - &conversation_id, - turn_id, - item_id, - *completion_item, - CommandExecutionStatus::Declined, - /*completed_at_ms*/ None, - &outgoing, - thread_state, - ) - .await; - } ThreadListenerCommand::ResolveServerRequest { request_id, completion_tx, diff --git a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs index 0b2cce3658..a8c96c4e6e 100644 --- a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs @@ -93,9 +93,35 @@ pub(super) async fn test_processor( } #[tokio::test] -async fn late_command_cancellation_reaches_the_current_subscriber() -> Result<()> { - let server = wiremock::MockServer::start().await; - let test = test_codex().build_with_auto_env(&server).await?; +async fn cancelled_command_approval_reaches_the_current_subscriber() -> Result<()> { + use codex_app_server_protocol::ServerRequest; + use codex_config::Constrained; + use codex_core::TurnInputRequest; + use codex_protocol::config_types::ApprovalsReviewer; + use codex_protocol::protocol::AskForApproval; + + let server = responses::start_mock_server().await; + responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("approval"), + responses::ev_function_call( + "pending-command", + "exec_command", + r#"{"cmd":"git status"}"#, + ), + responses::ev_completed("approval"), + ]), + ) + .await; + let test = test_codex() + .with_config(|config| { + config.permissions.approval_policy = + Constrained::allow_any(AskForApproval::UnlessTrusted); + config.approvals_reviewer = ApprovalsReviewer::User; + }) + .build_with_auto_env(&server) + .await?; let thread_id = test.session_configured.thread_id; let (processor, mut messages) = test_processor(&test).await?; let thread_state_manager = &processor.thread_state_manager; @@ -109,32 +135,27 @@ async fn late_command_cancellation_reaches_the_current_subscriber() -> Result<() processor .try_attach_thread_listener(thread_id, test.codex.clone(), vec![original]) .await; - let outgoing = ThreadScopedOutgoingMessageSender::new( - processor.outgoing.clone(), - vec![original], - thread_id, - ); - let approval = serde_json::from_value(serde_json::json!({ - "turn_id": "finished-turn", - "call_id": "late-command", - "started_at_ms": 42, - "command": ["echo", "late"], - "parsed_cmd": [], - "cwd": test.config.cwd, - }))?; - apply_bespoke_event_handling( - codex_protocol::protocol::Event { - id: "finished-turn".into(), - msg: EventMsg::ExecApprovalRequest(approval), - }, - thread_id, - test.codex.clone(), - test.thread_manager.clone(), - outgoing.clone(), - thread_state_manager.thread_state(thread_id).await, - processor.thread_watch_manager.clone(), - ) - .await; + test.codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "check git status".into(), + text_elements: Vec::new(), + }])) + .await?; + loop { + if let OutgoingEnvelope::ToConnection { + connection_id, + message: + OutgoingMessage::Request(ServerRequest::CommandExecutionRequestApproval { + params, .. + }), + .. + } = messages.recv().await.context("outgoing channel closed")? + { + assert_eq!(connection_id, original); + assert_eq!(params.item_id, "pending-command"); + break; + } + } assert!( thread_state_manager @@ -146,7 +167,7 @@ async fn late_command_cancellation_reaches_the_current_subscriber() -> Result<() .unsubscribe_connection_from_thread(thread_id, original) .await ); - outgoing.abort_pending_server_requests().await; + test.codex.submit(Op::Interrupt).await?; let recipient = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async { while let Some(message) = messages.recv().await { @@ -156,12 +177,12 @@ async fn late_command_cancellation_reaches_the_current_subscriber() -> Result<() .. } = message && let ServerNotification::ItemCompleted(event) = notification.notification - && event.item.id() == "late-command" + && event.item.id() == "pending-command" { return Ok(connection_id); } } - anyhow::bail!("missing late command completion") + anyhow::bail!("missing cancelled command completion") }) .await??; assert_eq!(recipient, resumed); diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index b64b775273..f58f36e9aa 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -1,4 +1,3 @@ -use crate::bespoke_event_handling::CommandExecutionCompletionItem; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::ConnectionRequestId; use codex_app_server_protocol::RequestId; @@ -93,11 +92,6 @@ pub(crate) enum ThreadListenerCommand { EmitThreadGoalSnapshot { state_db: StateDbHandle, }, - CompleteLateCommandApproval { - turn_id: String, - item_id: String, - completion_item: Box, - }, // ResolveServerRequest is used to notify the client that the request has been resolved. // It is executed in the thread listener's context to ensure that the resolved notification is ordered with regard to the request itself. ResolveServerRequest { diff --git a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs index ce096c47f6..e95ee715ae 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs @@ -16,12 +16,16 @@ use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ServerRequestResolvedNotification; +use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ThreadItemPayload; 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::TurnCompletedNotification; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnInterruptResponse; +use codex_app_server_protocol::TurnItemsView; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStartedNotification; @@ -291,6 +295,7 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<() let ThreadStartResponse { thread, .. } = mcp .start_thread(ThreadStartParams { model: Some("mock-model".to_string()), + history_mode: Some(ThreadHistoryMode::Paginated), ..Default::default() }) .await?; @@ -363,6 +368,38 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<() ); assert!(call.execution.ended_at_unix_ms >= Some(call.execution.started_at_unix_ms)); + let mut restarted = TestAppServer::builder() + .with_codex_home(&codex_home) + .build_initialized() + .await?; + let page_id = restarted + .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 = restarted.read_response(page_id).await?; + let [saved] = page.data.as_slice() else { + anyhow::bail!("expected the interrupted turn in history"); + }; + assert_eq!(saved.id, turn.id); + assert_eq!(saved.status, TurnStatus::Interrupted); + let commands = saved + .items + .iter() + .filter_map(|item| match &item.payload { + ThreadItemPayload::CommandExecution { id, status, .. } => Some((id, status)), + _ => None, + }) + .collect::>(); + assert_eq!( + commands, + vec![(¶ms.item_id, &CommandExecutionStatus::Declined)] + ); + Ok(()) } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 6f2dc38cc3..56ea6250c7 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1791,7 +1791,9 @@ async fn maybe_request_mcp_tool_approval( retry_reason: None, network_approval_context: None, }; - let approval = sess.request_approval(action, approval_context).await; + let approval = sess + .request_approval(action, approval_context, /*command_approval*/ None) + .await; Some(McpToolApproval { decision: match approval.result { Ok(decision) => decision, diff --git a/codex-rs/core/src/session/command_approval.rs b/codex-rs/core/src/session/command_approval.rs index 6fcc1a5f21..94c8876237 100644 --- a/codex-rs/core/src/session/command_approval.rs +++ b/codex-rs/core/src/session/command_approval.rs @@ -1,4 +1,5 @@ -//! The pending approval owns the proposed command until the client replies. +//! The pending approval owns the proposal during review, then returns it to +//! the invocation for launch. Dropping either owner finishes an abandoned item. use super::Session; use super::TurnContext; @@ -14,20 +15,41 @@ use codex_protocol::protocol::ExecCommandSource; use codex_protocol::protocol::ReviewDecision; use codex_utils_path_uri::PathUri; use std::sync::Arc; +use tokio::task::JoinHandle; +use tokio_util::task::task_tracker::TaskTrackerToken; +use tracing::Instrument; -pub(crate) struct ProposedCommand { +pub(super) struct ApprovalRequestFailed; + +struct ProposedCommand { + publication: TaskTrackerToken, + interrupted_status: CommandExecutionStatus, + session: Arc, turn: Arc, item: CommandExecutionItem, + started_at_ms: i64, } -impl ProposedCommand { - pub(super) fn from_request( +/// The proposal belongs to one invocation across approvals and sandbox retries. +#[derive(Default)] +pub(crate) struct CommandApproval(Option>); + +impl CommandApproval { + pub(super) async fn start( + &mut self, + session: &Arc, turn: &Arc, request: &ExecApprovalRequestEvent, cwd: PathUri, - ) -> Option> { - if !request.starts_command() { - return None; + ) -> Result<(), ApprovalRequestFailed> { + if self.0.is_some() { + return Ok(()); + } + // Register before checking shutdown so it waits for every admitted proposal, + // including the completion task spawned when the caller is dropped. + let publication = session.command_approval_publications.token(); + if session.command_approval_publications.is_closed() { + return Err(ApprovalRequestFailed); } let item = CommandExecutionItem { id: request.call_id.clone(), @@ -46,15 +68,67 @@ impl ProposedCommand { exit_code: None, duration: None, }; - Some(Box::new(Self { + let event = session + .prepare_item_started( + turn, + TurnItem::CommandExecution(item.clone()), + request.started_at_ms, + ) + .await; + let started_at_ms = event.started_at_ms; + // Sending to the client queue is the last step of send_event_raw. Take + // ownership before the next await. The legacy begin waits for launch. + session + .send_event_raw(Event { + id: turn.sub_id.clone(), + msg: EventMsg::ItemStarted(event), + }) + .await; + self.0 = Some(Box::new(ProposedCommand { + publication, + interrupted_status: CommandExecutionStatus::Declined, + session: Arc::clone(session), turn: Arc::clone(turn), item, - })) + started_at_ms, + })); + Ok(()) } - async fn complete(mut self, session: &Session, status: CommandExecutionStatus) { + /// Release the proposal when execution takes over completion. + /// Its original start time is used for the legacy begin event. + pub(crate) fn handoff(&mut self) -> Option { + self.0.take().map(|command| command.started_at_ms) + } + + pub(crate) async fn fail(&mut self) { + self.finish(CommandExecutionStatus::Failed).await; + } + + async fn finish(&mut self, status: CommandExecutionStatus) { + if let Some(command) = self.0.take() + && let Err(err) = command.publish_completion(status).await + { + tracing::warn!(%err, "command approval publication failed"); + } + } + + fn approved(&mut self) { + if let Some(command) = self.0.as_mut() { + command.interrupted_status = CommandExecutionStatus::Failed; + } + } +} + +impl ProposedCommand { + fn publish_completion(self, status: CommandExecutionStatus) -> JoinHandle<()> { + tokio::spawn(self.complete(status).in_current_span()) + } + + async fn complete(mut self, status: CommandExecutionStatus) { self.item.status = status; - let event = session + let event = self + .session .prepare_item_completed( &self.turn, TurnItem::CommandExecution(self.item), @@ -63,24 +137,37 @@ impl ProposedCommand { ) .await; // No process launched, so there is no legacy ExecCommandEnd to emit. - session + self.session .send_event_raw(Event { id: self.turn.sub_id.clone(), msg: EventMsg::ItemCompleted(event), }) .await; + drop(self.publication); + } +} + +impl Drop for CommandApproval { + fn drop(&mut self) { + // A tool can be cancelled while awaiting a reply or preparing to launch. + if let Some(command) = self.0.take() { + let status = command.interrupted_status; + drop(command.publish_completion(status)); + } } } impl PendingApproval { - pub(super) async fn resolve_command(&mut self, session: &Session, decision: &ReviewDecision) { + pub(super) async fn resolve_command(&mut self, decision: &ReviewDecision) { let status = match decision { ReviewDecision::Approved | ReviewDecision::ApprovedForSession - | ReviewDecision::ApprovedExecpolicyAmendment { .. } => return, + | ReviewDecision::ApprovedExecpolicyAmendment { .. } => return self.command.approved(), ReviewDecision::NetworkPolicyAmendment { network_policy_amendment, - } if network_policy_amendment.action == NetworkPolicyRuleAction::Allow => return, + } if network_policy_amendment.action == NetworkPolicyRuleAction::Allow => { + return self.command.approved(); + } ReviewDecision::NetworkPolicyAmendment { .. } | ReviewDecision::Denied { .. } | ReviewDecision::Abort => CommandExecutionStatus::Declined, @@ -88,21 +175,16 @@ impl PendingApproval { CommandExecutionStatus::Failed } }; - if let Some(command) = self.command.take() { - command.complete(session, status).await; - } + self.command.finish(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")); + if let Some((mut pending, _)) = self.take_pending_approval(approval_id, Some(turn_id)).await + { + pending.command.fail().await; + pending.reply(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 0492b09128..ae99129f9e 100644 --- a/codex-rs/core/src/session/elicitation_holders_tests.rs +++ b/codex-rs/core/src/session/elicitation_holders_tests.rs @@ -9,8 +9,6 @@ use std::time::Duration; use std::time::Instant; use crate::tools::handlers::PreparedPermissionRequest; -use codex_core_plugins::PluginCommandAttribution; -use codex_plugin::PluginId; use codex_protocol::approvals::ExecApprovalKind; use codex_protocol::protocol::ReviewDecision; use codex_protocol::request_permissions::PermissionGrantScope; @@ -22,9 +20,13 @@ use pretty_assertions::assert_eq; use tokio::sync::watch; use tokio_util::sync::CancellationToken; +use super::command_approval::CommandApproval; use super::tests::make_session_and_context_with_rx; use crate::session::step_context::StepContext; use crate::state::ActiveTurn; +use codex_protocol::items::CommandExecutionStatus; +use codex_protocol::items::TurnItem; +use codex_protocol::protocol::EventMsg; fn start_timing( turn: &mut Arc, @@ -79,16 +81,14 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro let mut pause_state = session.subscribe_elicitation_pause_state(); #[allow(deprecated)] let cwd = turn_context.cwd.clone(); - let plugin_attribution = PluginCommandAttribution { - plugin_id: PluginId::parse("sample@openai-curated").expect("valid plugin id"), - normalized_relative_path: "scripts/run.py".to_string(), - }; let request = tokio::spawn({ let prompt_id = prompt_id.to_owned(); let session = session.clone(); let turn_context = turn_context.clone(); async move { + // Dropping the invocation after approval simulates interruption during setup. + let mut command = CommandApproval::default(); session .request_command_approval( &turn_context, @@ -106,25 +106,36 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro /*proposed_execpolicy_amendment*/ None, /*additional_permissions*/ None, /*available_decisions*/ None, - /*plugin_attribution_override*/ Some(plugin_attribution), + /*command_environment*/ None, + Some(&mut command), ) .await } }); + let start = events.recv().await.expect("command start"); + assert!(matches!(start.msg, EventMsg::ItemStarted(_))); let event = events.recv().await.expect("approval event"); - let codex_protocol::protocol::EventMsg::ExecApprovalRequest(event) = event.msg else { - panic!("expected command approval event"); - }; - assert_eq!(event.plugin_id.as_deref(), Some("sample@openai-curated")); - assert_eq!(event.script_path.as_deref(), Some("scripts/run.py")); + assert!(matches!(event.msg, EventMsg::ExecApprovalRequest(_))); wait_until_held(&mut pause_state).await; session .notify_approval(prompt_id, ReviewDecision::Approved) .await; - request.await.expect("approval task"); + assert_eq!( + request.await.expect("approval task"), + ReviewDecision::Approved + ); wait_until_released(&mut pause_state).await; assert_user_wait(&timing, timing_start, capture); + + let EventMsg::ItemCompleted(event) = events.recv().await.expect("command completion").msg + else { + panic!("expected completion after interruption"); + }; + let TurnItem::CommandExecution(item) = event.item else { + panic!("expected a command"); + }; + assert_eq!(item.status, CommandExecutionStatus::Failed); } #[test_case::test_case(true; "capture_on")] diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 79fe41b193..24a6a79dcb 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -195,7 +195,7 @@ impl Session { return; }; let decision = pending.validate(decision); - pending.resolve_command(self, &decision).await; + pending.resolve_command(&decision).await; if decision == ReviewDecision::Abort { let turn_id = if pending.kind == ExecApprovalKind::HumanCommand { Some(&pending.turn_id) @@ -225,7 +225,7 @@ impl Session { }) .await; } - let _ = pending.sender.send(decision); + pending.reply(decision); } } @@ -239,7 +239,7 @@ async fn cancel_patch_approval(sess: &Arc, id: &str, expected_turn_id: /*error*/ None, ) .await; - let _ = pending.sender.send(ReviewDecision::Abort); + pending.reply(ReviewDecision::Abort); } pub async fn request_user_input_response( @@ -364,6 +364,7 @@ pub async fn set_thread_memory_mode(sess: &Arc, sub_id: String, mode: T } pub(super) async fn shutdown_session_runtime(sess: &Arc) { + sess.command_approval_publications.close(); if let Some(reporting) = &sess.outcome_reporting { reporting.handoffs.close(); } @@ -465,6 +466,8 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc) { sess.services.mcp_runtime.shutdown().await; sess.drain_code_mode_messages().await; + // Cancelled prompts can still be appending their terminal items. + sess.command_approval_publications.wait().await; let writes = &sess.services.unified_exec_manager.launch_failure_writes; writes.close(); diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 5ce21a21ad..c38f3c9bb0 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2808,7 +2808,7 @@ impl Session { /// Persist the event to rollout and send it to clients. pub(crate) async fn send_event(&self, turn_context: &TurnContext, msg: EventMsg) { crate::agent::turn_metrics::record_terminal_event(turn_context, &msg); - if let Some((item_id, started_at_ms)) = msg.command_approval_start() { + if let Some((item_id, started_at_ms)) = msg.guardian_command_start() { // The client can see the command before execution. Keep its first start // for the canonical lifecycle events that will be saved in history. turn_context @@ -3164,20 +3164,29 @@ impl Session { } pub(crate) async fn emit_turn_item_started(&self, turn_context: &TurnContext, item: &TurnItem) { + let event = self + .prepare_item_started(turn_context, item.clone(), now_unix_timestamp_ms()) + .await; + self.send_event(turn_context, EventMsg::ItemStarted(event)) + .await; + } + + async fn prepare_item_started( + &self, + turn_context: &TurnContext, + item: TurnItem, + started_at_ms: i64, + ) -> ItemStartedEvent { let started_at_ms = turn_context .turn_timing_state - .record_item_started(item.id(), now_unix_timestamp_ms()) + .record_item_started(item.id(), started_at_ms) .await; - self.send_event( - turn_context, - EventMsg::ItemStarted(ItemStartedEvent { - thread_id: self.thread_id, - turn_id: turn_context.sub_id.clone(), - item: item.clone(), - started_at_ms, - }), - ) - .await; + ItemStartedEvent { + thread_id: self.thread_id, + turn_id: turn_context.sub_id.clone(), + item, + started_at_ms, + } } pub(crate) async fn emit_turn_item_completed( @@ -3432,7 +3441,7 @@ impl Session { reason = "active turn checks and turn state updates must remain atomic" )] pub(crate) async fn request_command_approval( - &self, + self: &Arc, turn_context: &Arc, kind: ExecApprovalKind, model_context: ModelInvocationContext, @@ -3447,7 +3456,8 @@ impl Session { proposed_execpolicy_amendment: Option, additional_permissions: Option, available_decisions: Option>, - plugin_attribution_override: Option, + command_environment: Option<&Environment>, + mut command_approval: Option<&mut command_approval::CommandApproval>, ) -> ReviewDecision { let (network_approval_context, turn_binding) = network_approval.unzip(); let user_wait_owner = self.user_wait_timing_owner(turn_context, timing_call_id); @@ -3476,11 +3486,23 @@ impl Session { additional_permissions.as_ref(), ) }); - let plugin_attribution = plugin_attribution_override.or_else(|| { + let plugin_attribution = if let Some(environment) = + command_environment.filter(|env| env.is_remote()) + { + // A slow attribution lookup should not prevent the approval prompt. + let fs = environment.get_filesystem_without_reconnect(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + turn_context.plugin_attribution_for_executor_command(&command, &cwd, fs.as_ref()), + ) + .await + .ok() + .flatten() + } else { cwd.to_abs_path() .ok() .and_then(|cwd| turn_context.plugin_attribution_for_command(&command, &cwd)) - }); + }; let (plugin_id, script_path) = plugin_attribution .as_ref() .map(PluginCommandAttribution::serialized_fields) @@ -3505,10 +3527,36 @@ impl Session { available_decisions: Some(available_decisions), parsed_cmd, }; - let command = command_approval::ProposedCommand::from_request(turn_context, &request, cwd); + // The pending approval owns the proposal during review. An accepted + // reply transfers it back to the invocation for setup and sandbox retries. + let mut command = command_approval + .as_deref_mut() + .map(std::mem::take) + .unwrap_or_default(); + let serving_turn = if command_approval.is_some() && request.starts_command() { + let Some(state) = self + .active_turn + .lock() + .await + .as_ref() + .map(|turn| Arc::clone(&turn.turn_state)) + else { + return ReviewDecision::Abort; + }; + if command + .start(self, turn_context, &request, cwd) + .await + .is_err() + { + return ReviewDecision::Abort; + } + Some(state) + } else { + None + }; // 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 (prev_entry, mut 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. @@ -3525,6 +3573,10 @@ impl Session { } match active.as_mut() { Some(at) => { + // Publishing item/started can outlive the turn servicing this prompt. + if serving_turn.is_some_and(|state| !Arc::ptr_eq(&state, &at.turn_state)) { + return ReviewDecision::Abort; + } let mut ts = at.turn_state.lock().await; let prev = ts.insert_pending_approval( effective_approval_id.clone(), @@ -3535,13 +3587,15 @@ impl Session { command, }, ); - let prompt = request.network_approval_context.as_ref().map(|_| { - ts.track_network_prompt( - &self.tx_event, - &turn_context.sub_id, - &effective_approval_id, - ) - }); + let prompt = ts.track_prompt( + request + .network_approval_context + .as_ref() + .map(|_| &self.tx_event), + rx_approve, + &turn_context.sub_id, + &effective_approval_id, + ); (prev, prompt) } // Without an active turn there is no owner to receive a reply. @@ -3555,7 +3609,13 @@ impl Session { let _user_wait = self.start_user_wait_timing(turn_context, user_wait_owner.as_deref()); self.send_event(turn_context, EventMsg::ExecApprovalRequest(request)) .await; - rx_approve.await.unwrap_or(ReviewDecision::Abort) + let Ok((decision, command)) = (&mut prompt.reply).await else { + return ReviewDecision::Abort; + }; + if let Some(owner) = command_approval { + *owner = command; + } + decision } #[expect( @@ -3586,7 +3646,7 @@ impl Session { sender: tx_approve, kind: ExecApprovalKind::Command, turn_id: turn_context.sub_id.clone(), - command: None, + command: Default::default(), }, ) } @@ -3607,7 +3667,10 @@ impl Session { }); let _user_wait = self.start_user_wait_timing(turn_context, user_wait_owner.as_deref()); self.send_event(turn_context, event).await; - rx_approve.await.unwrap_or(ReviewDecision::Abort) + rx_approve + .await + .map(|(decision, _)| decision) + .unwrap_or(ReviewDecision::Abort) } #[expect( @@ -4068,12 +4131,13 @@ impl Session { } pub async fn notify_approval(&self, approval_id: &str, decision: ReviewDecision) { - if let Some((pending, _)) = self + if let Some((mut pending, _)) = self .take_pending_approval(approval_id, /*expected_turn_id*/ None) .await { let decision = pending.validate(decision); - let _ = pending.sender.send(decision); + pending.resolve_command(&decision).await; + pending.reply(decision); } else { warn!("No pending approval found for call_id: {approval_id}"); } diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 7518e8c297..7659d7a1b0 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -77,6 +77,7 @@ pub(crate) struct Session { pub(crate) context_ids: ThreadContextIds, pub(crate) agent_runtime: AgentRuntimeServices, pub(crate) outcome_reporting: Option, + pub(super) command_approval_publications: TaskTracker, /// Finish saving review evidence even if the turn that recorded it is interrupted. pub(super) preserve_review_writes: bool, pub(crate) installation_id: String, @@ -2048,6 +2049,7 @@ impl Session { context_ids, agent_runtime, outcome_reporting, + command_approval_publications: TaskTracker::new(), preserve_review_writes: services .thread_extension_data .get::() diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index b7eaa2c787..759631d377 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -6844,6 +6844,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { context_ids, agent_runtime: crate::agent::host::AgentRuntimeServices::Controller, outcome_reporting: None, + command_approval_publications: tokio_util::task::TaskTracker::new(), preserve_review_writes: false, installation_id: "11111111-1111-4111-8111-111111111111".to_string(), tx_event, @@ -9213,6 +9214,7 @@ where context_ids, agent_runtime: crate::agent::host::AgentRuntimeServices::Controller, outcome_reporting: None, + command_approval_publications: tokio_util::task::TaskTracker::new(), preserve_review_writes: false, installation_id: "11111111-1111-4111-8111-111111111111".to_string(), tx_event, diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index 261d036dce..94f64575e3 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -24,7 +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::command_approval::CommandApproval; use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnEnvironment; @@ -125,14 +125,18 @@ pub(crate) struct TurnState { } pub(crate) struct PendingApproval { - pub(crate) command: Option>, - pub(crate) sender: oneshot::Sender, + pub(crate) command: CommandApproval, + pub(crate) sender: oneshot::Sender<(ReviewDecision, CommandApproval)>, pub(crate) kind: codex_protocol::approvals::ExecApprovalKind, // A yielded cell can emit a prompt for its original turn while a later turn services it. pub(crate) turn_id: String, } impl PendingApproval { + pub(crate) fn reply(self, decision: ReviewDecision) { + let _ = self.sender.send((decision, self.command)); + } + pub(crate) fn validate(&self, decision: ReviewDecision) -> ReviewDecision { if self.kind == codex_protocol::approvals::ExecApprovalKind::HumanCommand && !matches!( @@ -157,24 +161,33 @@ pub(crate) struct PendingRequestPermissions { type PendingApprovals = SyncMutex>; -/// The originating turn and its unique prompt ID stay valid even if the active turn changes. -pub(crate) struct NetworkApprovalPrompt<'a> { +/// Remove the pending approval from its original registry if the caller goes away. +pub(crate) struct ApprovalPrompt<'a> { approvals: Weak, - events: &'a async_channel::Sender, + network_events: Option<&'a async_channel::Sender>, + pub(crate) reply: oneshot::Receiver<(ReviewDecision, CommandApproval)>, turn_id: &'a str, approval_id: &'a str, } -impl Drop for NetworkApprovalPrompt<'_> { +impl Drop for ApprovalPrompt<'_> { fn drop(&mut self) { + self.reply.close(); if let Some(approvals) = self.approvals.upgrade() { - approvals - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(self.approval_id); + let mut approvals = approvals.lock().unwrap_or_else(PoisonError::into_inner); + // A retry can already have a live waiter under the same command ID. + if approvals + .get(self.approval_id) + .is_some_and(|pending| pending.sender.is_closed()) + { + approvals.remove(self.approval_id); + } } // The session channel is unbounded. Enqueue resolution before a same-host waiter can prompt. - let _ = self.events.try_send(Event { + let Some(events) = self.network_events else { + return; + }; + let _ = events.try_send(Event { id: self.turn_id.to_owned(), msg: EventMsg::NetworkApprovalResolved { approval_id: self.approval_id.to_owned(), @@ -184,15 +197,17 @@ impl Drop for NetworkApprovalPrompt<'_> { } impl TurnState { - pub(crate) fn track_network_prompt<'a>( + pub(crate) fn track_prompt<'a>( &self, - events: &'a async_channel::Sender, + network_events: Option<&'a async_channel::Sender>, + reply: oneshot::Receiver<(ReviewDecision, CommandApproval)>, turn_id: &'a str, approval_id: &'a str, - ) -> NetworkApprovalPrompt<'a> { - NetworkApprovalPrompt { + ) -> ApprovalPrompt<'a> { + ApprovalPrompt { approvals: Arc::downgrade(&self.pending_approvals), - events, + network_events, + reply, turn_id, approval_id, } diff --git a/codex-rs/core/src/tools/approvals.rs b/codex-rs/core/src/tools/approvals.rs index 02d09571e0..cd5e3b1bbf 100644 --- a/codex-rs/core/src/tools/approvals.rs +++ b/codex-rs/core/src/tools/approvals.rs @@ -13,6 +13,7 @@ use crate::hook_runtime::run_permission_request_hooks; use crate::mcp_tool_call::request_mcp_tool_user_approval; use crate::sandboxing::SandboxPermissions; use crate::session::NetworkApprovalTurn; +use crate::session::command_approval::CommandApproval; use crate::session::session::Session; use crate::tools::hook_names::HookToolName; use crate::tools::runtimes::apply_patch::ApplyPatchApprovalKey; @@ -551,11 +552,12 @@ impl Session { self: &Arc, action: ApprovalAction, ctx: ApprovalContext, + command_approval: Option<&mut CommandApproval>, ) -> ApprovalResult { self.request_approval_with_user_prompt( &action, &ctx, - self.request_user_approval(&action, &ctx), + self.request_user_approval(&action, &ctx, command_approval), ) .await } @@ -785,9 +787,10 @@ impl Session { } pub(super) async fn request_user_approval( - &self, + self: &Arc, action: &ApprovalAction, ctx: &ApprovalContext, + command_approval: Option<&mut CommandApproval>, ) -> ApprovalResolution { let decision = match action { ApprovalAction::ExecCommand { @@ -805,6 +808,11 @@ impl Session { .or_else(|| ctx.approval_reason.clone()) .or_else(|| justification.clone()); let human_once = ctx.requires_human_approval(); + let environment = ctx + .review_context + .environments() + .turn_environments() + .find(|environment| environment.selection.environment_id == *environment_id); let request = || async { self.request_command_approval( ctx.review_context.turn(), @@ -841,7 +849,10 @@ impl Session { ReviewDecision::Abort, ] }), - /*plugin_attribution_override*/ None, + environment + .filter(|_| !human_once && ctx.network_approval_context.is_none()) + .map(|env| env.environment().as_ref()), + command_approval, ) .await }; @@ -849,11 +860,7 @@ impl Session { request().await } else { let tool_name = "unified_exec"; - let policy_fingerprint = ctx - .review_context - .environments() - .turn_environments() - .find(|environment| environment.selection.environment_id == *environment_id) + let policy_fingerprint = environment .and_then(|environment| environment.config().exec_policy.as_ref()) .map(codex_execpolicy::RequirementsExecPolicy::fingerprint); let cache_keys = action @@ -894,7 +901,8 @@ impl Session { /*proposed_execpolicy_amendment*/ None, additional_permissions.clone(), Some(vec![ReviewDecision::Approved, ReviewDecision::Abort]), - /*plugin_attribution_override*/ None, + /*command_environment*/ None, + command_approval, ) .await } @@ -970,7 +978,8 @@ impl Session { /*proposed_execpolicy_amendment*/ None, /*additional_permissions*/ None, /*available_decisions*/ None, - /*plugin_attribution_override*/ None, + /*command_environment*/ None, + command_approval, ) .await } diff --git a/codex-rs/core/src/tools/approvals_tests.rs b/codex-rs/core/src/tools/approvals_tests.rs index a56a2bb2b1..ca0254d3f9 100644 --- a/codex-rs/core/src/tools/approvals_tests.rs +++ b/codex-rs/core/src/tools/approvals_tests.rs @@ -155,7 +155,7 @@ async fn non_utf8_cwd_preserves_approval_routing( tty: false, proposed_execpolicy_amendment: None, }; - let prompt = session.request_user_approval(&action, &context); + let prompt = session.request_user_approval(&action, &context, /*command_approval*/ None); let approval = session.request_reviewer_approval(&action, &context, prompt); tokio::pin!(approval); let expected = if reviewer == ApprovalsReviewer::User { @@ -229,7 +229,7 @@ async fn explicit_mcp_reviewer_override_takes_precedence_over_action_context() { network_approval_context: None, }; - let prompt = session.request_user_approval(&action, &context); + let prompt = session.request_user_approval(&action, &context, /*command_approval*/ None); tokio::select! { resolution = session.request_reviewer_approval(&action, &context, prompt) => { panic!("expected a user approval request, got {resolution:?}"); diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 2d5262ee9b..9691fd73d2 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -42,6 +42,7 @@ pub(super) fn truncate_rejection_message(message: &str) -> String { #[derive(Clone, Copy)] pub(crate) struct ToolEventCtx<'a> { + pub proposal_started_at_ms: Option, pub sandbox_type: Option, pub model_context: Option<&'a ModelInvocationContext>, pub session: &'a Session, @@ -61,6 +62,7 @@ impl<'a> ToolEventCtx<'a> { turn_diff_tracker: Option<&'a SharedTurnDiffTracker>, ) -> Self { Self { + proposal_started_at_ms: None, model_context: None, sandbox_type: None, session, @@ -167,28 +169,35 @@ async fn emit_exec_command_begin(ctx: ToolEventCtx<'_>, exec_input: &ExecCommand ); } let (plugin_id, script_path) = plugin_attribution_fields(exec_input.plugin_attribution); - ctx.session - .emit_turn_item_started( - ctx.turn, - &TurnItem::CommandExecution(CommandExecutionItem { - id: ctx.call_id.to_string(), - model_context: ctx.model_context.cloned(), - sandbox_type: ctx.sandbox_type, - plugin_id, - script_path, - process_id: exec_input.process_id.map(str::to_owned), - command: exec_input.command.to_vec(), - cwd: exec_input.cwd.clone(), - parsed_cmd: exec_input.parsed_cmd.to_vec(), - source: exec_input.source, - interaction_input: exec_input.interaction_input.map(str::to_owned), - status: CommandExecutionStatus::InProgress, - aggregated_output: None, - exit_code: None, - duration: None, - }), - ) - .await; + let item = CommandExecutionItem { + id: ctx.call_id.to_string(), + model_context: ctx.model_context.cloned(), + sandbox_type: ctx.sandbox_type, + plugin_id, + script_path, + process_id: exec_input.process_id.map(str::to_owned), + command: exec_input.command.to_vec(), + cwd: exec_input.cwd.clone(), + parsed_cmd: exec_input.parsed_cmd.to_vec(), + source: exec_input.source, + interaction_input: exec_input.interaction_input.map(str::to_owned), + status: CommandExecutionStatus::InProgress, + aggregated_output: None, + exit_code: None, + duration: None, + }; + if let Some(started_at_ms) = ctx.proposal_started_at_ms { + ctx.session + .send_event( + ctx.turn, + item.as_legacy_begin_event(ctx.turn.sub_id.clone(), started_at_ms), + ) + .await; + } else { + ctx.session + .emit_turn_item_started(ctx.turn, &TurnItem::CommandExecution(item)) + .await; + } } // Concrete, allocation-free emitter: avoid trait objects and boxed futures. pub(crate) enum ToolEmitter { diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index f9093cc7b9..b8179f01f7 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -934,7 +934,11 @@ impl NetworkApprovalService { .as_ref() .map(|call| call.trigger.call_id.as_str()), &policy_denial_message, - session.request_user_approval(&action, &approval_context), + session.request_user_approval( + &action, + &approval_context, + /*command_approval*/ None, + ), ); let approval = session.request_approval_with_user_prompt(&action, &approval_context, user_prompt); diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index 4c948352b3..17050b80ec 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -183,7 +183,7 @@ impl ToolOrchestrator { }; let approval = tool_ctx .session - .request_approval(action, approval_ctx) + .request_approval(action, approval_ctx, tool.command_approval()) .await; approval.result?; initial_approval_source = approval.source; @@ -219,7 +219,7 @@ impl ToolOrchestrator { }; let approval = tool_ctx .session - .request_approval(action, approval_ctx) + .request_approval(action, approval_ctx, tool.command_approval()) .await; approval.result?; initial_approval_source = approval.source; @@ -541,13 +541,13 @@ impl ToolOrchestrator { network_ctx.exec_requirement = None; tool_ctx .session - .request_approval(action.clone(), network_ctx) + .request_approval(action.clone(), network_ctx, tool.command_approval()) .await .result?; } tool_ctx .session - .request_approval(action, approval_ctx) + .request_approval(action, approval_ctx, tool.command_approval()) .await .result?; } diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 77a964db09..673b23b652 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -13,6 +13,7 @@ use crate::plugins::metrics::sidecar_for_command; use crate::sandboxing::ExecOptions; use crate::sandboxing::ExecServerEnvConfig; use crate::sandboxing::SandboxPermissions; +use crate::session::command_approval::CommandApproval; use crate::session::turn_context::TurnEnvironment; use crate::shell::ShellType; use crate::shell_snapshot::ShellSnapshotSandbox; @@ -100,10 +101,12 @@ pub struct UnifiedExecApprovalKey { /// Runtime adapter that keeps policy and sandbox orchestration on the /// unified-exec side while delegating process startup to the manager. pub struct UnifiedExecRuntime<'a> { + pub(crate) command_approval: CommandApproval, manager: &'a UnifiedExecProcessManager, } pub(crate) struct UnifiedExecAttempt { + pub(crate) command_approval: CommandApproval, pub(crate) process: UnifiedExecProcess, pub(crate) metrics_sidecar: Option, pub(crate) permissions: TerminalPermissions, @@ -125,7 +128,10 @@ fn unified_exec_options( impl<'a> UnifiedExecRuntime<'a> { /// Creates a runtime bound to the shared unified-exec process manager. pub fn new(manager: &'a UnifiedExecProcessManager) -> Self { - Self { manager } + Self { + manager, + command_approval: CommandApproval::default(), + } } } @@ -163,6 +169,10 @@ impl Approvable> for UnifiedExecRuntime<'_> { } impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExecRuntime<'a> { + fn command_approval(&mut self) -> Option<&mut CommandApproval> { + Some(&mut self.command_approval) + } + fn turn_environment<'b>(&self, req: &'b UnifiedExecRequest<'_>) -> &'b TurnEnvironment { &req.prepared.turn_environment } @@ -651,9 +661,11 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec prepared.turn_environment.environment().as_ref(), ) .await; - let mut process = with_launch_failure_events(process, prepared, ctx).await?; + let mut process = + with_launch_failure_events(process, prepared, ctx, &mut self.command_approval).await?; process._shell_snapshot = shell_snapshot; Ok(UnifiedExecAttempt { + command_approval: std::mem::take(&mut self.command_approval), process, metrics_sidecar, permissions, 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 66f6b717cc..76033a9a19 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec/launch.rs @@ -2,6 +2,7 @@ //! Approval rejections retain their own lifecycle, and sandbox denials remain retryable. //! Session shutdown drains failure publications that outlive the caller. +use crate::session::command_approval::CommandApproval; use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::events::ToolEventFailure; @@ -18,6 +19,7 @@ pub(super) async fn with_launch_failure_events( result: Result, req: &PreparedExecCommand, ctx: &ToolCtx, + command_approval: &mut CommandApproval, ) -> Result { let Err(ToolError::Rejected(message)) = &result else { return result; @@ -63,6 +65,8 @@ pub(super) async fn with_launch_failure_events( let step_context = Arc::clone(&ctx.step_context); let call_id = ctx.call_id.clone(); let message = message.clone(); + // The failure write is registered, so the proposal can release its shutdown token. + let proposal_started_at_ms = command_approval.handoff(); // Dropping the join handle on cancellation leaves both lifecycle events running. let publish = async move { let model_context = step_context.model_context(); @@ -73,6 +77,7 @@ pub(super) async fn with_launch_failure_events( &call_id, /*turn_diff_tracker*/ None, ); + event_ctx.proposal_started_at_ms = proposal_started_at_ms; event_ctx.model_context = Some(&model_context); emitter.emit(event_ctx, ToolEventStage::Begin).await; emitter diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 9c99bca7f1..5cd1dba9a1 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -6,6 +6,7 @@ use crate::sandboxing::ExecOptions; use crate::sandboxing::SandboxPermissions; +use crate::session::command_approval::CommandApproval; use crate::session::session::Session; use crate::session::step_context::StepContext; use crate::session::turn_context::TurnEnvironment; @@ -397,6 +398,10 @@ pub(crate) enum ToolError { } pub(crate) trait ToolRuntime: Approvable + Sandboxable { + fn command_approval(&mut self) -> Option<&mut CommandApproval> { + None + } + fn turn_environment<'a>(&self, req: &'a Req) -> &'a TurnEnvironment; fn uses_executor_managed_process_sandbox(&self, _req: &Req) -> bool { diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index c3068e13e8..8696318c98 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -536,6 +536,7 @@ impl UnifiedExecProcessManager { } }; let UnifiedExecAttempt { + mut command_approval, process, metrics_sidecar, permissions, @@ -580,6 +581,7 @@ impl UnifiedExecProcessManager { Some(request.process_id.to_string()), plugin_attribution.clone(), ); + event_ctx.proposal_started_at_ms = command_approval.handoff(); emitter.emit(event_ctx, ToolEventStage::Begin).await; // Serialize remote collection with later polls and final transcript publication. @@ -945,7 +947,7 @@ impl UnifiedExecProcessManager { }; context .session - .request_approval(approval, approval_context) + .request_approval(approval, approval_context, /*command_approval*/ None) .await .result .map_err(UnifiedExecError::StdinApproval)?; @@ -1489,6 +1491,9 @@ impl UnifiedExecProcessManager { }, other => UnifiedExecError::create_process(format!("{other:?}")), }); + if result.is_err() { + runtime.command_approval.fail().await; + } let outcome = match &result { Ok(_) => "completed", Err(_) if context.cancellation_token.is_cancelled() => "cancelled", diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index f7f9010551..f325f7836e 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -109,8 +109,14 @@ fn assert_no_matched_rules_invariant(output_item: &Value) { ); } +#[test_case::test_case(ReviewDecision::denied("git status was not approved"), None; "decline")] +#[test_case::test_case(ReviewDecision::Approved, None; "approve")] +#[test_case::test_case(ReviewDecision::Approved, Some("missing-working-directory"); "approve_then_launch_fails")] #[tokio::test] -async fn git_status_requires_approval_under_unless_trusted() -> Result<()> { +async fn git_status_requires_approval_under_unless_trusted( + decision: ReviewDecision, + workdir: Option<&str>, +) -> Result<()> { skip_if_wine_exec!(Ok(()), "command approval requires host-native paths"); let server = start_mock_server().await; @@ -128,7 +134,7 @@ async fn git_status_requires_approval_under_unless_trusted() -> Result<()> { }); let test = builder.build_with_auto_env(&server).await?; let call_id = "git-status-approval"; - let args = json!({"cmd": "git status", "yield_time_ms": 1_000}); + let args = json!({"cmd": "git status", "yield_time_ms": 1_000, "workdir": workdir}); let initial_mock = mount_sse_once( &server, sse(vec![ @@ -153,31 +159,53 @@ async fn git_status_requires_approval_under_unless_trusted() -> Result<()> { text_elements: Vec::new(), }])) .await?; - let event = wait_for_event(&test.codex, |event| { - matches!( - event, - EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_) - ) - }) - .await; - let EventMsg::ExecApprovalRequest(approval) = event else { - let output = results_mock.function_call_output_text(call_id); - panic!( - "expected git status to request approval before turn completion; output: {output:?}" - ); - }; - assert_eq!(approval.call_id, call_id); - test.codex - .submit(Op::ExecApproval { - id: approval.effective_approval_id(), - turn_id: None, - decision: ReviewDecision::denied("git status was not approved"), - }) - .await?; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; + let mut events = Vec::new(); + let mut process_id = None; + let mut turn_complete = false; + let mut awaiting_exit = decision == ReviewDecision::Approved; + // A yielded process can publish its exit after the model finishes the turn. + while !turn_complete || awaiting_exit { + match test.codex.next_event().await?.msg { + EventMsg::ItemStarted(event) if event.item.id() == call_id => { + events.push("start"); + } + EventMsg::ExecApprovalRequest(approval) => { + events.push("prompt"); + assert_eq!(approval.call_id, call_id); + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: Some(approval.turn_id), + decision: decision.clone(), + }) + .await?; + } + EventMsg::ExecCommandBegin(event) if event.call_id == call_id => { + events.push("launch"); + process_id = event.process_id; + assert_eq!(process_id.is_some(), workdir.is_none()); + } + EventMsg::ExecCommandEnd(event) if event.call_id == call_id => { + events.push("exit"); + awaiting_exit = false; + } + EventMsg::ItemCompleted(event) => { + if let codex_protocol::items::TurnItem::CommandExecution(item) = event.item { + if workdir.is_some() { + assert_eq!( + item.status, + codex_protocol::items::CommandExecutionStatus::Failed + ); + } + assert_eq!(item.id, call_id); + assert_eq!(item.process_id, process_id); + events.push("finish"); + } + } + EventMsg::TurnComplete(_) => turn_complete = true, + _ => {} + } + } assert!( initial_mock .single_request() @@ -189,7 +217,12 @@ async fn git_status_requires_approval_under_unless_trusted() -> Result<()> { .single_request() .function_call_output_text(call_id) .expect("shell command output"); - assert!(output.contains("git status was not approved"), "{output}"); + if decision == ReviewDecision::Approved { + assert_eq!(events, ["start", "prompt", "launch", "finish", "exit"]); + } else { + assert_eq!(events, ["start", "prompt", "finish"]); + assert!(output.contains("git status was not approved"), "{output}"); + } Ok(()) } diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index 78b600d5ce..9cd34f795f 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -24,16 +24,24 @@ use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID; use codex_model_provider_info::OPENAI_PROVIDER_ID; use codex_plugin::PluginId; use codex_protocol::auth::AuthMode; +#[cfg(unix)] +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_protocol::config_types::TrustLevel; +#[cfg(unix)] +use codex_protocol::items::TurnItem; use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; #[cfg(unix)] use codex_protocol::protocol::GranularApprovalConfig; +#[cfg(unix)] +use codex_protocol::protocol::Op; +#[cfg(unix)] +use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::user_input::UserInput; use codex_skills_extension::HostSkillsLoadInput; @@ -825,7 +833,8 @@ fi text_elements: Vec::new(), }]) .with_thread_settings(ThreadSettingsOverrides { - approval_policy: Some(AskForApproval::Never), + approval_policy: Some(AskForApproval::UnlessTrusted), + approvals_reviewer: Some(ApprovalsReviewer::User), sandbox_policy: Some(sandbox_policy), permission_profile, ..Default::default() @@ -834,6 +843,41 @@ fi .await?; for call_id in ["wrong-version", "matching-version"] { let expected = (Some(REMOTE_PLUGIN_CONFIG_NAME), Some("scripts/run.sh")); + let proposal = wait_for_event_match(&test.codex, |event| match event { + EventMsg::ItemStarted(event) + if let TurnItem::CommandExecution(item) = &event.item + && item.id == call_id => + { + Some(item.clone()) + } + _ => None, + }) + .await; + assert_eq!( + ( + proposal.plugin_id.as_deref(), + proposal.script_path.as_deref() + ), + expected + ); + let prompt = wait_for_event_match(&test.codex, |event| match event { + EventMsg::ExecApprovalRequest(prompt) if prompt.call_id == call_id => { + Some(prompt.clone()) + } + _ => None, + }) + .await; + assert_eq!( + (prompt.plugin_id.as_deref(), prompt.script_path.as_deref()), + expected + ); + test.codex + .submit(Op::ExecApproval { + id: prompt.effective_approval_id(), + turn_id: Some(prompt.turn_id), + decision: ReviewDecision::Approved, + }) + .await?; let begin = wait_for_event_match(&test.codex, |event| match event { EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()), _ => None, diff --git a/codex-rs/protocol/src/legacy_events.rs b/codex-rs/protocol/src/legacy_events.rs index 84f7472f66..d76640f191 100644 --- a/codex-rs/protocol/src/legacy_events.rs +++ b/codex-rs/protocol/src/legacy_events.rs @@ -200,7 +200,7 @@ impl ReasoningItem { } impl CommandExecutionItem { - pub(crate) fn as_legacy_begin_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg { + pub fn as_legacy_begin_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg { EventMsg::ExecCommandBegin(ExecCommandBeginEvent { call_id: self.id.clone(), plugin_id: self.plugin_id.clone(), diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2b9b6ce177..965a2d6d29 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1776,13 +1776,9 @@ pub enum EventMsg { } impl EventMsg { - /// Returns the ID and start time of the command this approval opens. - /// Stdin and network reviews have their own prompts for an existing operation. - pub fn command_approval_start(&self) -> Option<(&str, i64)> { + /// Returns the command item first exposed by a Guardian assessment. + pub fn guardian_command_start(&self) -> Option<(&str, i64)> { match self { - Self::ExecApprovalRequest(request) if request.starts_command() => { - Some((&request.call_id, request.started_at_ms)) - } Self::GuardianAssessment(assessment) if assessment.status == GuardianAssessmentStatus::InProgress && matches!(