mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Handle Stop after multiple command approval declines (#64960)
## Why The desktop client declines all open command approval prompts before sending Stop. If the first decline is still being recorded in history, a second queued decline can keep Stop from reaching the active turn. ## What changed Queue consecutive declines for the same active turn and record them in submission order. If Stop follows, interrupt the turn while the declines are still being recorded, then finish recording them before publishing the turn-aborted event. ## Testing Extend the interruption regression test to cover two declined prompts followed by Stop. It checks that the running sibling command stops while history is blocked, both commands are recorded as declined before the turn-aborted event, and completed sibling output is preserved. GitOrigin-RevId: 00ac946378cc5fcf6c77e4a657aaa64508d60421
This commit is contained in:
@@ -24,6 +24,7 @@ use crate::context::ContextualUserFragment;
|
||||
use crate::context::GuardianApprovedAction;
|
||||
use crate::review_prompts::resolve_review_request;
|
||||
use crate::session::spawn_review_thread;
|
||||
use crate::state::PendingApproval;
|
||||
use crate::tasks::CompactTask;
|
||||
use crate::tasks::UserShellCommandMode;
|
||||
use crate::tasks::UserShellCommandTask;
|
||||
@@ -57,8 +58,10 @@ use codex_protocol::protocol::AgentStatus;
|
||||
use codex_rmcp_client::ElicitationAction;
|
||||
use codex_rmcp_client::ElicitationResponse;
|
||||
use futures::StreamExt;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::stream::Peekable;
|
||||
use serde_json::Value;
|
||||
use std::collections::VecDeque;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use tracing::debug;
|
||||
@@ -67,6 +70,97 @@ use tracing::warn;
|
||||
|
||||
type SubmissionQueue<'a> = Pin<&'a mut Peekable<Receiver<Box<Submission>>>>;
|
||||
|
||||
/// Only the front write is polled. It stays here if another decline or Stop
|
||||
/// arrives while we are waiting for it to reach history.
|
||||
#[derive(Default)]
|
||||
struct PendingDeclines {
|
||||
writes: VecDeque<BoxFuture<'static, ()>>,
|
||||
}
|
||||
|
||||
impl PendingDeclines {
|
||||
fn push(
|
||||
&mut self,
|
||||
mut pending: PendingApproval,
|
||||
decision: ReviewDecision,
|
||||
span: tracing::Span,
|
||||
) {
|
||||
let publish = async move {
|
||||
pending.resolve_command(&decision).await;
|
||||
pending.reply(decision);
|
||||
};
|
||||
self.writes.push_back(Box::pin(publish.instrument(span)));
|
||||
}
|
||||
|
||||
async fn publish(&mut self) {
|
||||
while let Some(write) = self.writes.front_mut() {
|
||||
write.await;
|
||||
self.writes.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "claim consecutive declines only while the same turn owns the approval registry"
|
||||
)]
|
||||
async fn publish_with_interrupt(
|
||||
mut self,
|
||||
session: &Arc<Session>,
|
||||
active_turn_id: &str,
|
||||
mut submissions: SubmissionQueue<'_>,
|
||||
) {
|
||||
loop {
|
||||
// Desktop declines every open prompt before sending Stop. Only claim
|
||||
// consecutive declines for this serving turn. Leave other work queued.
|
||||
let next = tokio::select! {
|
||||
biased;
|
||||
() = self.publish() => return,
|
||||
() = session.services.local_agent_runtime.shutdown.cancelled() => break,
|
||||
sub = submissions.as_mut().peek() => sub,
|
||||
};
|
||||
let Some(sub) = next else { break };
|
||||
match sub.op.as_protocol() {
|
||||
Some(Op::ExecApproval {
|
||||
id,
|
||||
turn_id,
|
||||
decision: decision @ ReviewDecision::Denied { .. },
|
||||
}) => {
|
||||
let active = session.active_turn.lock().await;
|
||||
let Some(turn) = active.as_ref().filter(|turn| {
|
||||
turn.task
|
||||
.as_ref()
|
||||
.is_some_and(|task| task.turn_context.sub_id == active_turn_id)
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
if let Some(pending) = turn.take_pending_approval(id, turn_id.as_deref()).await
|
||||
{
|
||||
self.push(pending, decision.clone(), submission_dispatch_span(sub));
|
||||
}
|
||||
drop(active);
|
||||
submissions.next().await;
|
||||
}
|
||||
Some(Op::Interrupt) => {
|
||||
if session
|
||||
.abort_turn_if_active_with_publication(
|
||||
active_turn_id,
|
||||
TurnAbortReason::Interrupted,
|
||||
/*error*/ None,
|
||||
self.publish(),
|
||||
)
|
||||
.instrument(submission_dispatch_span(sub))
|
||||
.await
|
||||
{
|
||||
submissions.next().await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
self.publish().await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn interrupt(sess: &Arc<Session>) {
|
||||
sess.interrupt_task(sess.active_turn.lock().await).await;
|
||||
}
|
||||
@@ -203,39 +297,13 @@ impl Session {
|
||||
let decision = pending.validate(decision);
|
||||
if matches!(decision, ReviewDecision::Denied { .. })
|
||||
&& let Some(active_turn_id) = active_turn_id.as_ref()
|
||||
&& let Some(mut submissions) = submissions
|
||||
&& let Some(submissions) = submissions
|
||||
{
|
||||
let publish = async move {
|
||||
pending.resolve_command(&decision).await;
|
||||
pending.reply(decision);
|
||||
};
|
||||
tokio::pin!(publish);
|
||||
// Only the next Stop can interrupt this publication. Keep all other
|
||||
// submissions queued, including a Stop if its serving turn has finished.
|
||||
let next = tokio::select! {
|
||||
biased;
|
||||
() = &mut publish => return,
|
||||
() = self.services.local_agent_runtime.shutdown.cancelled() => None,
|
||||
sub = submissions.as_mut().peek() => sub,
|
||||
};
|
||||
let Some(stop) = next.filter(|sub| matches!(sub.op.as_protocol(), Some(Op::Interrupt)))
|
||||
else {
|
||||
return publish.await;
|
||||
};
|
||||
let span = submission_dispatch_span(stop);
|
||||
if self
|
||||
.abort_turn_if_active_with_publication(
|
||||
active_turn_id,
|
||||
TurnAbortReason::Interrupted,
|
||||
/*error*/ None,
|
||||
publish,
|
||||
)
|
||||
.instrument(span)
|
||||
.await
|
||||
{
|
||||
submissions.next().await;
|
||||
}
|
||||
return;
|
||||
let mut declines = PendingDeclines::default();
|
||||
declines.push(pending, decision, tracing::Span::current());
|
||||
return declines
|
||||
.publish_with_interrupt(self, active_turn_id, submissions)
|
||||
.await;
|
||||
}
|
||||
if decision == ReviewDecision::Abort {
|
||||
let turn_id = if pending.kind == ExecApprovalKind::HumanCommand {
|
||||
|
||||
@@ -4138,11 +4138,9 @@ impl Session {
|
||||
// A live Cancel interrupts the turn servicing the prompt, which can differ from its origin.
|
||||
let turn_id = turn.task.as_ref().map(|task| &task.turn_context.sub_id);
|
||||
let pending = turn
|
||||
.turn_state
|
||||
.lock()
|
||||
.await
|
||||
.remove_pending_approval(approval_id, expected_turn_id)?;
|
||||
(!pending.sender.is_closed()).then(|| (pending, turn_id.cloned()))
|
||||
.take_pending_approval(approval_id, expected_turn_id)
|
||||
.await?;
|
||||
Some((pending, turn_id.cloned()))
|
||||
}
|
||||
|
||||
pub async fn notify_approval(&self, approval_id: &str, decision: ReviewDecision) {
|
||||
|
||||
@@ -82,6 +82,20 @@ impl Default for ActiveTurn {
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveTurn {
|
||||
pub(crate) async fn take_pending_approval(
|
||||
&self,
|
||||
approval_id: &str,
|
||||
expected_turn_id: Option<&str>,
|
||||
) -> Option<PendingApproval> {
|
||||
self.turn_state
|
||||
.lock()
|
||||
.await
|
||||
.remove_pending_approval(approval_id, expected_turn_id)
|
||||
.filter(|pending| !pending.sender.is_closed())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum TaskKind {
|
||||
Regular,
|
||||
@@ -238,7 +252,7 @@ impl TurnState {
|
||||
.map(|entry| entry.approval)
|
||||
}
|
||||
|
||||
pub(crate) fn remove_pending_approval(
|
||||
fn remove_pending_approval(
|
||||
&mut self,
|
||||
key: &str,
|
||||
expected_turn_id: Option<&str>,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Exercises interruption and sibling timeouts while a command completion is waiting to reach history.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -44,6 +45,7 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const CALL_ID: &str = "gated-command";
|
||||
|
||||
@@ -72,26 +74,28 @@ impl TurnLifecycleContributor for PauseCommandCompletion {
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case::test_case(ReviewDecision::Abort; "cancel_prompt")]
|
||||
#[test_case::test_case(ReviewDecision::denied("declined"); "decline_then_stop")]
|
||||
#[test_case::test_case(ReviewDecision::Abort, &[CALL_ID]; "cancel_prompt")]
|
||||
#[test_case::test_case(ReviewDecision::denied("declined"), &[CALL_ID]; "decline_then_stop")]
|
||||
#[test_case::test_case(ReviewDecision::denied("declined"), &[CALL_ID, "second-prompt"]; "decline_both_then_stop")]
|
||||
#[tokio::test]
|
||||
async fn interrupt_during_decline_stops_running_sibling_and_preserves_completed_output(
|
||||
decision: ReviewDecision,
|
||||
pending_calls: &[&str],
|
||||
) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_target_windows!(Ok(()), "runs a POSIX sleep command");
|
||||
|
||||
#[derive(Default)]
|
||||
struct SiblingResults {
|
||||
completed: Notify,
|
||||
completed: CancellationToken,
|
||||
release_first: Notify,
|
||||
}
|
||||
|
||||
impl ToolLifecycleContributor for SiblingResults {
|
||||
fn on_command_start<'a>(&'a self, input: CommandStartInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if input.call_id == CALL_ID {
|
||||
self.completed.notified().await;
|
||||
if matches!(input.call_id, CALL_ID | "second-prompt") {
|
||||
self.completed.cancelled().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -102,7 +106,7 @@ async fn interrupt_during_decline_stops_running_sibling_and_preserves_completed_
|
||||
"sibling" => self.release_first.notified().await,
|
||||
"finished" => {
|
||||
assert_eq!(input.outcome, ToolCallOutcome::Completed { success: true });
|
||||
self.completed.notify_one();
|
||||
self.completed.cancel();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -133,22 +137,27 @@ decision = "prompt"
|
||||
.with_config(|config| config.approvals_reviewer = ApprovalsReviewer::User)
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let mut calls = vec![
|
||||
responses::ev_response_created("parallel"),
|
||||
responses::ev_exec_command_call_with_args(
|
||||
"sibling",
|
||||
&json!({"cmd": "sleep 120", "timeout_ms": 120_000}),
|
||||
),
|
||||
responses::ev_exec_command_call_with_args(
|
||||
"finished",
|
||||
&json!({"cmd": "echo sibling-output", "login": false}),
|
||||
),
|
||||
];
|
||||
calls.extend(
|
||||
pending_calls.iter().map(|id| {
|
||||
responses::ev_exec_command_call_with_args(id, &json!({"cmd": "echo pending"}))
|
||||
}),
|
||||
);
|
||||
calls.push(responses::ev_completed("parallel"));
|
||||
let requests = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("parallel"),
|
||||
responses::ev_exec_command_call_with_args(
|
||||
"sibling",
|
||||
&json!({"cmd": "sleep 120", "timeout_ms": 120_000}),
|
||||
),
|
||||
responses::ev_exec_command_call_with_args(
|
||||
"finished",
|
||||
&json!({"cmd": "echo sibling-output", "login": false}),
|
||||
),
|
||||
responses::ev_exec_command_call_with_args(CALL_ID, &json!({"cmd": "echo pending"})),
|
||||
responses::ev_completed("parallel"),
|
||||
]),
|
||||
responses::sse(calls),
|
||||
responses::sse(vec![responses::ev_completed("follow-up")]),
|
||||
],
|
||||
)
|
||||
@@ -169,32 +178,38 @@ decision = "prompt"
|
||||
)
|
||||
.await?;
|
||||
let mut started = false;
|
||||
let mut prompt = None;
|
||||
while !started || prompt.is_none() {
|
||||
let mut prompts = HashMap::new();
|
||||
while !started || prompts.len() < pending_calls.len() {
|
||||
match test.codex.next_event().await?.msg {
|
||||
EventMsg::ExecCommandBegin(event) if event.call_id == "sibling" => {
|
||||
assert!(event.process_id.is_some());
|
||||
started = true;
|
||||
}
|
||||
EventMsg::ExecApprovalRequest(event) if event.call_id == CALL_ID => {
|
||||
prompt = Some(event)
|
||||
EventMsg::ExecApprovalRequest(event)
|
||||
if pending_calls.contains(&event.call_id.as_str()) =>
|
||||
{
|
||||
prompts.insert(event.call_id.clone(), event);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let prompt = prompt.context("pending command approval")?;
|
||||
let stop_after_decline = matches!(decision, ReviewDecision::Denied { .. });
|
||||
test.codex
|
||||
.submit(Op::ExecApproval {
|
||||
id: prompt.effective_approval_id(),
|
||||
turn_id: Some(prompt.turn_id.clone()),
|
||||
decision,
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Desktop declines every open prompt before sending Stop.
|
||||
for id in pending_calls {
|
||||
let prompt = &prompts[*id];
|
||||
test.codex
|
||||
.submit(Op::ExecApproval {
|
||||
id: prompt.effective_approval_id(),
|
||||
turn_id: Some(prompt.turn_id.clone()),
|
||||
decision: decision.clone(),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
gate.entered.notified().await;
|
||||
if stop_after_decline {
|
||||
assert_eq!(test.codex.current_turn_id().await, Some(prompt.turn_id));
|
||||
if matches!(decision, ReviewDecision::Denied { .. }) {
|
||||
assert_eq!(
|
||||
test.codex.current_turn_id().await,
|
||||
Some(prompts[CALL_ID].turn_id.clone())
|
||||
);
|
||||
test.codex.submit(Op::Interrupt).await?;
|
||||
}
|
||||
// The sibling should stop even while history is waiting to record the decline.
|
||||
@@ -210,12 +225,14 @@ decision = "prompt"
|
||||
tokio::time::resume();
|
||||
results.release_first.notify_one();
|
||||
gate.release.notify_one();
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::ItemCompleted(completed)
|
||||
if matches!(&completed.item, TurnItem::CommandExecution(command)
|
||||
if command.id == CALL_ID && command.status == CommandExecutionStatus::Declined))
|
||||
})
|
||||
.await;
|
||||
for id in pending_calls {
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::ItemCompleted(completed)
|
||||
if matches!(&completed.item, TurnItem::CommandExecution(command)
|
||||
if command.id == *id && command.status == CommandExecutionStatus::Declined))
|
||||
})
|
||||
.await;
|
||||
}
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnAborted(_))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user