diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 85e54e2fb9..a92b4f7a3c 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -42,6 +42,7 @@ use serde::Serialize; use std::collections::HashMap; use std::collections::VecDeque; use std::sync::Arc; +use std::sync::Mutex; use std::sync::Weak; use tokio::sync::watch; use tracing::warn; @@ -103,10 +104,67 @@ pub(crate) struct AgentControl { state: Arc, v2_residency: Arc, agent_execution_limiter: Arc, + completion_watchers: Arc, /// Session-scoped state shared by the root thread and every cloned sub-agent control handle. rollout_budget: Arc, } +#[derive(Default)] +struct CompletionWatcherTracker { + state: Mutex>, +} + +#[derive(Default)] +struct CompletionWatcherState { + pending: usize, + generation: u64, +} + +pub(crate) struct CompletionWatcherGuard { + tracker: Arc, + parent_thread_id: ThreadId, +} + +impl CompletionWatcherTracker { + fn register(self: &Arc, parent_thread_id: ThreadId) -> CompletionWatcherGuard { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = state.entry(parent_thread_id).or_default(); + entry.pending += 1; + entry.generation = entry.generation.wrapping_add(1); + CompletionWatcherGuard { + tracker: Arc::clone(self), + parent_thread_id, + } + } + + fn snapshot(&self, parent_thread_id: ThreadId) -> (usize, u64) { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state + .get(&parent_thread_id) + .map(|entry| (entry.pending, entry.generation)) + .unwrap_or_default() + } +} + +impl Drop for CompletionWatcherGuard { + fn drop(&mut self) { + let mut state = self + .tracker + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(entry) = state.get_mut(&self.parent_thread_id) { + entry.pending = entry.pending.saturating_sub(1); + } + } +} + impl AgentControl { /// Construct a new `AgentControl` that can spawn/message agents via the given manager state. pub(crate) fn new( @@ -137,6 +195,46 @@ impl AgentControl { self.rollout_budget.as_ref() } + pub(crate) fn completion_watcher_snapshot(&self, parent_thread_id: ThreadId) -> (usize, u64) { + self.completion_watchers.snapshot(parent_thread_id) + } + + pub(crate) fn register_completion_watcher( + &self, + parent_thread_id: ThreadId, + ) -> CompletionWatcherGuard { + self.completion_watchers.register(parent_thread_id) + } + + pub(crate) async fn has_nonfinal_thread_spawn_children( + &self, + parent_thread_id: ThreadId, + ) -> bool { + let Ok(state) = self.upgrade() else { + return false; + }; + let Ok(children) = self.open_thread_spawn_children(parent_thread_id).await else { + return false; + }; + for (child_thread_id, _) in children { + let Ok(child_thread) = state.get_thread(child_thread_id).await else { + continue; + }; + if !is_final(&child_thread.agent_status().await) + || child_thread + .codex + .session + .active_turn + .lock() + .await + .is_some() + { + return true; + } + } + false + } + /// Send rich user input items to an existing agent thread. pub(crate) async fn send_input( &self, @@ -468,8 +566,10 @@ impl AgentControl { else { return; }; + let completion_watcher = self.register_completion_watcher(parent_thread_id); let control = self.clone(); tokio::spawn(async move { + let _completion_watcher = completion_watcher; let status = match control.subscribe_status(child_thread_id).await { Ok(mut status_rx) => { let mut status = status_rx.borrow().clone(); diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 4741c3c101..f33b710670 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -11,6 +11,7 @@ use crate::config::ConfigBuilder; use crate::context::ContextualUserFragment; use crate::context::SubagentNotification; use crate::init_state_db; +use crate::state::ActiveTurn; use crate::thread_manager::StartThreadOptions; use assert_matches::assert_matches; use codex_extension_api::ExtensionDataInit; @@ -2170,6 +2171,126 @@ async fn multi_agent_v2_completion_queues_message_for_direct_parent() { )); } +#[tokio::test] +#[expect( + clippy::await_holding_invalid_type, + reason = "the test intentionally blocks parent delivery while asserting the idle-shutdown gate" +)] +async fn multi_agent_v2_terminal_delivery_blocks_parent_idle_shutdown() { + let harness = AgentControlHarness::new().await; + let mut config = harness.config.clone(); + let _ = config.features.enable(Feature::MultiAgentV2); + let root = harness + .manager + .start_thread(config.clone()) + .await + .expect("root thread should start"); + let root_thread_id = root.thread_id; + let root_thread = root.thread; + let root_control = root_thread.codex.session.services.agent_control.clone(); + let child_path = AgentPath::root().join("worker_a").expect("child path"); + let child_thread_id = root_control + .spawn_agent( + config, + text_input("hello worker"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: root_thread_id, + depth: 1, + agent_path: Some(child_path), + agent_nickname: None, + agent_role: Some("explorer".to_string()), + })), + ) + .await + .expect("child spawn should succeed"); + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should exist"); + let child_session = Arc::clone(&child_thread.codex.session); + let child_submission_guard = timeout( + Duration::from_secs(5), + child_session.submission_send_lock.lock(), + ) + .await + .expect("child input submission should dispatch"); + drop(child_submission_guard); + child_session + .abort_all_tasks(TurnAbortReason::Interrupted) + .await; + assert!(child_session.active_turn.lock().await.is_none()); + + let error_turn = child_session.new_default_turn().await; + *child_session.active_turn.lock().await = Some(ActiveTurn::default()); + child_session + .send_event( + error_turn.as_ref(), + EventMsg::Error(ErrorEvent { + message: "terminal turn error".to_string(), + codex_error_info: None, + }), + ) + .await; + assert!( + root_thread + .codex + .session + .try_claim_idle_shutdown() + .await + .is_none(), + "an Error status must not hide an active child turn" + ); + assert!(!root_thread.codex.session.submission_lifecycle.is_closing()); + child_session.active_turn.lock().await.take(); + + let parent_send_guard = root_thread.codex.session.submission_send_lock.lock().await; + let child_turn = child_session.new_default_turn().await; + let terminal_delivery = tokio::spawn(async move { + child_session + .send_event( + child_turn.as_ref(), + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: child_turn.sub_id.clone(), + last_agent_message: Some("done".to_string()), + completed_at: None, + duration_ms: None, + time_to_first_token_ms: None, + }), + ) + .await; + }); + + timeout(Duration::from_secs(5), async { + loop { + let (pending, _) = root_control.completion_watcher_snapshot(root_thread_id); + if pending > 0 && is_final(&child_thread.agent_status().await) { + break; + } + sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("terminal status should publish while parent delivery is blocked"); + + assert!( + root_thread + .codex + .session + .try_claim_idle_shutdown() + .await + .is_none(), + "parent must remain reusable until child completion delivery finishes" + ); + assert!(!root_thread.codex.session.submission_lifecycle.is_closing()); + + drop(parent_send_guard); + timeout(Duration::from_secs(5), terminal_delivery) + .await + .expect("terminal delivery should unblock") + .expect("terminal delivery task should succeed"); +} + #[tokio::test] async fn completion_watcher_notifies_parent_when_child_is_missing() { let harness = AgentControlHarness::new().await; diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 4cba4bddc5..97adfb8691 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -232,7 +232,6 @@ pub(crate) async fn run_codex_thread_one_shot( // Bridge events so we can observe completion and shut down automatically. let (tx_bridge, rx_bridge) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); - let ops_tx = io.tx_sub.clone(); let agent_status = io.agent_status.clone(); let session = Arc::clone(&io.session); let session_loop_termination = io.session_loop_termination.clone(); @@ -245,14 +244,7 @@ pub(crate) async fn run_codex_thread_one_shot( ); let _ = tx_bridge.send(event).await; if should_shutdown { - let _ = ops_tx - .send(Submission { - id: "shutdown".to_string(), - op: Op::Shutdown {}, - client_user_message_id: None, - trace: None, - }) - .await; + let _ = io_for_bridge.submit(Op::Shutdown {}).await; child_cancel.cancel(); break; } diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index c80268e2f9..fc7f74f78c 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -211,6 +211,10 @@ impl CodexThread { self.codex.shutdown_and_wait().await } + pub async fn try_shutdown_if_idle(&self) -> CodexResult { + self.codex.try_shutdown_if_idle().await + } + /// Wait until the underlying session loop has terminated. pub async fn wait_until_terminated(&self) { self.codex.session_loop_termination.clone().await; @@ -452,6 +456,9 @@ impl CodexThread { /// Records a user-role session-prefix message without creating a new user turn boundary. pub(crate) async fn inject_user_message_without_turn(&self, message: String) { + let Some(_reservation) = self.codex.session.try_reserve_activity() else { + return; + }; let item = ResponseItem::Message { id: None, role: "user".to_string(), @@ -472,6 +479,11 @@ impl CodexThread { "items must not be empty".to_string(), )); } + let Some(_reservation) = self.codex.session.try_reserve_activity() else { + return Err(CodexErr::InvalidRequest( + "thread is shutting down".to_string(), + )); + }; let turn_context = self.codex.session.new_default_turn().await; if self.codex.session.reference_context_item().await.is_none() { @@ -634,6 +646,11 @@ impl CodexThread { server: &str, uri: &str, ) -> anyhow::Result { + let _reservation = self + .codex + .session + .try_reserve_activity() + .ok_or_else(|| anyhow::anyhow!("thread is shutting down"))?; let result = self .current_mcp_runtime() .await @@ -651,6 +668,11 @@ impl CodexThread { arguments: Option, meta: Option, ) -> anyhow::Result { + let _reservation = self + .codex + .session + .try_reserve_activity() + .ok_or_else(|| anyhow::anyhow!("thread is shutting down"))?; self.current_mcp_runtime() .await .manager_arc() @@ -663,6 +685,11 @@ impl CodexThread { } pub async fn increment_out_of_band_elicitation_count(&self) -> CodexResult { + let Some(_reservation) = self.codex.session.try_reserve_activity() else { + return Err(CodexErr::InvalidRequest( + "thread is shutting down".to_string(), + )); + }; let mut elicitations = self.out_of_band_elicitations.lock().await; let incremented = elicitations.count.checked_add(1).ok_or_else(|| { CodexErr::Fatal("out-of-band elicitation count overflowed".to_string()) @@ -675,6 +702,11 @@ impl CodexThread { } pub async fn decrement_out_of_band_elicitation_count(&self) -> CodexResult { + let Some(_reservation) = self.codex.session.try_reserve_activity() else { + return Err(CodexErr::InvalidRequest( + "thread is shutting down".to_string(), + )); + }; let mut elicitations = self.out_of_band_elicitations.lock().await; if elicitations.count == 0 { return Err(CodexErr::InvalidRequest( diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 924750bc34..0c6a32e5a6 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -841,6 +841,7 @@ pub(super) async fn submission_loop( } .instrument(dispatch_span) .await; + sess.submission_lifecycle.finish_submission(); if should_exit { shutdown_received = true; break; diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs index 5c5b7d1feb..2ad7285757 100644 --- a/codex-rs/core/src/session/inject.rs +++ b/codex-rs/core/src/session/inject.rs @@ -62,6 +62,12 @@ impl Session { )); } + let Some(reservation) = self.try_reserve_activity() else { + return Err(TryStartTurnIfIdleError::new( + TryStartTurnIfIdleRejectionReason::Busy, + input, + )); + }; let turn_state = { let mut active_turn = self.active_turn.lock().await; if active_turn.is_some() { @@ -73,6 +79,7 @@ impl Session { let active_turn = active_turn.get_or_insert_with(ActiveTurn::default); Arc::clone(&active_turn.turn_state) }; + drop(reservation); if self.input_queue.has_trigger_turn_mailbox_items().await { self.clear_reserved_idle_turn(&turn_state).await; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index ba8eacb395..710fafc94d 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -767,17 +767,59 @@ impl Codex { /// Use sparingly: prefer `submit()` so Codex is responsible for generating /// unique IDs for each submission. + #[expect( + clippy::await_holding_invalid_type, + reason = "submission ordering must remain serialized while a bounded-channel send waits" + )] pub async fn submit_with_id(&self, mut sub: Submission) -> CodexResult<()> { if sub.trace.is_none() { sub.trace = current_span_w3c_trace_context(); } - self.tx_sub - .send(sub) - .await - .map_err(|_| CodexErr::InternalAgentDied)?; + let is_shutdown = matches!(&sub.op, Op::Shutdown); + let _send_guard = self.session.submission_send_lock.lock().await; + let Some(reservation) = self.session.submission_lifecycle.try_reserve(is_shutdown) else { + if is_shutdown { + return Ok(()); + } + return Err(CodexErr::InvalidRequest( + "thread is shutting down".to_string(), + )); + }; + if self.tx_sub.send(sub).await.is_err() { + return Err(CodexErr::InternalAgentDied); + } + reservation.commit(); Ok(()) } + /// Atomically submits shutdown only when no work is active, queued, or + /// being dispatched. Once claimed, new submissions and automatic idle work + /// are rejected so shutdown cannot race a newly starting turn. + #[expect( + clippy::await_holding_invalid_type, + reason = "the send lock serializes the idle claim with submission delivery" + )] + pub async fn try_shutdown_if_idle(&self) -> CodexResult { + let _send_guard = self.session.submission_send_lock.lock().await; + if self.session.submission_lifecycle.is_closing() { + return Ok(true); + } + let Some(reservation) = self.session.try_claim_idle_shutdown().await else { + return Ok(false); + }; + let sub = Submission { + id: new_submission_id(), + op: Op::Shutdown, + client_user_message_id: None, + trace: current_span_w3c_trace_context(), + }; + if self.tx_sub.send(sub).await.is_err() { + return Err(CodexErr::InternalAgentDied); + } + reservation.commit(); + Ok(true) + } + /// Persist a thread-level memory mode update for the active session. /// /// This is a local-only operation that updates rollout metadata directly @@ -978,6 +1020,44 @@ fn push_prompt_fragment( } impl Session { + async fn has_idle_shutdown_blocker(&self) -> bool { + matches!(self.agent_status.borrow().clone(), AgentStatus::Running) + || self.conversation.running_state().await.is_some() + || *self.services.elicitations.subscribe().borrow() + || self.input_queue.has_pending_mailbox_items().await + || self.active_turn.lock().await.is_some() + || !self.list_background_terminals().await.is_empty() + || self + .services + .agent_control + .has_nonfinal_thread_spawn_children(self.thread_id) + .await + } + + pub(crate) async fn try_claim_idle_shutdown( + &self, + ) -> Option> { + let watcher_snapshot = self + .services + .agent_control + .completion_watcher_snapshot(self.thread_id); + if watcher_snapshot.0 > 0 || self.has_idle_shutdown_blocker().await { + return None; + } + let reservation = self.submission_lifecycle.try_reserve_idle_shutdown()?; + let watcher_recheck = self + .services + .agent_control + .completion_watcher_snapshot(self.thread_id); + if watcher_recheck.0 > 0 + || watcher_recheck.1 != watcher_snapshot.1 + || self.has_idle_shutdown_blocker().await + { + return None; + } + Some(reservation) + } + pub(crate) async fn app_server_client_metadata(&self) -> AppServerClientMetadata { let state = self.state.lock().await; AppServerClientMetadata { @@ -1194,6 +1274,9 @@ impl Session { } pub(crate) async fn route_realtime_text_input(self: &Arc, text: String) { + let Some(_reservation) = self.try_reserve_activity() else { + return; + }; handlers::user_input_or_turn_inner( self, Uuid::now_v7().to_string(), @@ -1757,9 +1840,27 @@ impl Session { id: turn_context.sub_id.clone(), msg, }; + let parent_completion_guard = if turn_context.multi_agent_version == MultiAgentVersion::V2 + && matches!( + legacy_source, + EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_) + ) + && let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, .. + }) = &turn_context.session_source + { + Some( + self.services + .agent_control + .register_completion_watcher(*parent_thread_id), + ) + } else { + None + }; self.send_event_raw(event).await; self.maybe_notify_parent_of_terminal_turn(turn_context, &legacy_source) .await; + drop(parent_completion_guard); self.maybe_mirror_event_text_to_realtime(&legacy_source) .await; self.maybe_clear_realtime_handoff_for_event(&legacy_source) diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 2261eaa495..59d47ea471 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -20,11 +20,107 @@ use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TurnEnvironmentSelections; use std::sync::OnceLock; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use tokio::sync::Semaphore; /// Context for an initialized model agent /// /// A session has at most 1 running task at a time, and can be interrupted by user input. +pub(crate) struct SubmissionLifecycle { + state: AtomicUsize, +} + +const SUBMISSION_CLOSING: usize = 1 << (usize::BITS - 1); +const SUBMISSION_COUNT_MASK: usize = SUBMISSION_CLOSING - 1; + +impl Default for SubmissionLifecycle { + fn default() -> Self { + Self { + state: AtomicUsize::new(0), + } + } +} + +impl SubmissionLifecycle { + pub(crate) fn is_closing(&self) -> bool { + self.state.load(Ordering::SeqCst) & SUBMISSION_CLOSING != 0 + } + + pub(crate) fn try_reserve(&self, close: bool) -> Option> { + self.state + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| { + if state & SUBMISSION_CLOSING != 0 { + return None; + } + let count = state & SUBMISSION_COUNT_MASK; + assert!(count < SUBMISSION_COUNT_MASK, "submission count overflow"); + Some((state + 1) | if close { SUBMISSION_CLOSING } else { 0 }) + }) + .ok()?; + Some(SubmissionReservation { + lifecycle: self, + clear_closing_on_drop: close, + active: true, + }) + } + + pub(crate) fn try_reserve_idle_shutdown(&self) -> Option> { + self.state + .compare_exchange( + 0, + SUBMISSION_CLOSING | 1, + Ordering::SeqCst, + Ordering::SeqCst, + ) + .ok() + .map(|_| SubmissionReservation { + lifecycle: self, + clear_closing_on_drop: true, + active: true, + }) + } + + pub(crate) fn finish_submission(&self) { + self.release(/*clear_closing*/ false); + } + + fn release(&self, clear_closing: bool) { + let _ = self + .state + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| { + if state & SUBMISSION_COUNT_MASK == 0 { + return None; + } + let mut next = state - 1; + if clear_closing { + next &= !SUBMISSION_CLOSING; + } + Some(next) + }); + } +} + +pub(crate) struct SubmissionReservation<'a> { + lifecycle: &'a SubmissionLifecycle, + clear_closing_on_drop: bool, + active: bool, +} + +impl SubmissionReservation<'_> { + pub(crate) fn commit(mut self) { + self.active = false; + } +} + +impl Drop for SubmissionReservation<'_> { + fn drop(&mut self) { + if self.active { + self.lifecycle.release(self.clear_closing_on_drop); + } + } +} + pub(crate) struct Session { pub(crate) thread_id: ThreadId, pub(crate) installation_id: String, @@ -41,6 +137,8 @@ pub(crate) struct Session { pub(super) pending_mcp_server_refresh_config: Mutex>, pub(crate) conversation: Arc, pub(crate) active_turn: Mutex>, + pub(crate) submission_lifecycle: SubmissionLifecycle, + pub(crate) submission_send_lock: Mutex<()>, pub(crate) input_queue: InputQueue, pub(crate) guardian_review_session: GuardianReviewSessionManager, pub(crate) services: SessionServices, @@ -465,6 +563,10 @@ impl Session { self.thread_id } + pub(crate) fn try_reserve_activity(&self) -> Option> { + self.submission_lifecycle.try_reserve(/*close*/ false) + } + /// Returns the identity shared by the root thread and all descendant threads. pub(crate) fn session_id(&self) -> SessionId { self.services.agent_control.session_id() @@ -1137,6 +1239,8 @@ impl Session { pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + submission_lifecycle: SubmissionLifecycle::default(), + submission_send_lock: Mutex::new(()), input_queue: InputQueue::new(), guardian_review_session: GuardianReviewSessionManager::default(), services, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 6cc223cd7d..860bdf18a9 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1,3 +1,4 @@ +use super::session::SubmissionLifecycle; use super::turn_context::TurnEnvironment; use super::*; use crate::agents_md_manager::AgentsMdManager; @@ -5518,6 +5519,8 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + submission_lifecycle: SubmissionLifecycle::default(), + submission_send_lock: Mutex::new(()), input_queue: super::input_queue::InputQueue::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), services, @@ -6483,6 +6486,94 @@ async fn submit_with_id_captures_current_span_trace_context() { assert_eq!(submitted.trace, Some(expected_trace)); } +#[tokio::test] +async fn cancelled_submission_and_idle_shutdown_release_lifecycle_reservations() { + let (session, _turn_context) = make_session_and_context().await; + let session = Arc::new(session); + let (tx_sub, rx_sub) = async_channel::bounded(1); + let (_tx_event, rx_event) = async_channel::unbounded(); + let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); + + tx_sub + .send(Submission { + id: "filler".into(), + op: Op::Interrupt, + client_user_message_id: None, + trace: None, + }) + .await + .expect("fill submission channel"); + + let codex = Arc::new(Codex { + tx_sub, + rx_event, + agent_status, + session: Arc::clone(&session), + session_loop_termination: completed_session_loop_termination(), + }); + + let blocked_submit = { + let codex = Arc::clone(&codex); + tokio::spawn(async move { codex.submit(Op::Interrupt).await }) + }; + tokio::time::timeout(StdDuration::from_secs(1), async { + while session.submission_send_lock.try_lock().is_ok() { + tokio::task::yield_now().await; + } + }) + .await + .expect("submission should hold the send lock while blocking"); + blocked_submit.abort(); + assert!( + blocked_submit + .await + .expect_err("blocked submission should be cancelled") + .is_cancelled() + ); + let released_submission = session + .try_claim_idle_shutdown() + .await + .expect("cancelled submission should release its lifecycle reservation"); + drop(released_submission); + assert!(!session.submission_lifecycle.is_closing()); + + let blocked_shutdown = { + let codex = Arc::clone(&codex); + tokio::spawn(async move { codex.try_shutdown_if_idle().await }) + }; + tokio::time::timeout(StdDuration::from_secs(1), async { + while !session.submission_lifecycle.is_closing() { + tokio::task::yield_now().await; + } + }) + .await + .expect("idle shutdown should claim lifecycle state before blocking"); + blocked_shutdown.abort(); + assert!( + blocked_shutdown + .await + .expect_err("blocked idle shutdown should be cancelled") + .is_cancelled() + ); + let released_shutdown = session + .try_claim_idle_shutdown() + .await + .expect("cancelled idle shutdown should release its lifecycle reservation"); + drop(released_shutdown); + assert!(!session.submission_lifecycle.is_closing()); + + let filler = rx_sub.recv().await.expect("filler submission"); + assert_eq!(filler.id, "filler"); + assert!( + codex + .try_shutdown_if_idle() + .await + .expect("idle shutdown should submit after cancellation") + ); + let shutdown = rx_sub.recv().await.expect("shutdown submission"); + assert_eq!(shutdown.op, Op::Shutdown); +} + #[tokio::test] async fn new_default_turn_captures_current_span_trace_id() { let (session, _turn_context) = make_session_and_context().await; @@ -7644,6 +7735,8 @@ where pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + submission_lifecycle: SubmissionLifecycle::default(), + submission_send_lock: Mutex::new(()), input_queue: super::input_queue::InputQueue::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), services, @@ -9951,6 +10044,43 @@ async fn try_start_turn_if_idle_rejects_active_turn_without_injecting() { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; } +#[tokio::test] +async fn idle_shutdown_claim_waits_for_submissions_and_blocks_automatic_turns() { + let (sess, _tc, _rx) = make_session_and_context_with_rx().await; + let pending = sess + .try_reserve_activity() + .expect("open session should reserve a submission"); + assert!(sess.try_claim_idle_shutdown().await.is_none()); + drop(pending); + + sess.input_queue + .enqueue_mailbox_communication(InterAgentCommunication::new( + AgentPath::root(), + AgentPath::root(), + Vec::new(), + "pending context".to_string(), + /*trigger_turn*/ false, + )) + .await; + assert!(sess.try_claim_idle_shutdown().await.is_none()); + sess.input_queue.drain_mailbox_input_items().await; + + let shutdown = sess + .try_claim_idle_shutdown() + .await + .expect("idle session should claim shutdown"); + let item = user_message("synthetic idle input"); + let err = sess + .try_start_turn_if_idle(vec![item.clone()]) + .await + .expect_err("claimed shutdown should reject automatic idle work"); + + assert_eq!(TryStartTurnIfIdleRejectionReason::Busy, err.reason()); + assert_eq!(vec![item], err.into_input()); + assert!(sess.active_turn.lock().await.is_none()); + drop(shutdown); +} + #[tokio::test] async fn try_start_turn_if_idle_rejects_plan_mode_without_injecting() { let (sess, _tc, _rx) = make_session_and_context_with_rx().await; diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index c6d9d2990c..a7145f8db8 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -474,6 +474,9 @@ impl Session { return; } + let Some(reservation) = self.try_reserve_activity() else { + return; + }; { let mut active_turn = self.active_turn.lock().await; if active_turn.is_some() { @@ -481,6 +484,7 @@ impl Session { } *active_turn = Some(ActiveTurn::default()); } + drop(reservation); let turn_context = self.new_default_turn_with_sub_id(sub_id).await; self.maybe_emit_model_warnings_for_turn(turn_context.as_ref())