Preserve command approval items through turn interruption (#64349)

## Why

The app server could show a command awaiting approval before core had
recorded its start. Interrupting the turn or abandoning launch after
approval could leave the live command item and saved history out of sync.

## What changed

Have core publish the command item before prompting for approval and
retain it across approval and sandbox retries until execution takes over.
Complete abandoned items as declined when interrupted while awaiting
approval, or as failed when interrupted after approval but before launch.
Wait for pending approval item writes during shutdown.

## Testing

Extend the app-server interrupt test to restart the server and verify
that the interrupted turn contains exactly one declined command item with
the original approval item ID.

GitOrigin-RevId: c9f027fc7096d091dc8cf1936c88aa69d3eed8c1
This commit is contained in:
jif
2026-11-27 16:25:10 +00:00
committed by copyberry
parent c8cb4e36ed
commit 30ffdd0619
26 changed files with 572 additions and 315 deletions
+107 -25
View File
@@ -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<Session>,
turn: Arc<TurnContext>,
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<Box<ProposedCommand>>);
impl CommandApproval {
pub(super) async fn start(
&mut self,
session: &Arc<Session>,
turn: &Arc<TurnContext>,
request: &ExecApprovalRequestEvent,
cwd: PathUri,
) -> Option<Box<Self>> {
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<i64> {
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"));
}
}
}
@@ -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<super::turn_context::TurnContext>,
@@ -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")]
+6 -3
View File
@@ -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<Session>, 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<Session>, sub_id: String, mode: T
}
pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
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<Session>) {
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();
+94 -30
View File
@@ -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<Self>,
turn_context: &Arc<TurnContext>,
kind: ExecApprovalKind,
model_context: ModelInvocationContext,
@@ -3447,7 +3456,8 @@ impl Session {
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
additional_permissions: Option<AdditionalPermissionProfile>,
available_decisions: Option<Vec<ReviewDecision>>,
plugin_attribution_override: Option<PluginCommandAttribution>,
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}");
}
+2
View File
@@ -77,6 +77,7 @@ pub(crate) struct Session {
pub(crate) context_ids: ThreadContextIds,
pub(crate) agent_runtime: AgentRuntimeServices,
pub(crate) outcome_reporting: Option<AgentOutcomeReporting>,
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::<PreserveReviewWrites>()
+2
View File
@@ -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,