From fba35c92c0cedeea9d58b86717a635e201558629 Mon Sep 17 00:00:00 2001 From: Guinness Chen Date: Tue, 9 Jun 2026 01:39:34 -0700 Subject: [PATCH] Clear realtime handoff on aborted turn --- .../tests/suite/v2/realtime_conversation.rs | 170 ++++++++++++++++++ codex-rs/core/src/realtime_conversation.rs | 126 ++++++++++--- .../core/src/realtime_conversation_tests.rs | 17 +- codex-rs/core/src/session/handlers.rs | 41 ++++- codex-rs/core/src/session/inject.rs | 13 +- codex-rs/core/src/session/mod.rs | 8 +- codex-rs/core/src/session/session.rs | 4 + codex-rs/core/src/session/tests.rs | 2 + codex-rs/core/src/tasks/mod.rs | 100 ++++++++++- 9 files changed, 434 insertions(+), 47 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs index 1d53bfa63b..99d06a206c 100644 --- a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs +++ b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs @@ -36,6 +36,7 @@ use codex_app_server_protocol::ThreadRealtimeTranscriptDoneNotification; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnCompletedNotification; +use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStartedNotification; @@ -81,6 +82,7 @@ const V2_STEERING_ACKNOWLEDGEMENT: &str = "This was sent to steer the previous background agent task."; const V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT: &str = "Background agent finished. Use the preceding [BACKEND] messages as the result."; +const V2_HANDOFF_CANCELLED_ACKNOWLEDGEMENT: &str = "Background agent task was cancelled."; #[derive(Debug, Clone, Copy)] enum StartupContextConfig<'a> { @@ -1438,6 +1440,174 @@ async fn webrtc_terminal_output_without_handoff_reaches_realtime() -> Result<()> Ok(()) } +#[tokio::test] +async fn webrtc_handoff_during_abort_starts_after_old_handoff_is_cancelled() -> Result<()> { + skip_if_no_network!(Ok(())); + + #[cfg(windows)] + let long_running_command = vec![ + "powershell.exe".to_string(), + "-NoProfile".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 60".to_string(), + ]; + #[cfg(not(windows))] + let long_running_command = vec!["sleep".to_string(), "60".to_string()]; + + for version in [RealtimeTestVersion::V1, RealtimeTestVersion::V2] { + let first_handoff_events = match version { + RealtimeTestVersion::V1 => vec![ + session_updated("sess_aborted_handoff"), + json!({ + "type": "conversation.input_transcript.delta", + "delta": "start a long task" + }), + json!({ + "type": "conversation.handoff.requested", + "handoff_id": "stale_handoff", + "item_id": "item_stale_handoff", + "input_transcript": "start a long task" + }), + ], + RealtimeTestVersion::V2 => vec![ + session_updated("sess_aborted_handoff"), + v2_background_agent_tool_call("stale_handoff", "start a long task"), + ], + }; + let second_handoff_events = match version { + RealtimeTestVersion::V1 => vec![ + json!({ + "type": "conversation.input_transcript.delta", + "delta": "start the replacement task" + }), + json!({ + "type": "conversation.handoff.requested", + "handoff_id": "replacement_handoff", + "item_id": "item_replacement_handoff", + "input_transcript": "start the replacement task" + }), + ], + RealtimeTestVersion::V2 => vec![v2_background_agent_tool_call( + "replacement_handoff", + "start the replacement task", + )], + }; + let mut harness = RealtimeE2eHarness::new_with_sandbox( + version, + main_loop_responses(vec![ + create_shell_command_sse_response( + long_running_command.clone(), + /*workdir*/ None, + /*timeout_ms*/ Some(60_000), + "call_abort", + )?, + create_final_assistant_message_sse_response("direct result after abort")?, + ]), + realtime_sideband(vec![realtime_sideband_connection(vec![ + first_handoff_events, + second_handoff_events, + vec![], + vec![json!({ + "type": "response.done", + "response": { "id": "abort_response" } + })], + vec![], + vec![], + vec![], + ])]), + RealtimeTestSandbox::DangerFullAccess, + ) + .await?; + + let _ = harness.start_webrtc_realtime("v=offer\r\n").await?; + let delegated_turn = harness + .read_notification::("turn/started") + .await?; + let started_command = wait_for_started_command_execution(&mut harness.mcp).await?; + let ThreadItem::CommandExecution { id, status, .. } = started_command.item else { + unreachable!("helper returns command execution items"); + }; + assert_eq!( + (id.as_str(), status), + ("call_abort", CommandExecutionStatus::InProgress) + ); + + let interrupt_request_id = harness + .mcp + .send_turn_interrupt_request(TurnInterruptParams { + thread_id: harness.thread_id.clone(), + turn_id: delegated_turn.turn.id.clone(), + }) + .await?; + let _ = wait_for_completed_command_execution(&mut harness.mcp).await?; + + harness + .append_text(harness.thread_id.clone(), "inject replacement handoff") + .await?; + let injected_during_abort = harness.sideband_outbound_request(/*request_index*/ 1).await; + assert_eq!(injected_during_abort["item"]["role"], "user"); + + let _: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + harness + .mcp + .read_stream_until_response_message(RequestId::Integer(interrupt_request_id)), + ) + .await??; + let aborted_turn = harness + .read_notification::("turn/completed") + .await?; + assert_eq!(aborted_turn.turn.id, delegated_turn.turn.id); + let replacement_turn = harness + .read_notification::("turn/started") + .await?; + assert_ne!(replacement_turn.turn.id, delegated_turn.turn.id); + let completed_replacement_turn = harness + .read_notification::("turn/completed") + .await?; + assert_eq!(completed_replacement_turn.turn.id, replacement_turn.turn.id); + + match version { + RealtimeTestVersion::V1 => { + assert_eq!( + harness.sideband_outbound_request(/*request_index*/ 2).await, + json!({ + "type": "conversation.handoff.append", + "handoff_id": "replacement_handoff", + "output_text": "direct result after abort", + }) + ); + } + RealtimeTestVersion::V2 => { + assert_v2_function_call_output( + &harness.sideband_outbound_request(/*request_index*/ 2).await, + "stale_handoff", + V2_HANDOFF_CANCELLED_ACKNOWLEDGEMENT, + ); + assert_v2_response_create( + &harness.sideband_outbound_request(/*request_index*/ 3).await, + ); + assert_v2_terminal_output( + &harness.sideband_outbound_request(/*request_index*/ 4).await, + "direct result after abort", + ); + assert_v2_function_call_output( + &harness.sideband_outbound_request(/*request_index*/ 5).await, + "replacement_handoff", + V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT, + ); + assert_v2_response_create( + &harness.sideband_outbound_request(/*request_index*/ 6).await, + ); + } + } + + harness.shutdown().await; + } + + Ok(()) +} + #[tokio::test] async fn webrtc_v2_forwards_audio_and_text_between_client_and_sideband() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 72541d9217..a7f7503d4b 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -53,6 +53,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use tokio::sync::Mutex; +use tokio::sync::OwnedMutexGuard; use tokio::task::JoinHandle; use tracing::debug; use tracing::error; @@ -69,6 +70,7 @@ pub(crate) const REALTIME_USER_TEXT_PREFIX: &str = "[USER] "; pub(crate) const REALTIME_BACKEND_TEXT_PREFIX: &str = "[BACKEND] "; const REALTIME_V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT: &str = "Background agent finished. Use the preceding [BACKEND] messages as the result."; +const REALTIME_V2_HANDOFF_CANCELLED_ACKNOWLEDGEMENT: &str = "Background agent task was cancelled."; const REALTIME_V2_STEER_ACKNOWLEDGEMENT: &str = "This was sent to steer the previous background agent task."; const REALTIME_ACTIVE_RESPONSE_ERROR_PREFIX: &str = @@ -100,6 +102,7 @@ enum RealtimeSessionKind { struct RealtimeHandoffState { terminal_output_tx: Sender, active_handoff: Arc>>, + transition: Arc>, session_kind: RealtimeSessionKind, } @@ -112,6 +115,23 @@ enum RealtimeTerminalOutput { handoff_id: String, output_text: String, }, + Cancelled { + handoff_id: String, + }, +} + +struct RealtimeOutputEvent { + event: RealtimeEvent, + handoff_transition: Option>, +} + +impl From for RealtimeOutputEvent { + fn from(event: RealtimeEvent) -> Self { + Self { + event, + handoff_transition: None, + } + } } #[derive(Debug, PartialEq, Eq)] @@ -130,7 +150,7 @@ impl RealtimeResponseCreateQueue { async fn request_create( &mut self, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, reason: &str, ) -> anyhow::Result<()> { if self.active_default_response { @@ -147,7 +167,7 @@ impl RealtimeResponseCreateQueue { async fn mark_finished( &mut self, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, reason: &str, ) -> anyhow::Result<()> { self.active_default_response = false; @@ -161,7 +181,7 @@ impl RealtimeResponseCreateQueue { async fn send_create_now( &mut self, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, reason: &str, ) -> anyhow::Result<()> { if let Err(err) = writer.send_response_create().await { @@ -174,7 +194,9 @@ impl RealtimeResponseCreateQueue { return Ok(()); } warn!("failed to send {reason} response.create: {mapped_error}"); - let _ = events_tx.send(RealtimeEvent::Error(error_message)).await; + let _ = events_tx + .send(RealtimeEvent::Error(error_message).into()) + .await; return Err(mapped_error.into()); } self.active_default_response = true; @@ -188,7 +210,7 @@ struct RealtimeInputTask { user_text_rx: Receiver, terminal_output_rx: Receiver, audio_rx: Receiver, - events_tx: Sender, + events_tx: Sender, handoff_state: RealtimeHandoffState, session_kind: RealtimeSessionKind, event_parser: RealtimeEventParser, @@ -208,6 +230,7 @@ impl RealtimeHandoffState { Self { terminal_output_tx, active_handoff: Arc::new(Mutex::new(None)), + transition: Arc::new(Mutex::new(())), session_kind, } } @@ -217,9 +240,8 @@ impl RealtimeHandoffState { output_text: Option, ) -> Option { let handoff_id = self.active_handoff.lock().await.take(); - let output_text = output_text?; - match handoff_id { - Some(handoff_id) => Some(RealtimeTerminalOutput::Handoff { + match (handoff_id, output_text) { + (Some(handoff_id), Some(output_text)) => Some(RealtimeTerminalOutput::Handoff { handoff_id, output_text: prefix_realtime_text( output_text, @@ -227,7 +249,23 @@ impl RealtimeHandoffState { self.session_kind, ), }), - None => Some(RealtimeTerminalOutput::Direct { output_text }), + (None, Some(output_text)) => Some(RealtimeTerminalOutput::Direct { output_text }), + (Some(handoff_id), None) if self.session_kind == RealtimeSessionKind::V2 => { + Some(RealtimeTerminalOutput::Cancelled { handoff_id }) + } + _ => None, + } + } + + async fn lock_transition_for_event( + &self, + event: &RealtimeEvent, + ) -> Option> { + match event { + RealtimeEvent::HandoffRequested(_) => { + Some(Arc::clone(&self.transition).lock_owned().await) + } + _ => None, } } } @@ -253,7 +291,7 @@ struct RealtimeStart { struct RealtimeStartOutput { realtime_active: Arc, - events_rx: Receiver, + events_rx: Receiver, sdp: Option, } @@ -315,7 +353,7 @@ impl RealtimeConversationManager { let (terminal_output_tx, terminal_output_rx) = async_channel::bounded::(TERMINAL_OUTPUT_QUEUE_CAPACITY); let (events_tx, events_rx) = - async_channel::bounded::(OUTPUT_EVENTS_QUEUE_CAPACITY); + async_channel::bounded::(OUTPUT_EVENTS_QUEUE_CAPACITY); let realtime_active = Arc::new(AtomicBool::new(true)); let handoff = RealtimeHandoffState::new(terminal_output_tx, session_kind); @@ -488,6 +526,16 @@ impl RealtimeConversationManager { Ok(()) } + pub(crate) async fn lock_handoff_transition(&self) -> Option> { + let transition = { + let guard = self.state.lock().await; + guard + .as_ref() + .map(|state| Arc::clone(&state.handoff.transition)) + }?; + Some(transition.lock_owned().await) + } + pub(crate) async fn shutdown(&self) -> CodexResult<()> { let state = { let mut guard = self.state.lock().await; @@ -782,7 +830,11 @@ async fn handle_start_inner( msg, }; let mut end = RealtimeConversationEnd::TransportClosed; - while let Ok(event) = events_rx.recv().await { + while let Ok(output_event) = events_rx.recv().await { + let RealtimeOutputEvent { + event, + handoff_transition, + } = output_event; if !fanout_realtime_active.load(Ordering::Relaxed) { break; } @@ -804,10 +856,13 @@ async fn handle_start_inner( } _ => None, }; - if let Some(text) = maybe_routed_text { + if let (Some(text), Some(handoff_transition)) = (maybe_routed_text, handoff_transition) + { debug!(text = %text, "[realtime-text] realtime conversation text output"); let sess_for_routed_text = Arc::clone(&sess_clone); - sess_for_routed_text.route_realtime_text_input(text).await; + sess_for_routed_text + .route_realtime_text_input(text, handoff_transition) + .await; } if !fanout_realtime_active.load(Ordering::Relaxed) { break; @@ -984,7 +1039,7 @@ struct RealtimeWebrtcSidebandInputTask { call_id: String, sideband_headers: HeaderMap, input_channels: RealtimeInputChannels, - events_tx: Sender, + events_tx: Sender, handoff_state: RealtimeHandoffState, session_kind: RealtimeSessionKind, event_parser: RealtimeEventParser, @@ -1025,7 +1080,7 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J let mapped_error = map_api_error(err); warn!("failed to connect realtime sideband: {mapped_error}"); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; } return; @@ -1117,7 +1172,7 @@ async fn run_realtime_input_task(input: RealtimeInputTask) { async fn handle_user_text_input( text: Result, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, ) -> anyhow::Result<()> { let text = text.context("user text input channel closed")?; @@ -1125,7 +1180,7 @@ async fn handle_user_text_input( let mapped_error = map_api_error(err); warn!("failed to send input text: {mapped_error}"); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; return Err(mapped_error.into()); } @@ -1135,7 +1190,7 @@ async fn handle_user_text_input( async fn handle_terminal_output( terminal_output: Result, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, event_parser: RealtimeEventParser, response_create_queue: &mut RealtimeResponseCreateQueue, ) -> anyhow::Result<()> { @@ -1172,12 +1227,21 @@ async fn handle_terminal_output( true, ), }, + RealtimeTerminalOutput::Cancelled { handoff_id } => ( + writer + .send_conversation_function_call_output( + handoff_id, + REALTIME_V2_HANDOFF_CANCELLED_ACKNOWLEDGEMENT.to_string(), + ) + .await, + true, + ), }; if let Err(err) = result { let mapped_error = map_api_error(err); warn!("failed to send terminal output: {mapped_error}"); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; return Err(mapped_error.into()); } @@ -1193,7 +1257,7 @@ async fn handle_terminal_output( async fn handle_realtime_server_event( event: Result, ApiError>, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, handoff_state: &RealtimeHandoffState, session_kind: RealtimeSessionKind, output_audio_state: &mut Option, @@ -1205,7 +1269,7 @@ async fn handle_realtime_server_event( Err(err) => { let mapped_error = map_api_error(err); if events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await .is_err() { @@ -1215,6 +1279,7 @@ async fn handle_realtime_server_event( return Err(mapped_error.into()); } }; + let handoff_transition = handoff_state.lock_transition_for_event(&event).await; let should_stop = match &event { RealtimeEvent::AudioOut(frame) => { @@ -1288,7 +1353,7 @@ async fn handle_realtime_server_event( "failed to send handoff steering acknowledgement: {mapped_error}" ); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; return Err(mapped_error.into()); } @@ -1318,7 +1383,7 @@ async fn handle_realtime_server_event( let mapped_error = map_api_error(err); warn!("failed to send realtime noop function output: {mapped_error}"); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; return Err(mapped_error.into()); } @@ -1342,7 +1407,14 @@ async fn handle_realtime_server_event( | RealtimeEvent::ConversationItemDone { .. } => false, }; - if events_tx.send(event).await.is_err() { + if events_tx + .send(RealtimeOutputEvent { + event, + handoff_transition, + }) + .await + .is_err() + { anyhow::bail!("realtime output event channel closed"); } if should_stop { @@ -1355,7 +1427,7 @@ async fn handle_realtime_server_event( async fn handle_user_audio_input( frame: Result, writer: &RealtimeWebsocketWriter, - events_tx: &Sender, + events_tx: &Sender, ) -> anyhow::Result<()> { let frame = frame.context("user audio input channel closed")?; @@ -1363,7 +1435,7 @@ async fn handle_user_audio_input( let mapped_error = map_api_error(err); error!("failed to send input audio: {mapped_error}"); let _ = events_tx - .send(RealtimeEvent::Error(mapped_error.to_string())) + .send(RealtimeEvent::Error(mapped_error.to_string()).into()) .await; return Err(mapped_error.into()); } diff --git a/codex-rs/core/src/realtime_conversation_tests.rs b/codex-rs/core/src/realtime_conversation_tests.rs index 7d815c92ec..af67fee8d3 100644 --- a/codex-rs/core/src/realtime_conversation_tests.rs +++ b/codex-rs/core/src/realtime_conversation_tests.rs @@ -182,14 +182,25 @@ async fn terminal_output_without_handoff_stays_plain() { } #[tokio::test] -async fn terminal_output_without_message_still_consumes_handoff() { - for session_kind in [RealtimeSessionKind::V1, RealtimeSessionKind::V2] { +async fn aborted_terminal_output_only_resolves_v2_handoff() { + for (session_kind, expected_output) in [ + (RealtimeSessionKind::V1, None), + ( + RealtimeSessionKind::V2, + Some(RealtimeTerminalOutput::Cancelled { + handoff_id: "handoff_1".to_string(), + }), + ), + ] { let (tx, _rx) = bounded(1); let state = RealtimeHandoffState::new(tx, session_kind); *state.active_handoff.lock().await = Some("handoff_1".to_string()); - assert_eq!(state.take_terminal_output(/*output_text*/ None).await, None); + assert_eq!( + state.take_terminal_output(/*output_text*/ None).await, + expected_output + ); assert_eq!(state.active_handoff.lock().await.clone(), None); } } diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 10b0b27cc1..bffb56de32 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -55,6 +55,7 @@ use codex_rmcp_client::ElicitationAction; use codex_rmcp_client::ElicitationResponse; use serde_json::Value; use std::sync::Arc; +use tokio::sync::OwnedMutexGuard; use tracing::debug; use tracing::info; use tracing::warn; @@ -85,7 +86,19 @@ pub async fn user_input_or_turn( op: Op, client_user_message_id: Option, ) { - user_input_or_turn_inner(sess, sub_id, op, client_user_message_id).await; + user_input_or_turn_inner( + sess, + sub_id, + op, + client_user_message_id, + UserInputRoute::Default, + ) + .await; +} + +pub(super) enum UserInputRoute { + Default, + RealtimeHandoff(OwnedMutexGuard<()>), } pub async fn update_thread_settings( @@ -184,6 +197,7 @@ pub(super) async fn user_input_or_turn_inner( sub_id: String, op: Op, client_user_message_id: Option, + route: UserInputRoute, ) { let Op::UserInput { items, @@ -256,12 +270,25 @@ pub(super) async fn user_input_or_turn_inner( client_id: client_user_message_id, }); } - sess.spawn_task( - Arc::clone(¤t_context), - task_input, - crate::tasks::RegularTask::new(), - ) - .await; + match route { + UserInputRoute::Default => { + sess.spawn_task( + Arc::clone(¤t_context), + task_input, + crate::tasks::RegularTask::new(), + ) + .await; + } + UserInputRoute::RealtimeHandoff(handoff_transition) => { + sess.spawn_realtime_task( + Arc::clone(¤t_context), + task_input, + crate::tasks::RegularTask::new(), + handoff_transition, + ) + .await; + } + } } Err(err) => { sess.send_event_raw(Event { diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs index 3f73cd96d0..4ff37a31b5 100644 --- a/codex-rs/core/src/session/inject.rs +++ b/codex-rs/core/src/session/inject.rs @@ -62,6 +62,7 @@ impl Session { )); } + let task_transition = self.task_transition.lock().await; let turn_state = { let mut active_turn = self.active_turn.lock().await; if active_turn.is_some() { @@ -76,6 +77,7 @@ impl Session { if self.input_queue.has_trigger_turn_mailbox_items().await { self.clear_reserved_idle_turn(&turn_state).await; + drop(task_transition); self.maybe_start_turn_for_pending_work().await; return Err(TryStartTurnIfIdleError::new( TryStartTurnIfIdleRejectionReason::PendingTriggerTurn, @@ -88,6 +90,7 @@ impl Session { .await; if turn_context.collaboration_mode.mode == ModeKind::Plan { self.clear_reserved_idle_turn(&turn_state).await; + drop(task_transition); self.maybe_start_turn_for_pending_work().await; return Err(TryStartTurnIfIdleError::new( TryStartTurnIfIdleRejectionReason::PlanMode, @@ -98,6 +101,7 @@ impl Session { .await; if self.input_queue.has_trigger_turn_mailbox_items().await { self.clear_reserved_idle_turn(&turn_state).await; + drop(task_transition); self.maybe_start_turn_for_pending_work().await; return Err(TryStartTurnIfIdleError::new( TryStartTurnIfIdleRejectionReason::PendingTriggerTurn, @@ -124,8 +128,13 @@ impl Session { input.into_iter().map(TurnInput::ResponseItem).collect(), ) .await; - self.start_task(turn_context, Vec::new(), RegularTask::new()) - .await; + self.start_task( + turn_context, + Vec::new(), + RegularTask::new(), + &task_transition, + ) + .await; Ok(()) } diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 472011a2f8..e52f1c4a71 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -156,6 +156,7 @@ use rmcp::model::RequestId; use rmcp::model::UrlElicitationCapability; use serde_json::Value; use tokio::sync::Mutex; +use tokio::sync::OwnedMutexGuard; use tokio::sync::RwLock; use tokio::sync::oneshot; use tokio::sync::watch; @@ -1113,7 +1114,11 @@ impl Session { format!("auto-compact-{id}") } - pub(crate) async fn route_realtime_text_input(self: &Arc, text: String) { + pub(crate) async fn route_realtime_text_input( + self: &Arc, + text: String, + handoff_transition: OwnedMutexGuard<()>, + ) { handlers::user_input_or_turn_inner( self, self.next_internal_sub_id(), @@ -1128,6 +1133,7 @@ impl Session { thread_settings: Default::default(), }, /*client_user_message_id*/ None, + handlers::UserInputRoute::RealtimeHandoff(handoff_transition), ) .await; } diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index c6d0d9767e..ed38a5ac20 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -35,6 +35,9 @@ pub(crate) struct Session { pub(super) multi_agent_version: OnceLock, pub(super) pending_mcp_server_refresh_config: Mutex>, pub(crate) conversation: Arc, + /// Serializes task starts and aborts. Acquire the realtime handoff transition first when both + /// are needed. + pub(crate) task_transition: Mutex<()>, pub(crate) active_turn: Mutex>, pub(crate) input_queue: InputQueue, pub(crate) guardian_review_session: GuardianReviewSessionManager, @@ -1065,6 +1068,7 @@ impl Session { multi_agent_version, pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), + task_transition: Mutex::new(()), active_turn: Mutex::new(None), input_queue: InputQueue::new(), guardian_review_session: GuardianReviewSessionManager::default(), diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ef3f6dbfba..877f3f2935 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -4920,6 +4920,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { multi_agent_version: OnceLock::from(config.multi_agent_version_from_features()), pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), + task_transition: Mutex::new(()), active_turn: Mutex::new(None), input_queue: super::input_queue::InputQueue::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), @@ -6984,6 +6985,7 @@ where multi_agent_version: OnceLock::from(config.multi_agent_version_from_features()), pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), + task_transition: Mutex::new(()), active_turn: Mutex::new(None), input_queue: super::input_queue::InputQueue::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 911f30b319..28b842bcf4 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -11,11 +11,14 @@ use std::time::Instant; use codex_extension_api::ExtensionData; use futures::future::BoxFuture; use tokio::select; +use tokio::sync::MutexGuard; use tokio::sync::Notify; +use tokio::sync::OwnedMutexGuard; use tokio_util::sync::CancellationToken; use tokio_util::task::AbortOnDropHandle; use tracing::Instrument; use tracing::Span; +use tracing::debug; use tracing::field; use tracing::info_span; use tracing::trace; @@ -70,6 +73,12 @@ pub(crate) enum InterruptedTurnHistoryMarker { Developer, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum RealtimeHandoffAfterAbort { + Resolve, + Preserve, +} + impl InterruptedTurnHistoryMarker { pub(crate) fn from_config_and_version( config: &Config, @@ -308,9 +317,38 @@ impl Session { input: Vec, task: T, ) { - self.abort_all_tasks(TurnAbortReason::Replaced).await; + let realtime_handoff_transition = self.conversation.lock_handoff_transition().await; + let task_transition = self.task_transition.lock().await; + self.abort_all_tasks_inner( + TurnAbortReason::Replaced, + RealtimeHandoffAfterAbort::Resolve, + ) + .await; self.clear_connector_selection().await; - self.start_task(turn_context, input, task).await; + self.start_task(turn_context, input, task, &task_transition) + .await; + drop(task_transition); + drop(realtime_handoff_transition); + } + + pub(crate) async fn spawn_realtime_task( + self: &Arc, + turn_context: Arc, + input: Vec, + task: T, + handoff_transition: OwnedMutexGuard<()>, + ) { + let task_transition = self.task_transition.lock().await; + self.abort_all_tasks_inner( + TurnAbortReason::Replaced, + RealtimeHandoffAfterAbort::Preserve, + ) + .await; + self.clear_connector_selection().await; + self.start_task(turn_context, input, task, &task_transition) + .await; + drop(task_transition); + drop(handoff_transition); } pub(crate) async fn start_task( @@ -318,6 +356,7 @@ impl Session { turn_context: Arc, input: Vec, task: T, + _task_transition: &MutexGuard<'_, ()>, ) { let task: Arc = Arc::new(task); let task_kind = task.kind(); @@ -464,6 +503,7 @@ impl Session { return; } + let task_transition = self.task_transition.lock().await; { let mut active_turn = self.active_turn.lock().await; if active_turn.is_some() { @@ -475,11 +515,44 @@ impl Session { let turn_context = self.new_default_turn_with_sub_id(sub_id).await; self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref()) .await; - self.start_task(turn_context, Vec::new(), RegularTask::new()) - .await; + self.start_task( + turn_context, + Vec::new(), + RegularTask::new(), + &task_transition, + ) + .await; } pub async fn abort_all_tasks(self: &Arc, reason: TurnAbortReason) { + let realtime_handoff_transition = self.conversation.lock_handoff_transition().await; + let task_transition = self.task_transition.lock().await; + let aborted_turn = self + .abort_all_tasks_inner(reason.clone(), RealtimeHandoffAfterAbort::Resolve) + .await; + drop(task_transition); + drop(realtime_handoff_transition); + if reason == TurnAbortReason::Interrupted && aborted_turn { + self.maybe_start_turn_for_pending_work().await; + } + } + + async fn abort_all_tasks_inner( + self: &Arc, + reason: TurnAbortReason, + realtime_handoff_after_abort: RealtimeHandoffAfterAbort, + ) -> bool { + if reason == TurnAbortReason::Replaced { + let mut active_turn = self.active_turn.lock().await; + if active_turn + .as_ref() + .and_then(|active_turn| active_turn.task.as_ref()) + .is_none() + { + active_turn.take(); + return false; + } + } let mut aborted_turn = false; let mut active_turn_to_clear = None; let mut turn_context = None; @@ -495,6 +568,12 @@ impl Session { } } + if aborted_turn + && realtime_handoff_after_abort == RealtimeHandoffAfterAbort::Resolve + && let Err(err) = self.conversation.finish_turn(None).await + { + debug!("failed to cancel realtime handoff after abort: {err}"); + } if let Some(turn_context) = turn_context.as_deref() { self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref()) .await; @@ -504,9 +583,7 @@ impl Session { // in-flight approval wait can surface as a model-visible rejection before TurnAborted. self.input_queue.clear_pending(&active_turn).await; } - if reason == TurnAbortReason::Interrupted && aborted_turn { - self.maybe_start_turn_for_pending_work().await; - } + aborted_turn } pub(crate) async fn abort_turn_if_active( @@ -514,6 +591,8 @@ impl Session { turn_id: &str, reason: TurnAbortReason, ) -> bool { + let realtime_handoff_transition = self.conversation.lock_handoff_transition().await; + let task_transition = self.task_transition.lock().await; let active_turn = { let mut active = self.active_turn.lock().await; if active @@ -535,6 +614,11 @@ impl Session { if let Some(task) = task { self.handle_task_abort(task, reason.clone()).await; } + if turn_context.is_some() + && let Err(err) = self.conversation.finish_turn(None).await + { + debug!("failed to cancel realtime handoff after abort: {err}"); + } if let Some(turn_context) = turn_context.as_deref() { self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref()) .await; @@ -542,6 +626,8 @@ impl Session { // Let interrupted tasks observe cancellation before dropping pending approvals, or an // in-flight approval wait can surface as a model-visible rejection before TurnAborted. self.input_queue.clear_pending(&active_turn).await; + drop(task_transition); + drop(realtime_handoff_transition); if reason == TurnAbortReason::Interrupted { self.maybe_start_turn_for_pending_work().await;