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
This commit is contained in:
jif
2026-11-27 15:31:18 +00:00
committed by copyberry
parent 57b493a648
commit 6bf1e3e687
10 changed files with 332 additions and 219 deletions
+5
View File
@@ -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
@@ -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<TurnContext>,
item: CommandExecutionItem,
}
impl ProposedCommand {
pub(super) fn from_request(
turn: &Arc<TurnContext>,
request: &ExecApprovalRequestEvent,
cwd: PathUri,
) -> Option<Box<Self>> {
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"));
}
}
}
@@ -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(),
+2 -1
View File
@@ -188,13 +188,14 @@ impl Session {
turn_id: Option<String>,
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)
+88 -63
View File
@@ -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<u64>,
user_input_extension_data: Option<&BTreeMap<String, Value>>,
) {
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<u64>,
user_input_extension_data: Option<&BTreeMap<String, Value>>,
) -> 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<TurnContext>,
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,
+4 -11
View File
@@ -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<Box<ProposedCommand>>,
pub(crate) sender: oneshot::Sender<ReviewDecision>,
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<ReviewDecision>,
kind: codex_protocol::approvals::ExecApprovalKind,
turn_id: String,
pending: PendingApproval,
) -> Option<PendingApproval> {
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(